-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.py
2441 lines (2155 loc) · 96.4 KB
/
utils.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
from collections import OrderedDict
from copy import deepcopy
from numbers import Number
import pdb
import torch
from torch.fft import fft
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
import os
import sys
from tqdm import tqdm
import matplotlib.pyplot as plt
import copy
import yaml
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 lcm, L2Loss, Attr_Dict, Printer
p = Printer(n_digits=6)
INVALID_VALUE = -200
PDE_PATH = "data/"
EXP_PATH = "./results/"
DESIGN_PATH = ".."
FNO_PATH = "fno_data/"
def flatten(tensor):
"""Flatten the tensor except the first dimension."""
return tensor.reshape(tensor.shape[0], -1)
def get_activation(act_name, inplace=False):
if act_name == "relu":
return nn.ReLU(inplace=inplace)
elif act_name == "linear":
return nn.Identity()
elif act_name == "leakyrelu":
return nn.LeakyReLU(inplace=inplace)
elif act_name == "leakyrelu0.2":
return nn.LeakyReLU(inplace=inplace, negative_slope=0.2)
elif act_name == "elu":
return nn.ELU(inplace=inplace)
elif act_name == "gelu":
return nn.GELU()
elif act_name == "softplus":
return nn.Softplus()
elif act_name == "exp":
return Exp()
elif act_name == "sine":
from siren_pytorch import Sine
return Sine()
elif act_name == "rational":
return Rational()
elif act_name == "sigmoid":
return nn.Sigmoid()
elif act_name == "tanh":
return nn.Tanh()
elif act_name == "celu":
return nn.CELU()
elif act_name == "silu":
return nn.SiLU()
elif act_name == "selu":
return nn.SELU()
elif act_name == "prelu":
return nn.PReLU()
elif act_name == "rrelu":
return nn.RReLU()
elif act_name == "mish":
return nn.Mish()
else:
raise Exception("act_name '{}' is not valid!".format(act_name))
class Apply_Activation(nn.Module):
def __init__(self, apply_act_idx, act_name="relu", dim=1):
super().__init__()
if isinstance(apply_act_idx, str):
apply_act_idx = [int(ele) for ele in apply_act_idx.split(",")]
self.apply_act_idx = apply_act_idx
self.act = get_activation(act_name)
self.dim = dim
def forward(self, input):
assert len(input.shape) >= 2 # []
out = []
for i in range(input.shape[self.dim]):
if i in self.apply_act_idx:
if self.dim == 1:
out.append(self.act(input[:,i]))
elif self.dim == 2:
out.append(self.act(input[:,:,i]))
else:
raise
else:
if self.dim == 1:
out.append(input[:,i])
elif self.dim == 2:
out.append(input[:,:,i])
else:
raise
return torch.stack(out, self.dim)
def get_LCM_input_shape(input_shape):
input_shape_dict = dict(input_shape)
key_max = None
shape_len_max = -np.Inf
for key, shape in input_shape_dict.items():
if len(shape) > shape_len_max:
key_max = key
shape_len_max = len(shape)
return input_shape_dict[key_max]
def expand_same_shape(x_list, input_shape_LCM):
pos_dim_max = len(input_shape_LCM)
x_expand_list = []
for x in x_list:
shape = x.shape
if len(x.shape) < pos_dim_max + 2:
for i in range(pos_dim_max + 2 - len(x.shape)):
x = x.unsqueeze(2) # Here the field [B, C, X] is expanded to the full distribution [B, C, U, X]
x = x.expand(x.shape[:2] + input_shape_LCM)
x_expand_list.append(x)
else:
x_expand_list.append(x)
return x_expand_list
def get_data_next_step(
model,
data,
use_grads=True,
is_y_diff=False,
return_data=True,
forward_func_name=None,
is_rollout=False,
uncertainty_mode="None",
):
"""Apply the model to data and obtain the data at the next time step without grads.
Args:
data:
The returned data has features of
[computed_features [not containing grad], static_features, dyn_features]
The input data.node_feature does not contain the grads information.
if return_data is False, will only return pred.
if return_data is True, will also return the full data incorporating the prediction.
forward_func_name: if None, will use the model's own forward function. If a string, will use model.forward_func_name as the forward function.
is_rollout: if is_rollout=True, will stop gradient.
Returns:
pred: {key: [n_nodes, pred_steps, dyn_dims]}
"""
dyn_dims = dict(to_tuple_shape(data.dyn_dims)) # data.node_feature: [n_nodes, input_steps, static_dims + dyn_dims]
compute_func_dict = dict(to_tuple_shape(data.compute_func))
static_dims = {key: data.node_feature[key].shape[-1] - dyn_dims[key] - compute_func_dict[key][0] for key in data.node_feature}
# Compute pred:
# After this application, the data.node_feature may append the grads information at the left:
if is_rollout:
with torch.no_grad():
if forward_func_name is None:
pred, info = model(data, use_grads=use_grads, uncertainty_mode=uncertainty_mode) # pred: [n_nodes, pred_steps, dyn_dims]
else:
pred, info = getattr(model, forward_func_name)(data, use_grads=use_grads, uncertainty_mode=uncertainty_mode) # pred: [n_nodes, pred_steps, dyn_dims]
else:
if forward_func_name is None:
pred, info = model(data, use_grads=use_grads, uncertainty_mode=uncertainty_mode) # pred: [n_nodes, pred_steps, dyn_dims]
else:
pred, info = getattr(model, forward_func_name)(data, use_grads=use_grads, uncertainty_mode=uncertainty_mode) # pred: [n_nodes, pred_steps, dyn_dims]
if not return_data:
return None, pred, info
# Update data:
for key in pred:
compute_dims = compute_func_dict[key][0]
dynamic_features = pred[key]
if uncertainty_mode != "None" and len(uncertainty_mode.split("^")) > 1 and uncertainty_mode.split("^")[1] == "samplefull":
dynamic_features = dynamic_features + info["preds_ls"][key].exp() * torch.randn_like(info["preds_ls"][key])
if is_y_diff:
dynamic_features = dynamic_features + data.node_feature[key][..., -dyn_dims[key]:]
# Append the computed node features:
# [computed + static + dynamic]
input_steps = data.node_feature[key].shape[-2]
if input_steps > 1:
dynamic_features = torch.cat([data.node_feature[key][...,-dyn_dims[key]:], dynamic_features], -2)[...,-input_steps:,:]
static_features = data.node_feature[key][..., -static_dims[key]-dyn_dims[key]:-dyn_dims[key]]
# The returned data will not contain grad information:
if compute_dims > 0:
compute_features = compute_func_dict[key][1](dynamic_features)
node_features = torch.cat([compute_features, static_features, dynamic_features], -1)
else:
node_features = torch.cat([static_features, dynamic_features], -1)
data.node_feature[key] = node_features
return data, pred, info
def get_loss_ar(
model,
data,
multi_step,
use_grads=True,
is_y_diff=False,
loss_type="mse",
**kwargs
):
"""Get auto-regressive loss for multiple steps."""
multi_step_dict = parse_multi_step(multi_step)
if len(multi_step_dict) == 1 and next(iter(multi_step_dict)) == 1:
# Single-step prediction:
pred, _ = model(data, use_grads=use_grads)
loss = loss_op(pred, data.node_label, mask=data.mask, y_idx=0, loss_type=loss_type, **kwargs)
else:
# Multi-step prediction:
max_step = max(list(multi_step_dict.keys()))
loss = 0
dyn_dims = dict(to_tuple_shape(data.dyn_dims))
for i in range(1, max_step + 1):
if i != max_step:
data, _ = get_data_next_step(model, data, use_grads=use_grads, is_y_diff=is_y_diff, return_data=True)
if i in multi_step_dict:
pred_new = {key: item[..., -dyn_dims[key]:] for key, item in data.node_feature.items()}
else:
_, pred_new = get_data_next_step(model, data, use_grads=use_grads, is_y_diff=is_y_diff, return_data=False)
if i in multi_step_dict:
loss_i = loss_op(pred_new, data.node_label, data.mask, y_idx=i-1, loss_type=loss_type, **kwargs)
loss = loss + loss_i * multi_step_dict[i]
return loss
def get_precision_floor(loss_type):
"""Get precision_floor from loss_type, if mselog, huberlog or l1 is inside loss_type. Otherwise return None"""
precision_floor = None
if loss_type is not None and ("mselog" in loss_type or "huberlog" in loss_type or "l1log" in loss_type):
string_all = loss_type.split("+")
for string in string_all:
if "mselog" in string or "huberlog" in string or "l1log" in string:
precision_floor = eval(string.split("#")[1])
break
return precision_floor
def loss_op(
pred,
y,
mask=None,
pred_idx=None,
y_idx=None,
dyn_dims=None,
loss_type="mse",
keys=None,
reduction="mean",
time_step_weights=None,
normalize_mode="None",
is_y_variable_length=False,
preds_ls=None,
**kwargs
):
"""Compute loss.
Args:
pred: shape [n_nodes, pred_steps, features]
y: shape [n_nodes, out_steps, dyn_dims]
mask: shape [n_nodes]
pred_idx: range(0, pred_steps)
y_idx: range(0, out_steps)
dyn_dims: dictionary of {key: number of dynamic dimensions}. If not None, will get loss from pred[..., -dyn_dims:].
loss_type: choose from "mse", "huber", "l1" and "dl", or use e.g. "0:huber^1:mse" for {"0": "huber", "1": "mse"}.
if "+" in loss_type, the loss will be the sum of multiple loss components added together.
E.g., if loss_type == '0:mse^2:mse+l1log#1e-3', then the loss is
{"0": mse, "2": mse_loss + l1log loss}
keys: if not None, will only go through the keys provided. If None, will use the keys in "pred".
time_step_weights: if not None but an array, will weight each time step by some coefficients.
reduction: choose from "mean", "sum", "none" and "mean-dyn" (mean on the loss except on the last dyn_dims dimension).
normalize_mode: choose from "target", "targetindi", "None". If "target", will divide the loss by the global norm of the target.
if "targetindi", will divide the each individual loss by the individual norm of the target example.
Default "None" will not normalize.
**kwargs: additional kwargs for loss function.
Returns:
loss: loss.
"""
# Make pred and y both dictionary:
if (not isinstance(pred, dict)) and (not isinstance(y, dict)):
pred = {"key": pred}
y = {"key": y}
if mask is not None:
mask = {"key": mask}
if keys is None:
keys = list(pred.keys())
# Individual loss components:
loss = 0
if time_step_weights is not None:
assert len(time_step_weights.shape) == 1
reduction_core = "none"
else:
if reduction == "mean-dyn":
# Will perform mean on the loss except on the last dyn_dims dimension:
reduction_core = "none"
else:
reduction_core = reduction
if is_y_variable_length and loss_type != "lp":
reduction_core = "none"
if "^" in loss_type:
# Different loss for different keys:
loss_type_dict = parse_loss_type(loss_type)
else:
loss_type_dict = {key: loss_type for key in keys}
# Compute loss
for key in keys:
# Specify which time step do we want to use from y:
# y has shape of [n_nodes, output_steps, dyn_dims]
if pred[key] is None:
# Due to latent level turning off:
assert y[key] is None
continue
elif isinstance(pred[key], list) and len(pred[key]) == 0:
# The multi_step="" or latent_multi_step="":
continue
if pred_idx is not None:
if not isinstance(pred_idx, list):
pred_idx = [pred_idx]
pred_core = pred[key][..., pred_idx, :]
if preds_ls is not None:
preds_ls_core = preds_ls[key][..., pred_idx, :]
else:
preds_ls_core = None
else:
pred_core = pred[key]
if preds_ls is not None:
preds_ls_core = preds_ls[key]
else:
preds_ls_core = None
if y_idx is not None:
if not isinstance(y_idx, list):
y_idx = [y_idx]
y_core = y[key][..., y_idx, :]
else:
y_core = y[key]
# y_core: [n_nodes, output_steps, dyn_dims]
if is_y_variable_length:
is_nan_full = (y_core == INVALID_VALUE).view(kwargs["batch_size"], -1, *y_core.shape[-2:]) # [batch_size, n_nodes_per_batch, output_steps, dyn_dims]
n_nodes_per_batch = is_nan_full.shape[1]
is_not_nan_batch = ~is_nan_full.any(1).any(-1) # [batch_size, output_steps]
if is_not_nan_batch.sum() == 0:
continue
is_not_nan_batch = is_not_nan_batch[:,None,:].expand(kwargs["batch_size"], n_nodes_per_batch, is_not_nan_batch.shape[-1]) # [batch_size, n_nodes_per_batch, output_steps]
is_not_nan_batch = is_not_nan_batch.reshape(-1, is_not_nan_batch.shape[-1]) # [n_nodes, output_steps]
if loss_type == "lp":
kwargs["is_not_nan_batch"] = is_not_nan_batch[..., None] # [n_nodes, output_steps, 1]
else:
is_not_nan_batch = None
if dyn_dims is not None:
y_core = y_core[..., -dyn_dims[key]:]
if mask is not None:
pred_core = pred_core[mask[key]] # [n_nodes, pred_steps, dyn_dims]
y_core = y_core[mask[key]] # [n_nodes, output_steps, dyn_dims]
if preds_ls is not None:
preds_ls_core = preds_ls_core[mask[key]]
# Compute loss:
loss_i = loss_op_core(pred_core, y_core, reduction=reduction_core, loss_type=loss_type_dict[key], normalize_mode=normalize_mode, preds_ls_core=preds_ls_core, **kwargs)
if time_step_weights is not None:
shape = loss_i.shape
assert len(shape) >= 3 # [:, time_steps, ...]
time_step_weights = time_step_weights[None, :]
for i in range(len(shape) - 2):
time_step_weights = time_step_weights.unsqueeze(-1) # [:, time_steps, [1, ...]]
loss_i = loss_i * time_step_weights
if is_y_variable_length and is_not_nan_batch is not None:
loss_i = loss_i[is_not_nan_batch]
if reduction == "mean-dyn":
assert len(shape) == 3
loss_i = loss_i.mean((0,1))
else:
loss_i = reduce_tensor(loss_i, reduction)
elif is_y_variable_length and is_not_nan_batch is not None and loss_type != "lp":
loss_i = loss_i[is_not_nan_batch]
loss_i = reduce_tensor(loss_i, reduction)
else:
if reduction == "mean-dyn":
assert len(loss_i.shape) == 3
loss_i = loss_i.mean((0,1)) # [dyn_dims,]
if loss_type == "rmse":
loss_i = loss_i.sqrt()
loss = loss + loss_i
return loss
def reduce_tensor(tensor, reduction, dims_to_reduce=None, keepdims=False):
"""Reduce tensor using 'mean' or 'sum'."""
if reduction == "mean":
if dims_to_reduce is None:
tensor = tensor.mean()
else:
tensor = tensor.mean(dims_to_reduce, keepdims=keepdims)
elif reduction == "sum":
if dims_to_reduce is None:
tensor = tensor.sum()
else:
tensor = tensor.sum(dims_to_reduce, keepdims=keepdims)
elif reduction == "none":
pass
else:
raise
return tensor
def loss_op_core(pred_core, y_core, reduction="mean", loss_type="mse", normalize_mode="None", zero_weight=1, preds_ls_core=None, **kwargs):
"""Compute the loss. Here pred_core and y_core must both be tensors and have the same shape.
Generically they have the shape of [n_nodes, pred_steps, dyn_dims].
For hybrid loss_type, e.g. "mse+huberlog#1e-3", will recursively call itself.
"""
if "+" in loss_type:
loss_list = []
precision_floor = get_precision_floor(loss_type)
for loss_component in loss_type.split("+"):
loss_component_coef = eval(loss_component.split(":")[1]) if len(loss_component.split(":")) > 1 else 1
loss_component = loss_component.split(":")[0] if len(loss_component.split(":")) > 1 else loss_component
if precision_floor is not None and not ("mselog" in loss_component or "huberlog" in loss_component or "l1log" in loss_component):
pred_core_new = torch.exp(pred_core) - precision_floor
else:
pred_core_new = pred_core
loss_ele = loss_op_core(
pred_core=pred_core_new,
y_core=y_core,
reduction=reduction,
loss_type=loss_component,
normalize_mode=normalize_mode,
zero_weight=zero_weight,
preds_ls_core=preds_ls_core,
**kwargs
) * loss_component_coef
loss_list.append(loss_ele)
loss = torch.stack(loss_list).sum(dim=0)
return loss
if normalize_mode != "None":
assert normalize_mode in ["targetindi", "target"]
dims_to_reduce = list(np.arange(2, len(y_core.shape))) # [2, ...]
epsilon_latent_loss = kwargs["epsilon_latent_loss"] if "epsilon_latent_loss" in kwargs else 0
if normalize_mode == "target":
dims_to_reduce.insert(0, 0) # [0, 2, ...]
if loss_type.lower() in ["mse", "rmse"]:
if normalize_mode in ["target", "targetindi"]:
loss = F.mse_loss(pred_core, y_core, reduction='none')
loss = (loss + epsilon_latent_loss) / (reduce_tensor(y_core.square(), "mean", dims_to_reduce, keepdims=True) + epsilon_latent_loss)
loss = reduce_tensor(loss, reduction=reduction)
else:
if zero_weight == 1:
if preds_ls_core is None:
loss = F.mse_loss(pred_core, y_core, reduction=reduction)
else:
loss_tensor = ((pred_core - y_core) / preds_ls_core.exp().clip(min=1e-5)).square() + preds_ls_core * 2
loss = reduce_tensor(loss_tensor, reduction=reduction)
else:
loss_inter = F.mse_loss(pred_core, y_core, reduction="none")
zero_mask = y_core.abs() < 1e-8
nonzero_mask = ~zero_mask
loss = loss_inter * nonzero_mask + loss_inter * zero_mask * zero_weight
loss = reduce_tensor(loss, reduction=reduction)
elif loss_type.lower() == "huber":
if normalize_mode in ["target", "targetindi"]:
loss = F.smooth_l1_loss(pred_core, y_core, reduction='none')
loss = (loss + epsilon_latent_loss) / (reduce_tensor(y_core.abs(), "mean", dims_to_reduce, keepdims=True) + epsilon_latent_loss)
loss = reduce_tensor(loss, reduction=reduction)
else:
if zero_weight == 1:
if preds_ls_core is None:
loss = F.smooth_l1_loss(pred_core, y_core, reduction=reduction)
else:
loss = F.smooth_l1_loss((pred_core - y_core) / preds_ls_core.exp().clip(min=1e-5), torch.zeros_like(y_core), reduction=reduction) + reduce_tensor(preds_ls_core, reduction=reduction)
else:
loss_inter = F.smooth_l1_loss(pred_core, y_core, reduction="none")
zero_mask = y_core.abs() < 1e-6
nonzero_mask = ~zero_mask
loss = loss_inter * nonzero_mask + loss_inter * zero_mask * zero_weight
loss = reduce_tensor(loss, reduction)
elif loss_type.lower() == "l1":
if normalize_mode in ["target", "targetindi"]:
loss = F.l1_loss(pred_core, y_core, reduction='none')
loss = (loss + epsilon_latent_loss) / (reduce_tensor(y_core.abs(), "mean", dims_to_reduce, keepdims=True) + epsilon_latent_loss)
loss = reduce_tensor(loss, reduction)
else:
if zero_weight == 1:
if preds_ls_core is None:
loss = F.l1_loss(pred_core, y_core, reduction=reduction)
else:
loss_tensor = (pred_core - y_core).abs() / preds_ls_core.exp().clip(min=1e-5) + preds_ls_core
loss = reduce_tensor(loss_tensor, reduction=reduction)
else:
loss_inter = F.l1_loss(pred_core, y_core, reduction="none")
zero_mask = y_core.abs() < 1e-6
nonzero_mask = ~zero_mask
loss = loss_inter * nonzero_mask + loss_inter * zero_mask * zero_weight
loss = reduce_tensor(loss, reduction)
elif loss_type.lower() == "l2":
first_dim = kwargs["first_dim"] if "first_dim" in kwargs else 2
if normalize_mode in ["target", "targetindi"]:
loss = L2Loss(reduction='none', first_dim=first_dim)(pred_core, y_core)
y_L2 = L2Loss(reduction='none', first_dim=first_dim)(torch.zeros_like(y_core), y_core)
if normalize_mode == "target":
y_L2 = y_L2.mean(0, keepdims=True)
loss = loss / y_L2
loss = reduce_tensor(loss, reduction)
else:
if zero_weight == 1:
loss = L2Loss(reduction=reduction, first_dim=first_dim)(pred_core, y_core)
else:
loss_inter = L2Loss(reduction="none", first_dim=first_dim)(pred_core, y_core)
zero_mask = y_core.abs() < 1e-6
nonzero_mask = ~zero_mask
loss = loss_inter * nonzero_mask + loss_inter * zero_mask * zero_weight
loss = reduce_tensor(loss, reduction)
elif loss_type.lower() == "lp":
assert normalize_mode not in ["target", "targetindi"]
assert zero_weight == 1
batch_size = kwargs["batch_size"]
pred_core_reshape = pred_core.reshape(batch_size, -1) # [B, -1]
y_core_reshape = y_core.reshape(batch_size, -1) # [B, -1]
loss = LpLoss(reduction=True, size_average=True if reduction=="mean" else False)(pred_core_reshape, y_core_reshape, mask=kwargs["is_not_nan_batch"] if "is_not_nan_batch" in kwargs else None)
elif loss_type.lower().startswith("mpe"):
exponent = eval(loss_type.split("-")[1])
if normalize_mode in ["target", "targetindi"]:
loss = (pred_core - y_core).abs() ** exponent
loss = (loss + epsilon_latent_loss) / (reduce_tensor(y_core.abs() ** exponent, "mean", dims_to_reduce, keepdims=True) + epsilon_latent_loss)
loss = reduce_tensor(loss, reduction)
else:
if zero_weight == 1:
if preds_ls_core is None:
loss = reduce_tensor((pred_core - y_core).abs() ** exponent, reduction=reduction)
else:
loss_tensor = ((pred_core - y_core)/preds_ls_core.exp()).abs() ** exponent + preds_ls_core
loss = reduce_tensor(loss_tensor, reduction=reduction)
else:
loss_inter = (pred_core - y_core).abs() ** exponent
zero_mask = y_core.abs() < 1e-8
nonzero_mask = ~zero_mask
loss = loss_inter * nonzero_mask + loss_inter * zero_mask * zero_weight
loss = reduce_tensor(loss, reduction)
elif loss_type.lower() == "dl":
if zero_weight == 1:
loss = DLLoss(pred_core, y_core, reduction=reduction, **kwargs)
else:
loss_inter = DLLoss(pred_core, y_core, reduction="none", **kwargs)
zero_mask = y_core.abs() < 1e-6
nonzero_mask = ~zero_mask
loss = loss_inter * nonzero_mask + loss_inter * zero_mask * zero_weight
loss = reduce_tensor(loss, reduction)
# loss where the target is taking the log scale:
elif loss_type.lower().startswith("mselog"):
precision_floor = eval(loss_type.split("#")[1])
loss = F.mse_loss(pred_core, torch.log(y_core + precision_floor), reduction=reduction)
elif loss_type.lower().startswith("huberlog"):
precision_floor = eval(loss_type.split("#")[1])
loss = F.smooth_l1_loss(pred_core, torch.log(y_core + precision_floor), reduction=reduction)
elif loss_type.lower().startswith("l1log"):
precision_floor = eval(loss_type.split("#")[1])
loss = F.l1_loss(pred_core, torch.log(y_core + precision_floor), reduction=reduction)
else:
raise Exception("loss_type {} is not valid!".format(loss_type))
return loss
def loss_hybrid(
preds,
node_label,
mask,
node_pos_label,
input_shape,
pred_idx=None,
y_idx=None,
dyn_dims=None,
loss_type="mse",
part_keys=None,
reduction="mean",
**kwargs
):
"""Compute the loss at particle locations using by interpolating the values at the field grid.
Args:
preds: {key: [n_nodes, pred_steps, dyn_dims]}
node_label: {key: [n_nodes, output_steps, [static_dims + compute_dims] + dyn_dims]}
mask: {key: [n_nodes]}
node_pos_label: {key: [n_nodes, output_steps, pos_dims]}. Both used to obtain the pos_grid, and also compute the loss for the density.
input_shape: a tuple of the actual grid shape.
pred_idx: index for the pred_steps in preds
y_idx: index for the output_steps in node_label
dyn_dims: the last dyn_dims to obtain from node_label. If None, use full node_label.
loss_type: loss_type.
part_keys: keys for particle node types.
reduction: choose from "mean", "sum" and "none".
**kwargs: additional kwargs for loss_core.
Returns:
if reduction is 'none':
loss_dict = {"density": {key: loss_matrix with shape [B, n_grid, dyn_dims]}, "feature": {key: loss_matrix}}
else:
loss_dict = {"density": loss_density, "feature": loss_feature}
"""
grid_key = None
for key in node_pos_label:
if key not in part_keys:
grid_key = key
assert grid_key is not None
pos_dims = len(input_shape)
pos_grid = node_pos_label[grid_key][:, y_idx].reshape(-1, *input_shape, pos_dims) # [B, n_grid, pos_dims]
batch_size = pos_grid.shape[0]
n_grid = pos_grid.shape[1]
pos_dict = {}
for dim in range(pos_grid.shape[-1]):
pos_dict[dim] = {"pos_min": pos_grid[..., dim].min(),
"pos_max": pos_grid[..., dim].max()}
loss_dict = {"density": {}, "feature": {}}
for key in part_keys:
# Obtain the index information for each position dimension:
pos_part = node_pos_label[key][:, pred_idx].reshape(batch_size, -1, pos_dims) # [B, n_part, pos_dims]
n_part = pos_part.shape[1]
idx_dict = {}
for dim in range(pos_dims):
# idx_dict records the left index and remainder for each pos_part[..., dim] (with shape of [B, n_part]):
idx_left, idx_remainder = get_idx_rel(pos_part[..., dim], pos_dict[dim]["pos_min"], pos_dict[dim]["pos_max"], n_grid)
idx_dict[dim] = {}
idx_dict[dim]["idx_left"] = idx_left
idx_dict[dim]["idx_remainder"] = idx_remainder
# density_grid_logit, prection of the density logit at each location, shape [B, prod([pos_dims])]
density_grid_logit = preds[key][:, pred_idx, 0].reshape(batch_size, -1)
density_grid_logprob = F.log_softmax(density_grid_logit, dim=-1) # [B, prod([pos_dims])]
if pos_dims == 1:
dim = 0
# Density loss. density_part_logprob: [B, n_part]:
density_part_logprob = torch.gather(density_grid_logprob, dim=1, index=idx_dict[dim]["idx_left"]) * (1 - idx_dict[dim]["idx_remainder"]) + \
torch.gather(density_grid_logprob, dim=1, index=idx_dict[dim]["idx_left"]+1) * idx_dict[dim]["idx_remainder"]
loss_dict["density"][key] = -density_part_logprob.mean()
# Field value loss:
if dyn_dims is not None:
node_label_core = node_label[key][:, y_idx, -dyn_dims[key]:].reshape(batch_size, n_part, dyn_dims[key]) # [B, n_part, dyn_dims]
else:
node_label_core = node_label[key][:, y_idx].reshape(batch_size, n_part, -1) # [B, n_part, dyn_dims]
feature_size = node_label_core.shape[-1]
node_feature_pred_grid = preds[key][:, pred_idx, 1:].reshape(batch_size, n_grid, feature_size) # [B, n_grid, feature_size]
idx_left = idx_dict[dim]["idx_left"][...,None].expand(batch_size, n_part, feature_size)
# node_feature_pred_part: [B, n_part, feature_size]:
node_feature_pred_part = torch.gather(node_feature_pred_grid, dim=1, index=idx_left) * (1 - idx_dict[dim]["idx_remainder"])[..., None] + \
torch.gather(node_feature_pred_grid, dim=1, index=idx_left+1) * idx_dict[dim]["idx_remainder"][..., None]
loss_dict["feature"][key] = loss_op_core(node_feature_pred_part, node_label_core, reduction=reduction, loss_type=loss_type, **kwargs)
else:
raise Exception("Currently only supports pos_dims=1!")
if reduction != "none":
for mode in ["density", "feature"]:
if reduction == "mean":
loss_dict[mode] = torch.stack(list(loss_dict[mode].values())).mean()
elif reduction == "sum":
loss_dict[mode] = torch.stack(list(loss_dict[mode].values())).sum()
else:
raise
return loss_dict
def get_idx_rel(pos, pos_min, pos_max, n_grid):
"""
Obtain the left index on the grid as well as the relative distance to the left index.
Args:
pos: any tensor
pos_min, pos_max: position of the left and right end of the grid
n_grid: number of grid vertices
Returns:
idx_left: the left index. The pos is within [left_index, left_index + 1). Same shape as pos.
idx_remainder: distance to the left index (in index space). Same shape as pos.
"""
idx_real = (pos - pos_min) / (pos_max - pos_min) * (n_grid - 1)
idx_left = idx_real.long()
idx_remainder = idx_real - idx_left
return idx_left, idx_remainder
def DLLoss(pred, y, reduction="mean", quantile=0.5):
"""Compute the Description Length (DL) loss, according to AI Physicist (Wu and Tegmark, 2019)."""
diff = pred - y
if quantile == 0.5:
precision_floor = diff.abs().median().item() + 1e-10
else:
precision_floor = diff.abs().quantile(quantile).item() + 1e-10
loss = torch.log(1 + (diff / precision_floor) ** 2)
if reduction == "mean":
loss = loss.mean()
elif reduction == "sum":
loss = loss.sum()
elif reduction == "none":
pass
else:
raise Exception("Reduction can only choose from 'mean', 'sum' and 'none'.")
return loss
def to_cpu(state_dict):
state_dict_cpu = {}
for k, v in state_dict.items():
state_dict_cpu[k] = v.cpu()
return state_dict_cpu
def get_root_dir():
dirname = os.getcwd()
dirname_split = dirname.split("/")
index = dirname_split.index("le_pde_uq")
dirname = "/".join(dirname_split[:index + 1])
return dirname
def to_tuple_shape(item):
"""Transform [tuple] or tuple into tuple."""
if isinstance(item, list) or isinstance(item, torch.Tensor):
item = item[0]
assert isinstance(item, tuple) or isinstance(item, Number) or isinstance(item, torch.Tensor) or isinstance(item, str) or isinstance(item, bool)
return item
def parse_multi_step(string):
"""
Parse multi-step prediction setting from string to multi_step_dict.
Args:
string: default "1", meaning only 1 step MSE. "1^2:1e-2^4:1e-3" means loss has 1, 2, 4 steps, with the number after ":" being the scale.'
Returns:
multi_step_dict: E.g. {1: 1, 2: 1e-2, 4: 1e-3} for string="1^2:1e-2^4:1e-3".
"""
if string == "":
return {}
multi_step_dict = {}
if "^" in string:
string_split = string.split("^")
else:
string_split = string.split("$")
for item in string_split:
item_split = item.split(":")
time_step = eval(item_split[0])
multi_step_dict[time_step] = eval(item_split[1]) if len(item_split) == 2 else 1
multi_step_dict = OrderedDict(sorted(multi_step_dict.items()))
return multi_step_dict
def parse_act_name(string):
"""
Parse act_name_dict from string.
Returns:
act_name_dict: E.g. {"1": "softplus", "2": "elu"} for string="1:softplus^2:elu".
"""
act_name_dict = {}
string_split = string.split("^")
for item in string_split:
item_split = item.split(":")
assert len(item_split) == 2
time_step = item_split[0]
act_name_dict[time_step] = item_split[1]
return act_name_dict
def parse_loss_type(string):
"""
Parse loss_type_dict from string.
Returns:
loss_type_dict: E.g.
string == "1:mse^2:huber" => loss_type_dict = {"1": "mse", "2": "huber"} for .
string == '0:mse^2:mse+l1log#1e-3' => loss_type_dict = {"0": mse, "2": "mse+l1log#1e-3"}
"""
loss_type_dict = {}
string_split = string.split("^")
for item in string_split:
item_split = item.split(":")
assert len(item_split) == 2
key = item_split[0]
loss_type_dict[key] = item_split[1]
return loss_type_dict
def parse_hybrid_targets(hybrid_targets, default_value=1.):
"""
Example: M:0.1^xu
"""
if hybrid_targets == "all":
hybrid_target_dict = {key: 1 for key in ["M", "MNT", "xu", "J", "field", "full"]}
elif isinstance(hybrid_targets, str):
hybrid_target_dict = {}
for item in hybrid_targets.split("^"):
hybrid_target_dict[item.split(":")[0]] = eval(item.split(":")[1]) if len(item.split(":")) > 1 else default_value
else:
raise
return hybrid_target_dict
def parse_reg_type(reg_type):
"""Parse reg_type and returns reg_type_core and reg_target.
reg_type has the format of f"{reg-type}[-{model-target}]^..." as splited by "^"
where {reg-type} chooses from "srank", "spectral", "Jsim" (Jacobian simplicity), "l2", "l1".
The optional {model-target} chooses from "all" or "evo" (only effective for Contrastive).
If not appearing, default "all". The "Jsim" only targets "evo".
"""
reg_type_list = []
for reg_type_ele in reg_type.split("^"):
reg_type_split = reg_type_ele.split("-")
reg_type_core = reg_type_split[0]
if len(reg_type_split) == 1:
reg_target = "all"
else:
assert len(reg_type_split) == 2
reg_target = reg_type_split[1]
if reg_type_core == "Jsim":
assert len(reg_type_split) == 1 or reg_target == "evo"
reg_target = "evo"
elif reg_type_core == "None":
reg_target = "None"
reg_type_list.append((reg_type_core, reg_target))
return reg_type_list
def get_cholesky_inverse(scale_tril_logit, size):
"""Get the cholesky-inverse from the lower triangular matrix.
Args:
scale_tril_logit: has shape of [B, n_components, size*(size+1)/2]. It should be a logit
where the diagonal element will be passed into softplus.
size: dimension of the matrix.
Returns:
cholesky_inverse: has shape of [B, n_components, size, size]
"""
n_components = scale_tril_logit.shape[-2]
scale_tril = fill_triangular(scale_tril_logit.view(-1, scale_tril_logit.shape[-1]), dim=size)
scale_tril = matrix_diag_transform(scale_tril, F.softplus)
cholesky_inverse = torch.stack([torch.cholesky_inverse(matrix) for matrix in scale_tril]).reshape(-1, n_components, size, size)
return cholesky_inverse, scale_tril.reshape(-1, n_components, size, size)
class Rational(torch.nn.Module):
"""Rational Activation function.
Implementation provided by Mario Casado (https://github.com/Lezcano)
It follows:
`f(x) = P(x) / Q(x),
where the coefficients of P and Q are initialized to the best rational
approximation of degree (3,2) to the ReLU function
# Reference
- [Rational neural networks](https://arxiv.org/abs/2004.01902)
"""
def __init__(self):
super().__init__()
self.coeffs = torch.nn.Parameter(torch.Tensor(4, 2))
self.reset_parameters()
def reset_parameters(self):
self.coeffs.data = torch.Tensor([[1.1915, 0.0],
[1.5957, 2.383],
[0.5, 0.0],
[0.0218, 1.0]])
def forward(self, input: torch.Tensor) -> torch.Tensor:
self.coeffs.data[0,1].zero_()
exp = torch.tensor([3., 2., 1., 0.], device=input.device, dtype=input.dtype)
X = torch.pow(input.unsqueeze(-1), exp)
PQ = X @ self.coeffs
output = torch.div(PQ[..., 0], PQ[..., 1])
return output
def get_device(args):
"""Initialize device."""
if len(args.gpuid.split(",")) > 1:
os.environ['CUDA_VISIBLE_DEVICES'] = args.gpuid # later retrieved to set gpuids
# https://discuss.pytorch.org/t/cuda-visible-device-is-of-no-use/10018/9
cuda_str = args.gpuid.split(",")[0] # first device
else:
cuda_str = args.gpuid
is_cuda = eval(cuda_str)
if not isinstance(is_cuda, bool):
is_cuda = "cuda:{}".format(is_cuda)
device = torch.device(is_cuda if isinstance(is_cuda, str) else "cuda" if is_cuda else "cpu")
return device
def get_normalization(normalization_type, n_channels, n_groups=2):
"""Get normalization layer."""
if normalization_type.lower() == "bn1d":
layer = nn.BatchNorm1d(n_channels)
elif normalization_type.lower() == "bn2d":
layer = nn.BatchNorm2d(n_channels)
elif normalization_type.lower() == "gn":
layer = nn.GroupNorm(num_groups=n_groups, num_channels=n_channels)
elif normalization_type.lower() == "ln":
layer = nn.LayerNorm(n_channels)
elif normalization_type.lower() == "none":
layer = nn.Identity()
else:
raise Exception("normalization_type '{}' is not valid!".format(normalization_type))
return layer
def get_max_pool(pos_dims, kernel_size):
if pos_dims == 1:
return nn.MaxPool1d(kernel_size=kernel_size)
elif pos_dims == 2:
return nn.MaxPool2d(kernel_size=kernel_size)
elif pos_dims == 3:
return nn.MaxPool3d(kernel_size=kernel_size)
else:
raise
def get_regularization(model_list, reg_type_core):
"""Get regularization.
Args:
reg_type_core, Choose from:
"None": no regularization
"l1": L1 regularization
"l2": L2 regularization
"nuc": nuclear regularization
"fro": Frobenius norm
"snr": spectral regularization
"snn": spectral normalization
"SINDy": L1 regularization on the coefficient of SINDy
"Hall": regularize all the elements of Hessian
"Hoff": regularize the off-diagonal elements of Hessian
"Hdiag": regularize the diagonal elements of Hessian
Returns:
reg: computed regularization.
"""
if reg_type_core in ["None", "snn"]:
return 0
else:
List = []
if reg_type_core in ["l1", "l2", "nuc", "fro"]:
for model in model_list:
for param_key, param in model.named_parameters():
if "weight" in param_key and param.requires_grad:
if reg_type_core in ["nuc", "fro"]:
norm = torch.norm(param, reg_type_core)
elif reg_type_core == "l1":
norm = param.abs().sum()
elif reg_type_core == "l2":
norm = param.square().sum()
else:
raise
List.append(norm)
elif reg_type_core == "snr":
for model in model_list:
for module in model.modules():
if module.__class__.__name__ == "SpectralNormReg" and hasattr(module, "snreg"):
List.append(module.snreg)
elif reg_type_core == "sindy":
for model in model_list:
for module in model.modules():
if module.__class__.__name__ == "SINDy":
List.append(module.weight.abs().sum())
elif reg_type_core in ["Hall", "Hoff", "Hdiag"]:
for model in model_list:
if hasattr(model, "Hreg"):
List.append(model.Hreg)
else:
raise Exception("reg_type_core {} is not valid!".format(reg_type_core))
if len(List) > 0:
reg = torch.stack(List).sum()
else:
reg = 0
return reg
def get_edge_index_kernel(pos_part, grid_pos, kernel_size, stride, padding, batch_size):
"""Get the edge index from particle to kernel indices.
Args:
pos_part: particle position [B, n_part]
grid_pos: [B, n_grid, steps, pos_dims]
"""
def get_index_pos(pos_part, pos_min, pos_max, n_grid):
"""Get the index position (index_pos) for each real position."""
index_pos = (pos_part - pos_min) / (pos_max - pos_min) * (n_grid - 1)
return index_pos