-
Notifications
You must be signed in to change notification settings - Fork 2
/
main.py
2056 lines (1890 loc) · 132 KB
/
main.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
#!/usr/bin/env/python
"""
Usage:
main.py [options]
Options:
-h --help Show this screen
--dataset NAME Dataset name: zinc (or qm9, cep)
--config-file FILE Hyperparameter configuration file path (in JSON format)
--config CONFIG Hyperparameter configuration dictionary (in JSON format)
--log_dir NAME log dir name
--data_dir NAME data dir name
--restore FILE File to restore weights from.
--freeze-graph-model Freeze weights of graph model components
--restrict_data INT Limit data
--generation BOOL Train or test
--load_cpt STR Path to load checkpoint
"""
from docopt import docopt
from collections import defaultdict, deque
import numpy as np
import torch
from torch import nn
import sys, traceback
import json
import os
from rdkit.Chem import QED
from model import ChemModel
from utils import *
import pickle
import random
from rdkit import Chem
from copy import deepcopy
import os
import time
from data_augmentation import *
class Linker(ChemModel):
def __init__(self, args):
super().__init__(args)
@classmethod
def default_params(cls):
params = dict(super().default_params())
params.update({
'task_sample_ratios': {},
'use_edge_bias': True, # whether use edge bias in gnn
'clamp_gradient_norm': 0.25,
'out_layer_dropout_keep_prob': 1.0,
'tie_fwd_bkwd': True,
'random_seed': 0, # fixed for reproducibility
'batch_size': 8,
'prior_learning_rate': 0.05,
'stop_criterion': 1,
'num_epochs': 10,
'epoch_to_generate': 10,
'number_of_generation_per_valid': 250,
'maximum_distance': 50,
"use_argmax_generation": False, # use random sampling or argmax during generation
'residual_connection_on': True, # whether residual connection is on
'residual_connections': { # For iteration i, specify list of layers whose output is added as an input
2: [0],
4: [0, 2],
6: [0, 2, 4],
8: [0, 2, 4, 6],
10: [0, 2, 4, 6, 8],
12: [0, 2, 4, 6, 8, 10],
14: [0, 2, 4, 6, 8, 10, 12],
},
'num_timesteps': 5, # gnn propagation step
'hidden_size': 28,
'idx_size': 4,
'vector_size': 12,
'max_num_nodes': 48,
'encoding_size': 12,
'encoding_vec_size': 12,
'kl_trade_off_lambda': 0.6, # kl tradeoff
'pos_trade_off_lambda': 1,
'learning_rate': 0.0006,
'graph_state_dropout_keep_prob': 1,
'compensate_num': 0, # how many atoms to be added during generation
'try_different_starting': True,
"num_different_starting": 1,
'generation': False, # only generate
'use_graph': True, # use gnn
"label_one_hot": True, # one hot label or not
"multi_bfs_path": False, # whether sample several BFS paths for each molecule
"bfs_path_count": 30,
"path_random_order": False, # False: canonical order, True: random order
"sample_transition": False, # whether to use transition sampling
'edge_weight_dropout_keep_prob': 1,
'check_overlap_edge': False,
"truncate_distance": 10,
"output_name": '',
"check_point_path": 'check_points',
'if_save_check_point': True,
'save_params_file': False,
'use_cuda': True,
'decoder': 'VGNN',
'accumulation_steps': 1,
'num_rbf': 12,
'max_correlation_length': 5,
'lr_decay': 1,
'if_generate_pos': True,
'if_generate_exit': True,
'noise_free': False,
'prior_variance': 1,
'if_update_pos': True,
'reverse_augmentation': False,
})
return params
# Data preprocessing and chunking into minibatches:
def process_raw_graphs(self, raw_data, is_training_data, file_name, bucket_sizes=None):
if bucket_sizes is None:
bucket_sizes = dataset_info(self.params["dataset"])["bucket_sizes"]
# incremental_results, raw_data = self.calculate_incremental_results(raw_data, bucket_sizes, file_name,
# is_training_data)
incremental_results, raw_data = self.calculate_incremental_results(raw_data, bucket_sizes, file_name,
is_training_data)
bucketed = defaultdict(list)
x_dim = len(raw_data[0]["node_features_out"][0])
for d, incremental_result_1 in zip(raw_data, incremental_results[1]):
# choose a bucket
chosen_bucket_idx = np.argmax(bucket_sizes > max(max([v for e in d['graph_in'] for v in [e[0], e[2]]]),
max([v for e in d['graph_out'] for v in [e[0], e[2]]])))
chosen_bucket_size = bucket_sizes[chosen_bucket_idx]
# total number of nodes in this data point out
n_active_nodes_in = len(d["node_features_in"])
n_active_nodes_out = len(d["node_features_out"])
bucketed[chosen_bucket_idx].append({
#'adj_mat_in': graph_to_adj_mat(d['graph_in'], chosen_bucket_size, self.num_edge_types,
# self.params['tie_fwd_bkwd']),
#'adj_mat_out': graph_to_adj_mat(d['graph_out'], chosen_bucket_size, self.num_edge_types,
# self.params['tie_fwd_bkwd']),
'adj_mat_in': deepcopy(d['graph_in']),
'adj_mat_out': deepcopy(d['graph_out']),
'v_to_keep': node_keep_to_dense(d['v_to_keep'], chosen_bucket_size),
'exit_points': d['exit_points'],
'abs_dist': d['abs_dist'],
'it_num': 0,
'incre_adj_mat_out': incremental_result_1[0],
'distance_to_others_out': incremental_result_1[1],
'overlapped_edge_features_out': incremental_result_1[8],
'node_sequence_out': incremental_result_1[2],
'edge_type_masks_out': incremental_result_1[3],
'edge_type_labels_out': incremental_result_1[4],
'edge_masks_out': incremental_result_1[6],
'edge_labels_out': incremental_result_1[7],
'local_stop_out': incremental_result_1[5],
'number_iteration_out': len(incremental_result_1[5]),
'init_in': d["node_features_in"] + [[0 for _ in range(x_dim)] for __ in
range(chosen_bucket_size - n_active_nodes_in)],
'init_out': d["node_features_out"] + [[0 for _ in range(x_dim)] for __ in
range(chosen_bucket_size - n_active_nodes_out)],
'mask_in': [1. for _ in range(n_active_nodes_in)] + [0. for _ in
range(chosen_bucket_size - n_active_nodes_in)],
'mask_out': [1. for _ in range(n_active_nodes_out)] + [0. for _ in
range(chosen_bucket_size - n_active_nodes_out)],
'smiles_in': d['smiles_in'],
'smiles_out': d['smiles_out'],
'positions_out': positions_padding(d['positions_out'], chosen_bucket_size).astype("float16"),
'positions_in': positions_padding(d['positions_in'], chosen_bucket_size).astype("float16")
})
if is_training_data:
for (bucket_idx, bucket) in bucketed.items():
np.random.shuffle(bucket)
bucket_at_step = [[bucket_idx for _ in range(len(bucket_data) // self.params['batch_size'])]
for bucket_idx, bucket_data in bucketed.items()]
bucket_at_step = [x for y in bucket_at_step for x in y]
return bucketed, bucket_sizes, bucket_at_step
def calculate_incremental_results(self, raw_data, bucket_sizes, file_name, is_training_data):
incremental_results = [[], []]
# Copy the raw_data if more than 1 BFS path is added
# new_raw_data = []
for idx, d in enumerate(raw_data):
out_direc = "out"
res_idx = 1
# Use canonical order or random order here. canonical order starts from index 0. random order starts from random nodes
if not self.params["path_random_order"]:
# Use several different starting index if using multi BFS path
if self.params["multi_bfs_path"]:
list_of_starting_idx = list(range(self.params["bfs_path_count"]))
else:
list_of_starting_idx = [0] # the index 0
else:
# Get the node length for this output molecule
node_length = len(d["node_features_" + out_direc])
if self.params["multi_bfs_path"]:
list_of_starting_idx = np.random.choice(node_length, self.params["bfs_path_count"],
replace=True) # randomly choose several
else:
list_of_starting_idx = [random.choice(list(range(node_length)))] # randomly choose one
for list_idx, starting_idx in enumerate(list_of_starting_idx):
# Choose a bucket
chosen_bucket_idx = np.argmax(bucket_sizes > max(max([v for e in d['graph_out']
for v in [e[0], e[2]]]),
max([v for e in d['graph_in']
for v in [e[0], e[2]]])))
chosen_bucket_size = bucket_sizes[chosen_bucket_idx]
nodes_no_master = d['node_features_' + out_direc]
edges_no_master = d['graph_' + out_direc]
incremental_adj_mat, distance_to_others, node_sequence, edge_type_masks, edge_type_labels, local_stop, edge_masks, edge_labels, overlapped_edge_features = \
construct_incremental_graph_preselected(self.params['dataset'], edges_no_master, chosen_bucket_size,
len(nodes_no_master), d['v_to_keep'], d['exit_points'],
nodes_no_master, self.params, is_training_data,
initial_idx=starting_idx)
if self.params["sample_transition"] and list_idx > 0:
incremental_results[res_idx][-1] = [x + y for x, y in zip(incremental_results[res_idx][-1],
[incremental_adj_mat, distance_to_others,
node_sequence, edge_type_masks,
edge_type_labels, local_stop, edge_masks,
edge_labels, overlapped_edge_features])]
else:
incremental_results[res_idx].append(
[incremental_adj_mat, distance_to_others, node_sequence, edge_type_masks,
edge_type_labels, local_stop, edge_masks, edge_labels, overlapped_edge_features])
if self.params['reverse_augmentation']:
incremental_adj_mat, distance_to_others, node_sequence, edge_type_masks, edge_type_labels, local_stop, edge_masks, edge_labels, overlapped_edge_features = \
construct_incremental_graph_preselected(self.params['dataset'], edges_no_master,
chosen_bucket_size,
len(nodes_no_master), d['v_to_keep'],
d['exit_points'],
nodes_no_master, self.params, is_training_data,
initial_idx=starting_idx, reverse=True)
incremental_results[res_idx].append(
[incremental_adj_mat, distance_to_others, node_sequence, edge_type_masks,
edge_type_labels, local_stop, edge_masks, edge_labels, overlapped_edge_features])
# Copy the raw_data here
# new_raw_data.append(d)
# Progress
if idx % 100 == 0:
print('\r'+'finish calculating %d incremental matrices' % idx, end='')
print('\n')
if self.params['reverse_augmentation']:
raw_data_aug = []
for data in raw_data:
data_reverse = data.copy()
data_reverse['exit_points'] = sorted(data_reverse['exit_points'], reverse=True)
raw_data_aug.extend((data, data_reverse))
else:
raw_data_aug = raw_data
return incremental_results, raw_data_aug # , new_raw_data
def make_minibatch_iterator(self, data, is_training):
(bucketed, bucket_sizes, bucket_at_step) = data
batch_dataset = []
if is_training:
np.random.shuffle(bucket_at_step)
for _, bucketed_data in bucketed.items():
np.random.shuffle(bucketed_data)
bucket_counters = defaultdict(int)
for step in range(len(bucket_at_step)):
bucket = bucket_at_step[step]
start_idx = bucket_counters[bucket] * self.params['batch_size']
end_idx = (bucket_counters[bucket] + 1) * self.params['batch_size']
elements = bucketed[bucket][start_idx:end_idx]
batch_data = self.make_batch(elements, bucket_sizes[bucket])
batch_dataset.append(batch_data)
bucket_counters[bucket] += 1
return batch_dataset
def make_batch(self, elements, maximum_vertice_num):
# get maximum number of iterations in this batch. used to control while_loop
max_iteration_num = -1
for d in elements:
max_iteration_num = max(d['number_iteration_out'], max_iteration_num)
batch_data = {'adj_mat_in': [], 'adj_mat_out': [], 'v_to_keep': [], 'exit_points': [], 'abs_dist': [],
'it_num': [], 'init_in': [], 'init_out': [],
'edge_type_masks_out': [], 'edge_type_labels_out': [], 'edge_masks_out': [],
'edge_labels_out': [],
'node_mask_in': [], 'node_mask_out': [], 'task_masks': [], 'node_sequence_out': [],
'iteration_mask_out': [], 'local_stop_out': [], 'incre_adj_mat_out': [],
'distance_to_others_out': [], 'max_iteration_num': max_iteration_num,
'overlapped_edge_features_out': [], 'positions_out': [], 'positions_in': [], 'smiles_in': [], 'smiles_out': []}
for d in elements:
batch_data['adj_mat_in'].append(d['adj_mat_in'])
batch_data['adj_mat_out'].append(d['adj_mat_out'])
# batch_data['adj_mat_in'].append(graph_to_adj_mat(d['adj_mat_in'], len(d['init_in']) , self.num_edge_types,
# self.params['tie_fwd_bkwd']))
# batch_data['adj_mat_out'].append(graph_to_adj_mat(d['adj_mat_out'], len(d['init_in']), self.num_edge_types,
# self.params['tie_fwd_bkwd']))
batch_data['v_to_keep'].append(node_keep_to_dense(d['v_to_keep'], maximum_vertice_num))
batch_data['exit_points'].append(d['exit_points'])
batch_data['abs_dist'].append(d['abs_dist'])
batch_data['it_num'] = [0]
batch_data['init_in'].append(d['init_in'])
batch_data['init_out'].append(d['init_out'])
batch_data['node_mask_in'].append(d['mask_in'])
batch_data['node_mask_out'].append(d['mask_out'])
batch_data['positions_in'].append(d['positions_in'])
batch_data['positions_out'].append(d['positions_out'])
batch_data['smiles_in'].append(d['smiles_in'])
batch_data['smiles_out'].append(d['smiles_out'])
for direc in ['_out']:
# sparse to dense for saving memory
# incre_adj_mat = incre_adj_mat_to_dense(d['incre_adj_mat' + direc], self.num_edge_types,
# maximum_vertice_num)
incre_adj_mat = adj_list_padding(d['incre_adj_mat'+direc], max_iteration_num, d['number_iteration'+direc])
# incre_adj_mat = d['incre_adj_mat'+direc]
distance_to_others = distance_to_others_dense(d['distance_to_others' + direc], maximum_vertice_num)
overlapped_edge_features = overlapped_edge_features_to_dense(d['overlapped_edge_features' + direc],
maximum_vertice_num)
node_sequence = node_sequence_to_dense(d['node_sequence' + direc], maximum_vertice_num)
edge_type_masks = edge_type_masks_to_dense(d['edge_type_masks' + direc], maximum_vertice_num,
self.num_edge_types)
edge_type_labels = edge_type_labels_to_dense(d['edge_type_labels' + direc], maximum_vertice_num,
self.num_edge_types)
edge_masks = edge_masks_to_dense(d['edge_masks' + direc], maximum_vertice_num)
edge_labels = edge_labels_to_dense(d['edge_labels' + direc], maximum_vertice_num)
# batch_data['incre_adj_mat' + direc].append(incre_adj_mat +
# [np.zeros((self.num_edge_types, maximum_vertice_num,
# maximum_vertice_num))
# for _ in
# range(max_iteration_num - d['number_iteration' + direc])])
batch_data['incre_adj_mat' + direc].append(incre_adj_mat)
batch_data['distance_to_others' + direc].append(distance_to_others +
[np.zeros((maximum_vertice_num))
for _ in range(
max_iteration_num - d['number_iteration' + direc])])
batch_data['overlapped_edge_features' + direc].append(overlapped_edge_features +
[np.zeros((maximum_vertice_num))
for _ in range(max_iteration_num - d[
'number_iteration' + direc])])
batch_data['node_sequence' + direc].append(node_sequence +
[np.zeros((maximum_vertice_num))
for _ in
range(max_iteration_num - d['number_iteration' + direc])])
batch_data['edge_type_masks' + direc].append(edge_type_masks +
[np.zeros((self.num_edge_types, maximum_vertice_num))
for _ in
range(max_iteration_num - d['number_iteration' + direc])])
batch_data['edge_masks' + direc].append(edge_masks +
[np.zeros((maximum_vertice_num))
for _ in
range(max_iteration_num - d['number_iteration' + direc])])
batch_data['edge_type_labels' + direc].append(edge_type_labels +
[np.zeros((self.num_edge_types, maximum_vertice_num))
for _ in range(
max_iteration_num - d['number_iteration' + direc])])
batch_data['edge_labels' + direc].append(edge_labels +
[np.zeros((maximum_vertice_num))
for _ in
range(max_iteration_num - d['number_iteration' + direc])])
batch_data['iteration_mask' + direc].append([1 for _ in range(d['number_iteration' + direc])] +
[0 for _ in
range(max_iteration_num - d['number_iteration' + direc])])
batch_data['local_stop' + direc].append([int(s) for s in d['local_stop' + direc]] +
[0 for _ in
range(max_iteration_num - d['number_iteration' + direc])])
return batch_data
def load_current_batch_as_tensor(self, batch_data):
num_nodes = len(batch_data['init_in'][0])
num_graphs = len(batch_data['init_in'])
# initial_representations_in = batch_data['init_in']
initial_representations_in = torch.tensor(self.pad_annotations(batch_data['init_in']))
# initial_representations_out = batch_data['init_out']
initial_representations_out = torch.tensor(self.pad_annotations(batch_data['init_out']))
self.data['initial_node_representation_in'] = initial_representations_in
self.data['initial_node_representation_out'] = initial_representations_out
self.data['node_symbols_out'] = torch.tensor(batch_data['init_out'], dtype=torch.float32)
self.data['node_symbols_in'] = torch.tensor(batch_data['init_in'], dtype=torch.float32)
self.data['node_mask_in'] = torch.tensor(batch_data['node_mask_in'])
self.data['node_mask_out'] = torch.tensor(batch_data['node_mask_out'])
self.ops['graph_state_mask_in'] = torch.unsqueeze(self.data['node_mask_in'], 2)
self.ops['graph_state_mask_out'] = torch.unsqueeze(self.data['node_mask_out'], 2)
self.data['num_graphs'] = torch.tensor(num_graphs)
self.data['adjacency_matrix_in'] = torch.tensor(np.array([graph_to_adj_mat(batch_data['adj_mat_in'][i], num_nodes , self.num_edge_types,
self.params['tie_fwd_bkwd']) for i in range(num_graphs)]), dtype=torch.float32)
self.data['adjacency_matrix_out'] = torch.tensor(
np.array([graph_to_adj_mat(batch_data['adj_mat_out'][i], num_nodes, self.num_edge_types,
self.params['tie_fwd_bkwd']) for i in range(num_graphs)]), dtype=torch.float32)
# self.data['adjacency_matrix_in'] = torch.tensor(np.array(batch_data['adj_mat_in']), dtype=torch.float32)
# self.data['adjacency_matrix_out'] = torch.tensor(np.array(batch_data['adj_mat_out']), dtype=torch.float32)
self.data['num_vertices'] = torch.tensor(self.data['adjacency_matrix_in'].size(2))
self.data['z_prior_h'] = (0 if self.params['noise_free'] else 1) * torch.normal(0, 1, [self.params['batch_size'], self.data['num_vertices'], self.params['encoding_size']])
self.data['z_prior_h_in'] = (0 if self.params['noise_free'] else 1) * torch.normal(0, 1, [self.params['batch_size'], self.data['num_vertices'],
self.params['encoding_size']])
self.data['z_prior_v_in'] = (0 if self.params['noise_free'] else 1) * torch.normal(0, 1, [self.params['batch_size'],
self.data['num_vertices'], self.params['encoding_vec_size'], 3])
self.data['z_prior_v'] = (0 if self.params['noise_free'] else 1) * torch.normal(0, 1, [self.params['batch_size'],
self.data['num_vertices'], self.params['encoding_vec_size'], 3])
# self.data['z_prior_h'] = torch.normal(0, 1,[self.params['batch_size'], self.data['num_vertices'],
# self.params['encoding_size']])
# self.data['z_prior_h_in'] = torch.normal(0, 1, [self.params['batch_size'], self.data['num_vertices'], self.params['encoding_size']])
# self.data['z_prior_v_in'] = torch.normal(0, 1, [self.params['batch_size'], self.data['num_vertices'], self.params['encoding_size'], 3])
# self.data['pos_noise'] = torch.normal(0, 1, [self.params['batch_size'], self.data['num_vertices'], 3])
self.data['is_generative'] = False
self.data['iteration_mask_out'] = torch.tensor(batch_data['iteration_mask_out'])
self.data['max_iteration_num'] = torch.tensor(batch_data['max_iteration_num'])
self.data['latent_node_symbols_in'] = initial_representations_in
self.data['latent_node_symbols_out'] = initial_representations_out
incre_adj_mat_out = [incre_adj_list_to_adj_mat(self.data['adjacency_matrix_in'][i].numpy(), batch_data['incre_adj_mat_out'][i],
self.num_edge_types) for i in range(num_graphs)]
# self.data['incre_adj_mat_out'] = torch.tensor(np.array(batch_data['incre_adj_mat_out']), dtype=torch.float32)
self.data['incre_adj_mat_out'] = torch.tensor(np.array(incre_adj_mat_out), dtype=torch.float32)
self.data['distance_to_others_out'] = torch.tensor(np.array(batch_data['distance_to_others_out']), dtype=torch.int32)
self.data['overlapped_edge_features_out'] = torch.tensor(np.array(batch_data['overlapped_edge_features_out']), dtype=torch.int32)
self.data['node_sequence_out'] = torch.tensor(np.array(batch_data['node_sequence_out']), dtype=torch.float32)
self.data['edge_type_masks_out'] = torch.tensor(np.array(batch_data['edge_type_masks_out']), dtype=torch.float32)
self.data['edge_type_labels_out'] = torch.tensor(np.array(batch_data['edge_type_labels_out']), dtype=torch.float32)
self.data['edge_masks_out'] = torch.tensor(np.array(batch_data['edge_masks_out']), dtype=torch.float32)
self.data['edge_labels_out'] = torch.tensor(np.array(batch_data['edge_labels_out']), dtype=torch.float32)
self.data['local_stop_out'] = torch.tensor(batch_data['local_stop_out'], dtype=torch.float32)
self.data['abs_dist'] = torch.tensor(str2float(batch_data['abs_dist']), dtype=torch.float32)
self.data['it_num'] = torch.tensor(batch_data['it_num'], dtype=torch.int32)
self.data['positions_out'] = torch.tensor(np.array(batch_data['positions_out']), dtype=torch.float32)
self.data['positions_in'] = torch.tensor(np.array(batch_data['positions_in']), dtype=torch.float32)
self.data['exit_points'] = torch.tensor(np.array(batch_data['exit_points']), dtype=torch.float32)
# transfer to designated device
for key in self.data.keys():
if torch.is_tensor(self.data[key]):
self.data[key] = self.data[key].to(self.device)
self.ops['graph_state_mask_in'] = self.ops['graph_state_mask_in'].to(self.device)
self.ops['graph_state_mask_out'] = self.ops['graph_state_mask_out'].to(self.device)
def make_model(self):
node_dim = self.params['hidden_size']
out_dim = self.params['encoding_size']
out_vec_dim = self.params['encoding_vec_size']
idx_dim = self.params['idx_size']
h_dim = node_dim + idx_dim
expanded_h_dim = h_dim + node_dim + 1 # plus a node type embedding and a focus bit
v_dim = self.params['vector_size']
# Dict for all pure weights
self.weights = nn.ParameterDict()
# Dict for all submodules/units
self.units = nn.ModuleDict()
# weights for embedding
self.units['node_embedding'] = nn.Embedding(self.params['num_symbols'], node_dim)
self.units['distance_embedding_in'] = nn.Embedding(self.params['maximum_distance'], expanded_h_dim)
self.units['overlapped_edge_weight_in'] = nn.Embedding(2, expanded_h_dim)
self.units['idx_embedding'] = nn.Embedding(self.params['max_num_nodes'], idx_dim)
# weights for GNN of encoder and decoder
for scope in ['_encoder', '_decoder']:
if scope == '_encoder':
new_h_dim = h_dim
elif scope == '_decoder':
new_h_dim = expanded_h_dim
for iter_idx in range(self.params['num_timesteps']):
weights_suffix = scope + str(iter_idx)
# input size
input_size = new_h_dim * (1 + length(self.params['residual_connections'].get(iter_idx)))
input_vec_size = v_dim * (1 + length(self.params['residual_connections'].get(iter_idx)))
# pairwise size for message computation
pair_h_dim = new_h_dim + 1
# weights for edge convolution (message computation)
self.weights['wave_num'+weights_suffix] = nn.Parameter(torch.rand(1))
self.weights['weights_rbf_0'+weights_suffix] = nn.Parameter(glorot_init([self.params['num_rbf'], new_h_dim]))
self.weights['weights_rbf_1' + weights_suffix] = nn.Parameter(
glorot_init([self.params['num_rbf'], v_dim]))
self.weights['weights_rbf_2' + weights_suffix] = nn.Parameter(
glorot_init([self.params['num_rbf'], v_dim]))
self.weights['biases_rbf_0'+weights_suffix] = nn.Parameter(torch.zeros([1, new_h_dim], dtype=torch.float32))
self.weights['biases_rbf_1'+weights_suffix] = nn.Parameter(torch.zeros([1, v_dim], dtype=torch.float32))
self.weights['biases_rbf_2'+weights_suffix] = nn.Parameter(torch.zeros([1, v_dim], dtype=torch.float32))
self.weights['combine_h_v_weight'+weights_suffix] = nn.Parameter(glorot_init([v_dim, v_dim]))
for edge_type in range(self.num_edge_types):
#self.weights['edge_s_hidden_weights'+weights_suffix] = nn.Parameter(glorot_init([
# self.num_edge_types, new_h_dim+v_dim, new_h_dim+v_dim]))
self.weights['edge_s_biases'+weights_suffix] = nn.Parameter(torch.zeros([self.num_edge_types, 1,
new_h_dim], dtype=torch.float32))
self.weights['edge_s_output_weights'+weights_suffix] = nn.Parameter(glorot_init([self.num_edge_types,
new_h_dim+v_dim, new_h_dim]))
#self.weights['edge_v0_hidden_weights' + weights_suffix] = nn.Parameter(glorot_init([
# self.num_edge_types, new_h_dim, v_dim]))
self.weights['edge_v0_biases' + weights_suffix] = nn.Parameter(torch.zeros([self.num_edge_types, 1,
v_dim],
dtype=torch.float32))
self.weights['edge_v0_output_weights' + weights_suffix] = nn.Parameter(
glorot_init([self.num_edge_types,
new_h_dim, v_dim]))
#self.weights['edge_v1_hidden_weights' + weights_suffix] = nn.Parameter(glorot_init([
# self.num_edge_types, new_h_dim, v_dim]))
self.weights['edge_v1_biases' + weights_suffix] = nn.Parameter(torch.zeros([self.num_edge_types, 1,
v_dim],
dtype=torch.float32))
self.weights['edge_v1_output_weights' + weights_suffix] = nn.Parameter(
glorot_init([self.num_edge_types,
new_h_dim, v_dim]))
#self.weights['edge_v_hidden_weights'+weights_suffix] = nn.Parameter(glorot_init([self.num_edge_types,
# v_dim, v_dim]))
self.weights['edge_v_nonlinear_Q'+weights_suffix] = nn.Parameter(glorot_init([self.num_edge_types,
v_dim, v_dim]))
self.weights['edge_v_nonlinear_K'+weights_suffix] = nn.Parameter(glorot_init([self.num_edge_types,
v_dim, v_dim]))
#self.weights['edge_v_output_weights'+weights_suffix] = nn.Parameter(glorot_init([self.num_edge_types,
# v_dim, v_dim]))
# weights for aggregation
# self.weights['aggregate_v_hidden'+weights_suffix] = nn.Parameter(glorot_init([2 * v_dim, 2 * v_dim]))
self.weights['aggregate_Q_weights' + weights_suffix] = nn.Parameter(glorot_init([input_vec_size + v_dim, input_vec_size + v_dim]))
self.weights['aggregate_K_weights' + weights_suffix] = nn.Parameter(glorot_init([input_vec_size + v_dim, input_vec_size + v_dim]))
self.weights['aggregate_v_output'+weights_suffix] = nn.Parameter(glorot_init([input_vec_size + v_dim, v_dim]))
# messages and node representation combination function
self.units['node_gru' + weights_suffix] = torch.nn.GRUCell(input_size, new_h_dim)
# self.units['node_vec_gru' + weights_suffix] = GRUCell_vec(v_dim, input_vec_size)
# weights for computing mean and log variance
self.weights['mean_h_weights_out'] = nn.Parameter(glorot_init([h_dim, out_dim]))
self.weights['mean_h_biases_out'] = nn.Parameter(torch.zeros([1, out_dim]))
self.weights['variance_h_weights_out'] = nn.Parameter(glorot_init([h_dim, out_dim]))
self.weights['variance_h_biases_out'] = nn.Parameter(torch.zeros([1, out_dim]))
self.weights['mean_h_weights'] = nn.Parameter(glorot_init([h_dim, h_dim]))
self.weights['mean_h_biases'] = nn.Parameter(torch.zeros([1, h_dim]))
# self.weights['variance_h_weights'] = nn.Parameter(glorot_init([h_dim, h_dim]))
# self.weights['variance_h_biases'] = nn.Parameter(torch.zeros([1, h_dim]))
self.weights['mean_h_hidden_out_all'] = nn.Parameter(glorot_init([h_dim, h_dim]))
self.weights['mean_h_weights_out_all'] = nn.Parameter(glorot_init([h_dim, out_dim]))
self.weights['mean_h_biases_out_all'] = nn.Parameter(torch.zeros([1, h_dim]))
self.weights['variance_h_weights_out_all'] = nn.Parameter(glorot_init([h_dim, out_dim]))
self.weights['variance_h_hidden_out_all'] = nn.Parameter(glorot_init([h_dim, h_dim]))
self.weights['variance_h_biases_out_all'] = nn.Parameter(torch.zeros([1, h_dim]))
self.weights['mean_v_weights_out'] = nn.Parameter(glorot_init([v_dim, out_vec_dim]))
self.weights['mean_v_weights_out_all'] = nn.Parameter(glorot_init([v_dim, out_vec_dim]))
#self.weights['mean_v_biases_out'] = nn.Parameter(glorot_init([1, v_dim]))
self.weights['variance_v_weights_out'] = nn.Parameter(glorot_init([h_dim, out_vec_dim]))
self.weights['variance_v_biases_out'] = nn.Parameter(torch.zeros([1, out_vec_dim]))
#self.weights['mean_v_biases_out'] = nn.Parameter(glorot_init([1, v_dim]))
self.weights['variance_v_weights_out_all'] = nn.Parameter(glorot_init([h_dim, out_vec_dim]))
self.weights['variance_v_biases_out_all'] = nn.Parameter(torch.zeros([1, out_vec_dim]))
self.weights['mean_v_weights_in'] = nn.Parameter(glorot_init([v_dim, v_dim]))
##self.weights['mean_v_biases_in'] = nn.Parameter(glorot_init([1, v_dim]))
# weights for combining (sampling) means and log variances
self.weights['mean_h_combine_weights_in'] = nn.Parameter(glorot_init([out_dim, h_dim]))
self.weights['mean_h_all_combine_weights_in'] = nn.Parameter(glorot_init([out_dim, h_dim]))
self.weights['mean_v_all_combine_weights_in'] = nn.Parameter(glorot_init([out_vec_dim, v_dim]))
self.weights['mean_v_combine_weights_in'] = nn.Parameter(glorot_init([out_vec_dim, v_dim]))
self.weights['atten_h_weights_c_in'] = nn.Parameter(glorot_init([h_dim, h_dim]))
self.weights['atten_h_weights_y_in'] = nn.Parameter(glorot_init([h_dim, h_dim]))
self.weights['atten_v_weights_querys'] = nn.Parameter(glorot_init([v_dim, v_dim]))
self.weights['atten_v_weights_keys'] = nn.Parameter(glorot_init([v_dim, v_dim]))
# weights for exit points
if self.params['if_generate_exit']:
d_dim = 0
self.weights['exit_points_vec_weights'] = nn.Parameter(glorot_init([v_dim, v_dim]))
self.weights['exit_points_hidden_weights'] = nn.Parameter(glorot_init([v_dim + h_dim + d_dim, v_dim + h_dim + d_dim]))
self.weights['exit_points_biases'] = nn.Parameter(torch.zeros([1, v_dim + h_dim + d_dim], dtype=torch.float32))
self.weights['exit_points_output_weights'] = nn.Parameter(glorot_init([v_dim + h_dim + d_dim, 1]))
self.weights['exit_points_conditional_hidden_weights'] = nn.Parameter(
glorot_init([2 * (v_dim + h_dim), 2 * (v_dim + h_dim)]))
self.weights['exit_points_conditional_biases'] = nn.Parameter(
torch.zeros([1, 2 * (v_dim + h_dim)], dtype=torch.float32))
self.weights['exit_points_conditional_output_weights'] = nn.Parameter(glorot_init([2 * (v_dim + h_dim), 1]))
# record the total number of features
feature_dimension = 6 * expanded_h_dim + 2 * v_dim
self.params["feature_dimension"] = feature_dimension
# weights for edge logits
self.weights['combine_edge_v_weight'] = nn.Parameter(glorot_init([v_dim, v_dim]))
self.weights['edge_iteration_in'] = nn.Parameter(glorot_init([feature_dimension+1, feature_dimension+1]))
self.weights['edge_iteration_biases_in'] = nn.Parameter(torch.zeros([1, feature_dimension+1], dtype=torch.float32))
self.weights['edge_iteration_output_in'] = nn.Parameter(glorot_init([feature_dimension+1, 1]))
# weights for stop nodes
self.weights['stop_node_in'] = nn.Parameter(glorot_init([1, expanded_h_dim]))
self.weights['stop_node_vec_in'] = nn.Parameter(glorot_init([1, v_dim, 3]))
# atten weights for positions prediction
if self.params['if_generate_pos']:
cat_dim = 2 * expanded_h_dim + v_dim
self.weights['A1_matrix'] = nn.Parameter(glorot_init([v_dim, v_dim]))
self.weights['A2_matrix'] = nn.Parameter(glorot_init([v_dim, v_dim]))
self.weights['scores1_hidden'] = nn.Parameter(glorot_init([cat_dim, cat_dim]))
self.weights['scores1_biases'] = nn.Parameter(torch.zeros([1, cat_dim], dtype=torch.float32))
self.weights['scores1_output'] = nn.Parameter(glorot_init([cat_dim, 1]))
self.weights['scores2_hidden'] = nn.Parameter(glorot_init([cat_dim, cat_dim]))
self.weights['scores2_biases'] = nn.Parameter(torch.zeros([1, cat_dim], dtype=torch.float32))
self.weights['scores2_output'] = nn.Parameter(glorot_init([cat_dim, 1]))
# self.weights['self_interaction_hidden'] = nn.Parameter(glorot_init([2 * v_dim, 2 * v_dim]))
self.weights['self_interaction_Q'] = nn.Parameter(glorot_init([2 * v_dim, 2 * v_dim]))
self.weights['self_interaction_K'] = nn.Parameter(glorot_init([2 * v_dim, 2 * v_dim]))
self.weights['self_interaction_output'] = nn.Parameter(glorot_init([2 * v_dim, 2 * v_dim]))
# self.weights['cross_interaction_hidden'] = nn.Parameter(glorot_init([2 * v_dim, 2 * v_dim]))
self.weights['cross_interaction_Q'] = nn.Parameter(glorot_init([2 * v_dim, 2 * v_dim]))
self.weights['cross_interaction_K'] = nn.Parameter(glorot_init([2 * v_dim, 2 * v_dim]))
self.weights['cross_interaction_output'] = nn.Parameter(glorot_init([2 * v_dim, 1]))
# weights for updating positions
if self.params['if_update_pos']:
self.weights['A1_matrix_update'] = nn.Parameter(glorot_init([v_dim, v_dim]))
self.weights['A2_matrix_update'] = nn.Parameter(glorot_init([v_dim, v_dim]))
self.weights['scores1_hidden_update'] = nn.Parameter(glorot_init([cat_dim, cat_dim]))
self.weights['scores1_biases_update'] = nn.Parameter(torch.zeros([1, cat_dim], dtype=torch.float32))
self.weights['scores1_output_update'] = nn.Parameter(glorot_init([cat_dim, 1]))
self.weights['scores2_hidden_update'] = nn.Parameter(glorot_init([cat_dim, cat_dim]))
self.weights['scores2_biases_update'] = nn.Parameter(torch.zeros([1, cat_dim], dtype=torch.float32))
self.weights['scores2_output_update'] = nn.Parameter(glorot_init([cat_dim, 1]))
# self.weights['self_interaction_hidden'] = nn.Parameter(glorot_init([2 * v_dim, 2 * v_dim]))
self.weights['self_interaction_Q_update'] = nn.Parameter(glorot_init([2 * v_dim, 2 * v_dim]))
self.weights['self_interaction_K_update'] = nn.Parameter(glorot_init([2 * v_dim, 2 * v_dim]))
self.weights['self_interaction_output_update'] = nn.Parameter(glorot_init([2 * v_dim, 2 * v_dim]))
# self.weights['cross_interaction_hidden'] = nn.Parameter(glorot_init([2 * v_dim, 2 * v_dim]))
self.weights['cross_interaction_Q_update'] = nn.Parameter(glorot_init([2 * v_dim, 2 * v_dim]))
self.weights['cross_interaction_K_update'] = nn.Parameter(glorot_init([2 * v_dim, 2 * v_dim]))
self.weights['cross_interaction_output_update'] = nn.Parameter(glorot_init([2 * v_dim, 1]))
#self.weights['key_matrix'] = nn.Parameter(glorot_init([expanded_h_dim, expanded_h_dim]))
#self.weights['query_matrix'] = nn.Parameter(glorot_init([expanded_h_dim, expanded_h_dim]))
#self.weights['atten_hidden_weights'] = nn.Parameter(glorot_init([2*expanded_h_dim, 2*expanded_h_dim]))
#self.weights['atten_hidden_biases'] = nn.Parameter(torch.zeros([1, 2*expanded_h_dim], dtype=torch.float32))
#self.weights['atten_output_weights'] = nn.Parameter(glorot_init([2*expanded_h_dim, 1]))
#self.weights['atten_pred_x'] = nn.Parameter(glorot_init([expanded_h_dim, expanded_h_dim]))
# weights for edge type logits
for i in range(self.num_edge_types):
self.weights['edge_type_%d_in' % i] = nn.Parameter(glorot_init([feature_dimension+1,feature_dimension+1]))
self.weights['edge_type_biases_%d_in' % i] = nn.Parameter(torch.zeros([1, feature_dimension+1]))
self.weights['edge_type_output_%d_in' % i] = nn.Parameter(glorot_init([feature_dimension+1, 1]))
# weights for node symbol logits
self.weights['node_symbol_weights_in'] = nn.Parameter(glorot_init([h_dim+1, h_dim+1]))
self.weights['node_symbol_biases_in'] = nn.Parameter(torch.zeros([1, h_dim+1]))
self.weights['node_symbol_hidden_in'] = nn.Parameter(glorot_init([h_dim+1, self.params['num_symbols']]))
self.weights['node_combine_weights_in'] = nn.Parameter(glorot_init([h_dim+1, h_dim+1]))
self.weights['node_atten_weights_c_in'] = nn.Parameter(glorot_init([h_dim+1, h_dim+1]))
self.weights['node_atten_weights_y_in'] = nn.Parameter(glorot_init([h_dim+1, h_dim+1]))
# weights for prior distribution
# self.weights['prior_logvariance'] = nn.Parameter(torch.zeros([1, 3]))
# optimizer
self.optimizer = torch.optim.Adam(self.parameters(), lr=self.params['learning_rate'])
self.lr_scheduler = torch.optim.lr_scheduler.ExponentialLR(self.optimizer, gamma=self.params['lr_decay'])
def get_node_embedding_state(self, one_hot_state, source):
node_symbols = torch.argmax(one_hot_state, dim=2)
if source:
return self.units['node_embedding'](node_symbols) * self.ops['graph_state_mask_in']
else:
return self.units['node_embedding'](node_symbols) * self.ops['graph_state_mask_out']
def get_idx_embedding(self, one_hot_idx, source):
node_idx = torch.argmax(one_hot_idx, dim=2)
if source:
return self.units['idx_embedding'](node_idx) * self.ops['graph_state_mask_in']
else:
return self.units['idx_embedding'](node_idx) * self.ops['graph_state_mask_out']
def compute_final_node_representations_EGNN(self, h, x0, adj, scope_name, fixed_coor=False):
x = x0.clone()
v = self.data['num_vertices']
if scope_name == '_encoder': # encoding: h_dim (repr)
h_dim = self.params['hidden_size'] + self.params['idx_size']
else: # decoding: h_dim (repr) + h_dim (embedding) + 1 (focus bit)
h_dim = self.params['hidden_size'] + self.params['hidden_size'] + 1 + self.params['idx_size']
# record all hidden states at each iteration
h = torch.reshape(h, [-1, h_dim])
all_hidden_states = [h]
for iter_idx in range(self.params['num_timesteps']):
weights_suffix = scope_name + str(iter_idx)
# compute the (h_i, h_j) pair features. WARNING: this approach will consume a large amount of memory
_, h_sender = pairwise_construct(h.reshape([-1, v, h_dim]), v)
# H = torch.cat((h_receiver, h_sender),
# dim=3) # (batch_size, v, v, h_dim), H_{n, i, j} = (h_i, h_j) for n-th data
# compute distance matrix
x_self, x_others = pairwise_construct(x, v)
x_delta = torch.add(x_self, -x_others) # displacement vectors
dist = torch.linalg.norm(x_delta, dim=3)
dist = torch.unsqueeze(dist, dim=3)
# # final features (h_j, ||x_i-x_j||)
H = torch.cat((h_sender, dist), dim=3)
# free useless variables
del h_sender, x_self, x_others
for edge_type in range(self.num_edge_types):
# the message passed from this vertex to others
m = fully_connected(H, self.weights['edge_hidden_weights' + weights_suffix][edge_type],
self.weights['edge_biases' + weights_suffix][edge_type],
self.weights['edge_output_weights' + weights_suffix][edge_type])
m = torch.nn.SiLU()(m)
# collect the messages from other vertices to each vertex
if edge_type == 0:
message = m
# acts = torch.einsum('bijk, bij->bik', m, adj[:, edge_type]) # contraction of index j
acts = torch.sum(torch.unsqueeze(adj[:, edge_type], dim=3) * m, dim=2)
else:
message += m
# acts += torch.einsum('bijk, bij->bik', m, adj[:, edge_type])
acts += torch.sum(torch.unsqueeze(adj[:, edge_type], dim=3) * m, dim=2)
# all messages collected for each node
del m
acts = torch.reshape(acts, [-1, h_dim])
# add residual connection
layer_residual_connections = self.params['residual_connections'].get(iter_idx)
if layer_residual_connections is None:
layer_residual_states = []
else:
layer_residual_states = [all_hidden_states[residual_layer_idx]
for residual_layer_idx in layer_residual_connections]
# concat current hidden states with residual states
acts = torch.cat([acts] + layer_residual_states, dim=1)
# feed message inputs and hidden states to combine function
h = self.units['node_gru' + weights_suffix](acts, h)
# record the new hidden states
all_hidden_states.append(h)
del acts
# update coordinates
combine_weights = fully_connected(message, self.weights['coor_hidden_weights' + weights_suffix],
self.weights['coor_biases' + weights_suffix],
self.weights['coor_output_weights' + weights_suffix])
combine_weights = torch.tanh(combine_weights)
combine_weights = torch.reshape(combine_weights, [-1, v, v]) * \
torch.reshape(self.ops['graph_state_mask_out'], [-1, 1, v])
if not fixed_coor:
# x += self.weights['coor_coef' + weights_suffix] * torch.einsum('bijk, bij->bik', x_delta, combine_weights) # classic EGNN
x += torch.einsum('bijk, bij, beij->bik', x_delta / (dist + 1), combine_weights, adj) # normalized EGNN
last_h = torch.reshape(all_hidden_states[-1], [-1, v, h_dim])
return last_h, x
def compute_final_node_representations_VGNN(self, h, v, x, adj, scope_name):
# h: hidden scalars, x: 3d positions, v: hidden vectors
#x = v0.clone()
num_atoms = self.data['num_vertices']
v_dim = self.params['vector_size']
if scope_name == '_encoder': # encoding: h_dim (repr)
h_dim = self.params['hidden_size'] + self.params['idx_size']
else: # decoding: h_dim (repr) + h_dim (embedding) + 1 (focus bit)
h_dim = self.params['hidden_size'] + self.params['hidden_size'] + 1 + self.params['idx_size']
# record all hidden states at each iteration
# h = torch.reshape(h, [-1, h_dim])
all_hidden_states = [h]
all_hidden_vec = []
for iter_idx in range(self.params['num_timesteps']):
weights_suffix = scope_name + str(iter_idx)
# compute distance matrix
x_self, x_others = pairwise_construct(x, num_atoms)
x_delta = torch.add(x_self, -x_others) # displacement vectors
dist = torch.linalg.norm(x_delta, dim=3)
dist = torch.unsqueeze(dist, dim=3)
# dist += SMALL_NUMBER
# free useless variables
del x_self, x_others
# compute message
m_h, m_v = self.compute_message(h, v, x_delta, dist, adj, weights_suffix)
# compute update
# add residual connection
layer_residual_connections = self.params['residual_connections'].get(iter_idx)
if layer_residual_connections is None:
layer_residual_states = []
layer_residual_vec = []
else:
layer_residual_states = [all_hidden_states[residual_layer_idx]
for residual_layer_idx in layer_residual_connections]
layer_residual_vec = [all_hidden_vec[residual_layer_idx]
for residual_layer_idx in layer_residual_connections]
# concat current hidden states with residual states
m_h = torch.cat([m_h] + layer_residual_states, dim=2)
m_v = torch.cat([m_v] + layer_residual_vec, dim=2)
h, v = self.compute_update(h, v, m_h, m_v, weights_suffix)
all_hidden_states.append(h)
all_hidden_vec.append(v)
return h, v
def compute_message(self, h, v, x_delta, dist, adj, weights_suffix):
h_dim = h.size(-1)
# compute three rbf kernels
w_rbfs = []
v_norm = torch.norm(torch.einsum('bnci, cd->bndi', v, self.weights['combine_h_v_weight'+weights_suffix]), dim=3) + SMALL_NUMBER
rbf = torch.linspace(0, self.params['max_correlation_length'], self.params['num_rbf'],
device=self.device)
rbf = torch.square(torch.tile(dist, [1, 1, 1, self.params['num_rbf']]) - rbf) * self.weights[
'wave_num' + weights_suffix]
rbf = torch.exp(- rbf)
for i in range(3):
w_rbf = torch.einsum('nh, bijn->bijh', self.weights['weights_rbf_'+ str(i) +weights_suffix], rbf) + self.weights['biases_rbf_'+str(i)+weights_suffix]
w_rbfs.append(w_rbf)
m = 0
m_v = 0
for edge_type in range(self.num_edge_types):
#phi_h_s = fully_connected(h, self.weights['edge_s_hidden_weights' + weights_suffix][edge_type],
# self.weights['edge_s_biases' + weights_suffix][edge_type],
# self.weights['edge_s_output_weights' + weights_suffix][edge_type])
phi_h_s = scalar_neuron(torch.cat([h, v_norm], dim=2), self.weights['edge_s_output_weights'+weights_suffix][edge_type],
self.weights['edge_s_biases'+weights_suffix][edge_type])
#phi_h_s = fully_connected(torch.cat([h, v_norm], dim=2), self.weights['edge_s_hidden_weights' + weights_suffix][edge_type],
# self.weights['edge_s_biases' + weights_suffix][edge_type],
# self.weights['edge_s_output_weights' + weights_suffix][edge_type])
#phi_h_v0 = fully_connected(h, self.weights['edge_v0_hidden_weights' + weights_suffix][edge_type],
# self.weights['edge_v0_biases' + weights_suffix][edge_type],
# self.weights['edge_v0_output_weights' + weights_suffix][edge_type])
phi_h_v0 = scalar_neuron(h, self.weights['edge_v0_output_weights'+weights_suffix][edge_type],
self.weights['edge_v0_biases'+weights_suffix][edge_type])
phi_h_v1 = scalar_neuron(h, self.weights['edge_v1_output_weights' + weights_suffix][edge_type],
self.weights['edge_v1_biases' + weights_suffix][edge_type])
#phi_h_v1 = fully_connected(h, self.weights['edge_v1_hidden_weights' + weights_suffix][edge_type],
# self.weights['edge_v1_biases' + weights_suffix][edge_type],
# self.weights['edge_v1_output_weights' + weights_suffix][edge_type])
#phi_v_v = fully_connected_vec(v,
# self.weights['edge_v_nonlinear_Q'+weights_suffix][edge_type],
# self.weights['edge_v_nonlinear_K' + weights_suffix][edge_type],
# self.weights['edge_v_output_weights'+weights_suffix][edge_type])
#phi_v_v = vector_neuron_leaky(v, self.weights['edge_v_nonlinear_Q'+weights_suffix][edge_type],
# self.weights['edge_v_nonlinear_K' + weights_suffix][edge_type])
phi_v_v = vector_neuron(v, self.weights['edge_v_nonlinear_Q' + weights_suffix][edge_type],
self.weights['edge_v_nonlinear_K' + weights_suffix][edge_type])
# phi_v_norm = torch.unsqueeze(torch.norm(w_v, dim=3), dim=3) + SMALL_NUMBER
m += torch.einsum('bjh, bijh, bij->bijh', phi_h_s, w_rbfs[0], adj[:, edge_type])
m_v += torch.einsum('bjvk, bjv, bijv, bij->bijvk', phi_v_v, phi_h_v0, w_rbfs[1], adj[:, edge_type]) + \
torch.einsum('bijk, bjv, bijv, bij->bijvk', x_delta, phi_h_v1, w_rbfs[2], adj[:, edge_type])
# m += torch.einsum('bjh, bij->bijh', phi_h_s, adj[:, edge_type])
#m_v += torch.einsum('bjvk, bjv, bijv, bij->bijvk', phi_v_v, phi_h_v0, w_rbfs[1], adj[:, edge_type]) + torch.einsum('bijk, bjv, bijv, bij->bijvk', x_delta, phi_h_v1, w_rbfs[2], adj[:, edge_type])
#if edge_type == 0:
# m = torch.einsum('bjh, bijh, bij->bijh', phi_h_s, w_rbfs[0], adj[:, edge_type])
# m = torch.einsum('bjh, bij->bijh', phi_h_s, adj[:, edge_type])
# m_v = torch.einsum('bjvk, bjv, bijv, bij->bijvk', phi_v_v, phi_h_v0, w_rbfs[1], adj[:, edge_type]) + \
# torch.einsum('bijk, bjv, bijv, bij->bijvk', x_delta, phi_h_v1, w_rbfs[2], adj[:, edge_type])
#else:
# m += torch.einsum('bjh, bijh, bij->bijh', phi_h_s, w_rbfs[0], adj[:, edge_type])
# m += torch.einsum('bjh, bij->bijh', phi_h_s, adj[:, edge_type])
# m_v += torch.einsum('bjvk, bjv, bijv, bij->bijvk', phi_v_v, phi_h_v0, w_rbfs[1], adj[:, edge_type]) + \
# torch.einsum('bijk, bjv, bijv, bij->bijvk', x_delta, phi_h_v1, w_rbfs[2],
# adj[:, edge_type])
# aggregate messages
m = torch.sum(m, dim=2)
m_v = torch.sum(m_v, dim=2)
return m, m_v
def compute_update(self, h, v, m_h, m_v, weights_suffix):
h_shape = h.size()
h = h.reshape([-1, h.size(-1)])
m_h = m_h.reshape([-1, m_h.size(-1)])
h_new = self.units['node_gru'+weights_suffix](m_h, h)
# m_v = torch.zeros_like(m_v, device=self.device)
# v_new = 0.5 * v + 0.5 * vector_linear(torch.cat([m_v2, m_v], dim=-2), self.weights['aggregate_v_output'+weights_suffix])
v_new = fully_connected_vec(torch.cat([v, m_v], dim=-2),
self.weights['aggregate_Q_weights'+weights_suffix],
self.weights['aggregate_K_weights'+weights_suffix],
self.weights['aggregate_v_output'+weights_suffix])
# v_new = self.units['node_vec_gru' + weights_suffix](v, m_v)
#v_new = 0.8 * vector_linear(v, self.weights['self_aggregate_Q_weights' + weights_suffix]) + \
# 0.2 * vector_linear(m_v, self.weights['cross_aggregate_Q_weights' + weights_suffix])
# v_new = v
h_new = h_new.reshape(h_shape)
return h_new, v_new
def compute_update2(self, h, v, m_h, m_v, weights_suffix):
num_atoms = h.size(1)
h_dim = h.size(2)
v_dim = v.size(2)
h = h.reshape([-1, h_dim])
m_h = m_h.reshape([-1, h_dim])
v = v.reshape([-1, v_dim, 3])
m_v = m_v.reshape([-1, v_dim, 3])
V = torch.einsum('vu, nvj->nuj', self.weights['V_matrix'+weights_suffix], m_v)
U = torch.einsum('vu, nvj->nuj', self.weights['U_matrix'+weights_suffix], m_v)
#Q = torch.einsum('vu, nvj->nuj', self.weights['Q_matrix' + weights_suffix], m_v)
#K = torch.einsum('vu, nvj->nuj', self.weights['K_matrix' + weights_suffix], m_v)
V_norm = torch.linalg.norm(V, dim=2)
#K_norm = torch.linalg.norm(K, dim=2)
m_ex = torch.cat([m_h, V_norm], dim=1)
a_hh = fully_connected(m_ex, self.weights['aggregate_hh_hidden'+weights_suffix],
self.weights['aggregate_hh_biases'+weights_suffix],
self.weights['aggregate_hh_output'+weights_suffix])
a_hv = fully_connected(m_ex, self.weights['aggregate_hv_hidden'+weights_suffix],
self.weights['aggregate_hv_biases'+weights_suffix],
self.weights['aggregate_hv_output'+weights_suffix])
a_vv = fully_connected(m_ex, self.weights['aggregate_vv_hidden'+weights_suffix],
self.weights['aggregate_vv_biases'+weights_suffix],
self.weights['aggregate_vv_output'+weights_suffix])
inner_product = torch.einsum('nvi, nvi->nv', U, V)
inner_product = torch.matmul(inner_product, self.weights['inner_product_weights'+weights_suffix])
h_new = self.units['node_update_gru'+weights_suffix](a_hh + a_hv * inner_product,
h)
# v_new = torch.cat([v, torch.unsqueeze(a_vv, dim=2) * U], dim=1)
temp = torch.einsum('nvi, nvi->nv', U, V) / torch.square(V_norm+SMALL_NUMBER)
temp = torch.unsqueeze(temp * (temp < 0), dim=2)
v_new = torch.cat([v, torch.unsqueeze(a_vv, dim=2) * (U - temp * V)], dim=1)
#v_new = fully_connected_vec(v_new, self.weights['vec_update_hidden_weights'+weights_suffix],
#self.weights['vec_update_nonlinear_Q'+weights_suffix],
#self.weights['vec_update_nonlinear_K'+weights_suffix],
#self.weights['vec_update_output_weights'+weights_suffix])
v_new = torch.einsum('nvi, vu->nui', v_new, self.weights['vec_update_weights'+weights_suffix])
return h_new.reshape([-1, num_atoms, h_dim]), v_new.reshape([-1, num_atoms, v_dim, 3])
def compute_mean_and_logvariance(self):
v = self.data['num_vertices']
h_dim = self.params['hidden_size'] + self.params['idx_size']
out_dim = self.params['encoding_size']
out_vec_dim = self.params['encoding_vec_size']
v_dim = self.params['vector_size']
# Full molecule's encoding: average of all node's representations
avg_last_h_out = torch.sum(self.ops['final_node_representations_out'] * self.ops['graph_state_mask_out'], dim=1) / \
torch.sum(self.ops['graph_state_mask_out'], dim=1)
mean_h_out = torch.matmul(avg_last_h_out, self.weights['mean_h_weights_out']) + self.weights['mean_h_biases_out']
logvariance_h_out = torch.matmul(avg_last_h_out, self.weights['variance_h_weights_out']) + self.weights['variance_h_biases_out']
mean_h_out_ex = torch.reshape(torch.tile(torch.unsqueeze(mean_h_out, 1), [1, v, 1]), [-1, out_dim])
logvariance_h_out_ex = torch.reshape(torch.tile(torch.unsqueeze(logvariance_h_out, 1), [1, v, 1]), [-1, out_dim])
# Node's encoding of unlinked fragments
reshaped_last_h = torch.reshape(self.ops['final_node_representations_in'], [-1, h_dim])
mean_h = torch.matmul(reshaped_last_h, self.weights['mean_h_weights']) + self.weights['mean_h_biases']
# Node's encoding of full molecule
reshaped_last_h_out = torch.reshape(self.ops['final_node_representations_out'], [-1, h_dim])
# mean_h_out_all = torch.matmul(reshaped_last_h_out, self.weights['mean_h_weights_out_all']) + \
# self.weights['mean_h_biases_out_all']
mean_h_out_all = fully_connected(reshaped_last_h_out, self.weights['mean_h_hidden_out_all'],
self.weights['mean_h_biases_out_all'], self.weights['mean_h_weights_out_all'])
# logvariance_h_out_all = torch.matmul(reshaped_last_h_out, self.weights['variance_h_weights_out_all']) + self.weights[
# 'variance_h_biases_out_all']
logvariance_h_out_all = fully_connected(reshaped_last_h_out, self.weights['variance_h_hidden_out_all'],
self.weights['variance_h_biases_out_all'],
self.weights['variance_h_weights_out_all'])
# Node's vector encodings
reshaped_last_v_out = torch.reshape(self.ops['final_node_vec_representations_out'], [-1, v_dim, 3])
reshaped_last_v_in = torch.reshape(self.ops['final_node_vec_representations_in'], [-1, v_dim, 3])
mean_v_out_all = torch.einsum('nvi, vu->nui', reshaped_last_v_out, self.weights['mean_v_weights_out_all'])
#logvariance_v_out = torch.norm(torch.einsum('nvi, vu->nui', reshaped_last_v_out, self.weights['variance_v_weights_out']), dim=2) + \
# self.weights['variance_v_biases_out']
logvariance_v_out_all = torch.matmul(reshaped_last_h_out, self.weights['variance_v_weights_out_all']) + \
self.weights['variance_v_biases_out_all']
logvariance_v_out_all = torch.tile(torch.unsqueeze(logvariance_v_out_all, dim=2), [1, 1, 3])
mean_v_in = torch.einsum('nvi, vu->nui', reshaped_last_v_in, self.weights['mean_v_weights_in'])
# fully molecule's vector representation
avg_last_v_out = torch.sum(self.ops['final_node_vec_representations_out'] * torch.unsqueeze(self.ops['graph_state_mask_out'], dim=-2), dim=1)
mean_v_out = torch.einsum('bci, cd->bdi', avg_last_v_out, self.weights['mean_v_weights_out'])
logvariance_v_out = torch.matmul(avg_last_h_out, self.weights['variance_v_weights_out']) + \
self.weights['variance_v_biases_out']
logvariance_v_out = torch.tile(torch.unsqueeze(logvariance_v_out, dim=-1), [1, 1, 3])
logvariance_v_out_ex = torch.reshape(torch.tile(torch.unsqueeze(logvariance_v_out, dim=1), [1, v, 1, 1]), [-1, out_vec_dim, 3])
mean_v_out_ex = torch.reshape(torch.tile(torch.unsqueeze(mean_v_out, dim=1), [1, v, 1, 1]), [-1, out_vec_dim, 3])
# return: mean_h is the fragments' encodings; mean_h_out is the avg encoding; mean_h_out_all is the full
return mean_h, mean_h_out_ex, logvariance_h_out_ex, mean_h_out_all, logvariance_h_out_all, mean_v_in, \
mean_v_out_all, logvariance_v_out_all, mean_v_out_ex, logvariance_v_out_ex
def sample_with_mean_and_logvariance(self):
v = self.data['num_vertices']
h_dim = self.params['hidden_size'] + self.params['idx_size']
out_dim = self.params['encoding_size']
out_vec_dim = self.params['encoding_vec_size']
v_dim = self.params['vector_size']
# Sample from N(0,1)
z_prior_h = torch.reshape(self.data['z_prior_h'], [-1, out_dim])
z_prior_h_in = torch.reshape(self.data['z_prior_h_in'], [-1, out_dim])
z_prior_v = torch.reshape(self.data['z_prior_v'], [-1, out_vec_dim, 3])
z_prior_v_in = torch.reshape(self.data['z_prior_v_in'], [-1, out_vec_dim, 3])# * torch.sqrt(torch.exp(self.weights['prior_logvariance']))
# Train: sample from N(u, sigma). Genearation: sample from N(0,1)
if self.data['is_generative']:
z_sampled_h = z_prior_h
z_linker_sampled_h = z_prior_h_in
z_linker_sampled_v = z_prior_v_in
z_sampled_v = z_prior_v
else:
z_sampled_h = self.ops['mean_h_out'] + torch.multiply(torch.sqrt(torch.exp(self.ops['logvariance_h_out'])), z_prior_h)
z_linker_sampled_h = self.ops['mean_h_out_all'] + torch.multiply(torch.sqrt(torch.exp(
self.ops['logvariance_h_out_all'])), z_prior_h_in)
z_linker_sampled_v = self.ops['mean_v_out_all'] + torch.multiply(torch.sqrt(torch.exp(
self.ops['logvariance_v_out_all'])), z_prior_v_in)
# z_linker_sampled_v = self.ops['mean_v_out_all'] + torch.sqrt(torch.tensor(self.params['prior_variance'], device=self.device)) * torch.multiply(torch.sqrt(torch.exp(
#self.ops['logvariance_v_out_all'])), z_prior_v_in)
z_sampled_v = self.ops['mean_v_out'] + torch.multiply(torch.sqrt(torch.exp(
self.ops['logvariance_v_out'])), z_prior_v)
# z_sampled_v = self.ops['mean_v_out'] + torch.sqrt(torch.tensor(self.params['prior_variance'], device=self.device)) * torch.multiply(torch.sqrt(torch.exp(
# self.ops['logvariance_v_out'])), z_prior_v)
# z_linker_sampled_h = z_prior_h_in
z_sampled_h = torch.reshape(torch.matmul(z_sampled_h, self.weights['mean_h_combine_weights_in']), [-1, v, h_dim])