-
Notifications
You must be signed in to change notification settings - Fork 0
/
models.py
2963 lines (2755 loc) · 147 KB
/
models.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
# coding: utf-8
# In[ ]:
import datetime
import gc
import matplotlib.pylab as plt
from numbers import Number
import numpy as np
import pdb
import pickle
import random
import scipy
import time
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch import optim
from torch.autograd.functional import jvp
from torch.utils.data import DataLoader
from torch.optim import lr_scheduler
from torch_geometric.nn.inits import reset
import torch_geometric.nn as pyg_nn
import torch_geometric.utils as pyg_utils
import xarray as xr
from tqdm import tqdm
import matplotlib
from numba import jit
import math
import sys, os
sys.path.append(os.path.join(os.path.dirname("__file__"), '..'))
sys.path.append(os.path.join(os.path.dirname("__file__"), '..', '..'))
from le_pde_uq.pytorch_net.util import get_repeat_interleave, Printer, forward_Runge_Kutta, tuple_add, tuple_mul, clip_grad, Batch, make_dir, to_np_array, record_data, make_dir, ddeepcopy as deepcopy, filter_filename, Early_Stopping, str2bool, get_filename_short, print_banner, plot_matrices, to_string, init_args, get_poly_basis_tensor, get_num_params, get_pdict
from le_pde_uq.utils import sample_reward_beta, copy_data, fourier_encode_dist, requires_grad, endow_grads, process_data_for_CNN, get_regularization, get_batch_size
from le_pde_uq.utils import detach_data, get_model_dict, loss_op_core, MLP, MLP_Coupling, MLP_Attn, get_keys_values, flatten, get_elements, get_activation, to_cpu, to_tuple_shape, parse_multi_step, parse_act_name, parse_reg_type, loss_op, get_cholesky_inverse, get_normalization, get_edge_index_kernel, loss_hybrid, stack_tuple_elements, add_noise, get_neg_loss, get_pos_dims_dict
from le_pde_uq.utils import Channel_Gen, get_LCM_input_shape, expand_same_shape, SpectralNormReg
from le_pde_uq.utils import requires_grad, process_data_for_CNN, get_regularization, get_batch_size
from le_pde_uq.utils import detach_data, get_model_dict, loss_op_core, MLP, get_keys_values, flatten, get_elements, get_activation, to_cpu, to_tuple_shape, parse_multi_step, parse_act_name, parse_reg_type, loss_op, get_normalization, get_edge_index_kernel, stack_tuple_elements, add_noise, get_neg_loss, get_pos_dims_dict
from le_pde_uq.utils import p, seed_everything, is_diagnose, get_precision_floor, parse_string_idx_to_list, parse_loss_type, get_loss_ar, get_max_pool, get_data_next_step, get_LCM_input_shape, expand_same_shape, Sum, Mean, Channel_Gen, Flatten, Permute, Reshape, add_data_noise
from le_pde_uq.pytorch_net.util import Attr_Dict, set_seed, pdump, pload, get_time, check_same_model_dict, Zip, Interp1d_torch
from deepsnap.hetero_graph import HeteroGraph
from deepsnap.hetero_gnn import forward_op
from deepsnap.dataset import GraphDataset
from deepsnap.batch import Batch as deepsnap_Batch
from builtins import breakpoint
def get_conv_func(pos_dim, *args, **kwargs):
if "reg_type_list" in kwargs:
reg_type_list = kwargs.pop("reg_type_list")
else:
reg_type_list = None
if pos_dim == 2:
conv = nn.Conv2d(*args, **kwargs)
else:
raise Exception("The pos_dim can only be 1, 2 or 3!")
if reg_type_list is not None:
if "snn" in reg_type_list:
conv = SpectralNorm(conv)
elif "snr" in reg_type_list:
conv = SpectralNormReg(conv)
return conv
def get_conv_trans_func(pos_dim, *args, **kwargs):
if "reg_type_list" in kwargs:
reg_type_list = kwargs.pop("reg_type_list")
else:
reg_type_list = None
if pos_dim == 2:
conv_trans = nn.ConvTranspose2d(*args, **kwargs)
else:
raise Exception("The pos_dim can only be 1, 2 or 3!")
# The weight's output dim=1 for ConvTranspose
if reg_type_list is not None:
if "snn" in reg_type_list:
conv_trans = SpectralNorm(conv_trans, dim=1)
elif "snr" in reg_type_list:
conv_trans = SpectralNormReg(conv_trans, dim=1)
return conv_trans
class Contrastive(nn.Module):
def __init__(
self,
input_size,
output_size,
latent_size,
encoder_type,
evolution_type,
decoder_type,
input_shape,
grid_keys,
part_keys,
no_latent_evo=False,
temporal_bundle_steps=1,
forward_type="Euler",
channel_mode="exp-16",
kernel_size=4,
stride=2,
padding=1,
padding_mode="zeros",
output_padding_str="None",
encoder_mode="dense",
encoder_n_linear_layers=0,
act_name="rational",
decoder_last_act_name="linear",
is_pos_transform=False,
normalization_type="bn2d",
cnn_n_conv_layers=2,
is_latent_flatten=True,
reg_type="None",
n_conv_blocks=4,
n_latent_levs=1,
# Evolution_op specific:
n_conv_layers_latent=1,
evo_conv_type="cnn",
evo_pos_dims=-1,
evo_inte_dims=-1,
evo_groups=1,
loss_type=None,
static_latent_size=0,
static_encoder_type="None",
#static_axis=0,
static_input_size={"n0": 0},
decoder_act_name="None",
prioritized_dropout="None",
uncertainty_mode="None",
vae_mode="None",
):
super(Contrastive, self).__init__()
self.input_size = input_size
self.output_size = output_size
self.latent_size = latent_size
self.encoder_type = encoder_type
self.evolution_type = evolution_type
self.decoder_type = decoder_type
self.static_latent_size = static_latent_size
self.static_encoder_type = static_encoder_type
self.encoder_n_linear_layers = encoder_n_linear_layers
self.is_latent_flatten = is_latent_flatten
self.encoder_mode = encoder_mode
self.grid_keys = grid_keys
self.part_keys = part_keys
self.no_latent_evo = no_latent_evo
self.temporal_bundle_steps = temporal_bundle_steps
self.forward_type = forward_type
self.channel_mode = channel_mode
self.kernel_size = kernel_size
self.stride = stride
self.padding = padding
self.padding_mode = padding_mode
self.output_padding_str = output_padding_str
self.act_name = act_name
self.decoder_last_act_name = decoder_last_act_name
self.is_pos_transform = is_pos_transform
self.normalization_type = normalization_type
self.normalization_n_groups = 2
self.cnn_n_conv_layers = cnn_n_conv_layers
self.input_shape = input_shape
self.n_conv_blocks = n_conv_blocks
self.n_latent_levs = n_latent_levs
# Evolution_op specific:
self.n_conv_layers_latent = n_conv_layers_latent
self.evo_conv_type = evo_conv_type
self.evo_pos_dims = evo_pos_dims
self.evo_inte_dims = evo_inte_dims
self.evo_groups = evo_groups
self.loss_type = loss_type
self.static_input_size = static_input_size
self.decoder_act_name = decoder_act_name
self.prioritized_dropout = prioritized_dropout
self.uncertainty_mode = uncertainty_mode
self.vae_mode = vae_mode
if vae_mode != "None":
assert is_latent_flatten is True
if decoder_act_name is None or decoder_act_name == "None":
decoder_act_name = act_name
self.reg_type = reg_type
reg_type_list = parse_reg_type(self.reg_type)
encoder_list = []
if self.encoder_type == "cnn":
self.encoder = CNNEncoder(
in_channels=input_size,
out_channels=latent_size,
n_conv_layers=cnn_n_conv_layers,
encoder_mode=encoder_mode,
init_channel_number=32,
input_shape=input_shape,
act_name=act_name,
kernel_size=kernel_size,
padding_size=1,
padding_mode=padding_mode,
dilation_type="None",
dilation_base=2,
)
elif self.encoder_type == "cnn-s":
self.encoder = CNN_Encoder(
in_channels=input_size,
output_size=latent_size,
input_shape=input_shape,
grid_keys=grid_keys,
part_keys=part_keys,
channel_mode=channel_mode,
kernel_size=kernel_size,
stride=stride,
padding=padding,
padding_mode=padding_mode,
last_n_linear_layers=self.encoder_n_linear_layers,
act_name=act_name,
normalization_type=normalization_type,
n_conv_blocks=self.n_conv_blocks,
n_latent_levs=self.n_latent_levs,
is_latent_flatten=self.is_latent_flatten,
reg_type_list=[reg_type_core for reg_type_core, reg_target in reg_type_list if reg_target in ["all", "evoenc"]],
vae_mode=self.vae_mode,
)
elif self.encoder_type == "hybrid":
self.encoder = Hybrid(
input_size=input_size,
output_size=latent_size,
input_shape=input_shape,
grid_keys=grid_keys,
part_keys=part_keys,
channel_mode=self.channel_mode,
kernel_size=kernel_size,
stride=stride,
padding=padding,
padding_mode=padding_mode,
act_name=act_name,
normalization_type=normalization_type,
last_n_linear_layers=self.encoder_n_linear_layers,
n_conv_blocks=self.n_conv_blocks,
n_latent_levs=self.n_latent_levs,
is_latent_flatten=self.is_latent_flatten,
reg_type_list=[reg_type_core for reg_type_core, reg_target in reg_type_list if reg_target in ["all", "evoenc"]],
)
elif self.encoder_type == "cnn-VL":
self.encoder = Vlasov_Encoder(
input_size=input_size,
output_size=latent_size,
input_shape=input_shape,
n_conv_blocks=self.n_conv_blocks,
act_name=act_name,
normalization_type=self.normalization_type,
reg_type_list=[reg_type_core for reg_type_core, reg_target in reg_type_list if reg_target in ["all", "evoenc"]],
)
elif self.encoder_type.startswith("VL-u"):
self.encoder = Vlasov_U_Encoder(
model_type=encoder_type,
input_size=input_size,
output_size=latent_size,
input_shape=input_shape,
n_conv_blocks=self.n_conv_blocks,
padding_mode=padding_mode,
act_name=act_name,
normalization_type=self.normalization_type,
reg_type_list=[reg_type_core for reg_type_core, reg_target in reg_type_list if reg_target in ["all", "evoenc"]],
)
else:
raise Exception("encoder_type {} is not valid!".format(self.encoder_type))
if self.static_encoder_type == "cnn-s":
assert not (self.static_latent_size == 0 or self.static_input_size["n0"] == 0)
self.static_encoder = CNN_Encoder(
in_channels=static_input_size,
output_size=static_latent_size,
input_shape=input_shape,
grid_keys=grid_keys,
part_keys=part_keys,
channel_mode=channel_mode,
kernel_size=kernel_size,
stride=stride,
padding=padding,
padding_mode=padding_mode,
last_n_linear_layers=self.encoder_n_linear_layers,
act_name=act_name,
normalization_type=normalization_type,
n_conv_blocks=self.n_conv_blocks,
n_latent_levs=self.n_latent_levs,
is_latent_flatten=self.is_latent_flatten,
reg_type_list=[reg_type_core for reg_type_core, reg_target in reg_type_list if reg_target in ["all", "evoenc"]],
)
elif self.static_encoder_type.startswith("param"):
assert not (self.static_latent_size == 0 or self.static_input_size["n0"] == 0)
if len(static_encoder_type.split("-")) == 3:
string, static_encoder_n_layers, static_encoder_act_name = static_encoder_type.split("-")
else:
string, static_encoder_n_layers = static_encoder_type.split("-")
static_encoder_act_name = act_name
if static_encoder_n_layers == "expand":
self.static_encoder = None
else:
static_encoder_n_layers = int(static_encoder_n_layers)
if static_encoder_n_layers == 0:
if static_latent_size == static_input_size["n0"]:
self.static_encoder = nn.Identity()
else:
self.static_encoder = get_repeat_interleave(
input_size=static_input_size["n0"],
output_size=static_latent_size,
dim=-1,
)
else:
self.static_encoder = MLP(
input_size=static_input_size["n0"],
n_layers=static_encoder_n_layers,
n_neurons=static_latent_size,
output_size=static_latent_size,
act_name=static_encoder_act_name,
)
self.is_single_decoder = True
if self.uncertainty_mode != "None" and len(self.uncertainty_mode.split("^")) > 1 and (self.uncertainty_mode.split("^")[1].startswith("sub") or self.uncertainty_mode.split("^")[1].startswith("sep")):
self.decoder_latent_mean = int(self.uncertainty_mode.split("^")[1].split(":")[1])
self.decoder_latent_ls = latent_size - self.decoder_latent_mean
else:
self.decoder_latent_mean = latent_size
self.decoder_latent_ls = latent_size
self.latent_ordered_neuron = "None"
if self.uncertainty_mode != "None" and len(self.uncertainty_mode.split("^")) > 1 and self.uncertainty_mode.split("^")[1].startswith("sep"):
self.latent_ordered_neuron = "splitr:{}".format(self.decoder_latent_ls)
# Evolution operator:
self.evolution_op = Evolution_Op(
evolution_type=self.evolution_type,
latent_size=self.latent_size,
pos_dims=get_pos_dims_dict(self.input_shape),
normalization_type=self.normalization_type,
normalization_n_groups=self.normalization_n_groups,
n_latent_levs=self.n_latent_levs,
n_conv_layers_latent=self.n_conv_layers_latent,
evo_conv_type=self.evo_conv_type,
evo_pos_dims=self.evo_pos_dims,
evo_inte_dims=self.evo_inte_dims,
evo_groups=evo_groups,
channel_size_dict=self.encoder.channel_dict,
padding_mode=padding_mode,
act_name=self.act_name,
is_latent_flatten=is_latent_flatten,
reg_type_list=[reg_type_core for reg_type_core, reg_target in reg_type_list if reg_target in ["all", "evoenc", "evo"]],
static_latent_size=self.static_latent_size,
)
if self.evo_conv_type.startswith("VL-u"):
pass
# assert self.evolution_op.evolution_op1.model_version == self.encoder.model_version
if self.decoder_type.startswith("mixGau"):
Gaussian_mode = self.decoder_type.split("-")[1]
n_components = eval(self.decoder_type.split("-")[2])
self.decoder = Mixture_Gaussian_model(
latent_size=self.decoder_latent_mean,
output_size=output_size,
n_components=n_components,
Gaussian_mode=Gaussian_mode,
MLP_n_neurons=32,
MLP_n_layers=2,
act_name=act_name,
is_pos_transform=is_pos_transform,
)
elif self.decoder_type == "cnn-tr-hybrid":
self.decoder = CNN_Decoder_Hybrid(
latent_size=self.decoder_latent_mean,
latent_shape=self.encoder.latent_shape,
output_size=output_size,
output_shape=dict(input_shape),
fc_output_dim=self.encoder.flat_fts,
channel_mode=self.channel_mode,
kernel_size=kernel_size,
stride=stride,
padding=padding,
padding_mode="zeros",
act_name=act_name,
last_act_name=self.decoder_last_act_name,
normalization_type=normalization_type,
n_conv_blocks=self.n_conv_blocks,
n_latent_levs=self.n_latent_levs,
is_latent_flatten=self.is_latent_flatten,
reg_type_list=[reg_type_core for reg_type_core, reg_target in reg_type_list if reg_target in ["all", "evodec"]],
)
elif self.decoder_type == "cnn-tr-VL":
self.decoder = Vlasov_Decoder_Hybrid(
latent_size=self.decoder_latent_mean,
latent_shape=self.encoder.latent_shape,
output_size=output_size,
output_shape=dict(input_shape),
flat_sizes=self.encoder.flat_sizes,
conv_lat_sizes=self.encoder.conv_lat_sizes,
act_name=act_name,
normalization_type=self.normalization_type,
reg_type_list=[reg_type_core for reg_type_core, reg_target in reg_type_list if reg_target in ["all", "evodec"]],
)
elif self.decoder_type.startswith("VL-u"):
self.decoder = Vlasov_U_Decoder(
model_type=decoder_type,
latent_size=self.decoder_latent_mean,
latent_shape=self.encoder.latent_shape,
output_size=output_size,
output_shape=dict(input_shape),
fc_output_dim=self.encoder.flat_fts,
act_name=act_name,
normalization_type=self.normalization_type,
reg_type_list=[reg_type_core for reg_type_core, reg_target in reg_type_list if reg_target in ["all", "evodec"]],
)
elif self.decoder_type == "cnn-tr":
self.is_single_decoder = False
for key in output_size:
setattr(self, f"decoder_{key}", CNN_Decoder(
latent_size=self.decoder_latent_mean,
latent_shape=self.encoder.latent_shape,
output_size=output_size[key],
output_shape=dict(input_shape)[key if key in self.grid_keys else self.grid_keys[0]],
fc_output_dim=self.encoder.flat_fts,
temporal_bundle_steps=self.temporal_bundle_steps,
channel_mode=self.channel_mode,
kernel_size=kernel_size,
stride=stride,
padding=padding,
padding_mode="zeros",
output_padding_str=output_padding_str,
act_name=act_name,
normalization_type=normalization_type,
n_conv_blocks=self.n_conv_blocks,
n_latent_levs=self.n_latent_levs,
is_latent_flatten=self.is_latent_flatten,
reg_type_list=[reg_type_core for reg_type_core, reg_target in reg_type_list if reg_target in ["all", "evodec"]],
decoder_act_name=decoder_act_name,
uncertainty_mode=self.uncertainty_mode if self.uncertainty_mode in ["bayeslayer"] or self.uncertainty_mode.startswith("dropout") else "None",
))
if self.uncertainty_mode != "None" and self.uncertainty_mode not in ["bayeslayer"] and not self.uncertainty_mode.startswith("dropout"):
# predicts the log-scale (ls):
setattr(self, f"decoder_{key}_ls", CNN_Decoder(
latent_size=self.decoder_latent_ls,
latent_shape=self.encoder.latent_shape,
output_size=output_size[key],
output_shape=dict(input_shape)[key if key in self.grid_keys else self.grid_keys[0]],
fc_output_dim=self.encoder.flat_fts,
temporal_bundle_steps=self.temporal_bundle_steps,
channel_mode=self.channel_mode,
kernel_size=kernel_size,
stride=stride,
padding=padding,
padding_mode="zeros",
output_padding_str=output_padding_str,
act_name=act_name,
normalization_type=normalization_type,
n_conv_blocks=self.n_conv_blocks,
n_latent_levs=self.n_latent_levs,
is_latent_flatten=self.is_latent_flatten,
reg_type_list=[reg_type_core for reg_type_core, reg_target in reg_type_list if reg_target in ["all", "evodec"]],
decoder_act_name=decoder_act_name,
))
elif self.decoder_type.startswith("neural-basis"):
decoder_type_split = self.decoder_type.split("-")
coupling_mode = "concat" if len(decoder_type_split) == 2 else decoder_type_split[2]
freq_order = 6 if len(decoder_type_split) <= 3 else int(decoder_type_split[3])
n_layers = 4 if len(decoder_type_split) <= 4 else int(decoder_type_split[4])
is_z_x = False if len(decoder_type_split) <= 5 else eval(decoder_type_split[5])
assert self.is_latent_flatten == True
self.is_single_decoder = False
for key in output_size:
if decoder_act_name == "siren":
is_pos_encoding = False
else:
is_pos_encoding = True
setattr(self, f"decoder_{key}", NeuralBasis(
x_size=len(dict(input_shape)[key]),
z_size=self.decoder_latent_mean,
n_neurons=64,
n_layers=n_layers,
output_size=len(input_size),
act_name=decoder_act_name,
is_z_x=is_z_x,
is_pos_encoding=is_pos_encoding,
freq_order=freq_order,
is_freeze_basis=False,
coupling_mode=coupling_mode,
))
if self.uncertainty_mode != "None":
setattr(self, f"decoder_{key}_ls", NeuralBasis(
x_size=len(dict(input_shape)[key]),
z_size=self.decoder_latent_ls,
n_neurons=64,
n_layers=n_layers,
output_size=len(input_size),
act_name=decoder_act_name,
is_z_x=is_z_x,
is_pos_encoding=is_pos_encoding,
freq_order=freq_order,
is_freeze_basis=False,
coupling_mode=coupling_mode,
))
else:
raise Exception("decoder_type {} is not valid!".format(self.decoder_type))
def requires_grad(self, is_requires_grad, targets):
if not isinstance(targets, list):
targets = [targets]
for target in targets:
if target == "encoder":
requires_grad(self.encoder.parameters(), is_requires_grad)
elif target == "static-encoder":
if hasattr(self, "static_encoder"):
requires_grad(self.static_encoder.parameters(), is_requires_grad)
elif target == "evolution":
requires_grad(self.evolution_op.parameters(), is_requires_grad)
elif target == "decoder":
if hasattr(self, "decoder"):
requires_grad(self.decoder.parameters(), is_requires_grad)
else:
for key in self.output_size:
requires_grad(getattr(self, f"decoder_{key}").parameters(), is_requires_grad)
else:
raise
def set_input_shape(self, input_shape):
"""Update the input_shape."""
self.input_shape = input_shape
self.encoder.input_shape = input_shape
if self.is_single_decoder:
self.output_shape = dict(input_shape)
else:
for key in output_size:
getattr(self, f"decoder_{key}").output_shape = dict(input_shape)[key if key in self.grid_keys else self.grid_keys[0]]
def evolve_latent(self, latent):
"""Evolve latent using residual connection."""
if self.forward_type == "direct":
return self.evolution_op(latent)
elif self.forward_type == "Euler":
if self.static_encoder_type != "None":
out_latent = self.evolution_op(latent)
if isinstance(latent, tuple):
latent_dynamic = tuple(latent_ele[:,:out_latent[jj].shape[1]] if latent_ele is not None else None for jj, latent_ele in enumerate(latent))
out = tuple_add(latent_dynamic, out_latent)
else:
out = tuple_add(latent[:,:out_latent.shape[1]], out_latent)
else:
out = tuple_add(latent, self.evolution_op(latent))
return out
elif self.forward_type.startswith("RK"):
return forward_Runge_Kutta(self.evolution_op, latent, mode=self.forward_type)
else:
raise Exception("forward_type '{}' is not valid!".format(self.forward_type))
def get_latent_targets(self, data, latent_pred_steps, temporal_bundle_steps, use_grads=True, use_pos=False):
def get_future_data(data, k, temporal_bundle_steps):
"""Get the input data for the k'th step in the future.
If temporal_bundle_steps > 1, then each k will include {temporal_bundle_steps} number of steps
"""
dyn_dims_dict = dict(to_tuple_shape(data.dyn_dims))
compute_func_dict = dict(to_tuple_shape(data.compute_func))
static_dims_dict = {key: data.node_feature[key].shape[-1] - dyn_dims_dict[key] - compute_func_dict[key][0] for key in data.node_feature}
data_k = deepcopy(data)
for key in data.node_feature:
dynamic_input_list = []
input_steps_full = data.node_feature[key].shape[-2]
assert input_steps_full % temporal_bundle_steps == 0
input_steps_effective = input_steps_full // temporal_bundle_steps
y_idx_list = np.arange((k-1)*temporal_bundle_steps, k*temporal_bundle_steps).tolist()
dynamic_features = data.node_label[key][:, y_idx_list] # [n_nodes, temporal_bundle_steps, dyn_dims]
static_features = data.node_feature[key][:, -1:, -static_dims_dict[key]-dyn_dims_dict[key]:-dyn_dims_dict[key]] # [n_nodes, 1, static_dims]
if input_steps_full > 1:
static_features = static_features.expand(static_features.shape[0], input_steps_full, static_features.shape[-1]) # [n_nodes, args.input_steps*temporal_bundle_steps, static_dims]
dynamic_input_list.append(dynamic_features)
start_effective = k - input_steps_effective # k = 1, input_steps_effective = 2
start_effective_nonneg = max(0, k - input_steps_effective)
if k - 1 > 0:
start_effective_idx_list = np.arange(start_effective_nonneg * temporal_bundle_steps, (k-1)*temporal_bundle_steps).tolist()
prev_label_dynamic = data.node_label[key][:, start_effective_idx_list]
dynamic_input_list.insert(0, prev_label_dynamic)
if start_effective < 0:
prev_node_feature_idx = np.arange(start_effective * temporal_bundle_steps, 0).tolist()
prev_node_feature_dynamic = data.node_feature[key][:, prev_node_feature_idx, -dyn_dims_dict[key]:]
dynamic_input_list.insert(0, prev_node_feature_dynamic)
dynamic_input_list = torch.cat(dynamic_input_list, 1) # [n_nodes, input_steps*temporal_bundle_steps, dyn_dims]
compute_dims = compute_func_dict[key][0]
if compute_dims > 0:
compute_features = compute_func_dict[key][1](dynamic_input_list)
node_features = torch.cat([compute_features, static_features, dynamic_input_list], -1)
else:
node_features = torch.cat([static_features, dynamic_input_list], -1) # [n_nodes, temporal_bundle_steps, static_dims+dyn_dims]
data_k.node_feature[key] = node_features
return data_k
latent_targets = []
for k in range(1, max(latent_pred_steps + [0]) + 1):
data_k = get_future_data(data, k, temporal_bundle_steps=temporal_bundle_steps)
latent_target_k = self.encoder(data_k, use_grads=use_grads, use_pos=use_pos) # [B, latnet_size]
if self.vae_mode != "None":
latent_target_k = latent_target_k[0]
if k in latent_pred_steps:
latent_targets.append(latent_target_k) # [(z11, z12, ...), (z21, z22, ...)]
if len(latent_targets) > 0:
if not isinstance(latent_targets[0], tuple):
latent_targets = torch.stack(latent_targets, 1)
else:
latent_targets = stack_tuple_elements(latent_targets, 1) # [(z11, z12, ...), (z21, z22, ...)] -> (torch.stack([z11, z21, ...], 1), torch.stack([z12, z22, ...], 1))
return latent_targets
def get_reg(self, reg_type):
"""Get regularization."""
reg_type_list = parse_reg_type(reg_type)
reg_sum = 0
for reg_type_core, reg_target in reg_type_list:
if reg_type_core == "None":
reg = 0
else:
# Collect models:
model_list = []
if reg_target == "evo":
model_list.append(self.evolution_op)
elif reg_target == "all":
model_list += [self.evolution_op, self.encoder]
if self.is_single_decoder:
model_list.append(self.decoder)
else:
for key in self.output_size:
model_list.append(getattr(self, f"decoder_{key}"))
elif reg_target == "evoenc":
model_list += [self.evolution_op, self.encoder]
elif reg_target == "evodec":
model_list += [self.evolution_op]
if self.is_single_decoder:
model_list.append(self.decoder)
else:
for key in self.output_size:
model_list.append(getattr(self, f"decoder_{key}"))
else:
raise Exception("reg_target {} is not supported! Choose from 'evo' or 'all'.".format(reg_target))
# Get regularization:
reg = get_regularization(model_list, reg_type_core)
reg_sum = reg_sum + reg
return reg_sum
def forward_nolatent(
self,
data,
use_grads=True,
use_pos=False,
uncertainty_mode="None",
):
"""Make a forward step without latent evolution."""
# Encode:
latent = self.encoder(data, use_grads=use_grads, use_pos=use_pos) # [B, latent_size]
# Decode:
info = {}
if self.is_single_decoder:
if uncertainty_mode == "None":
pred = self.decoder(latent[...,-self.decoder_latent_mean:])
elif uncertainty_mode == "bayeslayer":
pred, info["preds_ls"] = self.decoder(latent[...,-self.decoder_latent_mean:])
else:
pred = self.decoder(latent[...,-self.decoder_latent_mean:])
info["preds_ls"] = self.decoder(latent[...,:self.decoder_latent_ls])
else:
if uncertainty_mode == "None":
pred = {key: getattr(self, f"decoder_{key}")(latent[...,-self.decoder_latent_mean:]) for key in self.output_size}
elif uncertainty_mode == "bayeslayer":
pred = {}
info["preds_ls"] = {}
for key in self.output_size:
pred[key], info["preds_ls"][key] = getattr(self, f"decoder_{key}")(latent[...,-self.decoder_latent_mean:])
else:
if isinstance(latent, tuple):
pred = {key: getattr(self, f"decoder_{key}")(tuple(ele[...,-self.decoder_latent_mean:] if ele is not None else None for ele in latent)) for key in self.output_size}
info["preds_ls"] = {key: getattr(self, f"decoder_{key}_ls")(tuple(ele[...,:self.decoder_latent_ls] if ele is not None else None for ele in latent)) for key in self.output_size}
else:
pred = {key: getattr(self, f"decoder_{key}")(latent[...,-self.decoder_latent_mean:]) for key in self.output_size}
info["preds_ls"] = {key: getattr(self, f"decoder_{key}_ls")(latent[...,:self.decoder_latent_ls]) for key in self.output_size}
return pred, info
def forward(
self,
data,
pred_steps=1,
latent_pred_steps=None,
is_recons=False,
use_grads=True,
is_y_diff=False,
reg_type="None",
use_pos=False,
latent_noise_amp=0,
is_rollout=False,
static_data=None,
is_multistep_detach=False,
):
def expand_static_latent(static_latent, latent):
if isinstance(latent, tuple):
return tuple(expand_static_latent(static_latent, latent_ele) if latent_ele is not None else None for latent_ele in latent)
for i in range(len(latent.shape) - len(static_latent.shape)):
static_latent = static_latent[...,None]
static_latent = static_latent.expand(*static_latent.shape[:2], *latent.shape[2:]) # [B, C, (H, W, ...)]
return static_latent
# Reshape x_pos:
info = {}
if not isinstance(pred_steps, list) and not isinstance(pred_steps, np.ndarray):
pred_steps = [pred_steps]
if latent_pred_steps is None:
latent_pred_steps = pred_steps
if not isinstance(latent_pred_steps, list) and not isinstance(latent_pred_steps, np.ndarray):
latent_pred_steps = [latent_pred_steps]
max_pred_step = max(pred_steps + [0])
max_latent_pred_step = max(latent_pred_steps + [0])
original_shape = dict(to_tuple_shape(data.original_shape))
n_pos = np.array(original_shape[self.grid_keys[0]]).prod()
if hasattr(data, "node_pos") and use_pos:
batch_size = data.node_feature[self.grid_keys[0]].shape[0] // n_pos
if isinstance(data.node_pos, dict):
node_pos_item = data.node_pos
else:
node_pos_item = data.node_pos[0][0] if isinstance(data.node_pos[0], list) or isinstance(data.node_pos[0], tuple) else data.node_pos[0]
x_pos = {key: node_pos_item[key].reshape(1, -1, len(original_shape[key if key in self.grid_keys else self.grid_keys[0]])).repeat_interleave(repeats=batch_size, dim=0).to(data.node_feature[key].device) for key in self.output_size} # [B, n_grid: prod(input_shape), pos_dim: len(input_shape)]
else:
x_pos = None
# Compute regularization:
info["reg"] = self.get_reg(reg_type)
# Compute loss:
if self.no_latent_evo:
if self.uncertainty_mode != "None":
info["preds_ls"] = {key: [] for key in self.output_size}
if len(pred_steps) == 1 and max_pred_step == 1:
# Single-step prediction:
preds, info_item = self.forward_nolatent(data, use_grads=use_grads, uncertainty_mode=self.uncertainty_mode)
if self.uncertainty_mode != "None":
for key in self.output_size:
info["preds_ls"][key] = info_item["preds_ls"][key]
else:
# Multi-step prediction:
dyn_dims = dict(to_tuple_shape(data.dyn_dims))
preds = {}
for k in range(1, max_pred_step + 1):
if is_multistep_detach:
data = detach_data(data)
if k != max_pred_step:
data, pred, info_item = get_data_next_step(self, data, forward_func_name="forward_nolatent", use_grads=use_grads, is_y_diff=is_y_diff, return_data=True, is_rollout=is_rollout, uncertainty_mode=self.uncertainty_mode)
else:
_, pred, info_item = get_data_next_step(self, data, forward_func_name="forward_nolatent",
use_grads=use_grads, is_y_diff=is_y_diff, return_data=False, is_rollout=is_rollout, uncertainty_mode=self.uncertainty_mode)
if k in pred_steps:
record_data(preds, list(pred.values()), list(pred.keys()))
if self.uncertainty_mode != "None":
for key in self.output_size:
info["preds_ls"][key].append(info_item["preds_ls"][key])
if len(preds) > 0:
for key in self.output_size:
preds[key] = torch.cat(preds[key], 1)
if self.uncertainty_mode != "None":
info["preds_ls"][key] = torch.cat(info["preds_ls"][key], 1)
else:
# Encode:
latent = self.encoder(data, use_grads=use_grads, use_pos=use_pos) # [B, latent_size]
if self.vae_mode != "None":
assert len(latent) == 2
info["latent_loc"] = latent[0]
info["latent_logscale"] = latent[1]
if self.training:
latent_recons = latent[0] + torch.exp(latent[1]) * torch.randn_like(latent[1])
else:
latent_recons = latent[0]
if self.vae_mode == "recons":
latent_forward = latent[0]
elif self.vae_mode == "recons+sample":
if self.training:
latent_forward = latent_recons
else:
latent_forward = latent[0]
else:
raise
else:
latent_recons = latent_forward = latent
if self.static_encoder_type != "None":
if self.static_encoder_type.startswith("param"):
if self.static_encoder_type.startswith("param-expand"):
static_latent = data.param["n0"]
static_latent = expand_static_latent(static_latent, latent_forward)
else:
if static_data is None:
static_data = data.param["n0"]
static_latent = self.static_encoder(static_data)
else:
static_latent = self.static_encoder(static_data)
else:
if static_data is None:
static_data = deepcopy(data)
static_dims = data.node_feature["n0"].shape[-1] - dict(to_tuple_shape(data.dyn_dims))["n0"] - dict(to_tuple_shape(data.compute_func))["n0"][0]
static_feature = data.node_feature["n0"][:,:,:static_dims]
static_data.node_feature["n0"] = static_feature
static_latent = self.static_encoder(static_data, use_grads=use_grads, use_pos=use_pos)
else:
static_latent = self.static_encoder(static_data, use_grads=use_grads, use_pos=use_pos)
info["latent"] = latent_forward
# Reconstruct:
if is_recons:
if hasattr(self, "decoder"):
recons = self.decoder(latent_recons[...,-self.decoder_latent_mean:])
if self.uncertainty_mode != "None":
recons_ls = self.decoder_ls(latent_recons[...,:self.decoder_latent_ls])
else:
if self.uncertainty_mode == "None" or self.uncertainty_mode.startswith("dropout"):
recons = {key: getattr(self, f"decoder_{key}")(latent_recons[...,-self.decoder_latent_mean:], x_pos=x_pos[key] if x_pos is not None else None) for key in self.output_size}
elif self.uncertainty_mode == "bayeslayer":
recons = {}
recons_ls = {}
for key in self.output_size:
recons[key], recons_ls[key] = getattr(self, f"decoder_{key}")(latent_recons[...,-self.decoder_latent_mean:], x_pos=x_pos[key] if x_pos is not None else None)
else:
recons = {key: getattr(self, f"decoder_{key}")(latent_recons[...,-self.decoder_latent_mean:], x_pos=x_pos[key] if x_pos is not None else None) for key in self.output_size}
recons_ls = {key: getattr(self, f"decoder_{key}_ls")(latent_recons[...,:self.decoder_latent_ls], x_pos=x_pos[key] if x_pos is not None else None) for key in self.output_size}
# Prediction:
info["latent_preds"] = []
preds = {key: [] for key in self.output_size}
if self.uncertainty_mode != "None" and not self.uncertainty_mode.startswith("dropout"):
info["preds_ls"] = {key: [] for key in self.output_size}
for k in range(1, max(max_pred_step, max_latent_pred_step) + 1):
if self.training and latent_noise_amp > 0:
latent_forward = add_noise(latent_forward, latent_noise_amp)
# latent: [B, latent_size]
if self.static_encoder_type != "None":
if self.n_latent_levs == 1:
latent_forward = torch.cat([latent_forward, static_latent], -1)
else:
latent_forward = tuple(torch.cat([latent_ele, static_latent_ele], 1) if latent_ele is not None else None for latent_ele, static_latent_ele in zip(latent_forward, static_latent))
# raise Exception("Boundary concatenation is not implemented for n_latent_levs > 1")
latent_forward = self.evolve_latent(latent_forward)
if k in latent_pred_steps:
info["latent_preds"].append(latent_forward)
if k in pred_steps:
if self.is_single_decoder:
if self.uncertainty_mode == "None" or self.uncertainty_mode.startswith("dropout"):
pred = self.decoder(latent_forward[...,-self.decoder_latent_mean:], x_pos=x_pos)
elif self.uncertainty_mode == "bayeslayer":
pred, info["preds_ls"] = self.decoder(latent_forward[...,-self.decoder_latent_mean:], x_pos=x_pos)
else:
pred = self.decoder(latent_forward[...,-self.decoder_latent_mean:], x_pos=x_pos)
info["preds_ls"] = self.decoder_ls(latent_forward[...,:self.decoder_latent_ls], x_pos=x_pos)
for key in self.output_size:
preds[key].append(pred[key])
else:
for key in self.output_size:
if self.uncertainty_mode == "None" or self.uncertainty_mode.startswith("dropout"):
preds[key].append(getattr(self, f"decoder_{key}")(latent_forward[...,-self.decoder_latent_mean:], x_pos=x_pos[key] if x_pos is not None else None))
elif self.uncertainty_mode == "bayeslayer":
pred, pred_ls = getattr(self, f"decoder_{key}")(latent_forward[...,-self.decoder_latent_mean:], x_pos=x_pos[key] if x_pos is not None else None)
preds[key].append(pred)
info["preds_ls"][key].append(pred_ls)
else:
preds[key].append(getattr(self, f"decoder_{key}")(latent_forward[...,-self.decoder_latent_mean:], x_pos=x_pos[key] if x_pos is not None else None))
info["preds_ls"][key].append(getattr(self, f"decoder_{key}_ls")(latent_forward[...,:self.decoder_latent_ls], x_pos=x_pos[key] if x_pos is not None else None))
for key in self.output_size:
if len(preds[key]) > 0:
preds[key] = torch.cat(preds[key], 1)
if self.uncertainty_mode != "None" and not self.uncertainty_mode.startswith("dropout"):
info["preds_ls"][key] = torch.cat(info["preds_ls"][key], 1)
if len(info["latent_preds"]) > 0:
if not isinstance(info["latent_preds"][0], tuple):
info["latent_preds"] = torch.stack(info["latent_preds"], 1) # [B, max_pred_steps, latent_size]
else:
info["latent_preds"] = stack_tuple_elements(info["latent_preds"], dim=1)
# Returns:
if is_recons:
info["recons"] = recons
if self.uncertainty_mode != "None" and not self.uncertainty_mode.startswith("dropout"):
info["recons_ls"] = recons_ls
if is_rollout:
"""Go to original representation."""
info["input"] = deepcopy(data.node_feature)
precision_floor = get_precision_floor(self.loss_type)
if self.loss_type is not None and precision_floor is not None:
preds_core = {}
if is_recons and "recons" in info:
recons_core = {}
for loss_type_key in self.loss_type.split("^"):
key = loss_type_key.split(":")[0]
if "mselog" in loss_type_key or "huberlog" in loss_type_key or "l1log" in loss_type_key:
if len(preds) > 0 and len(preds[key]) > 0:
preds_core[key] = torch.exp(preds[key]) - precision_floor
if is_recons and "recons" in info:
recons_core[key] = torch.exp(info["recons"][key]) - precision_floor
else:
if len(preds) > 0:
preds_core[key] = preds[key]
if is_recons and "recons" in info:
recons_core[key] = info["recons"][key]
preds = preds_core
if is_recons and "recons" in info:
info["recons"] = recons_core
return preds, info
def get_loss(self, data, args, is_rollout=False, **kwargs):
"""Get loss."""
# Make prediction:
if is_diagnose(loc="loss:0", filename=args.filename):
pdb.set_trace()
multi_step_dict = parse_multi_step(args.multi_step)
latent_multi_step_dict = parse_multi_step(args.latent_multi_step) if args.latent_multi_step is not None else multi_step_dict
if args.consistency_coef > 0 or args.contrastive_rel_coef > 0:
data_copy_cons = deepcopy(data)
self.info = {}
if args.loss_type == "lp" or args.is_y_variable_length:
original_shape = dict(to_tuple_shape(data.original_shape))
n_pos = np.array(original_shape[self.grid_keys[0]]).prod()
batch_size = data.node_feature[self.grid_keys[0]].shape[0] // n_pos
else:
batch_size = args.batch_size
if (not self.no_latent_evo) and (args.disc_coef > 0 or args.disc_coef == -1) and "discriminator" in kwargs:
"""Discriminator loss:"""
def get_time_step(latent, t):
if not isinstance(latent, tuple):
return latent[:, t]
else:
List = []
for element in latent:
if element is None:
List.append(None)
else:
List.append(element[:, t])
return tuple(List)
discriminator = kwargs["discriminator"]
if self.training:
opt = kwargs["opt"]
opt_disc = kwargs["opt_disc"]
loss_disc_latent_list = []
disc_t_list = parse_string_idx_to_list(args.disc_t, max_t=max(latent_multi_step_dict.keys()), is_inclusive=True) if args.disc_t != "None" else list(latent_multi_step_dict.keys())
assert len(disc_t_list) > 0, "args.disc_t must be within the scope of args.latent_multi_step!"
data_copy = deepcopy(data)
with torch.no_grad():
latent_targets = self.get_latent_targets(data_copy, disc_t_list, temporal_bundle_steps=args.temporal_bundle_steps, use_grads=args.use_grads, use_pos=args.use_pos) # [B, pred_steps, [latent_size]] or tuple(...)
_, disc_info = self(
data_copy,
pred_steps=[],
latent_pred_steps=disc_t_list,
is_recons=False,
use_grads=args.use_grads,
is_y_diff=args.is_y_diff,
use_pos=args.use_pos,
latent_noise_amp=args.latent_noise_amp,
reg_type=args.reg_type if args.reg_coef > 0 else "None",
)
for j in range(args.disc_iters):
if self.training:
opt.zero_grad()
opt_disc.zero_grad()
device = disc_info["latent"].device if not isinstance(disc_info["latent"], tuple) else disc_info["latent"][-1].device
t_chosen = np.random.choice(disc_t_list) if self.training else max(disc_t_list)
if args.disc_loss_type == 'hinge':
loss_disc_latent = nn.ReLU()(1.0 - discriminator(disc_info["latent"], get_time_step(latent_targets, t_chosen-1))).mean() + nn.ReLU()(1.0 + discriminator(disc_info["latent"], get_time_step(disc_info["latent_preds"], t_chosen-1))).mean()
elif args.disc_loss_type == 'wasserstein':
loss_disc_latent = -discriminator(disc_info["latent"], get_time_step(latent_targets, t_chosen-1)).mean() + discriminator(disc_info["latent"], get_time_step(disc_info["latent_preds"], t_chosen-1)).mean()
elif args.disc_loss_type == "bce":
disc_logit = discriminator(disc_info["latent"], get_time_step(latent_targets, t_chosen-1))
batch_size = disc_logit.shape[0]
loss_disc_latent = nn.BCEWithLogitsLoss()(disc_logit, torch.ones(batch_size, 1).to(device)) + nn.BCEWithLogitsLoss()(discriminator(disc_info["latent"], get_time_step(disc_info["latent_preds"], t_chosen-1)), torch.zeros(batch_size, 1).to(device))
else:
raise Exception("disc_loss_type '{}' is not valid!".format(args.disc_loss_type))
if self.training:
loss_disc_latent.backward()
opt_disc.step()
loss_disc_latent_list.append(to_np_array(loss_disc_latent))
self.info["loss_disc_latent"] = np.mean(loss_disc_latent_list)
if self.training:
opt.zero_grad()
opt_disc.zero_grad()
precision_floor_self = get_precision_floor(self.loss_type)
precision_floor_args = get_precision_floor(args.loss_type)
if precision_floor_self is not None and precision_floor_args is None:
is_rollout_core = is_rollout
else:
is_rollout_core = False
# Perform prediction:
preds, info = self(
data,
pred_steps=list(multi_step_dict.keys()),
latent_pred_steps=list(latent_multi_step_dict.keys()),
is_recons=True if args.recons_coef > 0 else False,