forked from NVIDIA/physicsnemo
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathlegacy.py
More file actions
1516 lines (1337 loc) · 48.4 KB
/
legacy.py
File metadata and controls
1516 lines (1337 loc) · 48.4 KB
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
# SPDX-FileCopyrightText: Copyright (c) 2023 - 2025 NVIDIA CORPORATION & AFFILIATES.
# SPDX-FileCopyrightText: All rights reserved.
# SPDX-License-Identifier: Apache-2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
Preconditioning schemes used in the paper"Elucidating the Design Space of
Diffusion-Based Generative Models".
"""
import importlib
import warnings
from dataclasses import dataclass
from typing import Any, List, Literal, Tuple, Union
import numpy as np
import torch
from physicsnemo.core.meta import ModelMetaData
from physicsnemo.core.module import Module
from physicsnemo.core.warnings import LegacyFeatureWarning
from ._utils import _wrapped_property
from .preconditioners import (
EDMPreconditioner,
IDDPMPreconditioner,
VEPreconditioner,
VPPreconditioner,
)
warnings.warn(
"The preconditioner classes 'VPPrecond', 'VEPrecond', 'iDDPMPrecond', "
"'EDMPrecond', 'EDMPrecondSuperResolution', 'EDMPrecondSR', 'VEPrecond_dfsr', "
"and 'VEPrecond_dfsr_cond' from 'physicsnemo.diffusion.preconditioners' are "
"legacy implementations that will be deprecated in a future release. Updated "
"implementations will be provided in an upcoming version.",
LegacyFeatureWarning,
stacklevel=2,
)
network_module = importlib.import_module("physicsnemo.models.diffusion_unets")
@dataclass
class VPPrecondMetaData(ModelMetaData):
"""VPPrecond meta data"""
# Optimization
jit: bool = False
cuda_graphs: bool = False
amp_cpu: bool = False
amp_gpu: bool = True
torch_fx: bool = False
# Data type
bf16: bool = False
# Inference
onnx: bool = False
# Physics informed
func_torch: bool = False
auto_grad: bool = False
class VPPrecond(VPPreconditioner):
"""
Preconditioning corresponding to the variance preserving (VP) formulation.
Parameters
----------
img_resolution : int
Image resolution.
img_channels : int
Number of color channels.
label_dim : int
Number of class labels, 0 = unconditional, by default 0.
use_fp16 : bool
Execute the underlying model at FP16 precision?, by default False.
beta_d : float
Extent of the noise level schedule, by default 19.9.
beta_min : float
Initial slope of the noise level schedule, by default 0.1.
M : int
Original number of timesteps in the DDPM formulation, by default 1000.
epsilon_t : float
Minimum t-value used during training, by default 1e-5.
model_type :str
Class name of the underlying model, by default "SongUNet".
**model_kwargs : dict
Keyword arguments for the underlying model.
Note
----
Reference: Song, Y., Sohl-Dickstein, J., Kingma, D.P., Kumar, A., Ermon, S. and
Poole, B., 2020. Score-based generative modeling through stochastic differential
equations. arXiv preprint arXiv:2011.13456.
"""
def __init__(
self,
img_resolution: int,
img_channels: int,
label_dim: int = 0,
use_fp16: bool = False,
beta_d: float = 19.9,
beta_min: float = 0.1,
M: int = 1000,
epsilon_t: float = 1e-5,
model_type: str = "SongUNet",
**model_kwargs: dict,
):
# Create the underlying model
model_class = getattr(network_module, model_type)
model = model_class(
img_resolution=img_resolution,
in_channels=img_channels,
out_channels=img_channels,
label_dim=label_dim,
**model_kwargs,
)
# Initialize parent class with model and VP parameters
super().__init__(
model=model,
beta_d=beta_d,
beta_min=beta_min,
M=M,
)
# Override meta from parent
self.meta = VPPrecondMetaData
# Store legacy-specific attributes
self.img_resolution = img_resolution
self.img_channels = img_channels
self.label_dim = label_dim
self.use_fp16 = use_fp16
self.epsilon_t = epsilon_t
self.sigma_min = float(self.sigma(torch.tensor(epsilon_t)))
self.sigma_max = float(self.sigma(torch.tensor(1.0)))
def forward(self, x, sigma, class_labels=None, force_fp32=False, **model_kwargs):
x = x.to(torch.float32)
sigma = sigma.to(torch.float32).reshape(-1, 1, 1, 1)
class_labels = (
None
if self.label_dim == 0
else torch.zeros([1, self.label_dim], device=x.device)
if class_labels is None
else class_labels.to(torch.float32).reshape(-1, self.label_dim)
)
dtype = (
torch.float16
if (self.use_fp16 and not force_fp32 and x.device.type == "cuda")
else torch.float32
)
# Use parent's compute_coefficients method
c_in, c_noise, c_out, c_skip = self.compute_coefficients(sigma)
F_x = self.model(
(c_in * x).to(dtype),
c_noise.flatten(),
class_labels=class_labels,
**model_kwargs,
)
if (F_x.dtype != dtype) and not torch.is_autocast_enabled():
raise ValueError(
f"Expected the dtype to be {dtype}, but got {F_x.dtype} instead."
)
D_x = c_skip * x + c_out * F_x.to(torch.float32)
return D_x
def sigma(self, t: Union[float, torch.Tensor]) -> torch.Tensor:
"""
Compute the sigma(t) value for a given t based on the VP formulation.
The function calculates the noise level schedule for the diffusion process based
on the given parameters `beta_d` and `beta_min`.
Parameters
----------
t : Union[float, torch.Tensor]
The timestep or set of timesteps for which to compute sigma(t).
Returns
-------
torch.Tensor
The computed sigma(t) value(s).
"""
t = torch.as_tensor(t)
return super().sigma(t)
def sigma_inv(self, sigma: Union[float, torch.Tensor]):
"""
Compute the inverse of the sigma function for a given sigma.
This function effectively calculates t from a given sigma(t) based on the
parameters `beta_d` and `beta_min`.
Parameters
----------
sigma : Union[float, torch.Tensor]
The sigma(t) value or set of sigma(t) values for which to compute the
inverse.
Returns
-------
torch.Tensor
The computed t value(s) corresponding to the provided sigma(t).
"""
sigma = torch.as_tensor(sigma)
return (
(self.beta_min**2 + 2 * self.beta_d * (1 + sigma**2).log()).sqrt()
- self.beta_min
) / self.beta_d
def round_sigma(self, sigma: Union[float, List, torch.Tensor]):
"""
Convert a given sigma value(s) to a tensor representation.
Parameters
----------
sigma : Union[float list, torch.Tensor]
The sigma value(s) to convert.
Returns
-------
torch.Tensor
The tensor representation of the provided sigma value(s).
"""
return torch.as_tensor(sigma)
@dataclass
class VEPrecondMetaData(ModelMetaData):
"""VEPrecond meta data"""
# Optimization
jit: bool = False
cuda_graphs: bool = False
amp_cpu: bool = False
amp_gpu: bool = True
torch_fx: bool = False
# Data type
bf16: bool = False
# Inference
onnx: bool = False
# Physics informed
func_torch: bool = False
auto_grad: bool = False
class VEPrecond(VEPreconditioner):
"""
Preconditioning corresponding to the variance exploding (VE) formulation.
Parameters
----------
img_resolution : int
Image resolution.
img_channels : int
Number of color channels.
label_dim : int
Number of class labels, 0 = unconditional, by default 0.
use_fp16 : bool
Execute the underlying model at FP16 precision?, by default False.
sigma_min : float
Minimum supported noise level, by default 0.02.
sigma_max : float
Maximum supported noise level, by default 100.0.
model_type :str
Class name of the underlying model, by default "SongUNet".
**model_kwargs : dict
Keyword arguments for the underlying model.
Note
----
Reference: Song, Y., Sohl-Dickstein, J., Kingma, D.P., Kumar, A., Ermon, S. and
Poole, B., 2020. Score-based generative modeling through stochastic differential
equations. arXiv preprint arXiv:2011.13456.
"""
def __init__(
self,
img_resolution: int,
img_channels: int,
label_dim: int = 0,
use_fp16: bool = False,
sigma_min: float = 0.02,
sigma_max: float = 100.0,
model_type: str = "SongUNet",
**model_kwargs: dict,
):
# Create the underlying model
model_class = getattr(network_module, model_type)
model = model_class(
img_resolution=img_resolution,
in_channels=img_channels,
out_channels=img_channels,
label_dim=label_dim,
**model_kwargs,
)
# Initialize parent class with model
super().__init__(model=model)
# Override meta from parent
self.meta = VEPrecondMetaData
# Store legacy-specific attributes
self.img_resolution = img_resolution
self.img_channels = img_channels
self.label_dim = label_dim
self.use_fp16 = use_fp16
self.sigma_min = sigma_min
self.sigma_max = sigma_max
def forward(self, x, sigma, class_labels=None, force_fp32=False, **model_kwargs):
x = x.to(torch.float32)
sigma = sigma.to(torch.float32).reshape(-1, 1, 1, 1)
class_labels = (
None
if self.label_dim == 0
else torch.zeros([1, self.label_dim], device=x.device)
if class_labels is None
else class_labels.to(torch.float32).reshape(-1, self.label_dim)
)
dtype = (
torch.float16
if (self.use_fp16 and not force_fp32 and x.device.type == "cuda")
else torch.float32
)
# Use parent's compute_coefficients method
c_in, c_noise, c_out, c_skip = self.compute_coefficients(sigma)
F_x = self.model(
(c_in * x).to(dtype),
c_noise.flatten(),
class_labels=class_labels,
**model_kwargs,
)
if (F_x.dtype != dtype) and not torch.is_autocast_enabled():
raise ValueError(
f"Expected the dtype to be {dtype}, but got {F_x.dtype} instead."
)
D_x = c_skip * x + c_out * F_x.to(torch.float32)
return D_x
def round_sigma(self, sigma: Union[float, List, torch.Tensor]):
"""
Convert a given sigma value(s) to a tensor representation.
Parameters
----------
sigma : Union[float list, torch.Tensor]
The sigma value(s) to convert.
Returns
-------
torch.Tensor
The tensor representation of the provided sigma value(s).
"""
return torch.as_tensor(sigma)
@dataclass
class iDDPMPrecondMetaData(ModelMetaData):
"""iDDPMPrecond meta data"""
# Optimization
jit: bool = False
cuda_graphs: bool = False
amp_cpu: bool = False
amp_gpu: bool = True
torch_fx: bool = False
# Data type
bf16: bool = False
# Inference
onnx: bool = False
# Physics informed
func_torch: bool = False
auto_grad: bool = False
class iDDPMPrecond(IDDPMPreconditioner):
"""
Preconditioning corresponding to the improved DDPM (iDDPM) formulation.
Parameters
----------
img_resolution : int
Image resolution.
img_channels : int
Number of color channels.
label_dim : int
Number of class labels, 0 = unconditional, by default 0.
use_fp16 : bool
Execute the underlying model at FP16 precision?, by default False.
C_1 : float
Timestep adjustment at low noise levels., by default 0.001.
C_2 : float
Timestep adjustment at high noise levels., by default 0.008.
M: int
Original number of timesteps in the DDPM formulation, by default 1000.
model_type :str
Class name of the underlying model, by default "DhariwalUNet".
**model_kwargs : dict
Keyword arguments for the underlying model.
Note
----
Reference: Nichol, A.Q. and Dhariwal, P., 2021, July. Improved denoising diffusion
probabilistic models. In International Conference on Machine Learning
(pp. 8162-8171). PMLR.
"""
def __init__(
self,
img_resolution,
img_channels,
label_dim=0,
use_fp16=False,
C_1=0.001,
C_2=0.008,
M=1000,
model_type="DhariwalUNet",
**model_kwargs,
):
# Create the underlying model
model_class = getattr(network_module, model_type)
model = model_class(
img_resolution=img_resolution,
in_channels=img_channels,
out_channels=img_channels * 2,
label_dim=label_dim,
**model_kwargs,
)
# Initialize parent class with model and iDDPM parameters
super().__init__(
model=model,
C_1=C_1,
C_2=C_2,
M=M,
)
# Override meta from parent
self.meta = iDDPMPrecondMetaData
# Store legacy-specific attributes
self.img_resolution = img_resolution
self.img_channels = img_channels
self.label_dim = label_dim
self.use_fp16 = use_fp16
# Use the u buffer from parent to compute sigma_min and sigma_max
self.sigma_min = float(self.u[M - 1])
self.sigma_max = float(self.u[0])
def forward(self, x, sigma, class_labels=None, force_fp32=False, **model_kwargs):
x = x.to(torch.float32)
sigma = sigma.to(torch.float32).reshape(-1, 1, 1, 1)
class_labels = (
None
if self.label_dim == 0
else torch.zeros([1, self.label_dim], device=x.device)
if class_labels is None
else class_labels.to(torch.float32).reshape(-1, self.label_dim)
)
dtype = (
torch.float16
if (self.use_fp16 and not force_fp32 and x.device.type == "cuda")
else torch.float32
)
# Compute coefficients using parent's method
c_in, c_noise, c_out, c_skip = self.compute_coefficients(sigma)
F_x = self.model(
(c_in * x).to(dtype),
c_noise.flatten(),
class_labels=class_labels,
**model_kwargs,
)
if (F_x.dtype != dtype) and not torch.is_autocast_enabled():
raise ValueError(
f"Expected the dtype to be {dtype}, but got {F_x.dtype} instead."
)
D_x = c_skip * x + c_out * F_x[:, : self.img_channels].to(torch.float32)
return D_x
def alpha_bar(self, j):
"""
Compute the alpha_bar(j) value for a given j based on the iDDPM formulation.
Parameters
----------
j : Union[int, torch.Tensor]
The timestep or set of timesteps for which to compute alpha_bar(j).
Returns
-------
torch.Tensor
The computed alpha_bar(j) value(s).
"""
j = torch.as_tensor(j)
return (0.5 * np.pi * j / self.M / (self.C_2 + 1)).sin() ** 2
def round_sigma(self, sigma, return_index=False):
"""
Round the provided sigma value(s) to the nearest value(s) in a
pre-defined set `u`.
Parameters
----------
sigma : Union[float, list, torch.Tensor]
The sigma value(s) to round.
return_index : bool, optional
Whether to return the index/indices of the rounded value(s) in `u` instead
of the rounded value(s) themselves, by default False.
Returns
-------
torch.Tensor
The rounded sigma value(s) or their index/indices in `u`, depending on the
value of `return_index`.
"""
sigma = torch.as_tensor(sigma)
index = torch.cdist(
sigma.to(self.u.device).to(torch.float32).reshape(1, -1, 1),
self.u.reshape(1, -1, 1),
).argmin(2)
result = index if return_index else self.u[index.flatten()].to(sigma.dtype)
return result.reshape(sigma.shape).to(sigma.device)
@dataclass
class EDMPrecondMetaData(ModelMetaData):
"""EDMPrecond meta data"""
# Optimization
jit: bool = False
cuda_graphs: bool = False
amp_cpu: bool = False
amp_gpu: bool = True
torch_fx: bool = False
# Data type
bf16: bool = False
# Inference
onnx: bool = False
# Physics informed
func_torch: bool = False
auto_grad: bool = False
class EDMPrecond(EDMPreconditioner):
"""
Improved preconditioning proposed in the paper "Elucidating the Design Space of
Diffusion-Based Generative Models" (EDM)
Parameters
----------
img_resolution : int
Image resolution.
img_channels : int
Number of color channels (for both input and output). If your model
requires a different number of input or output chanels,
override this by passing either of the optional
img_in_channels or img_out_channels args
label_dim : int
Number of class labels, 0 = unconditional, by default 0.
use_fp16 : bool
Execute the underlying model at FP16 precision?, by default False.
sigma_min : float
Minimum supported noise level, by default 0.0.
sigma_max : float
Maximum supported noise level, by default inf.
sigma_data : float
Expected standard deviation of the training data, by default 0.5.
model_type :str
Class name of the underlying model, by default "DhariwalUNet".
img_in_channels: int
Optional setting for when number of input channels =/= number of output
channels. If set, will override img_channels for the input
This is useful in the case of additional (conditional) channels
img_out_channels: int
Optional setting for when number of input channels =/= number of output
channels. If set, will override img_channels for the output
**model_kwargs : dict
Keyword arguments for the underlying model.
Note
----
Reference: Karras, T., Aittala, M., Aila, T. and Laine, S., 2022. Elucidating the
design space of diffusion-based generative models. Advances in Neural Information
Processing Systems, 35, pp.26565-26577.
"""
def __init__(
self,
img_resolution,
img_channels,
label_dim=0,
use_fp16=False,
sigma_min=0.0,
sigma_max=float("inf"),
sigma_data=0.5,
model_type="DhariwalUNet",
img_in_channels=None,
img_out_channels=None,
**model_kwargs,
):
# Resolve input/output channels
if img_in_channels is None:
img_in_channels = img_channels
if img_out_channels is None:
img_out_channels = img_channels
# Create the underlying model
model_class = getattr(network_module, model_type)
model = model_class(
img_resolution=img_resolution,
in_channels=img_in_channels,
out_channels=img_out_channels,
label_dim=label_dim,
**model_kwargs,
)
# Initialize parent class with model and sigma_data
super().__init__(
model=model,
sigma_data=sigma_data,
)
# Override meta from parent
self.meta = EDMPrecondMetaData
# Store legacy-specific attributes
self.img_resolution = img_resolution
self.label_dim = label_dim
self.use_fp16 = use_fp16
self.sigma_min = sigma_min
self.sigma_max = sigma_max
def forward( # type: ignore[override]
self,
x,
sigma,
condition=None,
class_labels=None,
force_fp32=False,
**model_kwargs,
):
x = x.to(torch.float32)
sigma = sigma.to(torch.float32).reshape(-1, 1, 1, 1)
class_labels = (
None
if self.label_dim == 0
else torch.zeros([1, self.label_dim], device=x.device)
if class_labels is None
else class_labels.to(torch.float32).reshape(-1, self.label_dim)
)
dtype = (
torch.float16
if (self.use_fp16 and not force_fp32 and x.device.type == "cuda")
else torch.float32
)
# Use parent's compute_coefficients method
c_in, c_noise, c_out, c_skip = self.compute_coefficients(sigma)
arg = c_in * x
if condition is not None:
arg = torch.cat([arg, condition], dim=1)
F_x = self.model(
arg.to(dtype),
c_noise.flatten(),
class_labels=class_labels,
**model_kwargs,
)
if (F_x.dtype != dtype) and not torch.is_autocast_enabled():
raise ValueError(
f"Expected the dtype to be {dtype}, but got {F_x.dtype} instead."
)
D_x = c_skip * x + c_out * F_x.to(torch.float32)
return D_x
@staticmethod
def round_sigma(sigma: Union[float, List, torch.Tensor]):
"""
Convert a given sigma value(s) to a tensor representation.
Parameters
----------
sigma : Union[float list, torch.Tensor]
The sigma value(s) to convert.
Returns
-------
torch.Tensor
The tensor representation of the provided sigma value(s).
"""
return torch.as_tensor(sigma)
@dataclass
class EDMPrecondSuperResolutionMetaData(ModelMetaData):
"""EDMPrecondSuperResolution meta data"""
# Optimization
jit: bool = False
cuda_graphs: bool = False
amp_cpu: bool = False
amp_gpu: bool = True
torch_fx: bool = False
# Data type
bf16: bool = False
# Inference
onnx: bool = False
# Physics informed
func_torch: bool = False
auto_grad: bool = False
class EDMPrecondSuperResolution(Module):
"""
Improved preconditioning proposed in the paper "Elucidating the Design Space of
Diffusion-Based Generative Models" (EDM).
This is a variant of `EDMPrecond` that is specifically designed for super-resolution
tasks. It wraps a neural network that predicts the denoised high-resolution image
given a noisy high-resolution image, and additional conditioning that includes a
low-resolution image, and a noise level.
Parameters
----------
img_resolution : Union[int, Tuple[int, int]]
Spatial resolution :math:`(H, W)` of the image. If a single int is provided,
the image is assumed to be square.
img_in_channels : int
Number of input channels in the low-resolution input image.
img_out_channels : int
Number of output channels in the high-resolution output image.
use_fp16 : bool, optional
Whether to use half-precision floating point (FP16) for model execution,
by default False.
model_type : str, optional
Class name of the underlying model. Must be one of the following:
'SongUNet', 'SongUNetPosEmbd', 'SongUNetPosLtEmbd', 'DhariwalUNet'.
Defaults to 'SongUNetPosEmbd'.
sigma_data : float, optional
Expected standard deviation of the training data, by default 0.5.
sigma_min : float, optional
Minimum supported noise level, by default 0.0.
sigma_max : float, optional
Maximum supported noise level, by default inf.
**model_kwargs : dict
Keyword arguments passed to the underlying model `__init__` method.
See Also
--------
For information on model types and their usage:
:class:`~physicsnemo.models.diffusion_unets.SongUNet`: Basic U-Net for diffusion models
:class:`~physicsnemo.models.diffusion_unets.SongUNetPosEmbd`: U-Net with positional embeddings
:class:`~physicsnemo.models.diffusion_unets.SongUNetPosLtEmbd`: U-Net with positional and lead-time embeddings
Please refer to the documentation of these classes for details on how to call
and use these models directly.
Note
----
References:
- Karras, T., Aittala, M., Aila, T. and Laine, S., 2022. Elucidating the
design space of diffusion-based generative models. Advances in Neural Information
Processing Systems, 35, pp.26565-26577.
- Mardani, M., Brenowitz, N., Cohen, Y., Pathak, J., Chen, C.Y.,
Liu, C.C.,Vahdat, A., Kashinath, K., Kautz, J. and Pritchard, M., 2023.
Generative Residual Diffusion Modeling for Km-scale Atmospheric Downscaling.
arXiv preprint arXiv:2309.15214.
"""
# Classes that can be wrapped by this UNet class.
_wrapped_classes = {
"SongUNetPosEmbd",
"SongUNetPosLtEmbd",
"SongUNet",
"DhariwalUNet",
}
# Arguments of the __init__ method that can be overridden with the
# ``Module.from_checkpoint`` method. Here, since we use splatted arguments
# for the wrapped model instance, we allow overriding of any overridable
# argument of the wrapped classes.
_overridable_args = set.union(
*(
getattr(getattr(network_module, cls_name), "_overridable_args", set())
for cls_name in _wrapped_classes
)
)
def __init__(
self,
img_resolution: Union[int, Tuple[int, int]],
img_in_channels: int,
img_out_channels: int,
use_fp16: bool = False,
model_type: Literal[
"SongUNetPosEmbd", "SongUNetPosLtEmbd", "SongUNet", "DhariwalUNet"
] = "SongUNetPosEmbd",
sigma_data: float = 0.5,
sigma_min=0.0,
sigma_max=float("inf"),
**model_kwargs: Any,
):
super().__init__(meta=EDMPrecondSuperResolutionMetaData)
# Validation
if model_type not in self._wrapped_classes:
raise ValueError(
f"Model type '{model_type}' is not supported. "
f"Must be one of: {', '.join(self._wrapped_classes)}"
)
self.img_resolution = img_resolution
self.img_in_channels = img_in_channels
self.img_out_channels = img_out_channels
self.sigma_data = sigma_data
self.sigma_min = sigma_min
self.sigma_max = sigma_max
model_class = getattr(network_module, model_type)
self.model = model_class(
img_resolution=img_resolution,
in_channels=img_in_channels + img_out_channels,
out_channels=img_out_channels,
**model_kwargs,
) # TODO needs better handling
self.scaling_fn = self._scaling_fn
self.use_fp16 = use_fp16
@property
def use_fp16(self):
"""
bool: Whether the model uses float16 precision.
Returns
-------
bool
True if the model is in float16 mode, False otherwise.
"""
return self._use_fp16
@use_fp16.setter
def use_fp16(self, value: bool):
"""
Set whether the model should use float16 precision.
Parameters
----------
value : bool
If True, moves the model to torch.float16. If False, moves to torch.float32.
Raises
------
ValueError
If `value` is not a boolean.
"""
# NOTE: allow 0/1 values for older checkpoints
if not (isinstance(value, bool) or value in [0, 1]):
raise ValueError(
f"`use_fp16` must be a boolean, but got {type(value).__name__}."
)
self._use_fp16 = value
if value:
self.to(torch.float16)
else:
self.to(torch.float32)
@staticmethod
def _scaling_fn(
x: torch.Tensor, img_lr: torch.Tensor, c_in: torch.Tensor
) -> torch.Tensor:
"""
Scale input tensors by first scaling the high-resolution tensor and then
concatenating with the low-resolution tensor.
Parameters
----------
x : torch.Tensor
Noisy high-resolution image of shape (B, C_hr, H, W).
img_lr : torch.Tensor
Low-resolution image of shape (B, C_lr, H, W).
c_in : torch.Tensor
Scaling factor of shape (B, 1, 1, 1).
Returns
-------
torch.Tensor
Scaled and concatenated tensor of shape (B, C_in+C_out, H, W).
"""
return torch.cat([c_in * x, img_lr.to(x.dtype)], dim=1)
# Properties delegated to the wrapped model
amp_mode = _wrapped_property(
"amp_mode",
"model",
"Set to ``True`` when using automatic mixed precision.",
)
profile_mode = _wrapped_property(
"profile_mode",
"model",
"Set to ``True`` to enable profiling of the wrapped model.",
)
def forward(
self,
x: torch.Tensor,
img_lr: torch.Tensor,
sigma: torch.Tensor,
force_fp32: bool = False,
**model_kwargs: Any,
) -> torch.Tensor:
"""
Forward pass of the EDMPrecondSuperResolution model wrapper.
This method applies the EDM preconditioning to compute the denoised image
from a noisy high-resolution image and low-resolution conditioning image.
Parameters
----------
x : torch.Tensor
Noisy high-resolution image of shape (B, C_hr, H, W). The number of
channels `C_hr` should be equal to `img_out_channels`.
img_lr : torch.Tensor
Low-resolution conditioning image of shape (B, C_lr, H, W). The number
of channels `C_lr` should be equal to `img_in_channels`.
sigma : torch.Tensor
Noise level of shape (B) or (B, 1) or (B, 1, 1, 1).
force_fp32 : bool, optional
Whether to force FP32 precision regardless of the `use_fp16` attribute,
by default False.
**model_kwargs : dict
Additional keyword arguments to pass to the underlying model
`self.model` forward method.
Returns
-------
torch.Tensor
Denoised high-resolution image of shape (B, C_hr, H, W).
Raises
------
ValueError
If the model output dtype doesn't match the expected dtype.
"""
# Concatenate input channels
x = x.to(torch.float32)
sigma = sigma.to(torch.float32).reshape(-1, 1, 1, 1)
dtype = (
torch.float16
if (self.use_fp16 and not force_fp32 and x.device.type == "cuda")
else torch.float32
)
c_skip = self.sigma_data**2 / (sigma**2 + self.sigma_data**2)
c_out = sigma * self.sigma_data / (sigma**2 + self.sigma_data**2).sqrt()
c_in = 1 / (self.sigma_data**2 + sigma**2).sqrt()
c_noise = sigma.log() / 4
if img_lr is None:
arg = c_in * x
else:
arg = self.scaling_fn(x, img_lr, c_in)
arg = arg.to(dtype)
F_x = self.model(
arg,
c_noise.flatten(),
class_labels=None,
**model_kwargs,
)
if (F_x.dtype != dtype) and not torch.is_autocast_enabled():
raise ValueError(
f"Expected the dtype to be {dtype}, but got {F_x.dtype} instead."
)
D_x = c_skip * x + c_out * F_x.to(torch.float32)