-
Notifications
You must be signed in to change notification settings - Fork 0
/
parallelmodel.py
1573 lines (1337 loc) · 68.1 KB
/
parallelmodel.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
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
'''
Models for Model Parallel
'''
import torch
from torch import nn
from grover.util.utils import load_checkpoint
from grover.model.layers import Readout
import numpy as np
from grover.util.nn_utils import get_activation_function, select_neighbor_and_aggregate
import copy
from torch import distributed as dist
import time
def load_pretrained_model(checkpoint_paths=None):
cur_model = 0
debug(f'Loading model {cur_model} from {args.checkpoint_paths[cur_model]}')
model = load_checkpoint(checkpoint_paths[cur_model], current_args=None, logger=None)
return model
class Node_Block_parallel(nn.Module):
"""
Node block for model parallelism
"""
def __init__(self, model, rank):
super(Node_Block_parallel, self).__init__()
self.rank = rank
self.node_blocks = copy.deepcopy(model.grover.encoders.node_blocks.cuda())
def forward(self, f_atoms, f_bonds, a2b, b2a, b2revb, a_scope, b_scope, a2a, features_batch, rank):
node_batch = f_atoms, f_bonds, a2b, b2a, b2revb, a_scope, b_scope, a2a
original_f_atoms, original_f_bonds = f_atoms, f_bonds
for nb in self.node_blocks:
node_batch, features_batch = nb(node_batch, features_batch)
atom_output, _, _, _, _, _, _, _ = node_batch
return atom_output.cuda()
class Edge_Block_parallel(nn.Module):
"""
Node block for model parallelism
"""
def __init__(self, model, rank):
super(Edge_Block_parallel, self).__init__()
self.rank = rank
self.edge_blocks = copy.deepcopy(model.grover.encoders.edge_blocks.cuda())
def forward(self, f_atoms, f_bonds, a2b, b2a, b2revb, a_scope, b_scope, a2a, features_batch, rank):
edge_batch = f_atoms, f_bonds, a2b, b2a, b2revb, a_scope, b_scope, a2a
for eb in self.edge_blocks:
edge_batch, features_batch = eb(edge_batch, features_batch)
_, bond_output, _, _, _, _, _, _ = edge_batch
return bond_output.cuda()
class Edge_Block_parallel_plus_more_gpu(nn.Module):
"""
Node block for model parallelism
"""
def __init__(self, model, rank):
super(Edge_Block_parallel_plus_more_gpu, self).__init__()
self.rank = rank
self.edge_blocks = copy.deepcopy(model.grover.encoders.edge_blocks.cuda())
def forward(self, f_atoms, f_bonds, a2b, b2a, b2revb, a_scope, b_scope, a2a, features_batch, rank):
edge_batch = f_atoms, f_bonds, a2b, b2a, b2revb, a_scope, b_scope, a2a
for eb in self.edge_blocks:
edge_batch, features_batch = eb(edge_batch, features_batch)
_, bond_output, _, _, _, _, _, _ = edge_batch
return bond_output.cuda()
class ReadoutFFN(nn.Module):
'''
atom_output, bond_output -> atom_embedding, bond_embedding
'''
def __init__(self, model, rank: int, args):
'''
:model: pretrained model
:rank: rank of the process
'''
super(ReadoutFFN, self).__init__()
self.rank = rank
self.embedding_output_type = args.embedding_output_type
#self.atom_bond_transform = model.grover.encoders.atom_bond_transform
self.ffn_atom_from_atom = copy.deepcopy(model.grover.encoders.ffn_atom_from_atom.cuda())
self.ffn_atom_from_bond = copy.deepcopy(model.grover.encoders.ffn_atom_from_bond.cuda())
self.ffn_bond_from_atom = copy.deepcopy(model.grover.encoders.ffn_bond_from_atom.cuda())
self.ffn_bond_from_bond = copy.deepcopy(model.grover.encoders.ffn_bond_from_bond.cuda())
self.atom_from_atom_sublayer = copy.deepcopy(model.grover.encoders.atom_from_atom_sublayer.cuda())
self.atom_from_bond_sublayer = copy.deepcopy(model.grover.encoders.atom_from_bond_sublayer.cuda())
self.bond_from_atom_sublayer = copy.deepcopy(model.grover.encoders.bond_from_atom_sublayer.cuda())
self.bond_from_bond_sublayer = copy.deepcopy(model.grover.encoders.bond_from_bond_sublayer.cuda())
self.act_func_node = copy.deepcopy(model.grover.encoders.act_func_node.cuda())
self.act_func_edge = copy.deepcopy(model.grover.encoders.act_func_edge.cuda())
self.readout = copy.deepcopy(model.readout)
self.mol_atom_from_atom_ffn = copy.deepcopy(model.mol_atom_from_atom_ffn.cuda())
self.mol_atom_from_bond_ffn = copy.deepcopy(model.mol_atom_from_bond_ffn.cuda())
self.classification = args.dataset_type == 'classification'
if self.classification:
self.sigmoid = nn.Sigmoid()
def pointwise_feed_forward_to_atom_embedding(self, emb_output, atom_fea, index, ffn_layer):
"""
The point-wise feed forward and long-range residual connection for atom view.
aggregate to atom.
:param emb_output: the output embedding from the previous multi-head attentions.
:param atom_fea: the atom/node feature embedding.
:param index: the index of neighborhood relations.
:param ffn_layer: the feed forward layer
:return:
"""
aggr_output = select_neighbor_and_aggregate(emb_output, index)
aggr_outputx = torch.cat([atom_fea, aggr_output], dim=1)
return ffn_layer(aggr_outputx), aggr_output
def pointwise_feed_forward_to_bond_embedding(self, emb_output, bond_fea, a2nei, b2revb, ffn_layer):
"""
The point-wise feed forward and long-range residual connection for bond view.
aggregate to bond.
:param emb_output: the output embedding from the previous multi-head attentions.
:param bond_fea: the bond/edge feature embedding.
:param index: the index of neighborhood relations.
:param ffn_layer: the feed forward layer
:return:
"""
aggr_output = select_neighbor_and_aggregate(emb_output, a2nei)
# remove rev bond / atom --- need for bond view
aggr_output = self.remove_rev_bond_message(emb_output, aggr_output, b2revb)
aggr_outputx = torch.cat([bond_fea, aggr_output], dim=1)
return ffn_layer(aggr_outputx), aggr_output
def atom_bond_transform(self,
to_atom=True, # False: to bond
atomwise_input=None,
bondwise_input=None,
original_f_atoms=None,
original_f_bonds=None,
a2a=None,
a2b=None,
b2a=None,
b2revb=None
):
"""
Transfer the output of atom/bond multi-head attention to the final atom/bond output.
:param to_atom: if true, the output is atom emebedding, otherwise, the output is bond embedding.
:param atomwise_input: the input embedding of atom/node.
:param bondwise_input: the input embedding of bond/edge.
:param original_f_atoms: the initial atom features.
:param original_f_bonds: the initial bond features.
:param a2a: mapping from atom index to its neighbors. num_atoms * max_num_bonds
:param a2b: mapping from atom index to incoming bond indices.
:param b2a: mapping from bond index to the index of the atom the bond is coming from.
:param b2revb: mapping from bond index to the index of the reverse bond.
:return:
"""
if to_atom:
# atom input to atom output
atomwise_input, _ = self.pointwise_feed_forward_to_atom_embedding(atomwise_input, original_f_atoms, a2a,
self.ffn_atom_from_atom)
atom_in_atom_out = self.atom_from_atom_sublayer(None, atomwise_input)
# bond to atom
bondwise_input, _ = self.pointwise_feed_forward_to_atom_embedding(bondwise_input, original_f_atoms, a2b,
self.ffn_atom_from_bond)
bond_in_atom_out = self.atom_from_bond_sublayer(None, bondwise_input)
return atom_in_atom_out, bond_in_atom_out
else: # to bond embeddings
# atom input to bond output
atom_list_for_bond = torch.cat([b2a.unsqueeze(dim=1), a2a[b2a]], dim=1)
atomwise_input, _ = self.pointwise_feed_forward_to_bond_embedding(atomwise_input, original_f_bonds,
atom_list_for_bond,
b2a[b2revb], self.ffn_bond_from_atom)
atom_in_bond_out = self.bond_from_atom_sublayer(None, atomwise_input)
# bond input to bond output
bond_list_for_bond = a2b[b2a]
bondwise_input, _ = self.pointwise_feed_forward_to_bond_embedding(bondwise_input, original_f_bonds,
bond_list_for_bond,
b2revb, self.ffn_bond_from_bond)
bond_in_bond_out = self.bond_from_bond_sublayer(None, bondwise_input)
return atom_in_bond_out, bond_in_bond_out
@staticmethod
def remove_rev_bond_message(orginal_message, aggr_message, b2revb):
"""
:param orginal_message:
:param aggr_message:
:param b2revb:
:return:
"""
rev_message = orginal_message[b2revb]
return aggr_message - rev_message
def forward(self, atom_output, bond_output, original_f_atoms, original_f_bonds, a2a, a2b, b2a, b2revb, a_scope, b_scope, features_batch):
atom_embeddings = self.atom_bond_transform(to_atom=True,
atomwise_input=atom_output.cuda(),
bondwise_input=bond_output.cuda(),
original_f_atoms=original_f_atoms.cuda(),
original_f_bonds=original_f_bonds.cuda(),
a2a=a2a.cuda(),
a2b=a2b.cuda(),
b2a=b2a.cuda(),
b2revb=b2revb.cuda())
bond_embeddings = self.atom_bond_transform(to_atom=False,
atomwise_input=atom_output.cuda(),
bondwise_input=bond_output.cuda(),
original_f_atoms=original_f_atoms.cuda(),
original_f_bonds=original_f_bonds.cuda(),
a2a=a2a.cuda(),
a2b=a2b.cuda(),
b2a=b2a.cuda(),
b2revb=b2revb.cuda())
output = ((atom_embeddings[0], bond_embeddings[0]),
(atom_embeddings[1], bond_embeddings[1]))
if self.embedding_output_type == 'atom':
output = {"atom_from_atom": output[0], "atom_from_bond": output[1],
"bond_from_atom": None, "bond_from_bond": None} # atom_from_atom, atom_from_bond
elif self.embedding_output_type == 'bond':
output = {"atom_from_atom": None, "atom_from_bond": None,
"bond_from_atom": output[0], "bond_from_bond": output[1]} # bond_from_atom, bond_from_bond
elif self.embedding_output_type == "both":
output = {"atom_from_atom": output[0][0], "bond_from_atom": output[0][1],
"atom_from_bond": output[1][0], "bond_from_bond": output[1][1]}
a_scope = a_scope.data.cpu().numpy().tolist()
mol_atom_from_bond_output = self.readout(output["atom_from_bond"].cuda(), a_scope)
mol_atom_from_atom_output = self.readout(output["atom_from_atom"].cuda(), a_scope)
if features_batch[0] is not None:
features_batch = torch.from_numpy(np.stack(features_batch)).float()
if 1:
features_batch = features_batch.cuda()
features_batch = features_batch.to(output["atom_from_atom"])
if len(features_batch.shape) == 1:
features_batch = features_batch.view([1, features_batch.shape[0]])
else:
features_batch = None
if features_batch is not None:
mol_atom_from_atom_output = torch.cat([mol_atom_from_atom_output, features_batch.cuda()], 1)
mol_atom_from_bond_output = torch.cat([mol_atom_from_bond_output, features_batch.cuda()], 1)
if self.training:
atom_ffn_output = self.mol_atom_from_atom_ffn(mol_atom_from_atom_output.cuda())
bond_ffn_output = self.mol_atom_from_bond_ffn(mol_atom_from_bond_output.cuda())
return atom_ffn_output, bond_ffn_output
else:
atom_ffn_output = self.mol_atom_from_atom_ffn(mol_atom_from_atom_output.cuda())
bond_ffn_output = self.mol_atom_from_bond_ffn(mol_atom_from_bond_output.cuda())
if self.classification:
atom_ffn_output = self.sigmoid(atom_ffn_output.cuda())
bond_ffn_output = self.sigmoid(bond_ffn_output.cuda())
output = (atom_ffn_output + bond_ffn_output) / 2
return output
class Node_Readout_FFN(nn.Module):
'''
atom_output, bond_output -> atom_embedding
'''
def __init__(self, model, rank, args):
'''
:model: pretrained GROVER model
:args: args
'''
super(Node_Readout_FFN, self).__init__()
self.num_tasks = args.num_tasks
#self.atom_bond_transform = model.grover.encoders.atom_bond_transform
self.embedding_output_type = args.embedding_output_type
self.act_func_node = copy.deepcopy(model.grover.encoders.act_func_node.cuda())
self.readout = copy.deepcopy(model.readout.cuda())
self.mol_atom_from_atom_ffn = copy.deepcopy(model.mol_atom_from_atom_ffn.cuda())
#self.ffn_bond_from_atom = model.grover.encoders.ffn_bond_from_atom.cuda()
#self.ffn_bond_from_bond = model.grover.encoders.ffn_bond_from_bond.cuda()
#self.mol_atom_from_atom_ffn = self.create_ffn(args)
self.classification = args.dataset_type == 'classification'
if self.classification:
self.sigmoid = nn.Sigmoid()
def create_ffn(self, args):
"""
Creates the feed-forward network for the model.
:param args: Arguments.
"""
# Note: args.features_dim is set according the real loaded features data
if args.features_only:
first_linear_dim = args.features_size + args.features_dim
else:
if args.self_attention:
first_linear_dim = args.hidden_size * args.attn_out
# TODO: Ad-hoc!
# if args.use_input_features:
first_linear_dim += args.features_dim
else:
first_linear_dim = args.hidden_size + args.features_dim
dropout = nn.Dropout(args.dropout)
activation = get_activation_function(args.activation)
# TODO: ffn_hidden_size
# Create FFN layers
if args.ffn_num_layers == 1:
ffn = [
dropout.cuda(),
nn.Linear(first_linear_dim, args.output_size).cuda()
]
else:
ffn = [
dropout.cuda(),
nn.Linear(first_linear_dim, args.ffn_hidden_size).cuda()
]
for _ in range(args.ffn_num_layers - 2):
ffn.extend([
activation.cuda(),
dropout.cuda(),
nn.Linear(args.ffn_hidden_size, args.ffn_hidden_size).cuda(),
])
ffn.extend([
activation.cuda(),
dropout.cuda(),
nn.Linear(args.ffn_hidden_size, args.output_size).cuda(),
])
# Create FFN model
return nn.Sequential(*ffn)
def forward(self, output, a_scope, features_batch):
rank = dist.get_rank()
tag_id = int((rank//2)*100)
a_scope = a_scope.data.cpu().numpy().tolist()
mol_atom_from_atom_output = self.readout(output["atom_from_atom"], a_scope)
if features_batch[0] is not None:
features_batch = torch.from_numpy(np.stack(features_batch)).float()
if 1: # if cuda
features_batch = features_batch.cuda()
features_batch = features_batch.to(output["atom_from_atom"])
if len(features_batch.shape) == 1:
features_batch = features_batch.view([1, features_batch.shape[0]])
else:
features_batch = None
if features_batch is not None:
mol_atom_from_atom_output = torch.cat([mol_atom_from_atom_output, features_batch], 1)
if self.training:
atom_ffn_output = self.mol_atom_from_atom_ffn(mol_atom_from_atom_output)
# Recv bond_ffn_output
bond_ffn_output = torch.zeros(atom_ffn_output.size(0), self.num_tasks).cuda()
dist.recv(bond_ffn_output, rank+1, None, tag_id+10)
# Send atom_ffn_output
dist.isend(atom_ffn_output, rank+1, None, tag_id+11)
return atom_ffn_output, bond_ffn_output.cuda()
else:
atom_ffn_output = self.mol_atom_from_atom_ffn(mol_atom_from_atom_output)
if self.classification:
atom_ffn_output = self.sigmoid(atom_ffn_output)
# Recv bond_ffn_output
bond_ffn_output = torch.zeros(atom_ffn_output.size(0), self.num_tasks).cuda()
dist.recv(bond_ffn_output, rank+1, None, tag_id+10)
# Send atom_ffn_output
dist.isend(atom_ffn_output, rank+1, None, tag_id+11)
output = (atom_ffn_output + bond_ffn_output.cuda()) / 2
return output
class Node_Readout_FFN2(nn.Module):
'''
atom_output, bond_output -> atom_embedding
'''
def __init__(self, model, rank, args):
'''
:model: pretrained GROVER model
:args: args
'''
super(Node_Readout_FFN2, self).__init__()
self.hidden_size = args.hidden_size
self.num_tasks = args.num_tasks
#self.atom_bond_transform = model.grover.encoders.atom_bond_transform
self.embedding_output_type = args.embedding_output_type
self.ffn_atom_from_atom = copy.deepcopy(model.grover.encoders.ffn_atom_from_atom.cuda())
self.atom_from_atom_sublayer = copy.deepcopy(model.grover.encoders.atom_from_atom_sublayer.cuda())
self.ffn_atom_from_bond = copy.deepcopy(model.grover.encoders.ffn_atom_from_bond.cuda())
self.atom_from_bond_sublayer = copy.deepcopy(model.grover.encoders.atom_from_bond_sublayer.cuda())
self.act_func_node = copy.deepcopy(model.grover.encoders.act_func_node.cuda())
self.readout = copy.deepcopy(model.readout.cuda())
self.mol_atom_from_atom_ffn = copy.deepcopy(model.mol_atom_from_atom_ffn.cuda())
#self.ffn_bond_from_atom = model.grover.encoders.ffn_bond_from_atom.cuda()
#self.ffn_bond_from_bond = model.grover.encoders.ffn_bond_from_bond.cuda()
#self.mol_atom_from_atom_ffn = self.create_ffn(args)
self.classification = args.dataset_type == 'classification'
if self.classification:
self.sigmoid = nn.Sigmoid()
def atom_bond_transform(self,
to_atom=True, # False: to bond
atomwise_input=None,
bondwise_input=None,
original_f_atoms=None,
original_f_bonds=None,
a2a=None,
a2b=None,
b2a=None,
b2revb=None
):
"""
"""
# atom input to atom output
atomwise_input, _ = self.pointwise_feed_forward_to_atom_embedding(atomwise_input, original_f_atoms, a2a,
self.ffn_atom_from_atom)
atom_in_atom_out = self.atom_from_atom_sublayer(None, atomwise_input)
# bond to atom
bondwise_input, _ = self.pointwise_feed_forward_to_atom_embedding(bondwise_input, original_f_atoms, a2b,
self.ffn_atom_from_bond)
bond_in_atom_out = self.atom_from_bond_sublayer(None, bondwise_input)
return atom_in_atom_out, bond_in_atom_out
def create_ffn(self, args):
"""
Creates the feed-forward network for the model.
:param args: Arguments.
"""
# Note: args.features_dim is set according the real loaded features data
if args.features_only:
first_linear_dim = args.features_size + args.features_dim
else:
if args.self_attention:
first_linear_dim = args.hidden_size * args.attn_out
# TODO: Ad-hoc!
# if args.use_input_features:
first_linear_dim += args.features_dim
else:
first_linear_dim = args.hidden_size + args.features_dim
dropout = nn.Dropout(args.dropout)
activation = get_activation_function(args.activation)
# TODO: ffn_hidden_size
# Create FFN layers
if args.ffn_num_layers == 1:
ffn = [
dropout.cuda(),
nn.Linear(first_linear_dim, args.output_size).cuda()
]
else:
ffn = [
dropout.cuda(),
nn.Linear(first_linear_dim, args.ffn_hidden_size).cuda()
]
for _ in range(args.ffn_num_layers - 2):
ffn.extend([
activation.cuda(),
dropout.cuda(),
nn.Linear(args.ffn_hidden_size, args.ffn_hidden_size).cuda(),
])
ffn.extend([
activation.cuda(),
dropout.cuda(),
nn.Linear(args.ffn_hidden_size, args.output_size).cuda(),
])
# Create FFN model
return nn.Sequential(*ffn)
def pointwise_feed_forward_to_atom_embedding(self, emb_output, atom_fea, index, ffn_layer):
"""
The point-wise feed forward and long-range residual connection for atom view.
aggregate to atom.
:param emb_output: the output embedding from the previous multi-head attentions.
:param atom_fea: the atom/node feature embedding.
:param index: the index of neighborhood relations.
:param ffn_layer: the feed forward layer
:return:
"""
aggr_output = select_neighbor_and_aggregate(emb_output, index)
aggr_outputx = torch.cat([atom_fea.cuda(), aggr_output.cuda()], dim=1)
return ffn_layer(aggr_outputx), aggr_output
def forward(self, atom_output, bond_output, original_f_atoms, original_f_bonds, a2a, a2b, b2a, b2revb, a_scope, features_batch):
rank = dist.get_rank()
tag_id = int((rank//2)*100)
dist.isend(atom_output, rank+1, None, tag_id+0)
dist.recv(bond_output, rank+1, None, tag_id+1)
atom_embeddings = self.atom_bond_transform(to_atom=True, # False: to bond
atomwise_input=atom_output.cuda(),
bondwise_input=bond_output.cuda(),
original_f_atoms=original_f_atoms,
original_f_bonds=original_f_bonds,
a2a=a2a,
a2b=a2b,
b2a=b2a,
b2revb=b2revb)
# Recv bond_embeddings
atom_in_bond_out = torch.zeros(original_f_bonds.size(0), self.hidden_size).cuda()
bond_in_bond_out = torch.zeros(original_f_bonds.size(0), self.hidden_size).cuda()
dist.recv(atom_in_bond_out, rank+1, None, tag_id+2)
dist.recv(bond_in_bond_out, rank+1, None, tag_id+3)
bond_embeddings = (atom_in_bond_out.cuda(), bond_in_bond_out.cuda())
# Send atom_embeddings
atom_in_atom_out, bond_in_atom_out = atom_embeddings
dist.isend(atom_in_atom_out, rank+1, None, tag_id+4)
dist.isend(bond_in_atom_out, rank+1, None, tag_id+5)
output = ((atom_embeddings[0], bond_embeddings[0]),
(atom_embeddings[1], bond_embeddings[1]))
if self.embedding_output_type == 'atom':
output = {"atom_from_atom": output[0], "atom_from_bond": output[1],
"bond_from_atom": None, "bond_from_bond": None} # atom_from_atom, atom_from_bond
elif self.embedding_output_type == 'bond':
output = {"atom_from_atom": None, "atom_from_bond": None,
"bond_from_atom": output[0], "bond_from_bond": output[1]} # bond_from_atom, bond_from_bond
elif self.embedding_output_type == "both":
output = {"atom_from_atom": output[0][0], "bond_from_atom": output[0][1],
"atom_from_bond": output[1][0], "bond_from_bond": output[1][1]}
a_scope = a_scope.data.cpu().numpy().tolist()
mol_atom_from_atom_output = self.readout(output["atom_from_atom"], a_scope)
if features_batch[0] is not None:
features_batch = torch.from_numpy(np.stack(features_batch)).float()
if 1: # if cuda
features_batch = features_batch.cuda()
features_batch = features_batch.to(output["atom_from_atom"])
if len(features_batch.shape) == 1:
features_batch = features_batch.view([1, features_batch.shape[0]])
else:
features_batch = None
if features_batch is not None:
mol_atom_from_atom_output = torch.cat([mol_atom_from_atom_output, features_batch], 1)
if self.training:
atom_ffn_output = self.mol_atom_from_atom_ffn(mol_atom_from_atom_output)
# Recv bond_ffn_output
bond_ffn_output = torch.zeros(atom_ffn_output.size(0), self.num_tasks).cuda()
dist.recv(bond_ffn_output, rank+1, None, tag_id+10)
# Send atom_ffn_output
dist.isend(atom_ffn_output, rank+1, None, tag_id+11)
return atom_ffn_output, bond_ffn_output.cuda()
else:
atom_ffn_output = self.mol_atom_from_atom_ffn(mol_atom_from_atom_output)
if self.classification:
atom_ffn_output = self.sigmoid(atom_ffn_output)
# Recv bond_ffn_output
bond_ffn_output = torch.zeros(atom_ffn_output.size(0), self.num_tasks).cuda()
dist.recv(bond_ffn_output, rank+1, None, tag_id+10)
# Send atom_ffn_output
dist.isend(atom_ffn_output, rank+1, None, tag_id+11)
output = (atom_ffn_output + bond_ffn_output.cuda()) / 2
return output
class Edge_Readout_FFN(nn.Module):
'''
atom_output, bond_output -> bond_embedding
'''
def __init__(self, model, rank: int, args):
'''
:model: pretrained model
:rank: rank of the process
'''
super(Edge_Readout_FFN, self).__init__()
self.num_tasks = args.num_tasks
self.rank = rank
self.embedding_output_type = args.embedding_output_type
self.act_func_edge = copy.deepcopy(model.grover.encoders.act_func_edge.cuda())
self.readout = copy.deepcopy(model.readout.cuda())
self.mol_atom_from_bond_ffn = copy.deepcopy(model.mol_atom_from_bond_ffn.cuda())
#self.mol_atom_from_bond_ffn = self.create_ffn(args)
self.classification = args.dataset_type == 'classification'
if self.classification:
self.sigmoid = nn.Sigmoid()
def create_ffn(self, args):
"""
Creates the feed-forward network for the model.
:param args: Arguments.
"""
# Note: args.features_dim is set according the real loaded features data
if args.features_only:
first_linear_dim = args.features_size + args.features_dim
else:
if args.self_attention:
first_linear_dim = args.hidden_size * args.attn_out
# TODO: Ad-hoc!
# if args.use_input_features:
first_linear_dim += args.features_dim
else:
first_linear_dim = args.hidden_size + args.features_dim
dropout = nn.Dropout(args.dropout)
activation = get_activation_function(args.activation)
# TODO: ffn_hidden_size
# Create FFN layers
if args.ffn_num_layers == 1:
ffn = [
dropout.cuda(),
nn.Linear(first_linear_dim, args.output_size).cuda()
]
else:
ffn = [
dropout.cuda(),
nn.Linear(first_linear_dim, args.ffn_hidden_size).cuda()
]
for _ in range(args.ffn_num_layers - 2):
ffn.extend([
activation.cuda(),
dropout.cuda(),
nn.Linear(args.ffn_hidden_size, args.ffn_hidden_size).cuda(),
])
ffn.extend([
activation.cuda(),
dropout.cuda(),
nn.Linear(args.ffn_hidden_size, args.output_size).cuda(),
])
# Create FFN model
return nn.Sequential(*ffn)
def forward(self, output, a_scope, features_batch):
rank = dist.get_rank()
tag_id = int((rank//2)*100)
a_scope = a_scope.data.cpu().numpy().tolist()
mol_atom_from_bond_output = self.readout(output["atom_from_bond"], a_scope)
if features_batch[0] is not None:
features_batch = copy.deepcopy(torch.from_numpy(np.stack(features_batch)).float())
if True: # if self.iscuda:
features_batch = features_batch.cuda()
features_batch = features_batch.to(output["atom_from_atom"])
if len(features_batch.shape) == 1:
features_batch = features_batch.view([1, features_batch.shape[0]])
else:
features_batch = None
if features_batch is not None:
mol_atom_from_bond_output = torch.cat([mol_atom_from_bond_output, features_batch], 1)
if self.training:
bond_ffn_output = self.mol_atom_from_bond_ffn(mol_atom_from_bond_output)
# Send bond_ffn_output
dist.isend(bond_ffn_output, rank-1, None, tag_id+10)
# Recv atom_ffn_output
atom_ffn_output = torch.zeros(bond_ffn_output.size(0), self.num_tasks).cuda()
dist.recv(atom_ffn_output, rank-1, None, tag_id+11)
return atom_ffn_output.cuda(), bond_ffn_output
else:
bond_ffn_output = self.mol_atom_from_bond_ffn(mol_atom_from_bond_output)
if self.classification:
bond_ffn_output = self.sigmoid(bond_ffn_output)
# Send bond_ffn_output
dist.isend(bond_ffn_output, rank-1, None, tag_id+10)
# Recv atom_ffn_output
atom_ffn_output = torch.zeros(bond_ffn_output.size(0), self.num_tasks).cuda()
dist.recv(atom_ffn_output, rank-1, None, tag_id+11)
output = (atom_ffn_output.cuda() + bond_ffn_output) / 2
return output
class Edge_Readout_FFN2(nn.Module):
'''
atom_output, bond_output -> bond_embedding
'''
def __init__(self, model, rank: int, args):
'''
:model: pretrained model
:rank: rank of the process
'''
super(Edge_Readout_FFN2, self).__init__()
self.hidden_size = args.hidden_size
self.num_tasks = args.num_tasks
self.rank = rank
self.embedding_output_type = args.embedding_output_type
self.bond_from_atom_sublayer = copy.deepcopy(model.grover.encoders.bond_from_atom_sublayer.cuda())
self.bond_from_bond_sublayer = copy.deepcopy(model.grover.encoders.bond_from_bond_sublayer.cuda())
self.ffn_bond_from_atom = copy.deepcopy(model.grover.encoders.ffn_bond_from_atom.cuda())
self.ffn_bond_from_bond = copy.deepcopy(model.grover.encoders.ffn_bond_from_bond.cuda())
self.act_func_edge = copy.deepcopy(model.grover.encoders.act_func_edge.cuda())
self.readout = copy.deepcopy(model.readout.cuda())
self.mol_atom_from_bond_ffn = copy.deepcopy(model.mol_atom_from_bond_ffn.cuda())
#self.mol_atom_from_bond_ffn = self.create_ffn(args)
self.classification = args.dataset_type == 'classification'
if self.classification:
self.sigmoid = nn.Sigmoid()
@staticmethod
def remove_rev_bond_message(orginal_message, aggr_message, b2revb):
"""
:param orginal_message:
:param aggr_message:
:param b2revb:
:return:
"""
rev_message = orginal_message[b2revb]
return aggr_message - rev_message
def pointwise_feed_forward_to_bond_embedding(self, emb_output, bond_fea, a2nei, b2revb, ffn_layer):
"""
The point-wise feed forward and long-range residual connection for bond view.
aggregate to bond.
:param emb_output: the output embedding from the previous multi-head attentions.
:param bond_fea: the bond/edge feature embedding.
:param index: the index of neighborhood relations.
:param ffn_layer: the feed forward layer
:return:
"""
aggr_output = select_neighbor_and_aggregate(emb_output, a2nei)
# remove rev bond / atom --- need for bond view
aggr_output = self.remove_rev_bond_message(emb_output, aggr_output, b2revb)
aggr_outputx = torch.cat([bond_fea.cuda(), aggr_output], dim=1)
return ffn_layer(aggr_outputx), aggr_output
def atom_bond_transform(self,
to_atom=True, # False: to bond
atomwise_input=None,
bondwise_input=None,
original_f_atoms=None,
original_f_bonds=None,
a2a=None,
a2b=None,
b2a=None,
b2revb=None
):
"""
"""
# atom input to bond output
atom_list_for_bond = torch.cat([b2a.unsqueeze(dim=1), a2a[b2a]], dim=1)
atomwise_input, _ = self.pointwise_feed_forward_to_bond_embedding(atomwise_input, original_f_bonds,
atom_list_for_bond,
b2a[b2revb], self.ffn_bond_from_atom)
atom_in_bond_out = self.bond_from_atom_sublayer(None, atomwise_input)
# bond input to bond output
bond_list_for_bond = a2b[b2a]
bondwise_input, _ = self.pointwise_feed_forward_to_bond_embedding(bondwise_input, original_f_bonds,
bond_list_for_bond,
b2revb, self.ffn_bond_from_bond)
bond_in_bond_out = self.bond_from_bond_sublayer(None, bondwise_input)
return atom_in_bond_out, bond_in_bond_out
def create_ffn(self, args):
"""
Creates the feed-forward network for the model.
:param args: Arguments.
"""
# Note: args.features_dim is set according the real loaded features data
if args.features_only:
first_linear_dim = args.features_size + args.features_dim
else:
if args.self_attention:
first_linear_dim = args.hidden_size * args.attn_out
# TODO: Ad-hoc!
# if args.use_input_features:
first_linear_dim += args.features_dim
else:
first_linear_dim = args.hidden_size + args.features_dim
dropout = nn.Dropout(args.dropout)
activation = get_activation_function(args.activation)
# TODO: ffn_hidden_size
# Create FFN layers
if args.ffn_num_layers == 1:
ffn = [
dropout.cuda(),
nn.Linear(first_linear_dim, args.output_size).cuda()
]
else:
ffn = [
dropout.cuda(),
nn.Linear(first_linear_dim, args.ffn_hidden_size).cuda()
]
for _ in range(args.ffn_num_layers - 2):
ffn.extend([
activation.cuda(),
dropout.cuda(),
nn.Linear(args.ffn_hidden_size, args.ffn_hidden_size).cuda(),
])
ffn.extend([
activation.cuda(),
dropout.cuda(),
nn.Linear(args.ffn_hidden_size, args.output_size).cuda(),
])
# Create FFN model
return nn.Sequential(*ffn)
def forward(self, atom_output, bond_output, original_f_atoms, original_f_bonds, a2a, a2b, b2a, b2revb, a_scope, features_batch):
rank = dist.get_rank() # 0, 1
tag_id = int((rank//2)*100)
dist.recv(atom_output, rank-1, None, tag_id+0)
dist.isend(bond_output, rank-1, None, tag_id+1)
bond_embeddings = self.atom_bond_transform(to_atom=False, # False: to bond
atomwise_input=atom_output.cuda(),
bondwise_input=bond_output,
original_f_atoms=original_f_atoms,
original_f_bonds=original_f_bonds,
a2a=a2a,
a2b=a2b,
b2a=b2a,
b2revb=b2revb)
# Send bond embeddings
atom_in_bond_out, bond_in_bond_out = bond_embeddings[0], bond_embeddings[1]
dist.isend(atom_in_bond_out, rank-1, None, tag_id+2)
dist.isend(bond_in_bond_out, rank-1, None, tag_id+3)
# Recv atom embeddings
atom_in_atom_out = torch.zeros(original_f_atoms.size(0), self.hidden_size).cuda()
bond_in_atom_out = torch.zeros(original_f_atoms.size(0), self.hidden_size).cuda()
dist.recv(atom_in_atom_out, rank-1, None, tag_id+4)
dist.recv(bond_in_atom_out, rank-1, None, tag_id+5)
atom_embeddings = (atom_in_atom_out, bond_in_atom_out)
# Return output
output = ((atom_embeddings[0], bond_embeddings[0]), # atom in atom out, atom in bond out
(atom_embeddings[1], bond_embeddings[1])) # bond in atom out, bond in bond out
if self.embedding_output_type == 'atom':
output = {"atom_from_atom": output[0], "atom_from_bond": output[1],
"bond_from_atom": None, "bond_from_bond": None} # atom_from_atom, atom_from_bond
elif self.embedding_output_type == 'bond':
output = {"atom_from_atom": None, "atom_from_bond": None,
"bond_from_atom": output[0], "bond_from_bond": output[1]} # bond_from_atom, bond_from_bond
elif self.embedding_output_type == "both":
output = {"atom_from_atom": output[0][0], "bond_from_atom": output[0][1],
"atom_from_bond": output[1][0], "bond_from_bond": output[1][1]}
a_scope = a_scope.data.cpu().numpy().tolist()
mol_atom_from_bond_output = self.readout(output["atom_from_bond"], a_scope)
if features_batch[0] is not None:
features_batch = torch.from_numpy(np.stack(features_batch)).float()
if True: # if self.iscuda:
features_batch = features_batch.cuda()
features_batch = features_batch.to(output["atom_from_atom"])
if len(features_batch.shape) == 1:
features_batch = features_batch.view([1, features_batch.shape[0]])
else:
features_batch = None
if features_batch is not None:
mol_atom_from_bond_output = torch.cat([mol_atom_from_bond_output, features_batch], 1)
if self.training:
bond_ffn_output = self.mol_atom_from_bond_ffn(mol_atom_from_bond_output)
# Send bond_ffn_output
dist.isend(bond_ffn_output, rank-1, None, tag_id+10)
# Recv atom_ffn_output
atom_ffn_output = torch.zeros(bond_ffn_output.size(0), self.num_tasks).cuda()
dist.recv(atom_ffn_output, rank-1, None, tag_id+11)
return atom_ffn_output.cuda(), bond_ffn_output
else:
bond_ffn_output = self.mol_atom_from_bond_ffn(mol_atom_from_bond_output)
if self.classification:
bond_ffn_output = self.sigmoid(bond_ffn_output)
# Send bond_ffn_output
dist.isend(bond_ffn_output, rank-1, None, tag_id+10)
# Recv atom_ffn_output
atom_ffn_output = torch.zeros(bond_ffn_output.size(0), self.num_tasks).cuda()
dist.recv(atom_ffn_output, rank-1, None, tag_id+11)
output = (atom_ffn_output.cuda() + bond_ffn_output) / 2
return output
class Node_Readout_atom_embedding_only(nn.Module):
'''
atom_output, bond_output -> atom_embedding
'''
def __init__(self, model, rank, args):
'''
:model: pretrained GROVER model
:args: args
'''
super(Node_Readout_atom_embedding_only, self).__init__()
self.hidden_size = args.hidden_size
self.num_tasks = args.num_tasks
#self.atom_bond_transform = model.grover.encoders.atom_bond_transform
self.embedding_output_type = args.embedding_output_type
self.ffn_atom_from_atom = copy.deepcopy(model.grover.encoders.ffn_atom_from_atom.cuda())
self.atom_from_atom_sublayer = copy.deepcopy(model.grover.encoders.atom_from_atom_sublayer.cuda())
self.ffn_atom_from_bond = copy.deepcopy(model.grover.encoders.ffn_atom_from_bond.cuda())
self.atom_from_bond_sublayer = copy.deepcopy(model.grover.encoders.atom_from_bond_sublayer.cuda())
self.act_func_node = copy.deepcopy(model.grover.encoders.act_func_node.cuda())
self.readout = copy.deepcopy(model.readout.cuda())
self.mol_atom_from_atom_ffn = copy.deepcopy(model.mol_atom_from_atom_ffn.cuda())
#self.ffn_bond_from_atom = model.grover.encoders.ffn_bond_from_atom.cuda()
#self.ffn_bond_from_bond = model.grover.encoders.ffn_bond_from_bond.cuda()
#self.mol_atom_from_atom_ffn = self.create_ffn(args)
self.classification = args.dataset_type == 'classification'
if self.classification:
self.sigmoid = nn.Sigmoid()
def atom_bond_transform(self,
to_atom=True, # False: to bond
atomwise_input=None,
bondwise_input=None,
original_f_atoms=None,
original_f_bonds=None,
a2a=None,
a2b=None,
b2a=None,
b2revb=None
):
"""
"""
# atom input to atom output
atomwise_input, _ = self.pointwise_feed_forward_to_atom_embedding(atomwise_input, original_f_atoms, a2a,
self.ffn_atom_from_atom)
atom_in_atom_out = self.atom_from_atom_sublayer(None, atomwise_input)
# bond to atom
bondwise_input, _ = self.pointwise_feed_forward_to_atom_embedding(bondwise_input, original_f_atoms, a2b,
self.ffn_atom_from_bond)
bond_in_atom_out = self.atom_from_bond_sublayer(None, bondwise_input)
return atom_in_atom_out, bond_in_atom_out
def create_ffn(self, args):
"""
Creates the feed-forward network for the model.
:param args: Arguments.
"""
# Note: args.features_dim is set according the real loaded features data
if args.features_only:
first_linear_dim = args.features_size + args.features_dim