-
Notifications
You must be signed in to change notification settings - Fork 0
/
modules_sigma.py
1119 lines (947 loc) · 50 KB
/
modules_sigma.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
'''
This code is based on https://github.com/ekwebb/fNRI which in turn is based on https://github.com/ethanfetaya/NRI
(MIT licence)
'''
import torch
import torch.nn as nn
import torch.nn.functional as F
import math
import numpy as np
import time
import utils
from torch.autograd import Variable
from utils import my_softmax, get_offdiag_indices, gumbel_softmax, softplus
_EPS = 1e-10
class MLP(nn.Module):
"""Two-layer fully-connected ELU net with batch norm."""
def __init__(self, n_in, n_hid, n_out, do_prob=0.):
super(MLP, self).__init__()
self.fc1 = nn.Linear(n_in, n_hid)
self.fc2 = nn.Linear(n_hid, n_out)
self.bn = nn.BatchNorm1d(n_out)
self.dropout_prob = do_prob
self.init_weights()
def init_weights(self):
for m in self.modules():
if isinstance(m, nn.Linear):
nn.init.xavier_normal_(m.weight.data)
m.bias.data.fill_(0.1)
elif isinstance(m, nn.BatchNorm1d):
m.weight.data.fill_(1)
m.bias.data.zero_()
def batch_norm(self, inputs):
x = inputs.view(inputs.size(0) * inputs.size(1), -1)
x = self.bn(x)
return x.view(inputs.size(0), inputs.size(1), -1)
def forward(self, inputs):
# Input shape: [num_sims, num_things, num_features]
x = F.elu(self.fc1(inputs))
x = F.dropout(x, self.dropout_prob, training=self.training)
x = F.elu(self.fc2(x))
return self.batch_norm(x)
class MLPDecoder_multi(nn.Module):
"""MLP decoder module."""
def __init__(self, n_in_node, edge_types, edge_types_list, msg_hid, msg_out, n_hid,
do_prob=0., skip_first=False, init_type='default'):
super(MLPDecoder_multi, self).__init__()
self.msg_fc1 = nn.ModuleList(
[nn.Linear(2 * n_in_node, msg_hid) for _ in range(edge_types)])
self.msg_fc2 = nn.ModuleList(
[nn.Linear(msg_hid, msg_out) for _ in range(edge_types)])
self.msg_out_shape = msg_out
self.skip_first = skip_first
self.edge_types = edge_types
self.edge_types_list = edge_types_list
self.out_fc1 = nn.Linear(n_in_node + msg_out, n_hid)
self.out_fc2 = nn.Linear(n_hid, n_hid)
self.out_fc3 = nn.Linear(n_hid, n_in_node)
print('Using learned interaction net decoder.')
self.dropout_prob = do_prob
self.init_type = init_type
if self.init_type not in [ 'xavier_normal', 'orthogonal', 'default' ]:
raise ValueError('This initialization type has not been coded')
#print('Using '+self.init_type+' for decoder weight initialization')
if self.init_type != 'default':
self.init_weights()
def init_weights(self):
for m in self.modules():
if isinstance(m, nn.Linear):
if self.init_type == 'orthogonal':
nn.init.orthogonal_(m.weight.data,gain=0.000001)
elif self.init_type == 'xavier_normal':
nn.init.xavier_normal_(m.weight.data,gain=0.000001)
#m.bias.data.fill_(0.1)
def single_step_forward(self, single_timestep_inputs, rel_rec, rel_send,
single_timestep_rel_type):
# single_timestep_inputs has shape
# [batch_size, num_timesteps, num_atoms, num_dims]
# single_timestep_rel_type has shape:
# [batch_size, num_timesteps, num_atoms*(num_atoms-1), num_edge_types]
# Node2edge
# size of [batchsize, no. of particles (N), N(N-1), no. of phase space components (x,y,vx,vy, sigma)]
receivers = torch.matmul(rel_rec, single_timestep_inputs)
senders = torch.matmul(rel_send, single_timestep_inputs)
# size of [batchsize, no. of particles (N), N(N-1), 2 * no. of phase space components (x,y,vx,vy, sigma)], concatinates the components [x_i||x_j]
pre_msg = torch.cat([receivers, senders], dim=-1)
# size of [batchsize, no. of particles (N), N(N-1), no. of hidden layers]
all_msgs = Variable(torch.zeros(pre_msg.size(0), pre_msg.size(1),
pre_msg.size(2), self.msg_out_shape))
if single_timestep_inputs.is_cuda:
all_msgs = all_msgs.cuda()
# non_null_idxs = list of indices of edge types which as non null (i.e. edges over which messages can be passed)
non_null_idxs = list(range(self.edge_types))
if self.skip_first:
# if skip_first is True, the first edge type in each factor block is null
edge = 0
for k in self.edge_types_list:
non_null_idxs.remove(edge)
edge += k
# Run separate MLP for every edge type
# NOTE: To exlude one edge type, simply offset range by 1
# f^k_e
for i in non_null_idxs:
msg = F.relu(self.msg_fc1[i](pre_msg))
msg = F.dropout(msg, p=self.dropout_prob)
msg = F.relu(self.msg_fc2[i](msg))
msg = msg * single_timestep_rel_type[:, :, :, i:i + 1]
all_msgs += msg
# Aggregate all msgs to receiver
agg_msgs = all_msgs.transpose(-2, -1).matmul(rel_rec).transpose(-2, -1)
agg_msgs = agg_msgs.contiguous()
# Skip connection
aug_inputs = torch.cat([single_timestep_inputs, agg_msgs], dim=-1)
# Output MLP
pred = F.dropout(F.relu(self.out_fc1(aug_inputs)), p=self.dropout_prob)
pred = F.dropout(F.relu(self.out_fc2(pred)), p=self.dropout_prob)
pred = self.out_fc3(pred)
# Predict position/velocity difference
return single_timestep_inputs + pred, pred
def forward(self, inputs, rel_type, rel_rec, rel_send, sigma, sigmavariable, anisotropic, beta ,pred_steps=1):
# NOTE: Assumes that we have the same graph across all samples.
if sigmavariable:
# concatinate the sigma component to the tensor making each point have components (x,y,vx,vy,{sigma})
inputs = torch.cat((inputs,sigma), dim = 3)
inputs = inputs.transpose(1, 2).contiguous()
sizes = [rel_type.size(0), inputs.size(1), rel_type.size(1),
rel_type.size(2)]
rel_type = rel_type.unsqueeze(1).expand(sizes)
time_steps = inputs.size(1)
assert (pred_steps <= time_steps)
preds = []
accelerations = []
velocities = []
# Only take n-th timesteps as starting points (n: pred_steps)
last_pred = inputs[:, 0::pred_steps, :, :]
curr_rel_type = rel_type[:, 0::pred_steps, :, :]
# NOTE: Assumes rel_type is constant (i.e. same across all time steps).
# Run n prediction steps, gets last predictions and the changes in values- will be used to calculate the acceleration
for step in range(0, pred_steps):
last_pred, differences = self.single_step_forward(last_pred, rel_rec, rel_send,
curr_rel_type)
preds.append(last_pred)
# index = torch.LongTensor([2,3])
# index_vel = torch.LongTensor([0,1])
# if inputs.is_cuda:
# index, index_vel = index.cuda(), index_vel.cuda()
# acceleration = torch.index_select(differences, 3, index)
# accelerations.append(acceleration)
# velocity = torch.index_select(differences, 3, index_vel)
# velocities.append(velocity)
sizes = [preds[0].size(0), preds[0].size(1) * pred_steps,
preds[0].size(2), preds[0].size(3)]
# accsizes = [accelerations[0].size(0), accelerations[0].size(1) * pred_steps,
# accelerations[0].size(2), accelerations[0].size(3)]
#
# velsizes = [velocities[0].size(0), velocities[0].size(1) * pred_steps,
# velocities[0].size(2), velocities[0].size(3)]
output = Variable(torch.zeros(sizes))
# get acceleration direction in (x,y) basis
# acc = Variable(torch.zeros(accsizes))
# vel = Variable(torch.zeros(velsizes))
if inputs.is_cuda:
output = output.cuda()
# acc = acc.cuda()
# vel =vel.cuda()
# Re-assemble correct timeline
for i in range(len(preds)):
output[:, i::pred_steps, :, :] = preds[i]
# acc[:, i::pred_steps, :, :] = accelerations[i]
# vel[:, i::pred_steps, :, :] = velocities[i]'
# here will need to take out the new predicted sigma values from the tensor.
# t = time.time()
future = output[:,1:, :,:]
current = output[:,:output.size()[1]-1, :, :]
acc = future[:,:,:,2:4]- current[:,:,:,2:4]
vel = future[:,:,:,0:2]- current[:,:,:,0:2]
accelzero = torch.zeros(acc.size()[0], 1, acc.size()[2],acc.size()[3], dtype = torch.float)
velzero = torch.zeros(vel.size()[0], 1, vel.size()[2],vel.size()[3], dtype = torch.float)
if inputs.is_cuda:
accelzero, velzero = accelzero.cuda(), velzero.cuda()
# print('arraygenerationtime: {:.1f}s'.format(time.time() - t))
# t = time.time()
acc = torch.cat((accelzero, acc), dim = 1)
vel = torch.cat((velzero, vel), dim = 1)
# print('arrayconcattime: {:.1f}s'.format(time.time() - t))
pred_all = output[:, :(inputs.size(1) - 1), :, :]
accel = acc[:, :(inputs.size(1)-1), :, :]
velocity = vel[:, :(inputs.size(1) - 1), :, :]
indices = (torch.from_numpy(np.arange(4,list(pred_all.size())[3]))).type(torch.LongTensor)
if inputs.is_cuda:
indices = indices.cuda()
sigma_1 = torch.index_select(pred_all, 3, indices)
sigma_1 = sigma_1.transpose(1, 2).contiguous()
# sigma must be >=0 therefore use a softplus function to confine values to positive values
sigma_1 = softplus(sigma_1, beta)
indices = torch.tensor([0,1,2,3])
if inputs.is_cuda:
indices = indices.cuda()
pred_all = torch.index_select(pred_all, 3, indices)
else:
inputs = inputs.transpose(1, 2).contiguous()
sizes = [rel_type.size(0), inputs.size(1), rel_type.size(1),
rel_type.size(2)]
rel_type = rel_type.unsqueeze(1).expand(sizes)
time_steps = inputs.size(1)
assert (pred_steps <= time_steps)
preds = []
# Only take n-th timesteps as starting points (n: pred_steps)
last_pred = inputs[:, 0::pred_steps, :, :]
curr_rel_type = rel_type[:, 0::pred_steps, :, :]
# NOTE: Assumes rel_type is constant (i.e. same across all time steps).
# Run n prediction steps
for step in range(0, pred_steps):
last_pred, differences = self.single_step_forward(last_pred, rel_rec, rel_send,
curr_rel_type)
preds.append(last_pred)
sizes = [preds[0].size(0), preds[0].size(1) * pred_steps,
preds[0].size(2), preds[0].size(3)]
output = Variable(torch.zeros(sizes))
if inputs.is_cuda:
output = output.cuda()
# Re-assemble correct timeline
for i in range(len(preds)):
output[:, i::pred_steps, :, :] = preds[i]
# no need for accel here
accel = torch.ones(1,1,1)
velocity = torch.ones(1,1,1)
if inputs.is_cuda:
accel, velocity = accel.cuda(), velocity.cuda()
pred_all = output[:, :(inputs.size(1) - 1), :, :]
sigma_1 = sigma
return pred_all.transpose(1, 2).contiguous(), sigma_1, accel.transpose(1,2).contiguous(), velocity.transpose(1,2).contiguous()
# 3 layer decoder instead of 2
class MLPDecoder_multi_threelayers(nn.Module):
"""MLP decoder module."""
def __init__(self, n_in_node, edge_types, edge_types_list, msg_hid, msg_out, n_hid,
do_prob=0., skip_first=False, init_type='default'):
super(MLPDecoder_multi_threelayers, self).__init__()
self.msg_fc1 = nn.ModuleList(
[nn.Linear(2 * n_in_node, msg_hid) for _ in range(edge_types)])
self.msg_fc2 = nn.ModuleList(
[nn.Linear(msg_hid, msg_hid) for _ in range(edge_types)])
self.msg_fc3 = nn.ModuleList(
[nn.Linear(msg_hid, msg_out) for _ in range(edge_types)])
self.msg_out_shape = msg_out
self.skip_first = skip_first
self.edge_types = edge_types
self.edge_types_list = edge_types_list
self.out_fc1 = nn.Linear(n_in_node + msg_out, n_hid)
self.out_fc2 = nn.Linear(n_hid, n_hid)
self.out_fc3 = nn.Linear(n_hid,n_hid)
self.out_fc4 = nn.Linear(n_hid, n_in_node)
print('Using learned interaction net decoder.')
self.dropout_prob = do_prob
self.init_type = init_type
if self.init_type not in [ 'xavier_normal', 'orthogonal', 'default' ]:
raise ValueError('This initialization type has not been coded')
#print('Using '+self.init_type+' for decoder weight initialization')
if self.init_type != 'default':
self.init_weights()
def init_weights(self):
for m in self.modules():
if isinstance(m, nn.Linear):
if self.init_type == 'orthogonal':
nn.init.orthogonal_(m.weight.data,gain=0.000001)
elif self.init_type == 'xavier_normal':
nn.init.xavier_normal_(m.weight.data,gain=0.000001)
#m.bias.data.fill_(0.1)
def single_step_forward(self, single_timestep_inputs, rel_rec, rel_send,
single_timestep_rel_type):
# single_timestep_inputs has shape
# [batch_size, num_timesteps, num_atoms, num_dims]
# single_timestep_rel_type has shape:
# [batch_size, num_timesteps, num_atoms*(num_atoms-1), num_edge_types]
# Node2edge
# size of [batchsize, no. of particles (N), N(N-1), no. of phase space components (x,y,vx,vy, sigma)]
receivers = torch.matmul(rel_rec, single_timestep_inputs)
senders = torch.matmul(rel_send, single_timestep_inputs)
# size of [batchsize, no. of particles (N), N(N-1), 2 * no. of phase space components (x,y,vx,vy, sigma)], concatinates the components [x_i||x_j]
pre_msg = torch.cat([receivers, senders], dim=-1)
# size of [batchsize, no. of particles (N), N(N-1), no. of hidden layers]
all_msgs = Variable(torch.zeros(pre_msg.size(0), pre_msg.size(1),
pre_msg.size(2), self.msg_out_shape))
if single_timestep_inputs.is_cuda:
all_msgs = all_msgs.cuda()
# non_null_idxs = list of indices of edge types which as non null (i.e. edges over which messages can be passed)
non_null_idxs = list(range(self.edge_types))
if self.skip_first:
# if skip_first is True, the first edge type in each factor block is null
edge = 0
for k in self.edge_types_list:
non_null_idxs.remove(edge)
edge += k
# Run separate MLP for every edge type
# NOTE: To exlude one edge type, simply offset range by 1
# f^k_e
for i in non_null_idxs:
msg = F.relu(self.msg_fc1[i](pre_msg))
msg = F.dropout(msg, p=self.dropout_prob)
msg = F.relu(self.msg_fc2[i](msg))
msg = F.dropout(msg, p=self.dropout_prob)
msg = F.relu(self.msg_fc3[i](msg))
msg = msg * single_timestep_rel_type[:, :, :, i:i + 1]
all_msgs += msg
# Aggregate all msgs to receiver
agg_msgs = all_msgs.transpose(-2, -1).matmul(rel_rec).transpose(-2, -1)
agg_msgs = agg_msgs.contiguous()
# Skip connection
aug_inputs = torch.cat([single_timestep_inputs, agg_msgs], dim=-1)
# Output MLP
pred = F.dropout(F.relu(self.out_fc1(aug_inputs)), p=self.dropout_prob)
pred = F.dropout(F.relu(self.out_fc2(pred)), p=self.dropout_prob)
pred = F.dropout(F.relu(self.out_fc3(pred)), p=self.dropout_prob)
pred = self.out_fc4(pred)
# Predict position/velocity difference
return single_timestep_inputs + pred, pred
def forward(self, inputs, rel_type, rel_rec, rel_send, sigma, sigmavariable, anisotropic, beta ,pred_steps=1):
# NOTE: Assumes that we have the same graph across all samples.
if sigmavariable:
# concatinate the sigma component to the tensor making each point have components (x,y,vx,vy,{sigma})
inputs = torch.cat((inputs,sigma), dim = 3)
inputs = inputs.transpose(1, 2).contiguous()
sizes = [rel_type.size(0), inputs.size(1), rel_type.size(1),
rel_type.size(2)]
rel_type = rel_type.unsqueeze(1).expand(sizes)
time_steps = inputs.size(1)
assert (pred_steps <= time_steps)
preds = []
accelerations = []
velocities = []
# Only take n-th timesteps as starting points (n: pred_steps)
last_pred = inputs[:, 0::pred_steps, :, :]
curr_rel_type = rel_type[:, 0::pred_steps, :, :]
# NOTE: Assumes rel_type is constant (i.e. same across all time steps).
# Run n prediction steps, gets last predictions and the changes in values- will be used to calculate the acceleration
for step in range(0, pred_steps):
last_pred, differences = self.single_step_forward(last_pred, rel_rec, rel_send,
curr_rel_type)
preds.append(last_pred)
# index = torch.LongTensor([2,3])
# index_vel = torch.LongTensor([0,1])
# if inputs.is_cuda:
# index, index_vel = index.cuda(), index_vel.cuda()
# acceleration = torch.index_select(differences, 3, index)
# accelerations.append(acceleration)
# velocity = torch.index_select(differences, 3, index_vel)
# velocities.append(velocity)
sizes = [preds[0].size(0), preds[0].size(1) * pred_steps,
preds[0].size(2), preds[0].size(3)]
# accsizes = [accelerations[0].size(0), accelerations[0].size(1) * pred_steps,
# accelerations[0].size(2), accelerations[0].size(3)]
#
# velsizes = [velocities[0].size(0), velocities[0].size(1) * pred_steps,
# velocities[0].size(2), velocities[0].size(3)]
output = Variable(torch.zeros(sizes))
# get acceleration direction in (x,y) basis
# acc = Variable(torch.zeros(accsizes))
# vel = Variable(torch.zeros(velsizes))
if inputs.is_cuda:
output = output.cuda()
# acc = acc.cuda()
# vel =vel.cuda()
# Re-assemble correct timeline
for i in range(len(preds)):
output[:, i::pred_steps, :, :] = preds[i]
# acc[:, i::pred_steps, :, :] = accelerations[i]
# vel[:, i::pred_steps, :, :] = velocities[i]'
# here will need to take out the new predicted sigma values from the tensor.
# t = time.time()
future = output[:,1:, :,:]
current = output[:,:output.size()[1]-1, :, :]
acc = future[:,:,:,2:4]- current[:,:,:,2:4]
vel = future[:,:,:,0:2]- current[:,:,:,0:2]
accelzero = torch.zeros(acc.size()[0], 1, acc.size()[2],acc.size()[3], dtype = torch.float)
velzero = torch.zeros(vel.size()[0], 1, vel.size()[2],vel.size()[3], dtype = torch.float)
if inputs.is_cuda:
accelzero, velzero = accelzero.cuda(), velzero.cuda()
# print('arraygenerationtime: {:.1f}s'.format(time.time() - t))
# t = time.time()
acc = torch.cat((accelzero, acc), dim = 1)
vel = torch.cat((velzero, vel), dim = 1)
# print('arrayconcattime: {:.1f}s'.format(time.time() - t))
pred_all = output[:, :(inputs.size(1) - 1), :, :]
accel = acc[:, :(inputs.size(1)-1), :, :]
velocity = vel[:, :(inputs.size(1) - 1), :, :]
indices = (torch.from_numpy(np.arange(4,list(pred_all.size())[3]))).type(torch.LongTensor)
if inputs.is_cuda:
indices = indices.cuda()
sigma_1 = torch.index_select(pred_all, 3, indices)
sigma_1 = sigma_1.transpose(1, 2).contiguous()
# sigma must be >=0 therefore use a softplus function to confine values to positive values
sigma_1 = softplus(sigma_1, beta)
indices = torch.tensor([0,1,2,3])
if inputs.is_cuda:
indices = indices.cuda()
pred_all = torch.index_select(pred_all, 3, indices)
else:
inputs = inputs.transpose(1, 2).contiguous()
sizes = [rel_type.size(0), inputs.size(1), rel_type.size(1),
rel_type.size(2)]
rel_type = rel_type.unsqueeze(1).expand(sizes)
time_steps = inputs.size(1)
assert (pred_steps <= time_steps)
preds = []
# Only take n-th timesteps as starting points (n: pred_steps)
last_pred = inputs[:, 0::pred_steps, :, :]
curr_rel_type = rel_type[:, 0::pred_steps, :, :]
# NOTE: Assumes rel_type is constant (i.e. same across all time steps).
# Run n prediction steps
for step in range(0, pred_steps):
last_pred, differences = self.single_step_forward(last_pred, rel_rec, rel_send,
curr_rel_type)
preds.append(last_pred)
sizes = [preds[0].size(0), preds[0].size(1) * pred_steps,
preds[0].size(2), preds[0].size(3)]
output = Variable(torch.zeros(sizes))
if inputs.is_cuda:
output = output.cuda()
# Re-assemble correct timeline
for i in range(len(preds)):
output[:, i::pred_steps, :, :] = preds[i]
# no need for accel here
accel = torch.ones(1,1,1)
velocity = torch.ones(1,1,1)
if inputs.is_cuda:
accel, velocity = accel.cuda(), velocity.cuda()
pred_all = output[:, :(inputs.size(1) - 1), :, :]
sigma_1 = sigma
return pred_all.transpose(1, 2).contiguous(), sigma_1, accel.transpose(1,2).contiguous(), velocity.transpose(1,2).contiguous()
class MLPDecoder_multi_randomfeatures(nn.Module):
"""MLP decoder module.
With added random features as suggested in arXiv:2002.03155 [cs.LG] this could help with structural issues as
suggested in that paper"""
def __init__(self, n_in_node, edge_types, edge_types_list, msg_hid, msg_out, n_hid,
do_prob=0., skip_first=False, init_type='default'):
super(MLPDecoder_multi_randomfeatures, self).__init__()
self.msg_fc1 = nn.ModuleList(
[nn.Linear(2 * n_in_node, msg_hid) for _ in range(edge_types)])
self.msg_fc2 = nn.ModuleList(
[nn.Linear(msg_hid, msg_out) for _ in range(edge_types)])
self.msg_out_shape = msg_out
self.skip_first = skip_first
self.edge_types = edge_types
self.edge_types_list = edge_types_list
self.out_fc1 = nn.Linear(n_in_node + msg_out, n_hid)
self.out_fc2 = nn.Linear(n_hid, n_hid)
self.out_fc3 = nn.Linear(n_hid, n_in_node)
print('Using learned interaction net decoder.')
self.dropout_prob = do_prob
self.init_type = init_type
if self.init_type not in [ 'xavier_normal', 'orthogonal', 'default' ]:
raise ValueError('This initialization type has not been coded')
#print('Using '+self.init_type+' for decoder weight initialization')
if self.init_type != 'default':
self.init_weights()
def init_weights(self):
for m in self.modules():
if isinstance(m, nn.Linear):
if self.init_type == 'orthogonal':
nn.init.orthogonal_(m.weight.data,gain=0.000001)
elif self.init_type == 'xavier_normal':
nn.init.xavier_normal_(m.weight.data,gain=0.000001)
#m.bias.data.fill_(0.1)
def single_step_forward(self, single_timestep_inputs, rel_rec, rel_send,
single_timestep_rel_type):
# single_timestep_inputs has shape
# [batch_size, num_timesteps, num_atoms, num_dims]
# single_timestep_rel_type has shape:
# [batch_size, num_timesteps, num_atoms*(num_atoms-1), num_edge_types]
# Node2edge
# size of [batchsize, no. of particles (N), N(N-1), no. of phase space components (x,y,vx,vy, sigma)]
receivers = torch.matmul(rel_rec, single_timestep_inputs)
senders = torch.matmul(rel_send, single_timestep_inputs)
# size of [batchsize, no. of particles (N), N(N-1), 2 * no. of phase space components (x,y,vx,vy, sigma)], concatinates the components [x_i||x_j]
pre_msg = torch.cat([receivers, senders], dim=-1)
# size of [batchsize, no. of particles (N), N(N-1), no. of hidden layers]
all_msgs = Variable(torch.zeros(pre_msg.size(0), pre_msg.size(1),
pre_msg.size(2), self.msg_out_shape))
if single_timestep_inputs.is_cuda:
all_msgs = all_msgs.cuda()
# non_null_idxs = list of indices of edge types which as non null (i.e. edges over which messages can be passed)
non_null_idxs = list(range(self.edge_types))
if self.skip_first:
# if skip_first is True, the first edge type in each factor block is null
edge = 0
for k in self.edge_types_list:
non_null_idxs.remove(edge)
edge += k
# Run separate MLP for every edge type
# NOTE: To exlude one edge type, simply offset range by 1
# f^k_e
for i in non_null_idxs:
msg = F.relu(self.msg_fc1[i](pre_msg))
msg = F.dropout(msg, p=self.dropout_prob)
msg = F.relu(self.msg_fc2[i](msg))
msg = msg * single_timestep_rel_type[:, :, :, i:i + 1]
all_msgs += msg
# Aggregate all msgs to receiver
agg_msgs = all_msgs.transpose(-2, -1).matmul(rel_rec).transpose(-2, -1)
agg_msgs = agg_msgs.contiguous()
# Skip connection
aug_inputs = torch.cat([single_timestep_inputs, agg_msgs], dim=-1)
# Output MLP
pred = F.dropout(F.relu(self.out_fc1(aug_inputs)), p=self.dropout_prob)
pred = F.dropout(F.relu(self.out_fc2(pred)), p=self.dropout_prob)
pred = self.out_fc3(pred)
# Predict position/velocity difference
return single_timestep_inputs + pred, pred
def forward(self, inputs, rel_type, rel_rec, rel_send, sigma, sigmavariable, anisotropic, beta ,pred_steps=1):
# NOTE: Assumes that we have the same graph across all samples.
if sigmavariable:
# concatinate the sigma component to the tensor making each point have components (x,y,vx,vy,{sigma})
inputs = torch.cat((inputs,sigma), dim = 3)
#### generate and concatinate a random tensor to the inputs- this will act as the label of the nodes ####
#### from the arXiv:2002.03155 [cs.LG] paper we will implement Algorithm 1 using the normal dist ####
#### This will generate a rGIN as they suggested ####
random_feature_label = torch.normal(0,0.5,size=(sigma.size(0), sigma.size(1), sigma.size(2),1))
if inputs.is_cuda:
random_feature_label = random_feature_label.cuda()
inputs = torch.cat((inputs, random_feature_label), dim=3)
inputs = inputs.transpose(1, 2).contiguous()
sizes = [rel_type.size(0), inputs.size(1), rel_type.size(1),
rel_type.size(2)]
rel_type = rel_type.unsqueeze(1).expand(sizes)
time_steps = inputs.size(1)
assert (pred_steps <= time_steps)
preds = []
accelerations = []
velocities = []
# Only take n-th timesteps as starting points (n: pred_steps)
last_pred = inputs[:, 0::pred_steps, :, :]
curr_rel_type = rel_type[:, 0::pred_steps, :, :]
# NOTE: Assumes rel_type is constant (i.e. same across all time steps).
# Run n prediction steps, gets last predictions and the changes in values- will be used to calculate the acceleration
for step in range(0, pred_steps):
last_pred, differences = self.single_step_forward(last_pred, rel_rec, rel_send,
curr_rel_type)
preds.append(last_pred)
# index = torch.LongTensor([2,3])
# index_vel = torch.LongTensor([0,1])
# if inputs.is_cuda:
# index, index_vel = index.cuda(), index_vel.cuda()
# acceleration = torch.index_select(differences, 3, index)
# accelerations.append(acceleration)
# velocity = torch.index_select(differences, 3, index_vel)
# velocities.append(velocity)
sizes = [preds[0].size(0), preds[0].size(1) * pred_steps,
preds[0].size(2), preds[0].size(3)]
# accsizes = [accelerations[0].size(0), accelerations[0].size(1) * pred_steps,
# accelerations[0].size(2), accelerations[0].size(3)]
#
# velsizes = [velocities[0].size(0), velocities[0].size(1) * pred_steps,
# velocities[0].size(2), velocities[0].size(3)]
output = Variable(torch.zeros(sizes))
# get acceleration direction in (x,y) basis
# acc = Variable(torch.zeros(accsizes))
# vel = Variable(torch.zeros(velsizes))
if inputs.is_cuda:
output = output.cuda()
# acc = acc.cuda()
# vel =vel.cuda()
# Re-assemble correct timeline
for i in range(len(preds)):
output[:, i::pred_steps, :, :] = preds[i]
# acc[:, i::pred_steps, :, :] = accelerations[i]
# vel[:, i::pred_steps, :, :] = velocities[i]'
# here will need to take out the new predicted sigma values from the tensor.
# t = time.time()
future = output[:,1:, :,:]
current = output[:,:output.size()[1]-1, :, :]
acc = future[:,:,:,2:4]- current[:,:,:,2:4]
vel = future[:,:,:,0:2]- current[:,:,:,0:2]
accelzero = torch.zeros(acc.size()[0], 1, acc.size()[2],acc.size()[3], dtype = torch.float)
velzero = torch.zeros(vel.size()[0], 1, vel.size()[2],vel.size()[3], dtype = torch.float)
if inputs.is_cuda:
accelzero, velzero = accelzero.cuda(), velzero.cuda()
# print('arraygenerationtime: {:.1f}s'.format(time.time() - t))
# t = time.time()
acc = torch.cat((accelzero, acc), dim = 1)
vel = torch.cat((velzero, vel), dim = 1)
# print('arrayconcattime: {:.1f}s'.format(time.time() - t))
pred_all = output[:, :(inputs.size(1) - 1), :, :]
accel = acc[:, :(inputs.size(1)-1), :, :]
velocity = vel[:, :(inputs.size(1) - 1), :, :]
# the sigma here runs from 4 -> len-1th term -> last term is just the labels
indices = (torch.from_numpy(np.arange(4,list(pred_all.size())[3]-1))).type(torch.LongTensor)
if inputs.is_cuda:
indices = indices.cuda()
sigma_1 = torch.index_select(pred_all, 3, indices)
sigma_1 = sigma_1.transpose(1, 2).contiguous()
# sigma must be >=0 therefore use a softplus function to confine values to positive values
sigma_1 = softplus(sigma_1, beta)
indices = torch.tensor([0,1,2,3])
if inputs.is_cuda:
indices = indices.cuda()
pred_all = torch.index_select(pred_all, 3, indices)
else:
inputs = inputs.transpose(1, 2).contiguous()
sizes = [rel_type.size(0), inputs.size(1), rel_type.size(1),
rel_type.size(2)]
rel_type = rel_type.unsqueeze(1).expand(sizes)
time_steps = inputs.size(1)
assert (pred_steps <= time_steps)
preds = []
# Only take n-th timesteps as starting points (n: pred_steps)
last_pred = inputs[:, 0::pred_steps, :, :]
curr_rel_type = rel_type[:, 0::pred_steps, :, :]
# NOTE: Assumes rel_type is constant (i.e. same across all time steps).
# Run n prediction steps
for step in range(0, pred_steps):
last_pred, differences = self.single_step_forward(last_pred, rel_rec, rel_send,
curr_rel_type)
preds.append(last_pred)
sizes = [preds[0].size(0), preds[0].size(1) * pred_steps,
preds[0].size(2), preds[0].size(3)]
output = Variable(torch.zeros(sizes))
if inputs.is_cuda:
output = output.cuda()
# Re-assemble correct timeline
for i in range(len(preds)):
output[:, i::pred_steps, :, :] = preds[i]
# no need for accel here
accel = torch.ones(1,1,1)
velocity = torch.ones(1,1,1)
if inputs.is_cuda:
accel, velocity = accel.cuda(), velocity.cuda()
pred_all = output[:, :(inputs.size(1) - 1), :, :]
sigma_1 = sigma
return pred_all.transpose(1, 2).contiguous(), sigma_1, accel.transpose(1,2).contiguous(), velocity.transpose(1,2).contiguous()
class MLPDecoder_sigmoid(nn.Module):
"""MLP decoder module."""
def __init__(self, n_in_node, num_factors, msg_hid, msg_out, n_hid,
do_prob=0., skip_first=False, init_type='default'):
super(MLPDecoder_sigmoid, self).__init__()
self.msg_fc1 = nn.ModuleList(
[nn.Linear(2 * n_in_node, msg_hid) for _ in range(num_factors)])
self.msg_fc2 = nn.ModuleList(
[nn.Linear(msg_hid, msg_out) for _ in range(num_factors)])
self.msg_out_shape = msg_out
self.num_factors = num_factors
self.out_fc1 = nn.Linear(n_in_node + msg_out, n_hid)
self.out_fc2 = nn.Linear(n_hid, n_hid)
self.out_fc3 = nn.Linear(n_hid, n_in_node)
print('Using learned interaction net decoder.')
self.dropout_prob = do_prob
self.init_type = init_type
if self.init_type not in [ 'xavier_normal', 'orthogonal', 'default' ]:
raise ValueError('This initialization type has not been coded')
#print('Using '+self.init_type+' for decoder weight initialization')
if self.init_type != 'default':
self.init_weights()
def init_weights(self):
for m in self.modules():
if isinstance(m, nn.Linear):
if self.init_type == 'orthogonal':
nn.init.orthogonal_(m.weight.data,gain=0.000001)
elif self.init_type == 'xavier_normal':
nn.init.xavier_normal_(m.weight.data,gain=0.000001)
#m.bias.data.fill_(0.1)
def single_step_forward(self, single_timestep_inputs, rel_rec, rel_send,
single_timestep_rel_type):
# single_timestep_inputs has shape
# [batch_size, num_timesteps, num_atoms, num_dims]
# single_timestep_rel_type has shape:
# [batch_size, num_timesteps, num_atoms*(num_atoms-1), num_edge_types]
# Node2edge
receivers = torch.matmul(rel_rec, single_timestep_inputs)
senders = torch.matmul(rel_send, single_timestep_inputs)
pre_msg = torch.cat([receivers, senders], dim=-1)
all_msgs = Variable(torch.zeros(pre_msg.size(0), pre_msg.size(1),
pre_msg.size(2), self.msg_out_shape))
if single_timestep_inputs.is_cuda:
all_msgs = all_msgs.cuda()
# Run separate MLP for every edge type
# NOTE: To exlude one edge type, simply offset range by 1
for i in range(self.num_factors):
msg = F.relu(self.msg_fc1[i](pre_msg))
msg = F.dropout(msg, p=self.dropout_prob)
msg = F.relu(self.msg_fc2[i](msg))
msg = msg * single_timestep_rel_type[:, :, :, i:i + 1]
all_msgs += msg
# Aggregate all msgs to receiver
agg_msgs = all_msgs.transpose(-2, -1).matmul(rel_rec).transpose(-2, -1)
agg_msgs = agg_msgs.contiguous()
# Skip connection
aug_inputs = torch.cat([single_timestep_inputs, agg_msgs], dim=-1)
# Output MLP
pred = F.dropout(F.relu(self.out_fc1(aug_inputs)), p=self.dropout_prob)
pred = F.dropout(F.relu(self.out_fc2(pred)), p=self.dropout_prob)
pred = self.out_fc3(pred)
# Predict position/velocity difference
return single_timestep_inputs + pred
def forward(self, inputs, rel_type, rel_rec, rel_send, pred_steps=1):
# NOTE: Assumes that we have the same graph across all samples.
inputs = inputs.transpose(1, 2).contiguous()
sizes = [rel_type.size(0), inputs.size(1), rel_type.size(1),
rel_type.size(2)]
rel_type = rel_type.unsqueeze(1).expand(sizes)
time_steps = inputs.size(1)
assert (pred_steps <= time_steps)
preds = []
# Only take n-th timesteps as starting points (n: pred_steps)
last_pred = inputs[:, 0::pred_steps, :, :]
curr_rel_type = rel_type[:, 0::pred_steps, :, :]
# NOTE: Assumes rel_type is constant (i.e. same across all time steps).
# Run n prediction steps
for step in range(0, pred_steps):
last_pred = self.single_step_forward(last_pred, rel_rec, rel_send,
curr_rel_type)
preds.append(last_pred)
sizes = [preds[0].size(0), preds[0].size(1) * pred_steps,
preds[0].size(2), preds[0].size(3)]
output = Variable(torch.zeros(sizes))
if inputs.is_cuda:
output = output.cuda()
# Re-assemble correct timeline
for i in range(len(preds)):
output[:, i::pred_steps, :, :] = preds[i]
pred_all = output[:, :(inputs.size(1) - 1), :, :]
return pred_all.transpose(1, 2).contiguous()
class MLPEncoder_multi(nn.Module):
def __init__(self, n_in, n_hid, edge_types_list, do_prob=0., split_point=1,
init_type='xavier_normal', bias_init=0.0):
super(MLPEncoder_multi, self).__init__()
self.edge_types_list = edge_types_list
self.mlp1 = MLP(n_in, n_hid, n_hid, do_prob)
#print(self.mlp1.fc1.weight[0][0:5])
self.mlp2 = MLP(n_hid * 2, n_hid, n_hid, do_prob)
self.init_type = init_type
if self.init_type not in [ 'xavier_normal', 'orthogonal', 'sparse' ]:
raise ValueError('This initialization type has not been coded')
#print('Using '+self.init_type+' for encoder weight initialization')
self.bias_init = bias_init
self.split_point = split_point
if split_point == 0:
self.mlp3 = MLP(n_hid, n_hid, n_hid, do_prob)
self.mlp4 = MLP(n_hid * 3, n_hid, n_hid, do_prob)
self.fc_out = nn.ModuleList([nn.Linear(n_hid, sum(edge_types_list))])
elif split_point == 1:
self.mlp3 = MLP(n_hid, n_hid, n_hid, do_prob)
self.mlp4 = nn.ModuleList([MLP(n_hid * 3, n_hid, n_hid, do_prob) for _ in edge_types_list])
self.fc_out = nn.ModuleList([nn.Linear(n_hid, K) for K in edge_types_list])
elif split_point == 2:
self.mlp3 = nn.ModuleList([MLP(n_hid, n_hid, n_hid, do_prob) for _ in edge_types_list])
self.mlp4 = nn.ModuleList([MLP(n_hid * 3, n_hid, n_hid, do_prob) for _ in edge_types_list])
self.fc_out = nn.ModuleList([nn.Linear(n_hid, K) for K in edge_types_list])
else:
raise ValueError('Split point is not valid, must be 0, 1, or 2')
self.init_weights()
def init_weights(self):
for m in self.modules():
if isinstance(m, nn.Linear):
if self.init_type == 'orthogonal':
nn.init.orthogonal_(m.weight.data)
elif self.init_type == 'xavier_normal':
nn.init.xavier_normal_(m.weight.data)
elif self.init_type == 'sparse':
nn.init.sparse_(m.weight.data, sparsity=0.1)
if not math.isclose(self.bias_init, 0, rel_tol=1e-9):
m.bias.data.fill_(self.bias_init)
def edge2node(self, x, rel_rec, rel_send):
# NOTE: Assumes that we have the same graph across all samples.
incoming = torch.matmul(rel_rec.t(), x)
return incoming / incoming.size(1)
def node2edge(self, x, rel_rec, rel_send):
# NOTE: Assumes that we have the same graph across all samples.
receivers = torch.matmul(rel_rec, x)
senders = torch.matmul(rel_send, x)
edges = torch.cat([receivers, senders], dim=2)
return edges
def forward(self, inputs, rel_rec, rel_send):
# Input shape: [num_sims, num_atoms, num_timesteps, num_dims]
x = inputs.view(inputs.size(0), inputs.size(1), -1)
# New shape: [num_sims, num_atoms, num_timesteps*num_dims]
x = self.mlp1(x) # 2-layer ELU net per node
x = self.node2edge(x, rel_rec, rel_send)
x = self.mlp2(x)
x_skip = x
x = self.edge2node(x, rel_rec, rel_send)
if self.split_point == 0:
x = self.mlp3(x)
x = self.node2edge(x, rel_rec, rel_send)
x = torch.cat((x, x_skip), dim=2) # Skip connection
x = self.mlp4(x)
return self.fc_out[0](x)
elif self.split_point == 1:
x = self.mlp3(x)
x = self.node2edge(x, rel_rec, rel_send)
x = torch.cat((x, x_skip), dim=2) # Skip connection
y_list = []
for i in range(len(self.edge_types_list)):
y = self.mlp4[i](x)
y_list.append( self.fc_out[i](y) )
return torch.cat(y_list,dim=-1)
elif self.split_point == 2:
y_list = []
for i in range(len(self.edge_types_list)):
y = self.mlp3[i](x)
y = self.node2edge(y, rel_rec, rel_send)
y = torch.cat((y, x_skip), dim=2) # Skip connection
y = self.mlp4[i](y)
y_list.append( self.fc_out[i](y) )
return torch.cat(y_list,dim=-1)
class MLPEncoder_sigmoid(nn.Module):
def __init__(self, n_in, n_hid, num_factors, do_prob=0., split_point=1):
super(MLPEncoder_sigmoid, self).__init__()
self.num_factors = num_factors
self.mlp1 = MLP(n_in, n_hid, n_hid, do_prob)
self.mlp2 = MLP(n_hid * 2, n_hid, n_hid, do_prob)
self.mlp3 = MLP(n_hid, n_hid, n_hid, do_prob)
self.split_point = split_point
if split_point == 0:
self.mlp4 = MLP(n_hid * 3, n_hid, n_hid, do_prob)
self.fc_out = nn.Linear(n_hid, num_factors)
elif split_point == 1:
self.mlp4 = nn.ModuleList([MLP(n_hid * 3, n_hid, n_hid, do_prob) for _ in range(num_factors)])
self.fc_out = nn.ModuleList([nn.Linear(n_hid, 1) for i in range(num_factors)])
elif split_point == 2:
self.mlp3 = nn.ModuleList([MLP(n_hid, n_hid, n_hid, do_prob) for _ in range(num_factors)])
self.mlp4 = nn.ModuleList([MLP(n_hid * 3, n_hid, n_hid, do_prob) for _ in range(num_factors)])
self.fc_out = nn.ModuleList([nn.Linear(n_hid, 1) for i in range(num_factors)])
else:
raise ValueError('Split point is not valid, must be 0, 1, or 2')
self.init_weights()
def init_weights(self):
for m in self.modules():
if isinstance(m, nn.Linear):
nn.init.xavier_normal_(m.weight.data)
m.bias.data.fill_(0.1)
def edge2node(self, x, rel_rec, rel_send):
# NOTE: Assumes that we have the same graph across all samples.
incoming = torch.matmul(rel_rec.t(), x)
return incoming / incoming.size(1)
def node2edge(self, x, rel_rec, rel_send):
# NOTE: Assumes that we have the same graph across all samples.
receivers = torch.matmul(rel_rec, x)
senders = torch.matmul(rel_send, x)
edges = torch.cat([receivers, senders], dim=2)
return edges