-
Notifications
You must be signed in to change notification settings - Fork 1
/
NDP4ND_testSparsity.py
2308 lines (1949 loc) · 109 KB
/
NDP4ND_testSparsity.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
"""Script that utilizes an ANP to regress points to a sine curve."""
import logging
import os
import time
import warnings
import sys
import torch
import torch.nn as nn
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import numpy as np
import random
from functools import partial
from sklearn.metrics import roc_auc_score
import torch.nn.functional as F
from torch_scatter import scatter_sum, scatter_mean
from torch_geometric.nn import GCNConv, GATConv, SAGEConv
import torchdiffeq as ode
from torchviz import make_dot
from tools import *
from plots import *
from load_dynamics_solution2and3 import dynamics_dataset, display_3D, display_diff
import argparse
parser = argparse.ArgumentParser(description='GraphNDP_OneForAll')
parser.add_argument('--seed', type=int, default=0, metavar='S',
help='random seed (default: 0)')
parser.add_argument('--topo_type', help='topo_type, default:"power_law"', default="power_law")
parser.add_argument('--dynamics_name', help='dynamics_name, default:"heat_diffusion_dynamics"',
default="heat_diffusion_dynamics")
parser.add_argument('--num_graphs', type=int, default=1000, metavar='S',
help='num_graphs (default: 1000)')
parser.add_argument('--time_steps', type=int, default=100, metavar='S',
help='time_steps (default: 100)')
parser.add_argument('--x_dim', type=int, default=1, metavar='S',
help='x_dim (default: 1)')
parser.add_argument('--latent_dim', type=int, default=20, metavar='S',
help='latent_dim (default: 20)')
parser.add_argument('--hidden_dim', type=int, default=20, metavar='S',
help='hidden_dim (default: 20)')
parser.add_argument('--gnn_type', help='gnn_typ, default:"gat"', default="gat")
parser.add_argument('--num_gnn_blocks', type=int, default=2, metavar='S',
help='num_gnn_blocks (default: 2)')
parser.add_argument('--use_ML_loss', action='store_true', default=False,
help='set use_ML_loss')
parser.add_argument('--is_determinate', action='store_true', default=False,
help='set is_determinate')
parser.add_argument('--is_uncertainty', action='store_true', default=False,
help='set is_determinate')
parser.add_argument('--train', action='store_true', default=False,
help='flag for training')
parser.add_argument('--test', action='store_true', default=False,
help='flag for testing')
parser.add_argument('--no-cuda', action='store_true', default=False,
help='enables CUDA training')
parser.add_argument('--tune', action='store_true', default=False,
help='output the result for tuning the hyperparams')
parser.add_argument('--bound_t_context', type=float, default=0., metavar='S',
help='bound_t_context (default: 0.)')
parser.add_argument('--test_topo_type', help='topo_type, default:"none"', default="none")
parser.add_argument('--start_epoch', type=int, default=0, metavar='S',
help='start_epoch (default: 0)')
parser.add_argument('--num_epochs', type=int, default=20, metavar='S',
help='num_epochs (default: 20)')
parser.add_argument('--constraint_state', action='store_true', default=False,
help='flag for the state constraint')
parser.add_argument('--is_fine_tune', action='store_true', default=False,
help='flag for is_fine_tune')
parser.add_argument('--train_2nd_phase', action='store_true', default=False,
help='flag for train_2nd_phase')
parser.add_argument('--test_with_2nd_phase', action='store_true', default=False,
help='flag for test_with_2nd_phase')
parser.add_argument('--sparsity', type=float, default=0.01, metavar='S',
help='sparsity (default: 0.01)')
os.chdir(".")
warnings.filterwarnings("ignore")
warnings.simplefilter("ignore")
logging.disable(logging.ERROR)
def get_mask_dim(dim, max_dim):
assert dim <= max_dim
res = []
for i in range(max_dim):
if i < dim:
res.append(1)
else:
res.append(0)
return np.array(res)
##=====================================================================
##
## models
##
##====================================================================
class ScoreNet(torch.nn.Module):
def __init__(self, hidden_dim, num_heads=8, dropout=0.4):
super().__init__()
self.self_attention = nn.MultiheadAttention(embed_dim=hidden_dim,
num_heads=num_heads,
batch_first=True,
dropout=dropout)
self.scorer = nn.Sequential(
nn.Linear(hidden_dim, hidden_dim),
nn.Dropout(dropout),
nn.LeakyReLU(inplace=True),
nn.Linear(hidden_dim, hidden_dim),
nn.Dropout(dropout),
nn.LeakyReLU(inplace=True),
)
self.read_out = nn.Sequential(
nn.Linear(hidden_dim, 1),
)
#save_last_rep
self.hidden_rep = None
def forward(self, R):
# R: [batch_size, #models, hidden_dim]
R_res, weights = self.self_attention(R, R, R)
# [batch_size, #models, hidden_dim]
hidden_rep = self.scorer(R_res)
self.hidden_rep = hidden_rep.detach()
# [batch_size, #models, 1]
scores = self.read_out(hidden_rep)
# [batch_size, #models, 1] -> # [batch_size, #models,]
# scores = torch.softmax(scores.sum(-1), dim=-1)
return scores.sum(-1)
class GNN(torch.nn.Module):
def __init__(self, name, num_layers, in_channels, hidden_channels, out_channels, use_edge_attr=False, num_heads=8):
super().__init__()
self.use_edge_attr = use_edge_attr
self.block_list = nn.ModuleList()
# self.LN_list = nn.ModuleList()
for i in range(num_layers):
if i == 0:
in_dim = in_channels
out_dim = hidden_channels
elif i > 0 and i < num_layers - 1:
in_dim = hidden_channels
out_dim = hidden_channels
else:
in_dim = hidden_channels
out_dim = out_channels
if name == 'gcn':
block = GCNConv(in_dim, out_dim)
elif name == 'gat':
if i == 0:
if use_edge_attr:
block = GATConv(in_dim, out_dim, heads=num_heads, concat=True, edge_dim=1)
else:
block = GATConv(in_dim, out_dim, heads=num_heads, concat=True)
elif i > 0 and i < num_layers - 1:
if use_edge_attr:
block = GATConv(in_dim * num_heads, out_dim, heads=num_heads, concat=True, edge_dim=1)
else:
block = GATConv(in_dim * num_heads, out_dim, heads=num_heads, concat=True)
else:
if use_edge_attr:
block = GATConv(in_dim * num_heads, out_dim, heads=num_heads, concat=False, edge_dim=1)
else:
block = GATConv(in_dim * num_heads, out_dim, heads=num_heads, concat=False)
elif name == 'sage':
block = SAGEConv(in_dim, out_dim)
self.block_list.append(block)
self.act_func = nn.LeakyReLU(inplace=True)
# self.LN_list.append(nn.LayerNorm(hidden_channels))
def forward(self, x: torch.Tensor, edge_index: torch.Tensor, edge_attr: torch.Tensor = None) -> torch.Tensor:
# x: Node feature matrix of shape [num_nodes, in_channels]
# edge_index: Graph connectivity matrix of shape [2, num_edges]
H = []
for i in range(len(self.block_list)):
if self.use_edge_attr:
x = self.act_func(self.block_list[i](x, edge_index.long(), edge_attr))
else:
x = self.act_func(self.block_list[i](x, edge_index.long()))
# x = self.LN_list[i](x)
H.append(x)
return H
def t2v(tau, f, out_features, w, b, w0, b0, arg=None):
if arg:
v1 = f(torch.matmul(tau, w) + b, arg)
else:
v1 = f(torch.matmul(tau, w) + b)
v2 = torch.matmul(tau, w0) + b0
return torch.cat([v1, v2], 1)
class SineActivation(nn.Module):
def __init__(self, in_features, out_features):
super(SineActivation, self).__init__()
self.out_features = out_features
self.w0 = nn.parameter.Parameter(torch.randn(in_features, 1))
self.b0 = nn.parameter.Parameter(torch.randn(in_features, 1))
self.w = nn.parameter.Parameter(torch.randn(in_features, out_features - 1))
self.b = nn.parameter.Parameter(torch.randn(in_features, out_features - 1))
self.f = torch.sin
def forward(self, tau):
return t2v(tau, self.f, self.out_features, self.w, self.b, self.w0, self.b0)
class CosineActivation(nn.Module):
def __init__(self, in_features, out_features):
super(CosineActivation, self).__init__()
self.out_features = out_features
self.w0 = nn.parameter.Parameter(torch.randn(in_features, 1))
self.b0 = nn.parameter.Parameter(torch.randn(in_features, 1))
self.w = nn.parameter.Parameter(torch.randn(in_features, out_features - 1))
self.b = nn.parameter.Parameter(torch.randn(in_features, out_features - 1))
self.f = torch.cos
def forward(self, tau):
return t2v(tau, self.f, self.out_features, self.w, self.b, self.w0, self.b0)
class Time2Vec(nn.Module):
def __init__(self, activation, hiddem_dim):
super(Time2Vec, self).__init__()
if activation == "sin":
self.l1 = SineActivation(1, hiddem_dim)
elif activation == "cos":
self.l1 = CosineActivation(1, hiddem_dim)
def forward(self, x):
x = self.l1(x)
return x
class ODEFunc(nn.Module):
def __init__(self, decode_F, decode_G):
super(ODEFunc, self).__init__()
self.decode_F = decode_F
self.decode_G = decode_G
#
self.Z = None
self.adj = None
self.task_info = None
def update(self, Z, adj, task_info):
self.Z = Z
self.adj = adj
self.task_info = task_info
def forward(self, t, x): # How to use t?
# print(x.size())
# [num_sampling, # points,d] -> [num_sampling, # points,d]
# x_encoded = self.encode_x(x)
# [num_sampling, # points,d], [num_sampling, # points,d] -> [num_sampling, # points,d + d]
x_encoded_augment = torch.cat([x, self.Z], dim=-1)
# [num_sampling, # points,d + d] -> [num_sampling, # points,d]
out_F = self.decode_F(x_encoded_augment)
if len(self.adj) > 2:
row, col, edge_weights = self.adj
# [num_sampling, # points's neighbors,d], [num_sampling, # points's neighbors,d+d] -> [num_sampling, # points's neighbors,d]
# print(x_encoded[:, col, :].size(), x_encoded_augment[:, row, :].size())
x_i_j_in = torch.cat([x[:, col.long(), :], x_encoded_augment[:, row.long(), :]], dim=-1)
out_G = self.decode_G(x_i_j_in) * edge_weights.view(1, -1, 1).float()
# print('edge_weights=',edge_weights)
# print('out_G=', out_G)
# print('edge_weights has nan =', torch.isnan(edge_weights).sum())
# print('out_G has nan =', torch.isnan(out_G).sum())
else:
row, col = self.adj
# [num_sampling, # points's neighbors,d], [num_sampling, # points's neighbors,d+d] -> [num_sampling, # points's neighbors,d]
# print(x_encoded[:, col, :].size(), x_encoded_augment[:, row, :].size())
x_i_j_in = torch.cat([x[:, col.long(), :], x_encoded_augment[:, row.long(), :]], dim=-1)
out_G = self.decode_G(x_i_j_in)
# [num_sampling, # points,out_dim], [num_sampling, # points's neighbors,out_dim] -> [num_sampling, # points,out_dim]
out_dynamics = out_F + scatter_sum(out_G, col.long(), dim=1, dim_size=x.size(1))
return out_dynamics
class GNDP(nn.Module):
def __init__(
self,
state_dim,
latent_dim,
hidden_dim,
gnn_type,
num_gnn_blocks=2,
is_determinate=True,
is_uncertainty=True,
use_ML_loss=False,
use_edge_attr=False,
):
super().__init__()
self.name = 'GNDP_OneForAll'
self.latent_dim = latent_dim
self.hidden_dim = hidden_dim
self.state_dim = state_dim
self.gnn_type = gnn_type
self.use_ML_loss = use_ML_loss
self.use_edge_attr = use_edge_attr
# encoders
# self.encode_t = Time2Vec('sin', hidden_dim).to(device)
self.encode_t = nn.Sequential(
nn.Linear(1, hidden_dim),
# nn.ReLU(),
nn.LeakyReLU(inplace=True),
# # nn.LayerNorm(hidden_dim),
# nn.Linear(hidden_dim, hidden_dim),
# nn.ReLU(),
)
self.encode_x = nn.Sequential(
nn.Linear(state_dim + 1, hidden_dim), ## add one dim parameters for "null" node type
# nn.ReLU(),
nn.LeakyReLU(inplace=True),
# # nn.LayerNorm(hidden_dim),
# nn.Linear(hidden_dim, hidden_dim),
# nn.ReLU(),
)
##
# gnn_type = 'sage'
self.encode_structure = GNN(gnn_type, num_gnn_blocks, hidden_dim, 16, 16, use_edge_attr)
##
if gnn_type == 'gat':
in_dim = 16 * 8 * (num_gnn_blocks - 1) + 16
else:
in_dim = 16 * num_gnn_blocks
# in_dim = hidden_dim
self.encode_self_phi = nn.Sequential(
nn.Linear(in_dim + hidden_dim, hidden_dim),
# nn.ReLU(),
nn.LeakyReLU(inplace=True),
# nn.LayerNorm(hidden_dim),
nn.Linear(hidden_dim, hidden_dim),
# nn.ReLU(),
nn.LeakyReLU(inplace=True),
# nn.LayerNorm(hidden_dim),
)
self.encode_self_rho = nn.Sequential(
nn.Linear(hidden_dim, hidden_dim),
nn.LeakyReLU(inplace=True),
# nn.Linear(hidden_dim, hidden_dim),
# nn.LeakyReLU(inplace=True),
)
self.encode_z_mean = nn.Sequential(
nn.Linear(hidden_dim, hidden_dim)
)
self.encode_z_logsigma = nn.Sequential(
nn.Linear(hidden_dim, hidden_dim)
)
# cross attention layers for determinate_path
# self.encode_cross_attention_enc_x = nn.Sequential(
# nn.Linear(state_dim, hidden_dim),
# nn.LeakyReLU(inplace=True),
# )
# self.encode_attention_enc_gnn = GNN(gnn_type, num_gnn_blocks, hidden_dim, 16, 16)
# ##
# if gnn_type == 'gat':
# in_dim = 16 * 8 * (num_gnn_blocks - 1) + 16
# else:
# in_dim = 16 * num_gnn_blocks
# self.encode_attention_enc_gnn_t = nn.Sequential(
# nn.Linear(in_dim + hidden_dim, hidden_dim),
# nn.LeakyReLU(inplace=True),
# )
# self.encode_attention = nn.MultiheadAttention(embed_dim=hidden_dim, num_heads=8, batch_first=False)
# parmas for path
self.is_determinate = is_determinate
self.is_uncertainty = is_uncertainty
assert self.is_determinate + self.is_uncertainty > 0
## decoders
self.decoder_encode_x = nn.Sequential(
nn.Linear(state_dim, hidden_dim),
# nn.ReLU(),
nn.LeakyReLU(inplace=True),
# nn.LayerNorm(latent_dim),
# nn.Linear(hidden_dim, hidden_dim),
# nn.ReLU(),
)
self.decoder_encode_x_mean = nn.Sequential(
nn.Linear(hidden_dim, latent_dim)
)
self.decoder_encode_x_logsigma = nn.Sequential(
nn.Linear(hidden_dim, latent_dim)
)
in_dim_for_decoder_F = latent_dim
if self.is_determinate:
in_dim_for_decoder_F += hidden_dim
if self.is_uncertainty:
in_dim_for_decoder_F += hidden_dim
# decoders
self.decode_F = nn.Sequential(
nn.Linear(in_dim_for_decoder_F, hidden_dim),
# nn.ReLU(),
nn.LeakyReLU(inplace=True),
# nn.Tanh(),
# nn.LayerNorm(hidden_dim),
# nn.Linear(hidden_dim, hidden_dim),
# nn.ReLU(),
# nn.Tanh(),
# nn.LayerNorm(hidden_dim),
nn.Linear(hidden_dim, latent_dim),
# nn.ReLU(),
nn.LeakyReLU(inplace=True),
# nn.Tanh(),
)
in_dim_for_decoder_G = latent_dim + latent_dim
if self.is_determinate:
in_dim_for_decoder_G += hidden_dim
if self.is_uncertainty:
in_dim_for_decoder_G += hidden_dim
self.decode_G = nn.Sequential(
nn.Linear(in_dim_for_decoder_G, hidden_dim),
# nn.ReLU(),
nn.LeakyReLU(inplace=True),
# nn.Tanh(),
# nn.LayerNorm(hidden_dim),
# nn.Linear(hidden_dim, hidden_dim),
# nn.ReLU(),
# nn.Tanh(),
# nn.LayerNorm(hidden_dim),
nn.Linear(hidden_dim, latent_dim),
# nn.ReLU(),
nn.LeakyReLU(inplace=True),
# nn.Tanh(),
)
in_dim_for_decode_state_hidden = latent_dim + hidden_dim
if self.is_uncertainty:
in_dim_for_decode_state_hidden += hidden_dim
if self.is_determinate:
in_dim_for_decode_state_hidden += hidden_dim
self.decode_state_hidden = nn.Sequential(
nn.Linear(in_dim_for_decode_state_hidden, hidden_dim),
# nn.ReLU(),
nn.LeakyReLU(inplace=True),
# nn.LayerNorm(hidden_dim),
nn.Linear(hidden_dim, latent_dim),
# nn.ReLU(),
nn.LeakyReLU(inplace=True),
)
self.decode_state_mean = nn.Sequential(
nn.Linear(latent_dim + latent_dim, state_dim),
)
self.decode_state_logsigma = nn.Sequential(
nn.Linear(latent_dim + latent_dim, state_dim),
)
# self.learned_logsigma = nn.Parameter(torch.zeros(state_dim))
# self.learned_logsigma = nn.Parameter(torch.ones(state_dim))
#
self.ode_func = ODEFunc(self.decode_F, self.decode_G)
# params for odeint
self.adjoint = True
self.rtol = .01
self.atol = .001
self.method = 'dopri5' # 'dopri5'
# For intermediate storage
self.Z = None
self.x_0 = None
self.adj = None
self.task_info = None
self.Z_determinate = None
# for Cyclical Annealing Schedule of KL's weight beta
self.beta = torch.ones(1).to(device)
self.reset_parameters()
def reset_parameters(self):
weights_init(self)
def update_beta(self, epoch, max_epoch):
# for Cyclical Annealing Schedule of KL's weight beta
M = torch.tensor([4.])
R = torch.tensor([.5])
tau = (torch.tensor([epoch - 1]) % (torch.tensor([max_epoch]) / M).ceil()) / (torch.tensor([max_epoch]) / M)
self.beta = tau / R if tau <= R else torch.ones(1)
self.beta = self.beta.to(device)
print('update beta %s' % str(self.beta))
def encode_context_graph(self, points):
# points: (t, x_self, mask, point_info, adj)
# where,
# t [# points, ]
# x_self [# points * N, d],
# mask [# points * N,],
# point_info [# points * N, ],
# adj [2, # edges,],
# task_info [# points, ]
t, x_self, mask, point_info, adj, task_info = points
## [#points, d]
t_encoded_all = self.encode_t(torch.cat(t, dim=0).view(-1, 1))
## make all batch
point_info_all = []
adj_all = []
num_nodes_last = 0
for idx in range(len(t)):
point_info_all.append(point_info[idx] + len(point_info_all))
#adj_all.append(adj[idx] + num_nodes_last)
adj_all.append(torch.cat([adj[idx][:2, :] + num_nodes_last, adj[idx][2:, :]], dim=0))
num_nodes_last += point_info_all[-1].size(0)
##
x_self_all = torch.cat(x_self, dim=0)
mask_all = torch.cat(mask, dim=0).long()
point_info_all = torch.cat(point_info_all, dim=0).view(-1).long()
adj_all = torch.cat(adj_all, dim=-1).long()
task_info_all = torch.cat(task_info, dim=0).view(-1).long()
## make init embedding on nodes for each point
# x_self_all_filter = torch.zeros_like(x_self_all)
# x_self_all_filter[mask_all == 1] = x_self_all[mask_all == 1]
# x_self_all_filter[mask_all < 1] = self.null_node_embedding
# x_self_all_augment = torch.zeros_like(x_self_all)
# x_self_all_augment[mask_all[:,0] == 1] = x_self_all[mask_all[:,0] == 1]
x_self_all_augment = x_self_all * mask_all.float()
## add 0 at first dim of node states and add 1 at first dim of null node
x_self_all_augment = torch.cat([1. - (mask_all.sum(-1) >= 1).float().view(-1, 1), x_self_all_augment], dim=-1)
x_self_all_augment_embedding = self.encode_x(x_self_all_augment)
#print(x_self_all_augment_embedding.size(), adj_all.size())
if self.use_edge_attr:
x_self_all_augment_embedding_new_list = self.encode_structure(x_self_all_augment_embedding,
adj_all[:2, :].long(), adj_all[-1, :].float().view(-1, 1))
else:
x_self_all_augment_embedding_new_list = self.encode_structure(x_self_all_augment_embedding,
adj_all[:2, :].long())
x_self_graph_glo_embedding = []
for x_self_all_augment_embedding_new_one in x_self_all_augment_embedding_new_list:
x_self_graph_glo_embedding.append(scatter_sum(x_self_all_augment_embedding_new_one, point_info_all, dim=0))
x_self_graph_glo_embedding = torch.cat(x_self_graph_glo_embedding, dim=-1)
r_i_all = self.encode_self_phi(torch.cat([t_encoded_all, x_self_graph_glo_embedding], dim=-1))
# self attention
# make query key and value
# graph_glo_embedding_list_1 = self.encode_attention_enc_gnn(self.encode_cross_attention_enc_x(mask_all.float()), adj_all)
# graph_glo_embedding_1 = []
# for x_self_all_augment_embedding_new_one in graph_glo_embedding_list_1:
# graph_glo_embedding_1.append(
# scatter_sum(x_self_all_augment_embedding_new_one, point_info_all, dim=0))
# graph_glo_embedding_1 = torch.cat(graph_glo_embedding_1, dim=-1)
# ##
# query = self.encode_attention_enc_gnn_t(torch.cat([t_encoded_all, graph_glo_embedding_1], dim=-1))
# key = self.encode_attention_enc_gnn_t(torch.cat([t_encoded_all, graph_glo_embedding_1], dim=-1))
# value = r_i_all
#
# r_i_all_self_atten = []
# for batch_idx in range(max(task_info_all)+1):
# # print(query[task_info_all==batch_idx].size(), key[task_info_all==batch_idx].size(), value[task_info_all==batch_idx].size())
# r_i_all_self_atten_batch_idx, _ = self.encode_attention(query[task_info_all==batch_idx], key[task_info_all==batch_idx], value[task_info_all==batch_idx])
# r_i_all_self_atten.append(r_i_all_self_atten_batch_idx)
# r_i_all_self_atten = torch.cat(r_i_all_self_atten, dim=0)
# [batch_size, d]
Z_determinate = scatter_mean(r_i_all, task_info_all, dim=0)
z_hidden = self.encode_self_rho(Z_determinate)
z_mean = self.encode_z_mean(z_hidden)
z_logsigma = self.encode_z_logsigma(z_hidden)
# Bound the variance
# z_sigma = 0.01 + 0.99 * F.softplus(z_logsigma)
# z_sigma = 0.1 + 0.9 * torch.sigmoid(z_logsigma)
z_sigma = 0.1 + 0.9 * torch.sigmoid(z_logsigma)
## [batch_size, d]
dist_z = torch.distributions.Normal(z_mean, z_sigma)
return Z_determinate, dist_z
def ode_integration(self, vt, x):
integration_time_vector = vt.type_as(x)
self.ode_func.update(self.Z, self.adj, self.task_info)
if self.adjoint:
out = ode.odeint_adjoint(self.ode_func,
x, integration_time_vector,
rtol=self.rtol, atol=self.atol, method=self.method)
else:
out = ode.odeint(self.ode_func,
x, integration_time_vector,
rtol=self.rtol, atol=self.atol, method=self.method)
# the size of out should be confirmed later
return out ## [#steps, num_sampling, #nodes, d]
def forward(self, adj, x0, task_info, x_context, x_target, num_sampling=1, use_NPLoss=True):
# x0 [# nodes, d],
# adj [2, #edges],
# task_info [# nodes,]
# x_context: (t, x_self, mask, point_info, adj)
# where,
# t [# points, ]
# x_self [# points, d],
# mask [# points,],
# point_info [# points, ],
# adj [2, # edges,],
# task_info [# points, ]
# x_target: similar to x_context
# if x_self in points in x_target is None then, just testing; otherwise training
t_target, x_self_target, mask_target, point_info_target, adj_target, task_info_target = x_target
if x_self_target is not None:
_train_flag = True
else:
_train_flag = False
if not self.is_uncertainty or (_train_flag and use_NPLoss):
num_sampling = 1
# encode init_x in decoding process
# [#batch_size*N, d]
decoder_encode_x_hidden = self.decoder_encode_x(x0)
decoder_encode_x_mean = self.decoder_encode_x_mean(decoder_encode_x_hidden)
decoder_encode_x_logsigma = self.decoder_encode_x_logsigma(decoder_encode_x_hidden)
# Bound the variance
# decoder_encode_x_sigma = 0.01 + 0.99 * F.softplus(decoder_encode_x_logsigma)
decoder_encode_x_sigma = 0.1 + 0.9 * torch.sigmoid(decoder_encode_x_logsigma)
# [batch_size, d]
dist_l_0 = torch.distributions.Normal(decoder_encode_x_mean, decoder_encode_x_sigma)
# [num_sampling, #batch_size*N, d]
self.x_0 = dist_l_0.rsample([num_sampling])
# self.x_0 = x0.unsqueeze(0).repeat(num_sampling, 1, 1) # [#batch_size*N, d]->[num_sampling, #batch_size*N, d]
self.adj = adj
self.task_info = task_info # [#batch_size*N,]
## encode context
Z_determinate, dist_prior_z = self.encode_context_graph(x_context)
self.Z_determinate = Z_determinate
if self.is_determinate:
Z_determinate = Z_determinate.unsqueeze(0).repeat(num_sampling, 1,
1) # [batch_size, d] -> [num_sampling, batch_size, d]
if self.is_uncertainty:
if _train_flag and use_NPLoss:
_, dist_poster_z = self.encode_context_graph(x_target)
else:
dist_poster_z = dist_prior_z
Z_sampling = dist_poster_z.rsample([num_sampling]) # [num_sampling, batch_size, d]
if self.is_determinate and self.is_uncertainty:
Z_augment = torch.cat([Z_determinate, Z_sampling], dim=-1)
elif not self.is_determinate and self.is_uncertainty:
Z_augment = Z_sampling
elif self.is_determinate and not self.is_uncertainty:
Z_augment = Z_determinate
else:
print("ERROR setting on is_determinate|is_uncertainty, %s,%s" % (
self.is_determinate, self.is_uncertainty))
exit(1)
# print(Z_sampling.size(),dist_poster_z.loc, dist_poster_z.scale)
# print(Z_sampling[0].view(-1))
# print(Z_sampling[1].view(-1))
# print(Z_sampling[2].view(-1))
# print(Z_sampling[3].view(-1))
# print(Z_sampling[4].view(-1))
# Z_augment = torch.zeros_like(Z_augment).detach()
## decode
# [num_sampling, batch_size, d] -> [num_sampling, batch_size*N, d]
self.Z = Z_augment[:, task_info, :]
# handle t
t_target = torch.cat(t_target, dim=0).view(-1)
t_target = t_target.clone().detach()
t_target_remove_duplicates_and_sort_increasing = torch.unique(t_target)
indices_t_target = t_target.detach()
for ttt_idx in range(len(t_target_remove_duplicates_and_sort_increasing)):
indices_t_target[indices_t_target == t_target_remove_duplicates_and_sort_increasing[ttt_idx]] = ttt_idx
indices_t_target = indices_t_target.long()
# print(t_target_remove_duplicates_and_sort_increasing, indices_t_target)
# exit(1)
# integration hidden
# [#steps, num_sampling, batch_size*N, d]
# print(t_target_remove_duplicates_and_sort_increasing, indices_t_target)
# [#steps, num_sampling, #nodes, d]
pre_state_out_hidden = self.ode_integration(t_target_remove_duplicates_and_sort_increasing, self.x_0)
# [#steps, num_sampling, batch_size*N, d] -> [num_sampling, #steps, batch_size*N, d]
pre_state_out_hidden = pre_state_out_hidden.transpose(0, 1)
# [num_sampling, #steps, batch_size*N, d] -> [num_sampling, #points, batch_size*N, d]
pre_state_out_hidden = pre_state_out_hidden[:, indices_t_target, :]
# decode hidden to state
# [num_sampling, batch_size*N, d] -> [num_sampling, #points, batch_size*N, d]
Z_ = self.Z.unsqueeze(1).repeat(1, pre_state_out_hidden.size(1), 1, 1)
# [#points, d]
t_target_encoded = self.encode_t(t_target.detach().view(-1, 1))
# [#points, d] -> [num_sampling, #points, batch_size*N, d]
t_target_encoded = t_target_encoded.view(1, -1, 1, self.hidden_dim).repeat(num_sampling, 1,
pre_state_out_hidden.size(2), 1)
# [num_sampling, #points, batch_size*N, d + d + d]
pre_state_out_hidden_ = torch.cat([pre_state_out_hidden, Z_, t_target_encoded], dim=-1)
# pre_state_out_hidden_ = torch.cat([pre_state_out_hidden, t_target_encoded], dim=-1)
# [num_sampling, #points, batch_size*N, d + d + d] -> [num_sampling, #points, batch_size*N, d]
# print(pre_state_out_hidden_.size())
pre_state_out_hidden_ = self.decode_state_hidden(pre_state_out_hidden_)
# [num_sampling, #points, batch_size*N, d + d] -> [num_sampling, #points, batch_size*N, d]
pre_state_out_hidden_ = torch.cat([pre_state_out_hidden, pre_state_out_hidden_], dim=-1)
pre_state = self.decode_state_mean(pre_state_out_hidden_)
pre_state_logsigma = self.decode_state_logsigma(pre_state_out_hidden_)
# Bound the variance
pre_state_sigma = 0.01 + 0.99 * F.softplus(pre_state_logsigma)
# pre_state_sigma = torch.sigmoid(pre_state_logsigma)
# [num_sampling, #points, batch_size*N, d] -> [num_sampling, #points * batch_size*N, d]
pre_state = pre_state.view(num_sampling, -1, self.state_dim)
## add state constraint when args.constraint_state is True
if args.constraint_state:
# pre_state = F.softplus(pre_state) / torch.sum(F.softplus(pre_state), dim=-1, keepdim=True)
pre_state = F.softmax(pre_state, dim=-1)
pre_state_sigma = pre_state_sigma.view(num_sampling, -1, self.state_dim)
# make mask and x_self
mask_all = torch.cat(mask_target, dim=0).long()
mask_target_extend = []
for idx in range(len(t_target)):
mask_target_ = torch.zeros_like(x0)
mask_target_[task_info == task_info_target[idx], :] = mask_target[idx].float()
mask_target_extend.append(mask_target_)
## [#points * batch_size*N, d]
mask_target_extend = torch.cat(mask_target_extend, dim=0).view(-1, self.state_dim)
## [num_sampling, # observations]
pre_state_target_mean = pre_state[:, mask_target_extend == 1]
pre_state_target_sigma = pre_state_sigma[:, mask_target_extend == 1]
poster_dist = torch.distributions.Normal(pre_state_target_mean, pre_state_target_sigma)
loss = None
loss_detail = None
if _train_flag:
# training
# make x_self
x_self_target_extend = []
for idx in range(len(t_target)):
x_self_target_ = torch.zeros_like(x0)
x_self_target_[task_info == task_info_target[idx]] = x_self_target[idx]
x_self_target_extend.append(x_self_target_)
## [#points * batch_size*N, d] -> [num_sampling, #points * batch_size*N, d]
x_self_target_extend = torch.cat(x_self_target_extend, dim=0).unsqueeze(0).repeat(num_sampling, 1, 1)
if self.is_determinate and not self.is_uncertainty:
# [1, #observations] -> [#observations]
log_p_ = poster_dist.log_prob(
x_self_target_extend[:, mask_target_extend == 1]).view(-1)
# [batch_size*N, ] -> [#points, batch_size*N, ] -> [#points*batch_size*N,] -> [# observations,]
# [batch_size*N, ] -> [batch_size*N, d] -> [#points, batch_size*N, d] -> [#points*batch_size*N, d] -> [# observations,]
task_info_observations = \
task_info.unsqueeze(1).repeat(1, self.state_dim).unsqueeze(0).repeat(len(t_target), 1, 1).view(-1,
self.state_dim)[
mask_target_extend == 1]
# [batch_size,]
log_p = scatter_sum(log_p_, task_info_observations, dim=0)
# [batch_size] -> 1
loss = -log_p.mean()
loss_detail = {'neg_log_p': 0., 'kl': 0.}
else:
if use_NPLoss: ##use NP loss
# get log probability
# Get KL between prior and posterior
# [batch_size, d] -> [batch_size,]
loss_kl = torch.distributions.kl_divergence(dist_poster_z, dist_prior_z).sum(-1)
# [num_sampling, #observations]
log_p_ = poster_dist.log_prob(
x_self_target_extend[:, mask_target_extend == 1])
# [batch_size*N, ] -> [batch_size*N, d] -> [#points, batch_size*N, d] -> [#points*batch_size*N, d] -> [# observations,]
task_info_observations = \
task_info.unsqueeze(1).repeat(1, self.state_dim).unsqueeze(0).repeat(len(t_target), 1, 1).view(-1,
self.state_dim)[
mask_target_extend == 1]
# [num_sampling, #observations] -> [num_sampling, batch_size]
log_p = scatter_sum(log_p_, task_info_observations, dim=1)
# [num_sampling, batch_size] -> [batch_size]
log_p = log_p.mean(0)
# print('torch.mean(loss_kl) =', torch.mean(loss_kl))
loss = - (log_p - self.beta * loss_kl).mean()
loss_detail = {'neg_log_p': (-log_p.mean()).item(), 'kl': loss_kl.mean().item()}
# loss = -log_p
else: # use ML loss
# get log probability
# [num_sampling, #observations, d]
log_p_ = poster_dist.log_prob(
x_self_target_extend[:, mask_target_extend == 1, :])
# [batch_size*N, ] -> [#points, batch_size*N, ] -> [#points*batch_size*N,] -> [# observations,]
task_info_observations = task_info.unsqueeze(0).repeat(len(t_target), 1).view(-1)[
mask_target_extend == 1]
# [num_sampling, #observations, d] -> [num_sampling, batch_size, d]
log_p = scatter_sum(log_p_, task_info_observations, dim=1)
# [num_sampling, batch_size, d] -> [num_sampling, batch_size]
log_p = log_p.sum(-1)
# [num_sampling, batch_size] -> [batch_size]
log_p = torch.logsumexp(log_p, 0) - torch.log(torch.tensor([num_sampling])).to(device)
# print('torch.mean(loss_kl) =', torch.mean(loss_kl))
loss = -log_p.mean()
loss_detail = {'neg_log_p': 0., 'kl': 0.}
return {'pre_dist': poster_dist, 'loss': loss, "loss_detail": loss_detail}
def make_model(x_dim, latent_dim, hidden_dim, gnn_type, num_gnn_blocks, is_determinate, is_uncertainty, use_ML_loss):
# make model
model = GNDP(state_dim=x_dim,
latent_dim=latent_dim,
hidden_dim=hidden_dim,
gnn_type=gnn_type,
num_gnn_blocks=num_gnn_blocks,
is_determinate=is_determinate,
is_uncertainty=is_uncertainty,
use_ML_loss=use_ML_loss)
print(f"# parameters of np_model: {count_parameters(model):,d}")
# exit(1)
return model
##=====================================================================
##
## make batch
##
##====================================================================
def make_batch(data, batch_size, is_shuffle=True, bound_t_context=None, is_test=False, is_shuffle_target=True,
max_x_dim=None):
if max_x_dim is None:
max_x_dim = x_dim
tasks_data = data['tasks']
if is_shuffle:
points_data_index_shuffle = []
for idx in range(len(data['tasks'])):
points_data = tasks_data[idx]['points']
index_shuffle = torch.randperm(len(points_data) - 1)
index_shuffle = torch.cat([torch.tensor([0]).long(),
index_shuffle + torch.tensor([1]).long()], dim=-1)
points_data_index_shuffle.append(index_shuffle)
tasks_data_index_shuffle = torch.randperm(len(tasks_data))
else:
points_data_index_shuffle = []
for idx in range(len(data['tasks'])):
points_data = tasks_data[idx]['points']
index_shuffle = torch.linspace(0, len(points_data) - 1, len(points_data)).long()
points_data_index_shuffle.append(index_shuffle)
tasks_data_index_shuffle = torch.linspace(0, len(tasks_data) - 1, len(tasks_data)).long()
# print(points_data_index_shuffle)
# we got tasks_data_shuffle,
# which is [(adj,
# x0,
# task_info,
# [{"t":, "x_self":, "mask":},...,{}]),
# (adj,
# x0,
# task_info,
# [{},...,{}]),
# ...]
start_idx = 0
while start_idx < len(tasks_data_index_shuffle):
start_time = time.time()
batch_adj = [] #
batch_x0 = [] #
batch_task_info = [] #
batch_name = []
contexts_batch_t = []
contexts_batch_x_self = []
contexts_batch_mask = []
contexts_batch_point_info = []
contexts_batch_adj = []
contexts_batch_task_info = []
targets_batch_t = []
targets_batch_x_self = []
targets_batch_mask = []
targets_batch_point_info = []
targets_batch_adj = []
targets_batch_task_info = []
for task_i_idx in tasks_data_index_shuffle[start_idx:start_idx + batch_size]:
# make batch for adj, x0 and task_info
task_i_adj_in_batch = tasks_data[task_i_idx]['adj']
task_i_x0_in_batch = tasks_data[task_i_idx]['X0']
task_i_task_info_in_batch = tasks_data[task_i_idx]['task_info']
task_i_points_in_batch = tasks_data[task_i_idx]['points']
batch_name.append(tasks_data[task_i_idx]['name'])
num_nodes_last = 0
for x0_ in batch_x0:
num_nodes_last += x0_.shape[0]
batch_adj.append(task_i_adj_in_batch + num_nodes_last)
# padding zeros to x0
task_i_x0_in_batch = np.concatenate(
[task_i_x0_in_batch, np.zeros((task_i_x0_in_batch.shape[0], max_x_dim - task_i_x0_in_batch.shape[-1]))],
axis=-1)
batch_x0.append(task_i_x0_in_batch)
batch_task_info.append(task_i_task_info_in_batch + len(batch_task_info))
# make context points and target points
num_targets = len(task_i_points_in_batch) ## number of targets = 50
## number of contexts, at least #nodes (i.e., the number of points with t=0)
# num_contexts = np.random.randint(2, max(num_targets // 5, 4)) # [2, num_targets // 5)
# num_contexts = np.random.randint(1, int(num_targets * 0.6)) # [2, num_targets // 5)
num_contexts = np.random.randint(2, 31)
# num_contexts = num_targets - 1
contexts_index = points_data_index_shuffle[task_i_idx][:num_contexts]
# print("context num = %s, target num = %s" % (num_contexts, num_targets))
if is_shuffle_target:
targets_index = points_data_index_shuffle[task_i_idx][:num_targets]
else:
targets_index = torch.linspace(0,
len(task_i_points_in_batch) - 1,
len(task_i_points_in_batch)).long()[:num_targets]
# print("num_contexts=%s, num_targets=%s" % (num_contexts, num_targets))
assert num_contexts < num_targets
contexts_point_mask = []
for contexts_point_idx in contexts_index:
contexts_point_i = task_i_points_in_batch[contexts_point_idx]
if is_test and contexts_point_i['t'] > 0.:
num_nodes = contexts_point_i['mask'].shape[0]
num_sampling_points_per_time = np.random.randint(1, int(num_nodes / 2) + 1) ## [1, N/2]
sampled_idxs = np.random.choice(a=list(range(num_nodes)), size=num_sampling_points_per_time,
replace=False)
new_mask = np.zeros(num_nodes)
new_mask[sampled_idxs] = 1.
contexts_point_mask.append(new_mask)
else:
contexts_point_mask.append(contexts_point_i['mask'])
# contexts_point_mask.append(contexts_point_i['mask'])
# make contexts
for idx in range(len(contexts_index)):
contexts_point_idx = contexts_index[idx]
contexts_point_i = task_i_points_in_batch[contexts_point_idx]
if bound_t_context is not None:
if contexts_point_i['t'] > bound_t_context:
continue
# print(contexts_point_i['t'])
contexts_batch_t.append(torch.from_numpy(contexts_point_i['t']).float())
# contexts_batch_x_self.append(torch.from_numpy(contexts_point_i['x_self']).float())