Spaces:
Sleeping
Sleeping
File size: 48,833 Bytes
c3d0544 |
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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 |
# 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.models.diffusion.utils import _wrapped_property
from physicsnemo.models.meta import ModelMetaData
from physicsnemo.models.module import Module
network_module = importlib.import_module("physicsnemo.models.diffusion")
@dataclass
class VPPrecondMetaData(ModelMetaData):
"""VPPrecond meta data"""
name: str = "VPPrecond"
# 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(Module):
"""
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,
):
super().__init__(meta=VPPrecondMetaData)
self.img_resolution = img_resolution
self.img_channels = img_channels
self.label_dim = label_dim
self.use_fp16 = use_fp16
self.beta_d = beta_d
self.beta_min = beta_min
self.M = M
self.epsilon_t = epsilon_t
self.sigma_min = float(self.sigma(epsilon_t))
self.sigma_max = float(self.sigma(1))
model_class = getattr(network_module, model_type)
self.model = model_class(
img_resolution=img_resolution,
in_channels=img_channels,
out_channels=img_channels,
label_dim=label_dim,
**model_kwargs,
) # TODO needs better handling
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
)
c_skip = 1
c_out = -sigma
c_in = 1 / (sigma**2 + 1).sqrt()
c_noise = (self.M - 1) * self.sigma_inv(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]):
"""
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 ((0.5 * self.beta_d * (t**2) + self.beta_min * t).exp() - 1).sqrt()
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"""
name: str = "VEPrecond"
# 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(Module):
"""
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,
):
super().__init__(meta=VEPrecondMetaData)
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
model_class = getattr(network_module, model_type)
self.model = model_class(
img_resolution=img_resolution,
in_channels=img_channels,
out_channels=img_channels,
label_dim=label_dim,
**model_kwargs,
) # TODO needs better handling
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
)
c_skip = 1
c_out = sigma
c_in = 1
c_noise = (0.5 * sigma).log()
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"""
name: str = "iDDPMPrecond"
# 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(Module):
"""
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,
):
super().__init__(meta=iDDPMPrecondMetaData)
self.img_resolution = img_resolution
self.img_channels = img_channels
self.label_dim = label_dim
self.use_fp16 = use_fp16
self.C_1 = C_1
self.C_2 = C_2
self.M = M
model_class = getattr(network_module, model_type)
self.model = model_class(
img_resolution=img_resolution,
in_channels=img_channels,
out_channels=img_channels * 2,
label_dim=label_dim,
**model_kwargs,
) # TODO needs better handling
u = torch.zeros(M + 1)
for j in range(M, 0, -1): # M, ..., 1
u[j - 1] = (
(u[j] ** 2 + 1)
/ (self.alpha_bar(j - 1) / self.alpha_bar(j)).clip(min=C_1)
- 1
).sqrt()
self.register_buffer("u", u)
self.sigma_min = float(u[M - 1])
self.sigma_max = float(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
)
c_skip = 1
c_out = -sigma
c_in = 1 / (sigma**2 + 1).sqrt()
c_noise = (
self.M - 1 - self.round_sigma(sigma, return_index=True).to(torch.float32)
)
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"""
name: str = "EDMPrecond"
# 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(Module):
"""
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,
):
super().__init__(meta=EDMPrecondMetaData)
self.img_resolution = img_resolution
if img_in_channels is not None:
img_in_channels = img_in_channels
else:
img_in_channels = img_channels
if img_out_channels is not None:
img_out_channels = img_out_channels
else:
img_out_channels = img_channels
self.label_dim = label_dim
self.use_fp16 = use_fp16
self.sigma_min = sigma_min
self.sigma_max = sigma_max
self.sigma_data = sigma_data
model_class = getattr(network_module, model_type)
self.model = model_class(
img_resolution=img_resolution,
in_channels=img_in_channels,
out_channels=img_out_channels,
label_dim=label_dim,
**model_kwargs,
) # TODO needs better handling
def forward(
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
)
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
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"""
name: str = "EDMPrecondSuperResolution"
# 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.SongUNet`: Basic U-Net for diffusion models
:class:`~physicsnemo.models.diffusion.SongUNetPosEmbd`: U-Net with positional embeddings
:class:`~physicsnemo.models.diffusion.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)
return D_x
@staticmethod
def round_sigma(sigma: Union[float, List, torch.Tensor]) -> torch.Tensor:
"""
Convert a given sigma value(s) to a tensor representation.
Parameters
----------
sigma : Union[float, List, torch.Tensor]
Sigma value(s) to convert.
Returns
-------
torch.Tensor
Tensor representation of sigma values.
See Also
--------
EDMPrecond.round_sigma
"""
return EDMPrecond.round_sigma(sigma)
# NOTE: This is a deprecated version of the EDMPrecondSuperResolution model.
# This was used to maintain backwards compatibility and allow loading old models.
@dataclass
class EDMPrecondSRMetaData(ModelMetaData):
"""EDMPrecondSR meta data"""
name: str = "EDMPrecondSR"
# 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 EDMPrecondSR(EDMPrecondSuperResolution):
"""
NOTE: This is a deprecated version of the EDMPrecondSuperResolution model.
This was used to maintain backwards compatibility and allow loading old models.
Please use the EDMPrecondSuperResolution model instead.
Improved preconditioning proposed in the paper "Elucidating the Design Space of
Diffusion-Based Generative Models" (EDM) for super-resolution tasks
Parameters
----------
img_resolution : int
Image resolution.
img_channels : int
Number of color channels (deprecated, not used).
img_in_channels : int
Number of input color channels.
img_out_channels : int
Number of output color channels.
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 "SongUNetPosEmbd".
scale_cond_input : bool
Whether to scale the conditional input (deprecated), by default True.
**model_kwargs : dict
Keyword arguments for the underlying model.
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.
"""
def __init__(
self,
img_resolution,
img_channels, # deprecated
img_in_channels,
img_out_channels,
use_fp16=False,
sigma_min=0.0,
sigma_max=float("inf"),
sigma_data=0.5,
model_type="SongUNetPosEmbd",
scale_cond_input=True, # deprecated
**model_kwargs,
):
warnings.warn(
"EDMPrecondSR is deprecated and will be removed in a future version. "
"Please use EDMPrecondSuperResolution instead.",
DeprecationWarning,
stacklevel=2,
)
super().__init__(
img_resolution=img_resolution,
img_in_channels=img_in_channels,
img_out_channels=img_out_channels,
use_fp16=use_fp16,
sigma_min=sigma_min,
sigma_max=sigma_max,
sigma_data=sigma_data,
model_type=model_type,
**model_kwargs,
)
if scale_cond_input:
warnings.warn(
"The `scale_cond_input=True` option does not properly scale the conditional input "
"and is deprecated. It is highly recommended to set `scale_cond_input=False`. "
"However, for loading a checkpoint previously trained with `scale_cond_input=True`, "
"this flag must be set to `True` to ensure compatibility. "
"For more details, see https://github.com/NVIDIA/modulus/issues/229.",
DeprecationWarning,
)
self.scaling_fn = self._legacy_scaling_fn
# Store deprecated parameters for backward compatibility
self.img_channels = img_channels
self.scale_cond_input = scale_cond_input
@staticmethod
def _legacy_scaling_fn(
x: torch.Tensor, img_lr: torch.Tensor, c_in: torch.Tensor
) -> torch.Tensor:
"""
This function does not properly scale the conditional input
(see https://github.com/NVIDIA/modulus/issues/229)
and will be deprecated.
Concatenate and scale the high-resolution and low-resolution tensors.
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 c_in * torch.cat([x, img_lr.to(x.dtype)], dim=1)
def forward(
self,
x,
img_lr,
sigma,
force_fp32=False,
**model_kwargs,
):
"""
Forward pass of the EDMPrecondSR model wrapper.
Parameters
----------
x : torch.Tensor
Noisy high-resolution image of shape (B, C_hr, H, W).
img_lr : torch.Tensor
Low-resolution conditioning image of shape (B, C_lr, H, W).
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.
Returns
-------
torch.Tensor
Denoised high-resolution image of shape (B, C_hr, H, W).
"""
return super().forward(
x=x, img_lr=img_lr, sigma=sigma, force_fp32=force_fp32, **model_kwargs
)
class VEPrecond_dfsr(torch.nn.Module):
"""
Preconditioning for dfsr model, modified from class VEPrecond, where the input
argument 'sigma' in forward propagation function is used to receive the timestep
of the backward diffusion process.
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: Ho J, Jain A, Abbeel P. Denoising diffusion probabilistic models.
Advances in neural information processing systems. 2020;33:6840-51.
"""
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,
dataset_mean: float = 5.85e-05,
dataset_scale: float = 4.79,
model_type: str = "SongUNet",
**model_kwargs: dict,
):
super().__init__()
self.img_resolution = img_resolution
self.img_channels = img_channels
self.label_dim = label_dim
self.use_fp16 = use_fp16
model_class = getattr(network_module, model_type)
self.model = model_class(
img_resolution=img_resolution,
in_channels=self.img_channels,
out_channels=img_channels,
label_dim=label_dim,
**model_kwargs,
) # TODO needs better handling
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)
# print("sigma: ", sigma)
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
)
c_in = 1
c_noise = sigma # Change the definitation of c_noise to avoid -inf values for zero sigma
F_x = self.model(
(c_in * x).to(dtype),
c_noise.flatten(),
class_labels=class_labels,
**model_kwargs,
)
if F_x.dtype != dtype:
raise ValueError(
f"Expected the dtype to be {dtype}, but got {F_x.dtype} instead."
)
return F_x
class VEPrecond_dfsr_cond(torch.nn.Module):
"""
Preconditioning for dfsr model with physics-informed conditioning input, modified
from class VEPrecond, where the input argument 'sigma' in forward propagation function
is used to receive the timestep of the backward diffusion process. The gradient of PDE
residual with respect to the vorticity in the governing Navier-Stokes equation is computed
as the physics-informed conditioning variable and is combined with the backward diffusion
timestep before being sent to the underlying model for noise prediction.
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:
[1] 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.
[2] Shu D, Li Z, Farimani AB. A physics-informed diffusion model for high-fidelity
flow field reconstruction. Journal of Computational Physics. 2023 Apr 1;478:111972.
"""
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,
dataset_mean: float = 5.85e-05,
dataset_scale: float = 4.79,
model_type: str = "SongUNet",
**model_kwargs: dict,
):
super().__init__()
self.img_resolution = img_resolution
self.img_channels = img_channels
self.label_dim = label_dim
self.use_fp16 = use_fp16
model_class = getattr(network_module, model_type)
self.model = model_class(
img_resolution=img_resolution,
in_channels=model_kwargs["model_channels"] * 2,
out_channels=img_channels,
label_dim=label_dim,
**model_kwargs,
) # TODO needs better handling
# modules to embed residual loss
self.conv_in = torch.nn.Conv2d(
img_channels,
model_kwargs["model_channels"],
kernel_size=3,
stride=1,
padding=1,
padding_mode="circular",
)
self.emb_conv = torch.nn.Sequential(
torch.nn.Conv2d(
img_channels,
model_kwargs["model_channels"],
kernel_size=1,
stride=1,
padding=0,
),
torch.nn.GELU(),
torch.nn.Conv2d(
model_kwargs["model_channels"],
model_kwargs["model_channels"],
kernel_size=3,
stride=1,
padding=1,
padding_mode="circular",
),
)
self.dataset_mean = dataset_mean
self.dataset_scale = dataset_scale
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
)
c_in = 1
c_noise = sigma
# Compute physics-informed conditioning information using vorticity residual
dx = (
self.voriticity_residual((x * self.dataset_scale + self.dataset_mean))
/ self.dataset_scale
)
x = self.conv_in(x)
cond_emb = self.emb_conv(dx)
x = torch.cat((x, cond_emb), dim=1)
F_x = self.model(
(c_in * x).to(dtype),
c_noise.flatten(),
class_labels=class_labels,
**model_kwargs,
)
if F_x.dtype != dtype:
raise ValueError(
f"Expected the dtype to be {dtype}, but got {F_x.dtype} instead."
)
return F_x
def voriticity_residual(self, w, re=1000.0, dt=1 / 32):
"""
Compute the gradient of PDE residual with respect to a given vorticity w using the
spectrum method.
Parameters
----------
w: torch.Tensor
The fluid flow data sample (vorticity).
re: float
The value of Reynolds number used in the governing Navier-Stokes equation.
dt: float
Time step used to compute the time-derivative of vorticity included in the governing
Navier-Stokes equation.
Returns
-------
torch.Tensor
The computed vorticity gradient.
"""
# w [b t h w]
w = w.clone()
w.requires_grad_(True)
nx = w.size(2)
device = w.device
w_h = torch.fft.fft2(w[:, 1:-1], dim=[2, 3])
# Wavenumbers in y-direction
k_max = nx // 2
N = nx
k_x = (
torch.cat(
(
torch.arange(start=0, end=k_max, step=1, device=device),
torch.arange(start=-k_max, end=0, step=1, device=device),
),
0,
)
.reshape(N, 1)
.repeat(1, N)
.reshape(1, 1, N, N)
)
k_y = (
torch.cat(
(
torch.arange(start=0, end=k_max, step=1, device=device),
torch.arange(start=-k_max, end=0, step=1, device=device),
),
0,
)
.reshape(1, N)
.repeat(N, 1)
.reshape(1, 1, N, N)
)
# Negative Laplacian in Fourier space
lap = k_x**2 + k_y**2
lap[..., 0, 0] = 1.0
psi_h = w_h / lap
u_h = 1j * k_y * psi_h
v_h = -1j * k_x * psi_h
wx_h = 1j * k_x * w_h
wy_h = 1j * k_y * w_h
wlap_h = -lap * w_h
u = torch.fft.irfft2(u_h[..., :, : k_max + 1], dim=[2, 3])
v = torch.fft.irfft2(v_h[..., :, : k_max + 1], dim=[2, 3])
wx = torch.fft.irfft2(wx_h[..., :, : k_max + 1], dim=[2, 3])
wy = torch.fft.irfft2(wy_h[..., :, : k_max + 1], dim=[2, 3])
wlap = torch.fft.irfft2(wlap_h[..., :, : k_max + 1], dim=[2, 3])
advection = u * wx + v * wy
wt = (w[:, 2:, :, :] - w[:, :-2, :, :]) / (2 * dt)
# establish forcing term
x = torch.linspace(0, 2 * np.pi, nx + 1, device=device)
x = x[0:-1]
X, Y = torch.meshgrid(x, x)
f = -4 * torch.cos(4 * Y)
residual = wt + (advection - (1.0 / re) * wlap + 0.1 * w[:, 1:-1]) - f
residual_loss = (residual**2).mean()
dw = torch.autograd.grad(residual_loss, w)[0]
return dw
|