├── .gitignore ├── LICENSE ├── Makefile ├── README.md ├── data ├── dataset.py ├── era5.py └── toy.py ├── guided_diffusion ├── __init__.py ├── dist_util.py ├── fp16_util.py ├── gaussian_diffusion.py ├── image_datasets.py ├── logger.py ├── losses.py ├── nn.py ├── resample.py ├── respace.py ├── script_util.py ├── train_util.py └── unet.py ├── img ├── deep_ensemble.png ├── era5.png └── hyperdm.png ├── model ├── mlp.py └── unet.py ├── requirements.txt └── src ├── hyperdm.py ├── test.py ├── toy_baseline.py ├── train.py └── util.py /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | share/python-wheels/ 24 | *.egg-info/ 25 | .installed.cfg 26 | *.egg 27 | MANIFEST 28 | 29 | # PyInstaller 30 | # Usually these files are written by a python script from a template 31 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 32 | *.manifest 33 | *.spec 34 | 35 | # Installer logs 36 | pip-log.txt 37 | pip-delete-this-directory.txt 38 | 39 | # Unit test / coverage reports 40 | htmlcov/ 41 | .tox/ 42 | .nox/ 43 | .coverage 44 | .coverage.* 45 | .cache 46 | nosetests.xml 47 | coverage.xml 48 | *.cover 49 | *.py,cover 50 | .hypothesis/ 51 | .pytest_cache/ 52 | cover/ 53 | 54 | # Translations 55 | *.mo 56 | *.pot 57 | 58 | # Django stuff: 59 | *.log 60 | local_settings.py 61 | db.sqlite3 62 | db.sqlite3-journal 63 | 64 | # Flask stuff: 65 | instance/ 66 | .webassets-cache 67 | 68 | # Scrapy stuff: 69 | .scrapy 70 | 71 | # Sphinx documentation 72 | docs/_build/ 73 | 74 | # PyBuilder 75 | .pybuilder/ 76 | target/ 77 | 78 | # Jupyter Notebook 79 | .ipynb_checkpoints 80 | 81 | # IPython 82 | profile_default/ 83 | ipython_config.py 84 | 85 | # pyenv 86 | # For a library or package, you might want to ignore these files since the code is 87 | # intended to run in multiple environments; otherwise, check them in: 88 | # .python-version 89 | 90 | # pipenv 91 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 92 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 93 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 94 | # install all needed dependencies. 95 | #Pipfile.lock 96 | 97 | # poetry 98 | # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. 99 | # This is especially recommended for binary packages to ensure reproducibility, and is more 100 | # commonly ignored for libraries. 101 | # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control 102 | #poetry.lock 103 | 104 | # pdm 105 | # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. 106 | #pdm.lock 107 | # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it 108 | # in version control. 109 | # https://pdm.fming.dev/latest/usage/project/#working-with-version-control 110 | .pdm.toml 111 | .pdm-python 112 | .pdm-build/ 113 | 114 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm 115 | __pypackages__/ 116 | 117 | # Celery stuff 118 | celerybeat-schedule 119 | celerybeat.pid 120 | 121 | # SageMath parsed files 122 | *.sage.py 123 | 124 | # Environments 125 | .env 126 | .venv 127 | env/ 128 | venv/ 129 | ENV/ 130 | env.bak/ 131 | venv.bak/ 132 | 133 | # Spyder project settings 134 | .spyderproject 135 | .spyproject 136 | 137 | # Rope project settings 138 | .ropeproject 139 | 140 | # mkdocs documentation 141 | /site 142 | 143 | # mypy 144 | .mypy_cache/ 145 | .dmypy.json 146 | dmypy.json 147 | 148 | # Pyre type checker 149 | .pyre/ 150 | 151 | # pytype static type analyzer 152 | .pytype/ 153 | 154 | # Cython debug symbols 155 | cython_debug/ 156 | 157 | # PyCharm 158 | # JetBrains specific template is maintained in a separate JetBrains.gitignore that can 159 | # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore 160 | # and can be added to the global gitignore or merged into this file. For a more nuclear 161 | # option (not recommended) you can uncomment the following to ignore the entire idea folder. 162 | #.idea/ 163 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | SHELL := /bin/bash 2 | export PYTHONPATH := $(PYTHONPATH):$(shell pwd) 3 | 4 | .PHONY: clean 5 | 6 | era5_result.pdf: src/test.py era5_model.pt 7 | time python src/test.py \ 8 | --seed 1 \ 9 | --dataset "era5" \ 10 | --dataset_size 1000 \ 11 | --image_size 256 \ 12 | --checkpoint era5_model.pt \ 13 | --M 10 \ 14 | --N 100 \ 15 | --diffusion_steps 1000 \ 16 | --hyper_net_dims 1 24 24 24 24 24 17 | 18 | era5_model.pt: src/train.py 19 | time python src/train.py \ 20 | --seed 1 \ 21 | --dataset "era5" \ 22 | --dataset_size 1000 \ 23 | --image_size 256 \ 24 | --checkpoint era5_model.pt \ 25 | --num_epochs 50 \ 26 | --lr 1e-4 \ 27 | --batch_size 8 \ 28 | --diffusion_steps 1000 \ 29 | --hyper_net_dims 1 24 24 24 24 24 30 | 31 | toy_result.pdf: src/test.py toy_model.pt 32 | time python src/test.py \ 33 | --seed 1 \ 34 | --dataset "toy" \ 35 | --dataset_size 10000 \ 36 | --checkpoint toy_model.pt \ 37 | --M 10 \ 38 | --N 100 \ 39 | --diffusion_steps 1000 \ 40 | --hyper_net_dims 1 8 8 8 8 8 41 | 42 | toy_model.pt: src/train.py 43 | time python src/train.py \ 44 | --seed 1 \ 45 | --dataset "toy" \ 46 | --dataset_size 10000 \ 47 | --checkpoint toy_model.pt \ 48 | --num_epochs 100 \ 49 | --lr 1e-3 \ 50 | --batch_size 64 \ 51 | --diffusion_steps 1000 \ 52 | --hyper_net_dims 1 8 8 8 8 8 53 | 54 | src/train.py: src/hyperdm.py data/era5.py data/toy.py model/mlp.py model/unet.py 55 | 56 | src/test.py: src/hyperdm.py data/era5.py data/toy.py model/mlp.py model/unet.py 57 | 58 | src/hyperdm.py: model/mlp.py 59 | 60 | toy_baseline.pdf: src/toy_baseline.py data/toy.py src/hyperdm.py model/mlp.py 61 | time python src/debug.py 62 | 63 | clean: 64 | rm -rf *.pt *.pdf -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Hyper-Diffusion Models (HyperDM) 2 | *Authors: [Matthew A. Chan](https://www.cs.umd.edu/~mattchan/), [Maria J. Molina](https://mariajmolina.github.io/), [Christopher A. Metzler](https://www.cs.umd.edu/~metzler/)* 3 | 4 | This is the official codebase for the NeurIPS 2024 paper ["Estimating Epistemic and Aleatoric Uncertainty with a Single Model"](https://arxiv.org/abs/2402.03478). 5 | 6 | ### Abstract 7 | 8 | > "Estimating and disentangling epistemic uncertainty, uncertainty that is reducible with more training data, and aleatoric uncertainty, uncertainty that is inherent to the task at hand, is critically important when applying machine learning to high-stakes applications such as medical imaging and weather forecasting. Conditional diffusion models' breakthrough ability to accurately and efficiently sample from the posterior distribution of a dataset now makes uncertainty estimation conceptually straightforward: One need only train and sample from a large ensemble of diffusion models. Unfortunately, training such an ensemble becomes computationally intractable as the complexity of the model architecture grows. In this work we introduce a new approach to ensembling, hyper-diffusion models (HyperDM), which allows one to accurately estimate both epistemic and aleatoric uncertainty with a single model. Unlike existing single-model uncertainty methods like Monte-Carlo dropout and Bayesian neural networks, HyperDM offers prediction accuracy on par with, and in some cases superior to, multi-model ensembles. Furthermore, our proposed approach scales to modern network architectures such as Attention U-Net and yields more accurate uncertainty estimates compared to existing methods. We validate our method on two distinct real-world tasks: x-ray computed tomography reconstruction and weather temperature forecasting." 9 | 10 | # Usage 11 | 12 | ### Dependencies 13 | 14 | Using Python (v3.11.9), please install dependencies by running: 15 | 16 | ```sh 17 | $ pip install -r requirements.txt 18 | ``` 19 | 20 | ## Toy Experiment 21 | 22 | We include `Makefile` build targets for generating toy experiment figures. 23 | 24 | - To visualize HyperDM results, run `make toy_result.pdf`. 25 | - To visualize deep ensemble results, run `make toy_baseline.pdf`. 26 | 27 | | `toy_result.pdf` | `toy_baseline.pdf` | 28 | | :------------------: | :------------------------: | 29 | | ![](img/hyperdm.png) | ![](img/deep_ensemble.png) | 30 | 31 | **Note:** As mentioned in our paper, AU is unreliable (and should be disregarded) when EU is high. 32 | 33 | ## Surface Temperature Forecasting Experiment 34 | 35 | Run `make era5_result.pdf` to train HyperDM on [ERA5](https://www.ecmwf.int/en/forecasts/dataset/ecmwf-reanalysis-v5) and validate EU on an out-of-distribution test input. 36 | 37 | **Note:** On your first run, download the dataset by adding the `--download` flag to ERA5 build instructions in `Makefile`. 38 | 39 | | `era5_result.pdf` | 40 | | :------------------: | 41 | | ![](img/era5.png) | 42 | 43 | # Citation 44 | 45 | Please cite us if you found our work useful :) 46 | 47 | ``` 48 | @article{chan2024hyper, 49 | title={Estimating Epistemic and Aleatoric Uncertainty with a Single Model}, 50 | author={Chan, Matthew A and Molina, Maria J and Metzler, Christopher A}, 51 | journal={arXiv preprint arXiv:2402.03478}, 52 | year={2024} 53 | } 54 | ``` 55 | -------------------------------------------------------------------------------- /data/dataset.py: -------------------------------------------------------------------------------- 1 | from enum import Enum 2 | 3 | 4 | class Dataset(Enum): 5 | TOY = "toy" 6 | LUNA16 = "luna16" 7 | ERA5 = "era5" 8 | 9 | def __str__(self): 10 | return self.value 11 | -------------------------------------------------------------------------------- /data/era5.py: -------------------------------------------------------------------------------- 1 | from functools import partial 2 | 3 | import cdsapi 4 | import numpy as np 5 | import torch as th 6 | import xarray as xr 7 | from cv2 import resize 8 | from numpy.lib.stride_tricks import sliding_window_view 9 | from torch.utils.data import Dataset, random_split 10 | 11 | from src.util import normalize_range 12 | 13 | 14 | class ERA5(Dataset): 15 | 16 | def __init__(self, image_size: int, split: str, download: bool = False): 17 | if download: 18 | print("Downloading ERA5 (takes ~1hr)...") 19 | dataset_name = "reanalysis-era5-single-levels" 20 | request = { 21 | "product_type": ["reanalysis"], 22 | "variable": ["2m_temperature"], 23 | "year": list(range(1940, 2023)), 24 | "month": ["01"], 25 | "day": list(range(1, 32)), 26 | "time": ["00:00", "06:00", "12:00", "18:00"], 27 | "data_format": "grib", 28 | "area": [83, -169, 7, -35] 29 | } 30 | client = cdsapi.Client() 31 | client.retrieve(dataset_name, request, 'data/era5_t2m.grib') 32 | print("Loading dataset...") 33 | dataset = xr.open_dataset("data/era5_t2m.grib")["t2m"].values 34 | 35 | # Pre-processing 36 | resize_func = partial(resize, dsize=(image_size, image_size)) 37 | dataset = np.array(list(map(resize_func, dataset))) 38 | dataset = normalize_range(dataset, low=-1, high=1) 39 | 40 | # Splits dataset into staggered time steps 41 | windows = sliding_window_view(dataset, window_shape=2, axis=0) 42 | y = windows[..., 0] # time t 43 | x = windows[..., 1] # time t+6hr 44 | assert len(x) == len(y), f"Size mismatch {len(x)} versus {len(y)}!" 45 | 46 | train_split, test_split = random_split(range(len(x)), [0.9, 0.1]) 47 | if split == "train": 48 | self.y = y[train_split] 49 | self.x = x[train_split] 50 | elif split == "test": 51 | self.y = y[test_split] 52 | self.x = x[test_split] 53 | else: 54 | raise ValueError(f"Invalid split {split} provided.") 55 | 56 | def __len__(self): 57 | return len(self.x) 58 | 59 | def __getitem__(self, idx): 60 | return th.from_numpy(self.x[idx:idx + 1]), th.from_numpy( 61 | self.y[idx:idx + 1]) 62 | -------------------------------------------------------------------------------- /data/toy.py: -------------------------------------------------------------------------------- 1 | import torch as th 2 | from torch.utils.data import Dataset, random_split 3 | 4 | from src.util import normalize_range 5 | 6 | 7 | class ToyDataset(Dataset): 8 | 9 | def __init__(self, density: int, split: str): 10 | x = th.rand(density) 11 | x_min, x_max = (-th.pi, th.pi) 12 | x = normalize_range(x, low=x_min, high=x_max) 13 | 14 | # Mask region out (epistemic) 15 | mask = th.logical_or(x < -1, x > 1) 16 | x = x[mask] 17 | 18 | # Increase noise variance with x (aleatoric) 19 | var = normalize_range(x.clip(0), low=0, high=0.04) 20 | y = th.sin(x) + th.sqrt(var) * th.randn(x.shape) 21 | 22 | # Rescale to [-1, 1] 23 | x = normalize_range(x) 24 | y = normalize_range(y) 25 | 26 | train_split, test_split = random_split(range(len(x)), [0.9, 0.1]) 27 | if split == "train": 28 | self.y = y[train_split] 29 | self.x = x[train_split] 30 | elif split == "test": 31 | self.y = y[test_split] 32 | self.x = x[test_split] 33 | else: 34 | raise ValueError(f"Invalid split {split} provided.") 35 | 36 | def __len__(self): 37 | return len(self.x) 38 | 39 | def __getitem__(self, idx): 40 | return self.y[idx].reshape(1, 1, 1), self.x[idx].reshape(1, 1, 1) 41 | -------------------------------------------------------------------------------- /guided_diffusion/__init__.py: -------------------------------------------------------------------------------- 1 | """ 2 | Codebase for "Improved Denoising Diffusion Probabilistic Models". 3 | """ 4 | -------------------------------------------------------------------------------- /guided_diffusion/dist_util.py: -------------------------------------------------------------------------------- 1 | """ 2 | Helpers for distributed training. 3 | """ 4 | 5 | import io 6 | import os 7 | import socket 8 | 9 | import blobfile as bf 10 | from mpi4py import MPI 11 | import torch as th 12 | import torch.distributed as dist 13 | 14 | # Change this to reflect your cluster layout. 15 | # The GPU for a given rank is (rank % GPUS_PER_NODE). 16 | GPUS_PER_NODE = 8 17 | 18 | SETUP_RETRY_COUNT = 3 19 | 20 | 21 | def setup_dist(): 22 | """ 23 | Setup a distributed process group. 24 | """ 25 | if dist.is_initialized(): 26 | return 27 | os.environ["CUDA_VISIBLE_DEVICES"] = f"{MPI.COMM_WORLD.Get_rank() % GPUS_PER_NODE}" 28 | 29 | comm = MPI.COMM_WORLD 30 | backend = "gloo" if not th.cuda.is_available() else "nccl" 31 | 32 | if backend == "gloo": 33 | hostname = "localhost" 34 | else: 35 | hostname = socket.gethostbyname(socket.getfqdn()) 36 | os.environ["MASTER_ADDR"] = comm.bcast(hostname, root=0) 37 | os.environ["RANK"] = str(comm.rank) 38 | os.environ["WORLD_SIZE"] = str(comm.size) 39 | 40 | port = comm.bcast(_find_free_port(), root=0) 41 | os.environ["MASTER_PORT"] = str(port) 42 | dist.init_process_group(backend=backend, init_method="env://") 43 | 44 | 45 | def dev(): 46 | """ 47 | Get the device to use for torch.distributed. 48 | """ 49 | if th.cuda.is_available(): 50 | return th.device(f"cuda") 51 | return th.device("cpu") 52 | 53 | 54 | def load_state_dict(path, **kwargs): 55 | """ 56 | Load a PyTorch file without redundant fetches across MPI ranks. 57 | """ 58 | chunk_size = 2 ** 30 # MPI has a relatively small size limit 59 | if MPI.COMM_WORLD.Get_rank() == 0: 60 | with bf.BlobFile(path, "rb") as f: 61 | data = f.read() 62 | num_chunks = len(data) // chunk_size 63 | if len(data) % chunk_size: 64 | num_chunks += 1 65 | MPI.COMM_WORLD.bcast(num_chunks) 66 | for i in range(0, len(data), chunk_size): 67 | MPI.COMM_WORLD.bcast(data[i : i + chunk_size]) 68 | else: 69 | num_chunks = MPI.COMM_WORLD.bcast(None) 70 | data = bytes() 71 | for _ in range(num_chunks): 72 | data += MPI.COMM_WORLD.bcast(None) 73 | 74 | return th.load(io.BytesIO(data), **kwargs) 75 | 76 | 77 | def sync_params(params): 78 | """ 79 | Synchronize a sequence of Tensors across ranks from rank 0. 80 | """ 81 | for p in params: 82 | with th.no_grad(): 83 | dist.broadcast(p, 0) 84 | 85 | 86 | def _find_free_port(): 87 | try: 88 | s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 89 | s.bind(("", 0)) 90 | s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) 91 | return s.getsockname()[1] 92 | finally: 93 | s.close() 94 | -------------------------------------------------------------------------------- /guided_diffusion/fp16_util.py: -------------------------------------------------------------------------------- 1 | """ 2 | Helpers to train with 16-bit precision. 3 | """ 4 | 5 | import numpy as np 6 | import torch as th 7 | import torch.nn as nn 8 | from torch._utils import _flatten_dense_tensors, _unflatten_dense_tensors 9 | 10 | from . import logger 11 | 12 | INITIAL_LOG_LOSS_SCALE = 20.0 13 | 14 | 15 | def convert_module_to_f16(l): 16 | """ 17 | Convert primitive modules to float16. 18 | """ 19 | if isinstance(l, (nn.Conv1d, nn.Conv2d, nn.Conv3d)): 20 | l.weight.data = l.weight.data.half() 21 | if l.bias is not None: 22 | l.bias.data = l.bias.data.half() 23 | 24 | 25 | def convert_module_to_f32(l): 26 | """ 27 | Convert primitive modules to float32, undoing convert_module_to_f16(). 28 | """ 29 | if isinstance(l, (nn.Conv1d, nn.Conv2d, nn.Conv3d)): 30 | l.weight.data = l.weight.data.float() 31 | if l.bias is not None: 32 | l.bias.data = l.bias.data.float() 33 | 34 | 35 | def make_master_params(param_groups_and_shapes): 36 | """ 37 | Copy model parameters into a (differently-shaped) list of full-precision 38 | parameters. 39 | """ 40 | master_params = [] 41 | for param_group, shape in param_groups_and_shapes: 42 | master_param = nn.Parameter( 43 | _flatten_dense_tensors( 44 | [param.detach().float() for (_, param) in param_group] 45 | ).view(shape) 46 | ) 47 | master_param.requires_grad = True 48 | master_params.append(master_param) 49 | return master_params 50 | 51 | 52 | def model_grads_to_master_grads(param_groups_and_shapes, master_params): 53 | """ 54 | Copy the gradients from the model parameters into the master parameters 55 | from make_master_params(). 56 | """ 57 | for master_param, (param_group, shape) in zip( 58 | master_params, param_groups_and_shapes 59 | ): 60 | master_param.grad = _flatten_dense_tensors( 61 | [param_grad_or_zeros(param) for (_, param) in param_group] 62 | ).view(shape) 63 | 64 | 65 | def master_params_to_model_params(param_groups_and_shapes, master_params): 66 | """ 67 | Copy the master parameter data back into the model parameters. 68 | """ 69 | # Without copying to a list, if a generator is passed, this will 70 | # silently not copy any parameters. 71 | for master_param, (param_group, _) in zip(master_params, param_groups_and_shapes): 72 | for (_, param), unflat_master_param in zip( 73 | param_group, unflatten_master_params(param_group, master_param.view(-1)) 74 | ): 75 | param.detach().copy_(unflat_master_param) 76 | 77 | 78 | def unflatten_master_params(param_group, master_param): 79 | return _unflatten_dense_tensors(master_param, [param for (_, param) in param_group]) 80 | 81 | 82 | def get_param_groups_and_shapes(named_model_params): 83 | named_model_params = list(named_model_params) 84 | scalar_vector_named_params = ( 85 | [(n, p) for (n, p) in named_model_params if p.ndim <= 1], 86 | (-1), 87 | ) 88 | matrix_named_params = ( 89 | [(n, p) for (n, p) in named_model_params if p.ndim > 1], 90 | (1, -1), 91 | ) 92 | return [scalar_vector_named_params, matrix_named_params] 93 | 94 | 95 | def master_params_to_state_dict( 96 | model, param_groups_and_shapes, master_params, use_fp16 97 | ): 98 | if use_fp16: 99 | state_dict = model.state_dict() 100 | for master_param, (param_group, _) in zip( 101 | master_params, param_groups_and_shapes 102 | ): 103 | for (name, _), unflat_master_param in zip( 104 | param_group, unflatten_master_params(param_group, master_param.view(-1)) 105 | ): 106 | assert name in state_dict 107 | state_dict[name] = unflat_master_param 108 | else: 109 | state_dict = model.state_dict() 110 | for i, (name, _value) in enumerate(model.named_parameters()): 111 | assert name in state_dict 112 | state_dict[name] = master_params[i] 113 | return state_dict 114 | 115 | 116 | def state_dict_to_master_params(model, state_dict, use_fp16): 117 | if use_fp16: 118 | named_model_params = [ 119 | (name, state_dict[name]) for name, _ in model.named_parameters() 120 | ] 121 | param_groups_and_shapes = get_param_groups_and_shapes(named_model_params) 122 | master_params = make_master_params(param_groups_and_shapes) 123 | else: 124 | master_params = [state_dict[name] for name, _ in model.named_parameters()] 125 | return master_params 126 | 127 | 128 | def zero_master_grads(master_params): 129 | for param in master_params: 130 | param.grad = None 131 | 132 | 133 | def zero_grad(model_params): 134 | for param in model_params: 135 | # Taken from https://pytorch.org/docs/stable/_modules/torch/optim/optimizer.html#Optimizer.add_param_group 136 | if param.grad is not None: 137 | param.grad.detach_() 138 | param.grad.zero_() 139 | 140 | 141 | def param_grad_or_zeros(param): 142 | if param.grad is not None: 143 | return param.grad.data.detach() 144 | else: 145 | return th.zeros_like(param) 146 | 147 | 148 | class MixedPrecisionTrainer: 149 | def __init__( 150 | self, 151 | *, 152 | model, 153 | use_fp16=False, 154 | fp16_scale_growth=1e-3, 155 | initial_lg_loss_scale=INITIAL_LOG_LOSS_SCALE, 156 | ): 157 | self.model = model 158 | self.use_fp16 = use_fp16 159 | self.fp16_scale_growth = fp16_scale_growth 160 | 161 | self.model_params = list(self.model.parameters()) 162 | self.master_params = self.model_params 163 | self.param_groups_and_shapes = None 164 | self.lg_loss_scale = initial_lg_loss_scale 165 | 166 | if self.use_fp16: 167 | self.param_groups_and_shapes = get_param_groups_and_shapes( 168 | self.model.named_parameters() 169 | ) 170 | self.master_params = make_master_params(self.param_groups_and_shapes) 171 | self.model.convert_to_fp16() 172 | 173 | def zero_grad(self): 174 | zero_grad(self.model_params) 175 | 176 | def backward(self, loss: th.Tensor): 177 | if self.use_fp16: 178 | loss_scale = 2 ** self.lg_loss_scale 179 | (loss * loss_scale).backward() 180 | else: 181 | loss.backward() 182 | 183 | def optimize(self, opt: th.optim.Optimizer): 184 | if self.use_fp16: 185 | return self._optimize_fp16(opt) 186 | else: 187 | return self._optimize_normal(opt) 188 | 189 | def _optimize_fp16(self, opt: th.optim.Optimizer): 190 | logger.logkv_mean("lg_loss_scale", self.lg_loss_scale) 191 | model_grads_to_master_grads(self.param_groups_and_shapes, self.master_params) 192 | grad_norm, param_norm = self._compute_norms(grad_scale=2 ** self.lg_loss_scale) 193 | if check_overflow(grad_norm): 194 | self.lg_loss_scale -= 1 195 | logger.log(f"Found NaN, decreased lg_loss_scale to {self.lg_loss_scale}") 196 | zero_master_grads(self.master_params) 197 | return False 198 | 199 | logger.logkv_mean("grad_norm", grad_norm) 200 | logger.logkv_mean("param_norm", param_norm) 201 | 202 | for p in self.master_params: 203 | p.grad.mul_(1.0 / (2 ** self.lg_loss_scale)) 204 | opt.step() 205 | zero_master_grads(self.master_params) 206 | master_params_to_model_params(self.param_groups_and_shapes, self.master_params) 207 | self.lg_loss_scale += self.fp16_scale_growth 208 | return True 209 | 210 | def _optimize_normal(self, opt: th.optim.Optimizer): 211 | grad_norm, param_norm = self._compute_norms() 212 | logger.logkv_mean("grad_norm", grad_norm) 213 | logger.logkv_mean("param_norm", param_norm) 214 | opt.step() 215 | return True 216 | 217 | def _compute_norms(self, grad_scale=1.0): 218 | grad_norm = 0.0 219 | param_norm = 0.0 220 | for p in self.master_params: 221 | with th.no_grad(): 222 | param_norm += th.norm(p, p=2, dtype=th.float32).item() ** 2 223 | if p.grad is not None: 224 | grad_norm += th.norm(p.grad, p=2, dtype=th.float32).item() ** 2 225 | return np.sqrt(grad_norm) / grad_scale, np.sqrt(param_norm) 226 | 227 | def master_params_to_state_dict(self, master_params): 228 | return master_params_to_state_dict( 229 | self.model, self.param_groups_and_shapes, master_params, self.use_fp16 230 | ) 231 | 232 | def state_dict_to_master_params(self, state_dict): 233 | return state_dict_to_master_params(self.model, state_dict, self.use_fp16) 234 | 235 | 236 | def check_overflow(value): 237 | return (value == float("inf")) or (value == -float("inf")) or (value != value) 238 | -------------------------------------------------------------------------------- /guided_diffusion/image_datasets.py: -------------------------------------------------------------------------------- 1 | import math 2 | import random 3 | 4 | from PIL import Image 5 | import blobfile as bf 6 | from mpi4py import MPI 7 | import numpy as np 8 | from torch.utils.data import DataLoader, Dataset 9 | 10 | 11 | def load_data( 12 | *, 13 | data_dir, 14 | batch_size, 15 | image_size, 16 | class_cond=False, 17 | deterministic=False, 18 | random_crop=False, 19 | random_flip=True, 20 | ): 21 | """ 22 | For a dataset, create a generator over (images, kwargs) pairs. 23 | 24 | Each images is an NCHW float tensor, and the kwargs dict contains zero or 25 | more keys, each of which map to a batched Tensor of their own. 26 | The kwargs dict can be used for class labels, in which case the key is "y" 27 | and the values are integer tensors of class labels. 28 | 29 | :param data_dir: a dataset directory. 30 | :param batch_size: the batch size of each returned pair. 31 | :param image_size: the size to which images are resized. 32 | :param class_cond: if True, include a "y" key in returned dicts for class 33 | label. If classes are not available and this is true, an 34 | exception will be raised. 35 | :param deterministic: if True, yield results in a deterministic order. 36 | :param random_crop: if True, randomly crop the images for augmentation. 37 | :param random_flip: if True, randomly flip the images for augmentation. 38 | """ 39 | if not data_dir: 40 | raise ValueError("unspecified data directory") 41 | all_files = _list_image_files_recursively(data_dir) 42 | classes = None 43 | if class_cond: 44 | # Assume classes are the first part of the filename, 45 | # before an underscore. 46 | class_names = [bf.basename(path).split("_")[0] for path in all_files] 47 | sorted_classes = {x: i for i, x in enumerate(sorted(set(class_names)))} 48 | classes = [sorted_classes[x] for x in class_names] 49 | dataset = ImageDataset( 50 | image_size, 51 | all_files, 52 | classes=classes, 53 | shard=MPI.COMM_WORLD.Get_rank(), 54 | num_shards=MPI.COMM_WORLD.Get_size(), 55 | random_crop=random_crop, 56 | random_flip=random_flip, 57 | ) 58 | if deterministic: 59 | loader = DataLoader( 60 | dataset, batch_size=batch_size, shuffle=False, num_workers=1, drop_last=True 61 | ) 62 | else: 63 | loader = DataLoader( 64 | dataset, batch_size=batch_size, shuffle=True, num_workers=1, drop_last=True 65 | ) 66 | while True: 67 | yield from loader 68 | 69 | 70 | def _list_image_files_recursively(data_dir): 71 | results = [] 72 | for entry in sorted(bf.listdir(data_dir)): 73 | full_path = bf.join(data_dir, entry) 74 | ext = entry.split(".")[-1] 75 | if "." in entry and ext.lower() in ["jpg", "jpeg", "png", "gif"]: 76 | results.append(full_path) 77 | elif bf.isdir(full_path): 78 | results.extend(_list_image_files_recursively(full_path)) 79 | return results 80 | 81 | 82 | class ImageDataset(Dataset): 83 | def __init__( 84 | self, 85 | resolution, 86 | image_paths, 87 | classes=None, 88 | shard=0, 89 | num_shards=1, 90 | random_crop=False, 91 | random_flip=True, 92 | ): 93 | super().__init__() 94 | self.resolution = resolution 95 | self.local_images = image_paths[shard:][::num_shards] 96 | self.local_classes = None if classes is None else classes[shard:][::num_shards] 97 | self.random_crop = random_crop 98 | self.random_flip = random_flip 99 | 100 | def __len__(self): 101 | return len(self.local_images) 102 | 103 | def __getitem__(self, idx): 104 | path = self.local_images[idx] 105 | with bf.BlobFile(path, "rb") as f: 106 | pil_image = Image.open(f) 107 | pil_image.load() 108 | pil_image = pil_image.convert("RGB") 109 | 110 | if self.random_crop: 111 | arr = random_crop_arr(pil_image, self.resolution) 112 | else: 113 | arr = center_crop_arr(pil_image, self.resolution) 114 | 115 | if self.random_flip and random.random() < 0.5: 116 | arr = arr[:, ::-1] 117 | 118 | arr = arr.astype(np.float32) / 127.5 - 1 119 | 120 | out_dict = {} 121 | if self.local_classes is not None: 122 | out_dict["y"] = np.array(self.local_classes[idx], dtype=np.int64) 123 | return np.transpose(arr, [2, 0, 1]), out_dict 124 | 125 | 126 | def center_crop_arr(pil_image, image_size): 127 | # We are not on a new enough PIL to support the `reducing_gap` 128 | # argument, which uses BOX downsampling at powers of two first. 129 | # Thus, we do it by hand to improve downsample quality. 130 | while min(*pil_image.size) >= 2 * image_size: 131 | pil_image = pil_image.resize( 132 | tuple(x // 2 for x in pil_image.size), resample=Image.BOX 133 | ) 134 | 135 | scale = image_size / min(*pil_image.size) 136 | pil_image = pil_image.resize( 137 | tuple(round(x * scale) for x in pil_image.size), resample=Image.BICUBIC 138 | ) 139 | 140 | arr = np.array(pil_image) 141 | crop_y = (arr.shape[0] - image_size) // 2 142 | crop_x = (arr.shape[1] - image_size) // 2 143 | return arr[crop_y : crop_y + image_size, crop_x : crop_x + image_size] 144 | 145 | 146 | def random_crop_arr(pil_image, image_size, min_crop_frac=0.8, max_crop_frac=1.0): 147 | min_smaller_dim_size = math.ceil(image_size / max_crop_frac) 148 | max_smaller_dim_size = math.ceil(image_size / min_crop_frac) 149 | smaller_dim_size = random.randrange(min_smaller_dim_size, max_smaller_dim_size + 1) 150 | 151 | # We are not on a new enough PIL to support the `reducing_gap` 152 | # argument, which uses BOX downsampling at powers of two first. 153 | # Thus, we do it by hand to improve downsample quality. 154 | while min(*pil_image.size) >= 2 * smaller_dim_size: 155 | pil_image = pil_image.resize( 156 | tuple(x // 2 for x in pil_image.size), resample=Image.BOX 157 | ) 158 | 159 | scale = smaller_dim_size / min(*pil_image.size) 160 | pil_image = pil_image.resize( 161 | tuple(round(x * scale) for x in pil_image.size), resample=Image.BICUBIC 162 | ) 163 | 164 | arr = np.array(pil_image) 165 | crop_y = random.randrange(arr.shape[0] - image_size + 1) 166 | crop_x = random.randrange(arr.shape[1] - image_size + 1) 167 | return arr[crop_y : crop_y + image_size, crop_x : crop_x + image_size] 168 | -------------------------------------------------------------------------------- /guided_diffusion/logger.py: -------------------------------------------------------------------------------- 1 | """ 2 | Logger copied from OpenAI baselines to avoid extra RL-based dependencies: 3 | https://github.com/openai/baselines/blob/ea25b9e8b234e6ee1bca43083f8f3cf974143998/baselines/logger.py 4 | """ 5 | 6 | import os 7 | import sys 8 | import shutil 9 | import os.path as osp 10 | import json 11 | import time 12 | import datetime 13 | import tempfile 14 | import warnings 15 | from collections import defaultdict 16 | from contextlib import contextmanager 17 | 18 | DEBUG = 10 19 | INFO = 20 20 | WARN = 30 21 | ERROR = 40 22 | 23 | DISABLED = 50 24 | 25 | 26 | class KVWriter(object): 27 | def writekvs(self, kvs): 28 | raise NotImplementedError 29 | 30 | 31 | class SeqWriter(object): 32 | def writeseq(self, seq): 33 | raise NotImplementedError 34 | 35 | 36 | class HumanOutputFormat(KVWriter, SeqWriter): 37 | def __init__(self, filename_or_file): 38 | if isinstance(filename_or_file, str): 39 | self.file = open(filename_or_file, "wt") 40 | self.own_file = True 41 | else: 42 | assert hasattr(filename_or_file, "read"), ( 43 | "expected file or str, got %s" % filename_or_file 44 | ) 45 | self.file = filename_or_file 46 | self.own_file = False 47 | 48 | def writekvs(self, kvs): 49 | # Create strings for printing 50 | key2str = {} 51 | for (key, val) in sorted(kvs.items()): 52 | if hasattr(val, "__float__"): 53 | valstr = "%-8.3g" % val 54 | else: 55 | valstr = str(val) 56 | key2str[self._truncate(key)] = self._truncate(valstr) 57 | 58 | # Find max widths 59 | if len(key2str) == 0: 60 | print("WARNING: tried to write empty key-value dict") 61 | return 62 | else: 63 | keywidth = max(map(len, key2str.keys())) 64 | valwidth = max(map(len, key2str.values())) 65 | 66 | # Write out the data 67 | dashes = "-" * (keywidth + valwidth + 7) 68 | lines = [dashes] 69 | for (key, val) in sorted(key2str.items(), key=lambda kv: kv[0].lower()): 70 | lines.append( 71 | "| %s%s | %s%s |" 72 | % (key, " " * (keywidth - len(key)), val, " " * (valwidth - len(val))) 73 | ) 74 | lines.append(dashes) 75 | self.file.write("\n".join(lines) + "\n") 76 | 77 | # Flush the output to the file 78 | self.file.flush() 79 | 80 | def _truncate(self, s): 81 | maxlen = 30 82 | return s[: maxlen - 3] + "..." if len(s) > maxlen else s 83 | 84 | def writeseq(self, seq): 85 | seq = list(seq) 86 | for (i, elem) in enumerate(seq): 87 | self.file.write(elem) 88 | if i < len(seq) - 1: # add space unless this is the last one 89 | self.file.write(" ") 90 | self.file.write("\n") 91 | self.file.flush() 92 | 93 | def close(self): 94 | if self.own_file: 95 | self.file.close() 96 | 97 | 98 | class JSONOutputFormat(KVWriter): 99 | def __init__(self, filename): 100 | self.file = open(filename, "wt") 101 | 102 | def writekvs(self, kvs): 103 | for k, v in sorted(kvs.items()): 104 | if hasattr(v, "dtype"): 105 | kvs[k] = float(v) 106 | self.file.write(json.dumps(kvs) + "\n") 107 | self.file.flush() 108 | 109 | def close(self): 110 | self.file.close() 111 | 112 | 113 | class CSVOutputFormat(KVWriter): 114 | def __init__(self, filename): 115 | self.file = open(filename, "w+t") 116 | self.keys = [] 117 | self.sep = "," 118 | 119 | def writekvs(self, kvs): 120 | # Add our current row to the history 121 | extra_keys = list(kvs.keys() - self.keys) 122 | extra_keys.sort() 123 | if extra_keys: 124 | self.keys.extend(extra_keys) 125 | self.file.seek(0) 126 | lines = self.file.readlines() 127 | self.file.seek(0) 128 | for (i, k) in enumerate(self.keys): 129 | if i > 0: 130 | self.file.write(",") 131 | self.file.write(k) 132 | self.file.write("\n") 133 | for line in lines[1:]: 134 | self.file.write(line[:-1]) 135 | self.file.write(self.sep * len(extra_keys)) 136 | self.file.write("\n") 137 | for (i, k) in enumerate(self.keys): 138 | if i > 0: 139 | self.file.write(",") 140 | v = kvs.get(k) 141 | if v is not None: 142 | self.file.write(str(v)) 143 | self.file.write("\n") 144 | self.file.flush() 145 | 146 | def close(self): 147 | self.file.close() 148 | 149 | 150 | class TensorBoardOutputFormat(KVWriter): 151 | """ 152 | Dumps key/value pairs into TensorBoard's numeric format. 153 | """ 154 | 155 | def __init__(self, dir): 156 | os.makedirs(dir, exist_ok=True) 157 | self.dir = dir 158 | self.step = 1 159 | prefix = "events" 160 | path = osp.join(osp.abspath(dir), prefix) 161 | import tensorflow as tf 162 | from tensorflow.python import pywrap_tensorflow 163 | from tensorflow.core.util import event_pb2 164 | from tensorflow.python.util import compat 165 | 166 | self.tf = tf 167 | self.event_pb2 = event_pb2 168 | self.pywrap_tensorflow = pywrap_tensorflow 169 | self.writer = pywrap_tensorflow.EventsWriter(compat.as_bytes(path)) 170 | 171 | def writekvs(self, kvs): 172 | def summary_val(k, v): 173 | kwargs = {"tag": k, "simple_value": float(v)} 174 | return self.tf.Summary.Value(**kwargs) 175 | 176 | summary = self.tf.Summary(value=[summary_val(k, v) for k, v in kvs.items()]) 177 | event = self.event_pb2.Event(wall_time=time.time(), summary=summary) 178 | event.step = ( 179 | self.step 180 | ) # is there any reason why you'd want to specify the step? 181 | self.writer.WriteEvent(event) 182 | self.writer.Flush() 183 | self.step += 1 184 | 185 | def close(self): 186 | if self.writer: 187 | self.writer.Close() 188 | self.writer = None 189 | 190 | 191 | def make_output_format(format, ev_dir, log_suffix=""): 192 | os.makedirs(ev_dir, exist_ok=True) 193 | if format == "stdout": 194 | return HumanOutputFormat(sys.stdout) 195 | elif format == "log": 196 | return HumanOutputFormat(osp.join(ev_dir, "log%s.txt" % log_suffix)) 197 | elif format == "json": 198 | return JSONOutputFormat(osp.join(ev_dir, "progress%s.json" % log_suffix)) 199 | elif format == "csv": 200 | return CSVOutputFormat(osp.join(ev_dir, "progress%s.csv" % log_suffix)) 201 | elif format == "tensorboard": 202 | return TensorBoardOutputFormat(osp.join(ev_dir, "tb%s" % log_suffix)) 203 | else: 204 | raise ValueError("Unknown format specified: %s" % (format,)) 205 | 206 | 207 | # ================================================================ 208 | # API 209 | # ================================================================ 210 | 211 | 212 | def logkv(key, val): 213 | """ 214 | Log a value of some diagnostic 215 | Call this once for each diagnostic quantity, each iteration 216 | If called many times, last value will be used. 217 | """ 218 | get_current().logkv(key, val) 219 | 220 | 221 | def logkv_mean(key, val): 222 | """ 223 | The same as logkv(), but if called many times, values averaged. 224 | """ 225 | get_current().logkv_mean(key, val) 226 | 227 | 228 | def logkvs(d): 229 | """ 230 | Log a dictionary of key-value pairs 231 | """ 232 | for (k, v) in d.items(): 233 | logkv(k, v) 234 | 235 | 236 | def dumpkvs(): 237 | """ 238 | Write all of the diagnostics from the current iteration 239 | """ 240 | return get_current().dumpkvs() 241 | 242 | 243 | def getkvs(): 244 | return get_current().name2val 245 | 246 | 247 | def log(*args, level=INFO): 248 | """ 249 | Write the sequence of args, with no separators, to the console and output files (if you've configured an output file). 250 | """ 251 | get_current().log(*args, level=level) 252 | 253 | 254 | def debug(*args): 255 | log(*args, level=DEBUG) 256 | 257 | 258 | def info(*args): 259 | log(*args, level=INFO) 260 | 261 | 262 | def warn(*args): 263 | log(*args, level=WARN) 264 | 265 | 266 | def error(*args): 267 | log(*args, level=ERROR) 268 | 269 | 270 | def set_level(level): 271 | """ 272 | Set logging threshold on current logger. 273 | """ 274 | get_current().set_level(level) 275 | 276 | 277 | def set_comm(comm): 278 | get_current().set_comm(comm) 279 | 280 | 281 | def get_dir(): 282 | """ 283 | Get directory that log files are being written to. 284 | will be None if there is no output directory (i.e., if you didn't call start) 285 | """ 286 | return get_current().get_dir() 287 | 288 | 289 | record_tabular = logkv 290 | dump_tabular = dumpkvs 291 | 292 | 293 | @contextmanager 294 | def profile_kv(scopename): 295 | logkey = "wait_" + scopename 296 | tstart = time.time() 297 | try: 298 | yield 299 | finally: 300 | get_current().name2val[logkey] += time.time() - tstart 301 | 302 | 303 | def profile(n): 304 | """ 305 | Usage: 306 | @profile("my_func") 307 | def my_func(): code 308 | """ 309 | 310 | def decorator_with_name(func): 311 | def func_wrapper(*args, **kwargs): 312 | with profile_kv(n): 313 | return func(*args, **kwargs) 314 | 315 | return func_wrapper 316 | 317 | return decorator_with_name 318 | 319 | 320 | # ================================================================ 321 | # Backend 322 | # ================================================================ 323 | 324 | 325 | def get_current(): 326 | if Logger.CURRENT is None: 327 | _configure_default_logger() 328 | 329 | return Logger.CURRENT 330 | 331 | 332 | class Logger(object): 333 | DEFAULT = None # A logger with no output files. (See right below class definition) 334 | # So that you can still log to the terminal without setting up any output files 335 | CURRENT = None # Current logger being used by the free functions above 336 | 337 | def __init__(self, dir, output_formats, comm=None): 338 | self.name2val = defaultdict(float) # values this iteration 339 | self.name2cnt = defaultdict(int) 340 | self.level = INFO 341 | self.dir = dir 342 | self.output_formats = output_formats 343 | self.comm = comm 344 | 345 | # Logging API, forwarded 346 | # ---------------------------------------- 347 | def logkv(self, key, val): 348 | self.name2val[key] = val 349 | 350 | def logkv_mean(self, key, val): 351 | oldval, cnt = self.name2val[key], self.name2cnt[key] 352 | self.name2val[key] = oldval * cnt / (cnt + 1) + val / (cnt + 1) 353 | self.name2cnt[key] = cnt + 1 354 | 355 | def dumpkvs(self): 356 | if self.comm is None: 357 | d = self.name2val 358 | else: 359 | d = mpi_weighted_mean( 360 | self.comm, 361 | { 362 | name: (val, self.name2cnt.get(name, 1)) 363 | for (name, val) in self.name2val.items() 364 | }, 365 | ) 366 | if self.comm.rank != 0: 367 | d["dummy"] = 1 # so we don't get a warning about empty dict 368 | out = d.copy() # Return the dict for unit testing purposes 369 | for fmt in self.output_formats: 370 | if isinstance(fmt, KVWriter): 371 | fmt.writekvs(d) 372 | self.name2val.clear() 373 | self.name2cnt.clear() 374 | return out 375 | 376 | def log(self, *args, level=INFO): 377 | if self.level <= level: 378 | self._do_log(args) 379 | 380 | # Configuration 381 | # ---------------------------------------- 382 | def set_level(self, level): 383 | self.level = level 384 | 385 | def set_comm(self, comm): 386 | self.comm = comm 387 | 388 | def get_dir(self): 389 | return self.dir 390 | 391 | def close(self): 392 | for fmt in self.output_formats: 393 | fmt.close() 394 | 395 | # Misc 396 | # ---------------------------------------- 397 | def _do_log(self, args): 398 | for fmt in self.output_formats: 399 | if isinstance(fmt, SeqWriter): 400 | fmt.writeseq(map(str, args)) 401 | 402 | 403 | def get_rank_without_mpi_import(): 404 | # check environment variables here instead of importing mpi4py 405 | # to avoid calling MPI_Init() when this module is imported 406 | for varname in ["PMI_RANK", "OMPI_COMM_WORLD_RANK"]: 407 | if varname in os.environ: 408 | return int(os.environ[varname]) 409 | return 0 410 | 411 | 412 | def mpi_weighted_mean(comm, local_name2valcount): 413 | """ 414 | Copied from: https://github.com/openai/baselines/blob/ea25b9e8b234e6ee1bca43083f8f3cf974143998/baselines/common/mpi_util.py#L110 415 | Perform a weighted average over dicts that are each on a different node 416 | Input: local_name2valcount: dict mapping key -> (value, count) 417 | Returns: key -> mean 418 | """ 419 | all_name2valcount = comm.gather(local_name2valcount) 420 | if comm.rank == 0: 421 | name2sum = defaultdict(float) 422 | name2count = defaultdict(float) 423 | for n2vc in all_name2valcount: 424 | for (name, (val, count)) in n2vc.items(): 425 | try: 426 | val = float(val) 427 | except ValueError: 428 | if comm.rank == 0: 429 | warnings.warn( 430 | "WARNING: tried to compute mean on non-float {}={}".format( 431 | name, val 432 | ) 433 | ) 434 | else: 435 | name2sum[name] += val * count 436 | name2count[name] += count 437 | return {name: name2sum[name] / name2count[name] for name in name2sum} 438 | else: 439 | return {} 440 | 441 | 442 | def configure(dir=None, format_strs=None, comm=None, log_suffix=""): 443 | """ 444 | If comm is provided, average all numerical stats across that comm 445 | """ 446 | if dir is None: 447 | dir = os.getenv("OPENAI_LOGDIR") 448 | if dir is None: 449 | dir = osp.join( 450 | tempfile.gettempdir(), 451 | datetime.datetime.now().strftime("openai-%Y-%m-%d-%H-%M-%S-%f"), 452 | ) 453 | assert isinstance(dir, str) 454 | dir = os.path.expanduser(dir) 455 | os.makedirs(os.path.expanduser(dir), exist_ok=True) 456 | 457 | rank = get_rank_without_mpi_import() 458 | if rank > 0: 459 | log_suffix = log_suffix + "-rank%03i" % rank 460 | 461 | if format_strs is None: 462 | if rank == 0: 463 | format_strs = os.getenv("OPENAI_LOG_FORMAT", "stdout,log,csv").split(",") 464 | else: 465 | format_strs = os.getenv("OPENAI_LOG_FORMAT_MPI", "log").split(",") 466 | format_strs = filter(None, format_strs) 467 | output_formats = [make_output_format(f, dir, log_suffix) for f in format_strs] 468 | 469 | Logger.CURRENT = Logger(dir=dir, output_formats=output_formats, comm=comm) 470 | if output_formats: 471 | log("Logging to %s" % dir) 472 | 473 | 474 | def _configure_default_logger(): 475 | configure() 476 | Logger.DEFAULT = Logger.CURRENT 477 | 478 | 479 | def reset(): 480 | if Logger.CURRENT is not Logger.DEFAULT: 481 | Logger.CURRENT.close() 482 | Logger.CURRENT = Logger.DEFAULT 483 | log("Reset logger") 484 | 485 | 486 | @contextmanager 487 | def scoped_configure(dir=None, format_strs=None, comm=None): 488 | prevlogger = Logger.CURRENT 489 | configure(dir=dir, format_strs=format_strs, comm=comm) 490 | try: 491 | yield 492 | finally: 493 | Logger.CURRENT.close() 494 | Logger.CURRENT = prevlogger 495 | 496 | -------------------------------------------------------------------------------- /guided_diffusion/losses.py: -------------------------------------------------------------------------------- 1 | """ 2 | Helpers for various likelihood-based losses. These are ported from the original 3 | Ho et al. diffusion models codebase: 4 | https://github.com/hojonathanho/diffusion/blob/1e0dceb3b3495bbe19116a5e1b3596cd0706c543/diffusion_tf/utils.py 5 | """ 6 | 7 | import numpy as np 8 | 9 | import torch as th 10 | 11 | 12 | def normal_kl(mean1, logvar1, mean2, logvar2): 13 | """ 14 | Compute the KL divergence between two gaussians. 15 | 16 | Shapes are automatically broadcasted, so batches can be compared to 17 | scalars, among other use cases. 18 | """ 19 | tensor = None 20 | for obj in (mean1, logvar1, mean2, logvar2): 21 | if isinstance(obj, th.Tensor): 22 | tensor = obj 23 | break 24 | assert tensor is not None, "at least one argument must be a Tensor" 25 | 26 | # Force variances to be Tensors. Broadcasting helps convert scalars to 27 | # Tensors, but it does not work for th.exp(). 28 | logvar1, logvar2 = [ 29 | x if isinstance(x, th.Tensor) else th.tensor(x).to(tensor) 30 | for x in (logvar1, logvar2) 31 | ] 32 | 33 | return 0.5 * ( 34 | -1.0 35 | + logvar2 36 | - logvar1 37 | + th.exp(logvar1 - logvar2) 38 | + ((mean1 - mean2) ** 2) * th.exp(-logvar2) 39 | ) 40 | 41 | 42 | def approx_standard_normal_cdf(x): 43 | """ 44 | A fast approximation of the cumulative distribution function of the 45 | standard normal. 46 | """ 47 | return 0.5 * (1.0 + th.tanh(np.sqrt(2.0 / np.pi) * (x + 0.044715 * th.pow(x, 3)))) 48 | 49 | 50 | def discretized_gaussian_log_likelihood(x, *, means, log_scales): 51 | """ 52 | Compute the log-likelihood of a Gaussian distribution discretizing to a 53 | given image. 54 | 55 | :param x: the target images. It is assumed that this was uint8 values, 56 | rescaled to the range [-1, 1]. 57 | :param means: the Gaussian mean Tensor. 58 | :param log_scales: the Gaussian log stddev Tensor. 59 | :return: a tensor like x of log probabilities (in nats). 60 | """ 61 | assert x.shape == means.shape == log_scales.shape 62 | centered_x = x - means 63 | inv_stdv = th.exp(-log_scales) 64 | plus_in = inv_stdv * (centered_x + 1.0 / 255.0) 65 | cdf_plus = approx_standard_normal_cdf(plus_in) 66 | min_in = inv_stdv * (centered_x - 1.0 / 255.0) 67 | cdf_min = approx_standard_normal_cdf(min_in) 68 | log_cdf_plus = th.log(cdf_plus.clamp(min=1e-12)) 69 | log_one_minus_cdf_min = th.log((1.0 - cdf_min).clamp(min=1e-12)) 70 | cdf_delta = cdf_plus - cdf_min 71 | log_probs = th.where( 72 | x < -0.999, 73 | log_cdf_plus, 74 | th.where(x > 0.999, log_one_minus_cdf_min, th.log(cdf_delta.clamp(min=1e-12))), 75 | ) 76 | assert log_probs.shape == x.shape 77 | return log_probs 78 | -------------------------------------------------------------------------------- /guided_diffusion/nn.py: -------------------------------------------------------------------------------- 1 | """ 2 | Various utilities for neural networks. 3 | """ 4 | 5 | import math 6 | 7 | import torch as th 8 | import torch.nn as nn 9 | 10 | 11 | # PyTorch 1.7 has SiLU, but we support PyTorch 1.5. 12 | class SiLU(nn.Module): 13 | def forward(self, x): 14 | return x * th.sigmoid(x) 15 | 16 | 17 | class GroupNorm32(nn.GroupNorm): 18 | def forward(self, x): 19 | return super().forward(x.float()).type(x.dtype) 20 | 21 | 22 | def conv_nd(dims, *args, **kwargs): 23 | """ 24 | Create a 1D, 2D, or 3D convolution module. 25 | """ 26 | if dims == 1: 27 | return nn.Conv1d(*args, **kwargs) 28 | elif dims == 2: 29 | return nn.Conv2d(*args, **kwargs) 30 | elif dims == 3: 31 | return nn.Conv3d(*args, **kwargs) 32 | raise ValueError(f"unsupported dimensions: {dims}") 33 | 34 | 35 | def linear(*args, **kwargs): 36 | """ 37 | Create a linear module. 38 | """ 39 | return nn.Linear(*args, **kwargs) 40 | 41 | 42 | def avg_pool_nd(dims, *args, **kwargs): 43 | """ 44 | Create a 1D, 2D, or 3D average pooling module. 45 | """ 46 | if dims == 1: 47 | return nn.AvgPool1d(*args, **kwargs) 48 | elif dims == 2: 49 | return nn.AvgPool2d(*args, **kwargs) 50 | elif dims == 3: 51 | return nn.AvgPool3d(*args, **kwargs) 52 | raise ValueError(f"unsupported dimensions: {dims}") 53 | 54 | 55 | def update_ema(target_params, source_params, rate=0.99): 56 | """ 57 | Update target parameters to be closer to those of source parameters using 58 | an exponential moving average. 59 | 60 | :param target_params: the target parameter sequence. 61 | :param source_params: the source parameter sequence. 62 | :param rate: the EMA rate (closer to 1 means slower). 63 | """ 64 | for targ, src in zip(target_params, source_params): 65 | targ.detach().mul_(rate).add_(src, alpha=1 - rate) 66 | 67 | 68 | def zero_module(module): 69 | """ 70 | Zero out the parameters of a module and return it. 71 | """ 72 | for p in module.parameters(): 73 | p.detach().zero_() 74 | return module 75 | 76 | 77 | def scale_module(module, scale): 78 | """ 79 | Scale the parameters of a module and return it. 80 | """ 81 | for p in module.parameters(): 82 | p.detach().mul_(scale) 83 | return module 84 | 85 | 86 | def mean_flat(tensor): 87 | """ 88 | Take the mean over all non-batch dimensions. 89 | """ 90 | return tensor.mean(dim=list(range(1, len(tensor.shape)))) 91 | 92 | 93 | def normalization(channels): 94 | """ 95 | Make a standard normalization layer. 96 | 97 | :param channels: number of input channels. 98 | :return: an nn.Module for normalization. 99 | """ 100 | return GroupNorm32(32, channels) 101 | 102 | 103 | def timestep_embedding(timesteps, dim, max_period=10000): 104 | """ 105 | Create sinusoidal timestep embeddings. 106 | 107 | :param timesteps: a 1-D Tensor of N indices, one per batch element. 108 | These may be fractional. 109 | :param dim: the dimension of the output. 110 | :param max_period: controls the minimum frequency of the embeddings. 111 | :return: an [N x dim] Tensor of positional embeddings. 112 | """ 113 | half = dim // 2 114 | freqs = th.exp( 115 | -math.log(max_period) * th.arange(start=0, end=half, dtype=th.float32) / half 116 | ).to(device=timesteps.device) 117 | args = timesteps[:, None].float() * freqs[None] 118 | embedding = th.cat([th.cos(args), th.sin(args)], dim=-1) 119 | if dim % 2: 120 | embedding = th.cat([embedding, th.zeros_like(embedding[:, :1])], dim=-1) 121 | return embedding 122 | 123 | 124 | def checkpoint(func, inputs, params, flag): 125 | """ 126 | Evaluate a function without caching intermediate activations, allowing for 127 | reduced memory at the expense of extra compute in the backward pass. 128 | 129 | :param func: the function to evaluate. 130 | :param inputs: the argument sequence to pass to `func`. 131 | :param params: a sequence of parameters `func` depends on but does not 132 | explicitly take as arguments. 133 | :param flag: if False, disable gradient checkpointing. 134 | """ 135 | if flag: 136 | args = tuple(inputs) + tuple(params) 137 | return CheckpointFunction.apply(func, len(inputs), *args) 138 | else: 139 | return func(*inputs) 140 | 141 | 142 | class CheckpointFunction(th.autograd.Function): 143 | @staticmethod 144 | def forward(ctx, run_function, length, *args): 145 | ctx.run_function = run_function 146 | ctx.input_tensors = list(args[:length]) 147 | ctx.input_params = list(args[length:]) 148 | with th.no_grad(): 149 | output_tensors = ctx.run_function(*ctx.input_tensors) 150 | return output_tensors 151 | 152 | @staticmethod 153 | def backward(ctx, *output_grads): 154 | ctx.input_tensors = [x.detach().requires_grad_(True) for x in ctx.input_tensors] 155 | with th.enable_grad(): 156 | # Fixes a bug where the first op in run_function modifies the 157 | # Tensor storage in place, which is not allowed for detach()'d 158 | # Tensors. 159 | shallow_copies = [x.view_as(x) for x in ctx.input_tensors] 160 | output_tensors = ctx.run_function(*shallow_copies) 161 | input_grads = th.autograd.grad( 162 | output_tensors, 163 | ctx.input_tensors + ctx.input_params, 164 | output_grads, 165 | allow_unused=True, 166 | ) 167 | del ctx.input_tensors 168 | del ctx.input_params 169 | del output_tensors 170 | return (None, None) + input_grads 171 | -------------------------------------------------------------------------------- /guided_diffusion/resample.py: -------------------------------------------------------------------------------- 1 | from abc import ABC, abstractmethod 2 | 3 | import numpy as np 4 | import torch as th 5 | import torch.distributed as dist 6 | 7 | 8 | def create_named_schedule_sampler(name, diffusion): 9 | """ 10 | Create a ScheduleSampler from a library of pre-defined samplers. 11 | 12 | :param name: the name of the sampler. 13 | :param diffusion: the diffusion object to sample for. 14 | """ 15 | if name == "uniform": 16 | return UniformSampler(diffusion) 17 | elif name == "loss-second-moment": 18 | return LossSecondMomentResampler(diffusion) 19 | else: 20 | raise NotImplementedError(f"unknown schedule sampler: {name}") 21 | 22 | 23 | class ScheduleSampler(ABC): 24 | """ 25 | A distribution over timesteps in the diffusion process, intended to reduce 26 | variance of the objective. 27 | 28 | By default, samplers perform unbiased importance sampling, in which the 29 | objective's mean is unchanged. 30 | However, subclasses may override sample() to change how the resampled 31 | terms are reweighted, allowing for actual changes in the objective. 32 | """ 33 | 34 | @abstractmethod 35 | def weights(self): 36 | """ 37 | Get a numpy array of weights, one per diffusion step. 38 | 39 | The weights needn't be normalized, but must be positive. 40 | """ 41 | 42 | def sample(self, batch_size, device): 43 | """ 44 | Importance-sample timesteps for a batch. 45 | 46 | :param batch_size: the number of timesteps. 47 | :param device: the torch device to save to. 48 | :return: a tuple (timesteps, weights): 49 | - timesteps: a tensor of timestep indices. 50 | - weights: a tensor of weights to scale the resulting losses. 51 | """ 52 | w = self.weights() 53 | p = w / np.sum(w) 54 | indices_np = np.random.choice(len(p), size=(batch_size,), p=p) 55 | indices = th.from_numpy(indices_np).long().to(device) 56 | weights_np = 1 / (len(p) * p[indices_np]) 57 | weights = th.from_numpy(weights_np).float().to(device) 58 | return indices, weights 59 | 60 | 61 | class UniformSampler(ScheduleSampler): 62 | def __init__(self, diffusion): 63 | self.diffusion = diffusion 64 | self._weights = np.ones([diffusion.num_timesteps]) 65 | 66 | def weights(self): 67 | return self._weights 68 | 69 | 70 | class LossAwareSampler(ScheduleSampler): 71 | def update_with_local_losses(self, local_ts, local_losses): 72 | """ 73 | Update the reweighting using losses from a model. 74 | 75 | Call this method from each rank with a batch of timesteps and the 76 | corresponding losses for each of those timesteps. 77 | This method will perform synchronization to make sure all of the ranks 78 | maintain the exact same reweighting. 79 | 80 | :param local_ts: an integer Tensor of timesteps. 81 | :param local_losses: a 1D Tensor of losses. 82 | """ 83 | batch_sizes = [ 84 | th.tensor([0], dtype=th.int32, device=local_ts.device) 85 | for _ in range(dist.get_world_size()) 86 | ] 87 | dist.all_gather( 88 | batch_sizes, 89 | th.tensor([len(local_ts)], dtype=th.int32, device=local_ts.device), 90 | ) 91 | 92 | # Pad all_gather batches to be the maximum batch size. 93 | batch_sizes = [x.item() for x in batch_sizes] 94 | max_bs = max(batch_sizes) 95 | 96 | timestep_batches = [th.zeros(max_bs).to(local_ts) for bs in batch_sizes] 97 | loss_batches = [th.zeros(max_bs).to(local_losses) for bs in batch_sizes] 98 | dist.all_gather(timestep_batches, local_ts) 99 | dist.all_gather(loss_batches, local_losses) 100 | timesteps = [ 101 | x.item() for y, bs in zip(timestep_batches, batch_sizes) for x in y[:bs] 102 | ] 103 | losses = [x.item() for y, bs in zip(loss_batches, batch_sizes) for x in y[:bs]] 104 | self.update_with_all_losses(timesteps, losses) 105 | 106 | @abstractmethod 107 | def update_with_all_losses(self, ts, losses): 108 | """ 109 | Update the reweighting using losses from a model. 110 | 111 | Sub-classes should override this method to update the reweighting 112 | using losses from the model. 113 | 114 | This method directly updates the reweighting without synchronizing 115 | between workers. It is called by update_with_local_losses from all 116 | ranks with identical arguments. Thus, it should have deterministic 117 | behavior to maintain state across workers. 118 | 119 | :param ts: a list of int timesteps. 120 | :param losses: a list of float losses, one per timestep. 121 | """ 122 | 123 | 124 | class LossSecondMomentResampler(LossAwareSampler): 125 | def __init__(self, diffusion, history_per_term=10, uniform_prob=0.001): 126 | self.diffusion = diffusion 127 | self.history_per_term = history_per_term 128 | self.uniform_prob = uniform_prob 129 | self._loss_history = np.zeros( 130 | [diffusion.num_timesteps, history_per_term], dtype=np.float64 131 | ) 132 | self._loss_counts = np.zeros([diffusion.num_timesteps], dtype=np.int) 133 | 134 | def weights(self): 135 | if not self._warmed_up(): 136 | return np.ones([self.diffusion.num_timesteps], dtype=np.float64) 137 | weights = np.sqrt(np.mean(self._loss_history ** 2, axis=-1)) 138 | weights /= np.sum(weights) 139 | weights *= 1 - self.uniform_prob 140 | weights += self.uniform_prob / len(weights) 141 | return weights 142 | 143 | def update_with_all_losses(self, ts, losses): 144 | for t, loss in zip(ts, losses): 145 | if self._loss_counts[t] == self.history_per_term: 146 | # Shift out the oldest loss term. 147 | self._loss_history[t, :-1] = self._loss_history[t, 1:] 148 | self._loss_history[t, -1] = loss 149 | else: 150 | self._loss_history[t, self._loss_counts[t]] = loss 151 | self._loss_counts[t] += 1 152 | 153 | def _warmed_up(self): 154 | return (self._loss_counts == self.history_per_term).all() 155 | -------------------------------------------------------------------------------- /guided_diffusion/respace.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import torch as th 3 | 4 | from .gaussian_diffusion import GaussianDiffusion 5 | 6 | def space_timesteps(num_timesteps, section_counts): 7 | """ 8 | Create a list of timesteps to use from an original diffusion process, 9 | given the number of timesteps we want to take from equally-sized portions 10 | of the original process. 11 | 12 | For example, if there's 300 timesteps and the section counts are [10,15,20] 13 | then the first 100 timesteps are strided to be 10 timesteps, the second 100 14 | are strided to be 15 timesteps, and the final 100 are strided to be 20. 15 | 16 | If the stride is a string starting with "ddim", then the fixed striding 17 | from the DDIM paper is used, and only one section is allowed. 18 | 19 | :param num_timesteps: the number of diffusion steps in the original 20 | process to divide up. 21 | :param section_counts: either a list of numbers, or a string containing 22 | comma-separated numbers, indicating the step count 23 | per section. As a special case, use "ddimN" where N 24 | is a number of steps to use the striding from the 25 | DDIM paper. 26 | :return: a set of diffusion steps from the original process to use. 27 | """ 28 | if isinstance(section_counts, str): 29 | if section_counts.startswith("ddim"): 30 | desired_count = int(section_counts[len("ddim") :]) 31 | for i in range(1, num_timesteps): 32 | if len(range(0, num_timesteps, i)) == desired_count: 33 | return set(range(0, num_timesteps, i)) 34 | raise ValueError( 35 | f"cannot create exactly {num_timesteps} steps with an integer stride" 36 | ) 37 | section_counts = [int(x) for x in section_counts.split(",")] 38 | size_per = num_timesteps // len(section_counts) 39 | extra = num_timesteps % len(section_counts) 40 | start_idx = 0 41 | all_steps = [] 42 | for i, section_count in enumerate(section_counts): 43 | size = size_per + (1 if i < extra else 0) 44 | if size < section_count: 45 | raise ValueError( 46 | f"cannot divide section of {size} steps into {section_count}" 47 | ) 48 | if section_count <= 1: 49 | frac_stride = 1 50 | else: 51 | frac_stride = (size - 1) / (section_count - 1) 52 | cur_idx = 0.0 53 | taken_steps = [] 54 | for _ in range(section_count): 55 | taken_steps.append(start_idx + round(cur_idx)) 56 | cur_idx += frac_stride 57 | all_steps += taken_steps 58 | start_idx += size 59 | return set(all_steps) 60 | 61 | 62 | class SpacedDiffusion(GaussianDiffusion): 63 | """ 64 | A diffusion process which can skip steps in a base diffusion process. 65 | 66 | :param use_timesteps: a collection (sequence or set) of timesteps from the 67 | original diffusion process to retain. 68 | :param kwargs: the kwargs to create the base diffusion process. 69 | """ 70 | 71 | def __init__(self, use_timesteps, **kwargs): 72 | self.use_timesteps = set(use_timesteps) 73 | self.timestep_map = [] 74 | self.original_num_steps = len(kwargs["betas"]) 75 | 76 | base_diffusion = GaussianDiffusion(**kwargs) # pylint: disable=missing-kwoa 77 | last_alpha_cumprod = 1.0 78 | new_betas = [] 79 | for i, alpha_cumprod in enumerate(base_diffusion.alphas_cumprod): 80 | if i in self.use_timesteps: 81 | new_betas.append(1 - alpha_cumprod / last_alpha_cumprod) 82 | last_alpha_cumprod = alpha_cumprod 83 | self.timestep_map.append(i) 84 | kwargs["betas"] = np.array(new_betas) 85 | super().__init__(**kwargs) 86 | 87 | 88 | def p_mean_variance( 89 | self, model, *args, **kwargs 90 | ): # pylint: disable=signature-differs 91 | return super().p_mean_variance(self._wrap_model(model), *args, **kwargs) 92 | 93 | def training_losses( 94 | self, model, *args, **kwargs 95 | ): # pylint: disable=signature-differs 96 | return super().training_losses(self._wrap_model(model), *args, **kwargs) 97 | 98 | def condition_mean(self, cond_fn, *args, **kwargs): 99 | return super().condition_mean(self._wrap_model(cond_fn), *args, **kwargs) 100 | 101 | def condition_score(self, cond_fn, *args, **kwargs): 102 | return super().condition_score(self._wrap_model(cond_fn), *args, **kwargs) 103 | 104 | def _wrap_model(self, model): 105 | if isinstance(model, _WrappedModel): 106 | return model 107 | return _WrappedModel( 108 | model, self.timestep_map, self.rescale_timesteps, self.original_num_steps 109 | ) 110 | 111 | def _scale_timesteps(self, t): 112 | # Scaling is done by the wrapped model. 113 | return t 114 | 115 | 116 | class _WrappedModel: 117 | def __init__(self, model, timestep_map, rescale_timesteps, original_num_steps): 118 | self.model = model 119 | self.timestep_map = timestep_map 120 | self.rescale_timesteps = rescale_timesteps 121 | self.original_num_steps = original_num_steps 122 | 123 | def __call__(self, x, ts, **kwargs): 124 | map_tensor = th.tensor(self.timestep_map, device=ts.device, dtype=ts.dtype) 125 | new_ts = map_tensor[ts] 126 | if self.rescale_timesteps: 127 | new_ts = new_ts.float() * (1000.0 / self.original_num_steps) 128 | # update args to match torch.func.functional_call() 129 | return self.model(args=(x, new_ts), kwargs=kwargs) 130 | -------------------------------------------------------------------------------- /guided_diffusion/script_util.py: -------------------------------------------------------------------------------- 1 | import argparse 2 | import inspect 3 | 4 | from . import gaussian_diffusion as gd 5 | from .respace import SpacedDiffusion, space_timesteps 6 | from .unet import SuperResModel, UNetModel, EncoderUNetModel 7 | 8 | NUM_CLASSES = 1000 9 | 10 | 11 | def diffusion_defaults(): 12 | """ 13 | Defaults for image and classifier training. 14 | """ 15 | return dict( 16 | learn_sigma=False, 17 | diffusion_steps=1000, 18 | noise_schedule="linear", 19 | timestep_respacing="", 20 | use_kl=False, 21 | predict_xstart=False, 22 | rescale_timesteps=False, 23 | rescale_learned_sigmas=False, 24 | ) 25 | 26 | 27 | def classifier_defaults(): 28 | """ 29 | Defaults for classifier models. 30 | """ 31 | return dict( 32 | image_size=64, 33 | classifier_use_fp16=False, 34 | classifier_width=128, 35 | classifier_depth=2, 36 | classifier_attention_resolutions="32,16,8", # 16 37 | classifier_use_scale_shift_norm=True, # False 38 | classifier_resblock_updown=True, # False 39 | classifier_pool="attention", 40 | ) 41 | 42 | 43 | def model_and_diffusion_defaults(): 44 | """ 45 | Defaults for image training. 46 | """ 47 | res = dict( 48 | image_size=64, 49 | num_channels=128, 50 | num_res_blocks=2, 51 | num_heads=4, 52 | num_heads_upsample=-1, 53 | num_head_channels=-1, 54 | attention_resolutions="16,8", 55 | channel_mult="", 56 | dropout=0.0, 57 | class_cond=False, 58 | use_checkpoint=False, 59 | use_scale_shift_norm=True, 60 | resblock_updown=False, 61 | use_fp16=False, 62 | use_new_attention_order=False, 63 | ) 64 | res.update(diffusion_defaults()) 65 | return res 66 | 67 | 68 | def classifier_and_diffusion_defaults(): 69 | res = classifier_defaults() 70 | res.update(diffusion_defaults()) 71 | return res 72 | 73 | 74 | def create_model_and_diffusion( 75 | image_size, 76 | class_cond, 77 | learn_sigma, 78 | num_channels, 79 | num_res_blocks, 80 | channel_mult, 81 | num_heads, 82 | num_head_channels, 83 | num_heads_upsample, 84 | attention_resolutions, 85 | dropout, 86 | diffusion_steps, 87 | noise_schedule, 88 | timestep_respacing, 89 | use_kl, 90 | predict_xstart, 91 | rescale_timesteps, 92 | rescale_learned_sigmas, 93 | use_checkpoint, 94 | use_scale_shift_norm, 95 | resblock_updown, 96 | use_fp16, 97 | use_new_attention_order, 98 | ): 99 | model = create_model( 100 | image_size, 101 | num_channels, 102 | num_res_blocks, 103 | channel_mult=channel_mult, 104 | learn_sigma=learn_sigma, 105 | class_cond=class_cond, 106 | use_checkpoint=use_checkpoint, 107 | attention_resolutions=attention_resolutions, 108 | num_heads=num_heads, 109 | num_head_channels=num_head_channels, 110 | num_heads_upsample=num_heads_upsample, 111 | use_scale_shift_norm=use_scale_shift_norm, 112 | dropout=dropout, 113 | resblock_updown=resblock_updown, 114 | use_fp16=use_fp16, 115 | use_new_attention_order=use_new_attention_order, 116 | ) 117 | diffusion = create_gaussian_diffusion( 118 | steps=diffusion_steps, 119 | learn_sigma=learn_sigma, 120 | noise_schedule=noise_schedule, 121 | use_kl=use_kl, 122 | predict_xstart=predict_xstart, 123 | rescale_timesteps=rescale_timesteps, 124 | rescale_learned_sigmas=rescale_learned_sigmas, 125 | timestep_respacing=timestep_respacing, 126 | ) 127 | return model, diffusion 128 | 129 | 130 | def create_model( 131 | image_size, 132 | num_channels, 133 | num_res_blocks, 134 | channel_mult="", 135 | learn_sigma=False, 136 | class_cond=False, 137 | use_checkpoint=False, 138 | attention_resolutions="16", 139 | num_heads=1, 140 | num_head_channels=-1, 141 | num_heads_upsample=-1, 142 | use_scale_shift_norm=False, 143 | dropout=0, 144 | resblock_updown=False, 145 | use_fp16=False, 146 | use_new_attention_order=False, 147 | ): 148 | if channel_mult == "": 149 | if image_size == 512: 150 | channel_mult = (0.5, 1, 1, 2, 2, 4, 4) 151 | elif image_size == 256: 152 | channel_mult = (1, 1, 2, 2, 4, 4) 153 | elif image_size == 128: 154 | channel_mult = (1, 1, 2, 3, 4) 155 | elif image_size == 64: 156 | channel_mult = (1, 2, 3, 4) 157 | else: 158 | raise ValueError(f"unsupported image size: {image_size}") 159 | else: 160 | channel_mult = tuple(int(ch_mult) for ch_mult in channel_mult.split(",")) 161 | 162 | attention_ds = [] 163 | for res in attention_resolutions.split(","): 164 | attention_ds.append(image_size // int(res)) 165 | 166 | return UNetModel( 167 | image_size=image_size, 168 | in_channels=3, 169 | model_channels=num_channels, 170 | out_channels=(3 if not learn_sigma else 6), 171 | num_res_blocks=num_res_blocks, 172 | attention_resolutions=tuple(attention_ds), 173 | dropout=dropout, 174 | channel_mult=channel_mult, 175 | num_classes=(NUM_CLASSES if class_cond else None), 176 | use_checkpoint=use_checkpoint, 177 | use_fp16=use_fp16, 178 | num_heads=num_heads, 179 | num_head_channels=num_head_channels, 180 | num_heads_upsample=num_heads_upsample, 181 | use_scale_shift_norm=use_scale_shift_norm, 182 | resblock_updown=resblock_updown, 183 | use_new_attention_order=use_new_attention_order, 184 | ) 185 | 186 | 187 | def create_classifier_and_diffusion( 188 | image_size, 189 | classifier_use_fp16, 190 | classifier_width, 191 | classifier_depth, 192 | classifier_attention_resolutions, 193 | classifier_use_scale_shift_norm, 194 | classifier_resblock_updown, 195 | classifier_pool, 196 | learn_sigma, 197 | diffusion_steps, 198 | noise_schedule, 199 | timestep_respacing, 200 | use_kl, 201 | predict_xstart, 202 | rescale_timesteps, 203 | rescale_learned_sigmas, 204 | ): 205 | classifier = create_classifier( 206 | image_size, 207 | classifier_use_fp16, 208 | classifier_width, 209 | classifier_depth, 210 | classifier_attention_resolutions, 211 | classifier_use_scale_shift_norm, 212 | classifier_resblock_updown, 213 | classifier_pool, 214 | ) 215 | diffusion = create_gaussian_diffusion( 216 | steps=diffusion_steps, 217 | learn_sigma=learn_sigma, 218 | noise_schedule=noise_schedule, 219 | use_kl=use_kl, 220 | predict_xstart=predict_xstart, 221 | rescale_timesteps=rescale_timesteps, 222 | rescale_learned_sigmas=rescale_learned_sigmas, 223 | timestep_respacing=timestep_respacing, 224 | ) 225 | return classifier, diffusion 226 | 227 | 228 | def create_classifier( 229 | image_size, 230 | classifier_use_fp16, 231 | classifier_width, 232 | classifier_depth, 233 | classifier_attention_resolutions, 234 | classifier_use_scale_shift_norm, 235 | classifier_resblock_updown, 236 | classifier_pool, 237 | ): 238 | if image_size == 512: 239 | channel_mult = (0.5, 1, 1, 2, 2, 4, 4) 240 | elif image_size == 256: 241 | channel_mult = (1, 1, 2, 2, 4, 4) 242 | elif image_size == 128: 243 | channel_mult = (1, 1, 2, 3, 4) 244 | elif image_size == 64: 245 | channel_mult = (1, 2, 3, 4) 246 | else: 247 | raise ValueError(f"unsupported image size: {image_size}") 248 | 249 | attention_ds = [] 250 | for res in classifier_attention_resolutions.split(","): 251 | attention_ds.append(image_size // int(res)) 252 | 253 | return EncoderUNetModel( 254 | image_size=image_size, 255 | in_channels=3, 256 | model_channels=classifier_width, 257 | out_channels=1000, 258 | num_res_blocks=classifier_depth, 259 | attention_resolutions=tuple(attention_ds), 260 | channel_mult=channel_mult, 261 | use_fp16=classifier_use_fp16, 262 | num_head_channels=64, 263 | use_scale_shift_norm=classifier_use_scale_shift_norm, 264 | resblock_updown=classifier_resblock_updown, 265 | pool=classifier_pool, 266 | ) 267 | 268 | 269 | def sr_model_and_diffusion_defaults(): 270 | res = model_and_diffusion_defaults() 271 | res["large_size"] = 256 272 | res["small_size"] = 64 273 | arg_names = inspect.getfullargspec(sr_create_model_and_diffusion)[0] 274 | for k in res.copy().keys(): 275 | if k not in arg_names: 276 | del res[k] 277 | return res 278 | 279 | 280 | def sr_create_model_and_diffusion( 281 | large_size, 282 | small_size, 283 | class_cond, 284 | learn_sigma, 285 | num_channels, 286 | num_res_blocks, 287 | num_heads, 288 | num_head_channels, 289 | num_heads_upsample, 290 | attention_resolutions, 291 | dropout, 292 | diffusion_steps, 293 | noise_schedule, 294 | timestep_respacing, 295 | use_kl, 296 | predict_xstart, 297 | rescale_timesteps, 298 | rescale_learned_sigmas, 299 | use_checkpoint, 300 | use_scale_shift_norm, 301 | resblock_updown, 302 | use_fp16, 303 | ): 304 | model = sr_create_model( 305 | large_size, 306 | small_size, 307 | num_channels, 308 | num_res_blocks, 309 | learn_sigma=learn_sigma, 310 | class_cond=class_cond, 311 | use_checkpoint=use_checkpoint, 312 | attention_resolutions=attention_resolutions, 313 | num_heads=num_heads, 314 | num_head_channels=num_head_channels, 315 | num_heads_upsample=num_heads_upsample, 316 | use_scale_shift_norm=use_scale_shift_norm, 317 | dropout=dropout, 318 | resblock_updown=resblock_updown, 319 | use_fp16=use_fp16, 320 | ) 321 | diffusion = create_gaussian_diffusion( 322 | steps=diffusion_steps, 323 | learn_sigma=learn_sigma, 324 | noise_schedule=noise_schedule, 325 | use_kl=use_kl, 326 | predict_xstart=predict_xstart, 327 | rescale_timesteps=rescale_timesteps, 328 | rescale_learned_sigmas=rescale_learned_sigmas, 329 | timestep_respacing=timestep_respacing, 330 | ) 331 | return model, diffusion 332 | 333 | 334 | def sr_create_model( 335 | large_size, 336 | small_size, 337 | num_channels, 338 | num_res_blocks, 339 | learn_sigma, 340 | class_cond, 341 | use_checkpoint, 342 | attention_resolutions, 343 | num_heads, 344 | num_head_channels, 345 | num_heads_upsample, 346 | use_scale_shift_norm, 347 | dropout, 348 | resblock_updown, 349 | use_fp16, 350 | ): 351 | _ = small_size # hack to prevent unused variable 352 | 353 | if large_size == 512: 354 | channel_mult = (1, 1, 2, 2, 4, 4) 355 | elif large_size == 256: 356 | channel_mult = (1, 1, 2, 2, 4, 4) 357 | elif large_size == 64: 358 | channel_mult = (1, 2, 3, 4) 359 | else: 360 | raise ValueError(f"unsupported large size: {large_size}") 361 | 362 | attention_ds = [] 363 | for res in attention_resolutions.split(","): 364 | attention_ds.append(large_size // int(res)) 365 | 366 | return SuperResModel( 367 | image_size=large_size, 368 | in_channels=3, 369 | model_channels=num_channels, 370 | out_channels=(3 if not learn_sigma else 6), 371 | num_res_blocks=num_res_blocks, 372 | attention_resolutions=tuple(attention_ds), 373 | dropout=dropout, 374 | channel_mult=channel_mult, 375 | num_classes=(NUM_CLASSES if class_cond else None), 376 | use_checkpoint=use_checkpoint, 377 | num_heads=num_heads, 378 | num_head_channels=num_head_channels, 379 | num_heads_upsample=num_heads_upsample, 380 | use_scale_shift_norm=use_scale_shift_norm, 381 | resblock_updown=resblock_updown, 382 | use_fp16=use_fp16, 383 | ) 384 | 385 | 386 | def create_gaussian_diffusion( 387 | *, 388 | steps=1000, 389 | learn_sigma=False, 390 | sigma_small=False, 391 | noise_schedule="linear", 392 | use_kl=False, 393 | predict_xstart=False, 394 | rescale_timesteps=False, 395 | rescale_learned_sigmas=False, 396 | timestep_respacing="", 397 | ): 398 | betas = gd.get_named_beta_schedule(noise_schedule, steps) 399 | if use_kl: 400 | loss_type = gd.LossType.RESCALED_KL 401 | elif rescale_learned_sigmas: 402 | loss_type = gd.LossType.RESCALED_MSE 403 | else: 404 | loss_type = gd.LossType.MSE 405 | if not timestep_respacing: 406 | timestep_respacing = [steps] 407 | return SpacedDiffusion( 408 | use_timesteps=space_timesteps(steps, timestep_respacing), 409 | betas=betas, 410 | model_mean_type=( 411 | gd.ModelMeanType.EPSILON if not predict_xstart else gd.ModelMeanType.START_X 412 | ), 413 | model_var_type=( 414 | ( 415 | gd.ModelVarType.FIXED_LARGE 416 | if not sigma_small 417 | else gd.ModelVarType.FIXED_SMALL 418 | ) 419 | if not learn_sigma 420 | else gd.ModelVarType.LEARNED_RANGE 421 | ), 422 | loss_type=loss_type, 423 | rescale_timesteps=rescale_timesteps, 424 | ) 425 | 426 | 427 | def add_dict_to_argparser(parser, default_dict): 428 | for k, v in default_dict.items(): 429 | v_type = type(v) 430 | if v is None: 431 | v_type = str 432 | elif isinstance(v, bool): 433 | v_type = str2bool 434 | parser.add_argument(f"--{k}", default=v, type=v_type) 435 | 436 | 437 | def args_to_dict(args, keys): 438 | return {k: getattr(args, k) for k in keys} 439 | 440 | 441 | def str2bool(v): 442 | """ 443 | https://stackoverflow.com/questions/15008758/parsing-boolean-values-with-argparse 444 | """ 445 | if isinstance(v, bool): 446 | return v 447 | if v.lower() in ("yes", "true", "t", "y", "1"): 448 | return True 449 | elif v.lower() in ("no", "false", "f", "n", "0"): 450 | return False 451 | else: 452 | raise argparse.ArgumentTypeError("boolean value expected") 453 | -------------------------------------------------------------------------------- /guided_diffusion/train_util.py: -------------------------------------------------------------------------------- 1 | import copy 2 | import functools 3 | import os 4 | 5 | import blobfile as bf 6 | import torch as th 7 | import torch.distributed as dist 8 | from torch.nn.parallel.distributed import DistributedDataParallel as DDP 9 | from torch.optim import AdamW 10 | 11 | from . import dist_util, logger 12 | from .fp16_util import MixedPrecisionTrainer 13 | from .nn import update_ema 14 | from .resample import LossAwareSampler, UniformSampler 15 | 16 | # For ImageNet experiments, this was a good default value. 17 | # We found that the lg_loss_scale quickly climbed to 18 | # 20-21 within the first ~1K steps of training. 19 | INITIAL_LOG_LOSS_SCALE = 20.0 20 | 21 | 22 | class TrainLoop: 23 | def __init__( 24 | self, 25 | *, 26 | model, 27 | diffusion, 28 | data, 29 | batch_size, 30 | microbatch, 31 | lr, 32 | ema_rate, 33 | log_interval, 34 | save_interval, 35 | resume_checkpoint, 36 | use_fp16=False, 37 | fp16_scale_growth=1e-3, 38 | schedule_sampler=None, 39 | weight_decay=0.0, 40 | lr_anneal_steps=0, 41 | ): 42 | self.model = model 43 | self.diffusion = diffusion 44 | self.data = data 45 | self.batch_size = batch_size 46 | self.microbatch = microbatch if microbatch > 0 else batch_size 47 | self.lr = lr 48 | self.ema_rate = ( 49 | [ema_rate] 50 | if isinstance(ema_rate, float) 51 | else [float(x) for x in ema_rate.split(",")] 52 | ) 53 | self.log_interval = log_interval 54 | self.save_interval = save_interval 55 | self.resume_checkpoint = resume_checkpoint 56 | self.use_fp16 = use_fp16 57 | self.fp16_scale_growth = fp16_scale_growth 58 | self.schedule_sampler = schedule_sampler or UniformSampler(diffusion) 59 | self.weight_decay = weight_decay 60 | self.lr_anneal_steps = lr_anneal_steps 61 | 62 | self.step = 0 63 | self.resume_step = 0 64 | self.global_batch = self.batch_size * dist.get_world_size() 65 | 66 | self.sync_cuda = th.cuda.is_available() 67 | 68 | self._load_and_sync_parameters() 69 | self.mp_trainer = MixedPrecisionTrainer( 70 | model=self.model, 71 | use_fp16=self.use_fp16, 72 | fp16_scale_growth=fp16_scale_growth, 73 | ) 74 | 75 | self.opt = AdamW( 76 | self.mp_trainer.master_params, lr=self.lr, weight_decay=self.weight_decay 77 | ) 78 | if self.resume_step: 79 | self._load_optimizer_state() 80 | # Model was resumed, either due to a restart or a checkpoint 81 | # being specified at the command line. 82 | self.ema_params = [ 83 | self._load_ema_parameters(rate) for rate in self.ema_rate 84 | ] 85 | else: 86 | self.ema_params = [ 87 | copy.deepcopy(self.mp_trainer.master_params) 88 | for _ in range(len(self.ema_rate)) 89 | ] 90 | 91 | if th.cuda.is_available(): 92 | self.use_ddp = True 93 | self.ddp_model = DDP( 94 | self.model, 95 | device_ids=[dist_util.dev()], 96 | output_device=dist_util.dev(), 97 | broadcast_buffers=False, 98 | bucket_cap_mb=128, 99 | find_unused_parameters=False, 100 | ) 101 | else: 102 | if dist.get_world_size() > 1: 103 | logger.warn( 104 | "Distributed training requires CUDA. " 105 | "Gradients will not be synchronized properly!" 106 | ) 107 | self.use_ddp = False 108 | self.ddp_model = self.model 109 | 110 | def _load_and_sync_parameters(self): 111 | resume_checkpoint = find_resume_checkpoint() or self.resume_checkpoint 112 | 113 | if resume_checkpoint: 114 | self.resume_step = parse_resume_step_from_filename(resume_checkpoint) 115 | if dist.get_rank() == 0: 116 | logger.log(f"loading model from checkpoint: {resume_checkpoint}...") 117 | self.model.load_state_dict( 118 | dist_util.load_state_dict( 119 | resume_checkpoint, map_location=dist_util.dev() 120 | ) 121 | ) 122 | 123 | dist_util.sync_params(self.model.parameters()) 124 | 125 | def _load_ema_parameters(self, rate): 126 | ema_params = copy.deepcopy(self.mp_trainer.master_params) 127 | 128 | main_checkpoint = find_resume_checkpoint() or self.resume_checkpoint 129 | ema_checkpoint = find_ema_checkpoint(main_checkpoint, self.resume_step, rate) 130 | if ema_checkpoint: 131 | if dist.get_rank() == 0: 132 | logger.log(f"loading EMA from checkpoint: {ema_checkpoint}...") 133 | state_dict = dist_util.load_state_dict( 134 | ema_checkpoint, map_location=dist_util.dev() 135 | ) 136 | ema_params = self.mp_trainer.state_dict_to_master_params(state_dict) 137 | 138 | dist_util.sync_params(ema_params) 139 | return ema_params 140 | 141 | def _load_optimizer_state(self): 142 | main_checkpoint = find_resume_checkpoint() or self.resume_checkpoint 143 | opt_checkpoint = bf.join( 144 | bf.dirname(main_checkpoint), f"opt{self.resume_step:06}.pt" 145 | ) 146 | if bf.exists(opt_checkpoint): 147 | logger.log(f"loading optimizer state from checkpoint: {opt_checkpoint}") 148 | state_dict = dist_util.load_state_dict( 149 | opt_checkpoint, map_location=dist_util.dev() 150 | ) 151 | self.opt.load_state_dict(state_dict) 152 | 153 | def run_loop(self): 154 | while ( 155 | not self.lr_anneal_steps 156 | or self.step + self.resume_step < self.lr_anneal_steps 157 | ): 158 | batch, cond = next(self.data) 159 | self.run_step(batch, cond) 160 | if self.step % self.log_interval == 0: 161 | logger.dumpkvs() 162 | if self.step % self.save_interval == 0: 163 | self.save() 164 | # Run for a finite amount of time in integration tests. 165 | if os.environ.get("DIFFUSION_TRAINING_TEST", "") and self.step > 0: 166 | return 167 | self.step += 1 168 | # Save the last checkpoint if it wasn't already saved. 169 | if (self.step - 1) % self.save_interval != 0: 170 | self.save() 171 | 172 | def run_step(self, batch, cond): 173 | self.forward_backward(batch, cond) 174 | took_step = self.mp_trainer.optimize(self.opt) 175 | if took_step: 176 | self._update_ema() 177 | self._anneal_lr() 178 | self.log_step() 179 | 180 | def forward_backward(self, batch, cond): 181 | self.mp_trainer.zero_grad() 182 | for i in range(0, batch.shape[0], self.microbatch): 183 | micro = batch[i : i + self.microbatch].to(dist_util.dev()) 184 | micro_cond = { 185 | k: v[i : i + self.microbatch].to(dist_util.dev()) 186 | for k, v in cond.items() 187 | } 188 | last_batch = (i + self.microbatch) >= batch.shape[0] 189 | t, weights = self.schedule_sampler.sample(micro.shape[0], dist_util.dev()) 190 | 191 | compute_losses = functools.partial( 192 | self.diffusion.training_losses, 193 | self.ddp_model, 194 | micro, 195 | t, 196 | model_kwargs=micro_cond, 197 | ) 198 | 199 | if last_batch or not self.use_ddp: 200 | losses = compute_losses() 201 | else: 202 | with self.ddp_model.no_sync(): 203 | losses = compute_losses() 204 | 205 | if isinstance(self.schedule_sampler, LossAwareSampler): 206 | self.schedule_sampler.update_with_local_losses( 207 | t, losses["loss"].detach() 208 | ) 209 | 210 | loss = (losses["loss"] * weights).mean() 211 | log_loss_dict( 212 | self.diffusion, t, {k: v * weights for k, v in losses.items()} 213 | ) 214 | self.mp_trainer.backward(loss) 215 | 216 | def _update_ema(self): 217 | for rate, params in zip(self.ema_rate, self.ema_params): 218 | update_ema(params, self.mp_trainer.master_params, rate=rate) 219 | 220 | def _anneal_lr(self): 221 | if not self.lr_anneal_steps: 222 | return 223 | frac_done = (self.step + self.resume_step) / self.lr_anneal_steps 224 | lr = self.lr * (1 - frac_done) 225 | for param_group in self.opt.param_groups: 226 | param_group["lr"] = lr 227 | 228 | def log_step(self): 229 | logger.logkv("step", self.step + self.resume_step) 230 | logger.logkv("samples", (self.step + self.resume_step + 1) * self.global_batch) 231 | 232 | def save(self): 233 | def save_checkpoint(rate, params): 234 | state_dict = self.mp_trainer.master_params_to_state_dict(params) 235 | if dist.get_rank() == 0: 236 | logger.log(f"saving model {rate}...") 237 | if not rate: 238 | filename = f"model{(self.step+self.resume_step):06d}.pt" 239 | else: 240 | filename = f"ema_{rate}_{(self.step+self.resume_step):06d}.pt" 241 | with bf.BlobFile(bf.join(get_blob_logdir(), filename), "wb") as f: 242 | th.save(state_dict, f) 243 | 244 | save_checkpoint(0, self.mp_trainer.master_params) 245 | for rate, params in zip(self.ema_rate, self.ema_params): 246 | save_checkpoint(rate, params) 247 | 248 | if dist.get_rank() == 0: 249 | with bf.BlobFile( 250 | bf.join(get_blob_logdir(), f"opt{(self.step+self.resume_step):06d}.pt"), 251 | "wb", 252 | ) as f: 253 | th.save(self.opt.state_dict(), f) 254 | 255 | dist.barrier() 256 | 257 | 258 | def parse_resume_step_from_filename(filename): 259 | """ 260 | Parse filenames of the form path/to/modelNNNNNN.pt, where NNNNNN is the 261 | checkpoint's number of steps. 262 | """ 263 | split = filename.split("model") 264 | if len(split) < 2: 265 | return 0 266 | split1 = split[-1].split(".")[0] 267 | try: 268 | return int(split1) 269 | except ValueError: 270 | return 0 271 | 272 | 273 | def get_blob_logdir(): 274 | # You can change this to be a separate path to save checkpoints to 275 | # a blobstore or some external drive. 276 | return logger.get_dir() 277 | 278 | 279 | def find_resume_checkpoint(): 280 | # On your infrastructure, you may want to override this to automatically 281 | # discover the latest checkpoint on your blob storage, etc. 282 | return None 283 | 284 | 285 | def find_ema_checkpoint(main_checkpoint, step, rate): 286 | if main_checkpoint is None: 287 | return None 288 | filename = f"ema_{rate}_{(step):06d}.pt" 289 | path = bf.join(bf.dirname(main_checkpoint), filename) 290 | if bf.exists(path): 291 | return path 292 | return None 293 | 294 | 295 | def log_loss_dict(diffusion, ts, losses): 296 | for key, values in losses.items(): 297 | logger.logkv_mean(key, values.mean().item()) 298 | # Log the quantiles (four quartiles, in particular). 299 | for sub_t, sub_loss in zip(ts.cpu().numpy(), values.detach().cpu().numpy()): 300 | quartile = int(4 * sub_t / diffusion.num_timesteps) 301 | logger.logkv_mean(f"{key}_q{quartile}", sub_loss) 302 | -------------------------------------------------------------------------------- /guided_diffusion/unet.py: -------------------------------------------------------------------------------- 1 | from abc import abstractmethod 2 | 3 | import math 4 | 5 | import numpy as np 6 | import torch as th 7 | import torch.nn as nn 8 | import torch.nn.functional as F 9 | 10 | from .fp16_util import convert_module_to_f16, convert_module_to_f32 11 | from .nn import ( 12 | checkpoint, 13 | conv_nd, 14 | linear, 15 | avg_pool_nd, 16 | zero_module, 17 | normalization, 18 | timestep_embedding, 19 | ) 20 | 21 | 22 | class AttentionPool2d(nn.Module): 23 | """ 24 | Adapted from CLIP: https://github.com/openai/CLIP/blob/main/clip/model.py 25 | """ 26 | 27 | def __init__( 28 | self, 29 | spacial_dim: int, 30 | embed_dim: int, 31 | num_heads_channels: int, 32 | output_dim: int = None, 33 | ): 34 | super().__init__() 35 | self.positional_embedding = nn.Parameter( 36 | th.randn(embed_dim, spacial_dim ** 2 + 1) / embed_dim ** 0.5 37 | ) 38 | self.qkv_proj = conv_nd(1, embed_dim, 3 * embed_dim, 1) 39 | self.c_proj = conv_nd(1, embed_dim, output_dim or embed_dim, 1) 40 | self.num_heads = embed_dim // num_heads_channels 41 | self.attention = QKVAttention(self.num_heads) 42 | 43 | def forward(self, x): 44 | b, c, *_spatial = x.shape 45 | x = x.reshape(b, c, -1) # NC(HW) 46 | x = th.cat([x.mean(dim=-1, keepdim=True), x], dim=-1) # NC(HW+1) 47 | x = x + self.positional_embedding[None, :, :].to(x.dtype) # NC(HW+1) 48 | x = self.qkv_proj(x) 49 | x = self.attention(x) 50 | x = self.c_proj(x) 51 | return x[:, :, 0] 52 | 53 | 54 | class TimestepBlock(nn.Module): 55 | """ 56 | Any module where forward() takes timestep embeddings as a second argument. 57 | """ 58 | 59 | @abstractmethod 60 | def forward(self, x, emb): 61 | """ 62 | Apply the module to `x` given `emb` timestep embeddings. 63 | """ 64 | 65 | 66 | class TimestepEmbedSequential(nn.Sequential, TimestepBlock): 67 | """ 68 | A sequential module that passes timestep embeddings to the children that 69 | support it as an extra input. 70 | """ 71 | 72 | def forward(self, x, emb): 73 | for layer in self: 74 | if isinstance(layer, TimestepBlock): 75 | x = layer(x, emb) 76 | else: 77 | x = layer(x) 78 | return x 79 | 80 | 81 | class Upsample(nn.Module): 82 | """ 83 | An upsampling layer with an optional convolution. 84 | 85 | :param channels: channels in the inputs and outputs. 86 | :param use_conv: a bool determining if a convolution is applied. 87 | :param dims: determines if the signal is 1D, 2D, or 3D. If 3D, then 88 | upsampling occurs in the inner-two dimensions. 89 | """ 90 | 91 | def __init__(self, channels, use_conv, dims=2, out_channels=None): 92 | super().__init__() 93 | self.channels = channels 94 | self.out_channels = out_channels or channels 95 | self.use_conv = use_conv 96 | self.dims = dims 97 | if use_conv: 98 | self.conv = conv_nd(dims, self.channels, self.out_channels, 3, padding=1) 99 | 100 | def forward(self, x): 101 | assert x.shape[1] == self.channels 102 | if self.dims == 3: 103 | x = F.interpolate( 104 | x, (x.shape[2], x.shape[3] * 2, x.shape[4] * 2), mode="nearest" 105 | ) 106 | else: 107 | x = F.interpolate(x, scale_factor=2, mode="nearest") 108 | if self.use_conv: 109 | x = self.conv(x) 110 | return x 111 | 112 | 113 | class Downsample(nn.Module): 114 | """ 115 | A downsampling layer with an optional convolution. 116 | 117 | :param channels: channels in the inputs and outputs. 118 | :param use_conv: a bool determining if a convolution is applied. 119 | :param dims: determines if the signal is 1D, 2D, or 3D. If 3D, then 120 | downsampling occurs in the inner-two dimensions. 121 | """ 122 | 123 | def __init__(self, channels, use_conv, dims=2, out_channels=None): 124 | super().__init__() 125 | self.channels = channels 126 | self.out_channels = out_channels or channels 127 | self.use_conv = use_conv 128 | self.dims = dims 129 | stride = 2 if dims != 3 else (1, 2, 2) 130 | if use_conv: 131 | self.op = conv_nd( 132 | dims, self.channels, self.out_channels, 3, stride=stride, padding=1 133 | ) 134 | else: 135 | assert self.channels == self.out_channels 136 | self.op = avg_pool_nd(dims, kernel_size=stride, stride=stride) 137 | 138 | def forward(self, x): 139 | assert x.shape[1] == self.channels 140 | return self.op(x) 141 | 142 | 143 | class ResBlock(TimestepBlock): 144 | """ 145 | A residual block that can optionally change the number of channels. 146 | 147 | :param channels: the number of input channels. 148 | :param emb_channels: the number of timestep embedding channels. 149 | :param dropout: the rate of dropout. 150 | :param out_channels: if specified, the number of out channels. 151 | :param use_conv: if True and out_channels is specified, use a spatial 152 | convolution instead of a smaller 1x1 convolution to change the 153 | channels in the skip connection. 154 | :param dims: determines if the signal is 1D, 2D, or 3D. 155 | :param use_checkpoint: if True, use gradient checkpointing on this module. 156 | :param up: if True, use this block for upsampling. 157 | :param down: if True, use this block for downsampling. 158 | """ 159 | 160 | def __init__( 161 | self, 162 | channels, 163 | emb_channels, 164 | dropout, 165 | out_channels=None, 166 | use_conv=False, 167 | use_scale_shift_norm=False, 168 | dims=2, 169 | use_checkpoint=False, 170 | up=False, 171 | down=False, 172 | ): 173 | super().__init__() 174 | self.channels = channels 175 | self.emb_channels = emb_channels 176 | self.dropout = dropout 177 | self.out_channels = out_channels or channels 178 | self.use_conv = use_conv 179 | self.use_checkpoint = use_checkpoint 180 | self.use_scale_shift_norm = use_scale_shift_norm 181 | 182 | self.in_layers = nn.Sequential( 183 | normalization(channels), 184 | nn.SiLU(), 185 | conv_nd(dims, channels, self.out_channels, 3, padding=1), 186 | ) 187 | 188 | self.updown = up or down 189 | 190 | if up: 191 | self.h_upd = Upsample(channels, False, dims) 192 | self.x_upd = Upsample(channels, False, dims) 193 | elif down: 194 | self.h_upd = Downsample(channels, False, dims) 195 | self.x_upd = Downsample(channels, False, dims) 196 | else: 197 | self.h_upd = self.x_upd = nn.Identity() 198 | 199 | self.emb_layers = nn.Sequential( 200 | nn.SiLU(), 201 | linear( 202 | emb_channels, 203 | 2 * self.out_channels if use_scale_shift_norm else self.out_channels, 204 | ), 205 | ) 206 | self.out_layers = nn.Sequential( 207 | normalization(self.out_channels), 208 | nn.SiLU(), 209 | nn.Dropout(p=dropout), 210 | zero_module( 211 | conv_nd(dims, self.out_channels, self.out_channels, 3, padding=1) 212 | ), 213 | ) 214 | 215 | if self.out_channels == channels: 216 | self.skip_connection = nn.Identity() 217 | elif use_conv: 218 | self.skip_connection = conv_nd( 219 | dims, channels, self.out_channels, 3, padding=1 220 | ) 221 | else: 222 | self.skip_connection = conv_nd(dims, channels, self.out_channels, 1) 223 | 224 | def forward(self, x, emb): 225 | """ 226 | Apply the block to a Tensor, conditioned on a timestep embedding. 227 | 228 | :param x: an [N x C x ...] Tensor of features. 229 | :param emb: an [N x emb_channels] Tensor of timestep embeddings. 230 | :return: an [N x C x ...] Tensor of outputs. 231 | """ 232 | return checkpoint( 233 | self._forward, (x, emb), self.parameters(), self.use_checkpoint 234 | ) 235 | 236 | def _forward(self, x, emb): 237 | if self.updown: 238 | in_rest, in_conv = self.in_layers[:-1], self.in_layers[-1] 239 | h = in_rest(x) 240 | h = self.h_upd(h) 241 | x = self.x_upd(x) 242 | h = in_conv(h) 243 | else: 244 | h = self.in_layers(x) 245 | emb_out = self.emb_layers(emb).type(h.dtype) 246 | while len(emb_out.shape) < len(h.shape): 247 | emb_out = emb_out[..., None] 248 | if self.use_scale_shift_norm: 249 | out_norm, out_rest = self.out_layers[0], self.out_layers[1:] 250 | scale, shift = th.chunk(emb_out, 2, dim=1) 251 | h = out_norm(h) * (1 + scale) + shift 252 | h = out_rest(h) 253 | else: 254 | h = h + emb_out 255 | h = self.out_layers(h) 256 | return self.skip_connection(x) + h 257 | 258 | 259 | class AttentionBlock(nn.Module): 260 | """ 261 | An attention block that allows spatial positions to attend to each other. 262 | 263 | Originally ported from here, but adapted to the N-d case. 264 | https://github.com/hojonathanho/diffusion/blob/1e0dceb3b3495bbe19116a5e1b3596cd0706c543/diffusion_tf/models/unet.py#L66. 265 | """ 266 | 267 | def __init__( 268 | self, 269 | channels, 270 | num_heads=1, 271 | num_head_channels=-1, 272 | use_checkpoint=False, 273 | use_new_attention_order=False, 274 | ): 275 | super().__init__() 276 | self.channels = channels 277 | if num_head_channels == -1: 278 | self.num_heads = num_heads 279 | else: 280 | assert ( 281 | channels % num_head_channels == 0 282 | ), f"q,k,v channels {channels} is not divisible by num_head_channels {num_head_channels}" 283 | self.num_heads = channels // num_head_channels 284 | self.use_checkpoint = use_checkpoint 285 | self.norm = normalization(channels) 286 | self.qkv = conv_nd(1, channels, channels * 3, 1) 287 | if use_new_attention_order: 288 | # split qkv before split heads 289 | self.attention = QKVAttention(self.num_heads) 290 | else: 291 | # split heads before split qkv 292 | self.attention = QKVAttentionLegacy(self.num_heads) 293 | 294 | self.proj_out = zero_module(conv_nd(1, channels, channels, 1)) 295 | 296 | def forward(self, x): 297 | return checkpoint(self._forward, (x,), self.parameters(), True) 298 | 299 | def _forward(self, x): 300 | b, c, *spatial = x.shape 301 | x = x.reshape(b, c, -1) 302 | qkv = self.qkv(self.norm(x)) 303 | h = self.attention(qkv) 304 | h = self.proj_out(h) 305 | return (x + h).reshape(b, c, *spatial) 306 | 307 | 308 | def count_flops_attn(model, _x, y): 309 | """ 310 | A counter for the `thop` package to count the operations in an 311 | attention operation. 312 | Meant to be used like: 313 | macs, params = thop.profile( 314 | model, 315 | inputs=(inputs, timestamps), 316 | custom_ops={QKVAttention: QKVAttention.count_flops}, 317 | ) 318 | """ 319 | b, c, *spatial = y[0].shape 320 | num_spatial = int(np.prod(spatial)) 321 | # We perform two matmuls with the same number of ops. 322 | # The first computes the weight matrix, the second computes 323 | # the combination of the value vectors. 324 | matmul_ops = 2 * b * (num_spatial ** 2) * c 325 | model.total_ops += th.DoubleTensor([matmul_ops]) 326 | 327 | 328 | class QKVAttentionLegacy(nn.Module): 329 | """ 330 | A module which performs QKV attention. Matches legacy QKVAttention + input/ouput heads shaping 331 | """ 332 | 333 | def __init__(self, n_heads): 334 | super().__init__() 335 | self.n_heads = n_heads 336 | 337 | def forward(self, qkv): 338 | """ 339 | Apply QKV attention. 340 | 341 | :param qkv: an [N x (H * 3 * C) x T] tensor of Qs, Ks, and Vs. 342 | :return: an [N x (H * C) x T] tensor after attention. 343 | """ 344 | bs, width, length = qkv.shape 345 | assert width % (3 * self.n_heads) == 0 346 | ch = width // (3 * self.n_heads) 347 | q, k, v = qkv.reshape(bs * self.n_heads, ch * 3, length).split(ch, dim=1) 348 | scale = 1 / math.sqrt(math.sqrt(ch)) 349 | weight = th.einsum( 350 | "bct,bcs->bts", q * scale, k * scale 351 | ) # More stable with f16 than dividing afterwards 352 | weight = th.softmax(weight.float(), dim=-1).type(weight.dtype) 353 | a = th.einsum("bts,bcs->bct", weight, v) 354 | return a.reshape(bs, -1, length) 355 | 356 | @staticmethod 357 | def count_flops(model, _x, y): 358 | return count_flops_attn(model, _x, y) 359 | 360 | 361 | class QKVAttention(nn.Module): 362 | """ 363 | A module which performs QKV attention and splits in a different order. 364 | """ 365 | 366 | def __init__(self, n_heads): 367 | super().__init__() 368 | self.n_heads = n_heads 369 | 370 | def forward(self, qkv): 371 | """ 372 | Apply QKV attention. 373 | 374 | :param qkv: an [N x (3 * H * C) x T] tensor of Qs, Ks, and Vs. 375 | :return: an [N x (H * C) x T] tensor after attention. 376 | """ 377 | bs, width, length = qkv.shape 378 | assert width % (3 * self.n_heads) == 0 379 | ch = width // (3 * self.n_heads) 380 | q, k, v = qkv.chunk(3, dim=1) 381 | scale = 1 / math.sqrt(math.sqrt(ch)) 382 | weight = th.einsum( 383 | "bct,bcs->bts", 384 | (q * scale).view(bs * self.n_heads, ch, length), 385 | (k * scale).view(bs * self.n_heads, ch, length), 386 | ) # More stable with f16 than dividing afterwards 387 | weight = th.softmax(weight.float(), dim=-1).type(weight.dtype) 388 | a = th.einsum("bts,bcs->bct", weight, v.reshape(bs * self.n_heads, ch, length)) 389 | return a.reshape(bs, -1, length) 390 | 391 | @staticmethod 392 | def count_flops(model, _x, y): 393 | return count_flops_attn(model, _x, y) 394 | 395 | 396 | class UNetModel(nn.Module): 397 | """ 398 | The full UNet model with attention and timestep embedding. 399 | 400 | :param in_channels: channels in the input Tensor. 401 | :param model_channels: base channel count for the model. 402 | :param out_channels: channels in the output Tensor. 403 | :param num_res_blocks: number of residual blocks per downsample. 404 | :param attention_resolutions: a collection of downsample rates at which 405 | attention will take place. May be a set, list, or tuple. 406 | For example, if this contains 4, then at 4x downsampling, attention 407 | will be used. 408 | :param dropout: the dropout probability. 409 | :param channel_mult: channel multiplier for each level of the UNet. 410 | :param conv_resample: if True, use learned convolutions for upsampling and 411 | downsampling. 412 | :param dims: determines if the signal is 1D, 2D, or 3D. 413 | :param num_classes: if specified (as an int), then this model will be 414 | class-conditional with `num_classes` classes. 415 | :param use_checkpoint: use gradient checkpointing to reduce memory usage. 416 | :param num_heads: the number of attention heads in each attention layer. 417 | :param num_heads_channels: if specified, ignore num_heads and instead use 418 | a fixed channel width per attention head. 419 | :param num_heads_upsample: works with num_heads to set a different number 420 | of heads for upsampling. Deprecated. 421 | :param use_scale_shift_norm: use a FiLM-like conditioning mechanism. 422 | :param resblock_updown: use residual blocks for up/downsampling. 423 | :param use_new_attention_order: use a different attention pattern for potentially 424 | increased efficiency. 425 | """ 426 | 427 | def __init__( 428 | self, 429 | image_size, 430 | in_channels, 431 | model_channels, 432 | out_channels, 433 | num_res_blocks, 434 | attention_resolutions, 435 | dropout=0, 436 | channel_mult=(1, 2, 4, 8), 437 | conv_resample=True, 438 | dims=2, 439 | num_classes=None, 440 | use_checkpoint=False, 441 | use_fp16=False, 442 | num_heads=1, 443 | num_head_channels=-1, 444 | num_heads_upsample=-1, 445 | use_scale_shift_norm=False, 446 | resblock_updown=False, 447 | use_new_attention_order=False, 448 | ): 449 | super().__init__() 450 | 451 | if num_heads_upsample == -1: 452 | num_heads_upsample = num_heads 453 | 454 | self.image_size = image_size 455 | self.in_channels = in_channels 456 | self.model_channels = model_channels 457 | self.out_channels = out_channels 458 | self.num_res_blocks = num_res_blocks 459 | self.attention_resolutions = attention_resolutions 460 | self.dropout = dropout 461 | self.channel_mult = channel_mult 462 | self.conv_resample = conv_resample 463 | self.num_classes = num_classes 464 | self.use_checkpoint = use_checkpoint 465 | self.dtype = th.float16 if use_fp16 else th.float32 466 | self.num_heads = num_heads 467 | self.num_head_channels = num_head_channels 468 | self.num_heads_upsample = num_heads_upsample 469 | 470 | time_embed_dim = model_channels * 4 471 | self.time_embed = nn.Sequential( 472 | linear(model_channels, time_embed_dim), 473 | nn.SiLU(), 474 | linear(time_embed_dim, time_embed_dim), 475 | ) 476 | 477 | if self.num_classes is not None: 478 | self.label_emb = nn.Embedding(num_classes, time_embed_dim) 479 | 480 | ch = input_ch = int(channel_mult[0] * model_channels) 481 | self.input_blocks = nn.ModuleList( 482 | [TimestepEmbedSequential(conv_nd(dims, in_channels, ch, 3, padding=1))] 483 | ) 484 | self._feature_size = ch 485 | input_block_chans = [ch] 486 | ds = 1 487 | for level, mult in enumerate(channel_mult): 488 | for _ in range(num_res_blocks): 489 | layers = [ 490 | ResBlock( 491 | ch, 492 | time_embed_dim, 493 | dropout, 494 | out_channels=int(mult * model_channels), 495 | dims=dims, 496 | use_checkpoint=use_checkpoint, 497 | use_scale_shift_norm=use_scale_shift_norm, 498 | ) 499 | ] 500 | ch = int(mult * model_channels) 501 | if ds in attention_resolutions: 502 | layers.append( 503 | AttentionBlock( 504 | ch, 505 | use_checkpoint=use_checkpoint, 506 | num_heads=num_heads, 507 | num_head_channels=num_head_channels, 508 | use_new_attention_order=use_new_attention_order, 509 | ) 510 | ) 511 | self.input_blocks.append(TimestepEmbedSequential(*layers)) 512 | self._feature_size += ch 513 | input_block_chans.append(ch) 514 | if level != len(channel_mult) - 1: 515 | out_ch = ch 516 | self.input_blocks.append( 517 | TimestepEmbedSequential( 518 | ResBlock( 519 | ch, 520 | time_embed_dim, 521 | dropout, 522 | out_channels=out_ch, 523 | dims=dims, 524 | use_checkpoint=use_checkpoint, 525 | use_scale_shift_norm=use_scale_shift_norm, 526 | down=True, 527 | ) 528 | if resblock_updown 529 | else Downsample( 530 | ch, conv_resample, dims=dims, out_channels=out_ch 531 | ) 532 | ) 533 | ) 534 | ch = out_ch 535 | input_block_chans.append(ch) 536 | ds *= 2 537 | self._feature_size += ch 538 | 539 | self.middle_block = TimestepEmbedSequential( 540 | ResBlock( 541 | ch, 542 | time_embed_dim, 543 | dropout, 544 | dims=dims, 545 | use_checkpoint=use_checkpoint, 546 | use_scale_shift_norm=use_scale_shift_norm, 547 | ), 548 | AttentionBlock( 549 | ch, 550 | use_checkpoint=use_checkpoint, 551 | num_heads=num_heads, 552 | num_head_channels=num_head_channels, 553 | use_new_attention_order=use_new_attention_order, 554 | ), 555 | ResBlock( 556 | ch, 557 | time_embed_dim, 558 | dropout, 559 | dims=dims, 560 | use_checkpoint=use_checkpoint, 561 | use_scale_shift_norm=use_scale_shift_norm, 562 | ), 563 | ) 564 | self._feature_size += ch 565 | 566 | self.output_blocks = nn.ModuleList([]) 567 | for level, mult in list(enumerate(channel_mult))[::-1]: 568 | for i in range(num_res_blocks + 1): 569 | ich = input_block_chans.pop() 570 | layers = [ 571 | ResBlock( 572 | ch + ich, 573 | time_embed_dim, 574 | dropout, 575 | out_channels=int(model_channels * mult), 576 | dims=dims, 577 | use_checkpoint=use_checkpoint, 578 | use_scale_shift_norm=use_scale_shift_norm, 579 | ) 580 | ] 581 | ch = int(model_channels * mult) 582 | if ds in attention_resolutions: 583 | layers.append( 584 | AttentionBlock( 585 | ch, 586 | use_checkpoint=use_checkpoint, 587 | num_heads=num_heads_upsample, 588 | num_head_channels=num_head_channels, 589 | use_new_attention_order=use_new_attention_order, 590 | ) 591 | ) 592 | if level and i == num_res_blocks: 593 | out_ch = ch 594 | layers.append( 595 | ResBlock( 596 | ch, 597 | time_embed_dim, 598 | dropout, 599 | out_channels=out_ch, 600 | dims=dims, 601 | use_checkpoint=use_checkpoint, 602 | use_scale_shift_norm=use_scale_shift_norm, 603 | up=True, 604 | ) 605 | if resblock_updown 606 | else Upsample(ch, conv_resample, dims=dims, out_channels=out_ch) 607 | ) 608 | ds //= 2 609 | self.output_blocks.append(TimestepEmbedSequential(*layers)) 610 | self._feature_size += ch 611 | 612 | self.out = nn.Sequential( 613 | normalization(ch), 614 | nn.SiLU(), 615 | zero_module(conv_nd(dims, input_ch, out_channels, 3, padding=1)), 616 | ) 617 | 618 | def convert_to_fp16(self): 619 | """ 620 | Convert the torso of the model to float16. 621 | """ 622 | self.input_blocks.apply(convert_module_to_f16) 623 | self.middle_block.apply(convert_module_to_f16) 624 | self.output_blocks.apply(convert_module_to_f16) 625 | 626 | def convert_to_fp32(self): 627 | """ 628 | Convert the torso of the model to float32. 629 | """ 630 | self.input_blocks.apply(convert_module_to_f32) 631 | self.middle_block.apply(convert_module_to_f32) 632 | self.output_blocks.apply(convert_module_to_f32) 633 | 634 | def forward(self, x, timesteps, y=None): 635 | """ 636 | Apply the model to an input batch. 637 | 638 | :param x: an [N x C x ...] Tensor of inputs. 639 | :param timesteps: a 1-D batch of timesteps. 640 | :param y: an [N] Tensor of labels, if class-conditional. 641 | :return: an [N x C x ...] Tensor of outputs. 642 | """ 643 | assert (y is not None) == ( 644 | self.num_classes is not None 645 | ), "must specify y if and only if the model is class-conditional" 646 | 647 | hs = [] 648 | emb = self.time_embed(timestep_embedding(timesteps, self.model_channels)) 649 | 650 | if self.num_classes is not None: 651 | assert y.shape == (x.shape[0],) 652 | emb = emb + self.label_emb(y) 653 | 654 | h = x.type(self.dtype) 655 | for module in self.input_blocks: 656 | h = module(h, emb) 657 | hs.append(h) 658 | h = self.middle_block(h, emb) 659 | for module in self.output_blocks: 660 | h = th.cat([h, hs.pop()], dim=1) 661 | h = module(h, emb) 662 | h = h.type(x.dtype) 663 | return self.out(h) 664 | 665 | 666 | class SuperResModel(UNetModel): 667 | """ 668 | A UNetModel that performs super-resolution. 669 | 670 | Expects an extra kwarg `low_res` to condition on a low-resolution image. 671 | """ 672 | 673 | def __init__(self, image_size, in_channels, *args, **kwargs): 674 | super().__init__(image_size, in_channels * 2, *args, **kwargs) 675 | 676 | def forward(self, x, timesteps, low_res=None, **kwargs): 677 | _, _, new_height, new_width = x.shape 678 | upsampled = F.interpolate(low_res, (new_height, new_width), mode="bilinear") 679 | x = th.cat([x, upsampled], dim=1) 680 | return super().forward(x, timesteps, **kwargs) 681 | 682 | 683 | class EncoderUNetModel(nn.Module): 684 | """ 685 | The half UNet model with attention and timestep embedding. 686 | 687 | For usage, see UNet. 688 | """ 689 | 690 | def __init__( 691 | self, 692 | image_size, 693 | in_channels, 694 | model_channels, 695 | out_channels, 696 | num_res_blocks, 697 | attention_resolutions, 698 | dropout=0, 699 | channel_mult=(1, 2, 4, 8), 700 | conv_resample=True, 701 | dims=2, 702 | use_checkpoint=False, 703 | use_fp16=False, 704 | num_heads=1, 705 | num_head_channels=-1, 706 | num_heads_upsample=-1, 707 | use_scale_shift_norm=False, 708 | resblock_updown=False, 709 | use_new_attention_order=False, 710 | pool="adaptive", 711 | ): 712 | super().__init__() 713 | 714 | if num_heads_upsample == -1: 715 | num_heads_upsample = num_heads 716 | 717 | self.in_channels = in_channels 718 | self.model_channels = model_channels 719 | self.out_channels = out_channels 720 | self.num_res_blocks = num_res_blocks 721 | self.attention_resolutions = attention_resolutions 722 | self.dropout = dropout 723 | self.channel_mult = channel_mult 724 | self.conv_resample = conv_resample 725 | self.use_checkpoint = use_checkpoint 726 | self.dtype = th.float16 if use_fp16 else th.float32 727 | self.num_heads = num_heads 728 | self.num_head_channels = num_head_channels 729 | self.num_heads_upsample = num_heads_upsample 730 | 731 | time_embed_dim = model_channels * 4 732 | self.time_embed = nn.Sequential( 733 | linear(model_channels, time_embed_dim), 734 | nn.SiLU(), 735 | linear(time_embed_dim, time_embed_dim), 736 | ) 737 | 738 | ch = int(channel_mult[0] * model_channels) 739 | self.input_blocks = nn.ModuleList( 740 | [TimestepEmbedSequential(conv_nd(dims, in_channels, ch, 3, padding=1))] 741 | ) 742 | self._feature_size = ch 743 | input_block_chans = [ch] 744 | ds = 1 745 | for level, mult in enumerate(channel_mult): 746 | for _ in range(num_res_blocks): 747 | layers = [ 748 | ResBlock( 749 | ch, 750 | time_embed_dim, 751 | dropout, 752 | out_channels=int(mult * model_channels), 753 | dims=dims, 754 | use_checkpoint=use_checkpoint, 755 | use_scale_shift_norm=use_scale_shift_norm, 756 | ) 757 | ] 758 | ch = int(mult * model_channels) 759 | if ds in attention_resolutions: 760 | layers.append( 761 | AttentionBlock( 762 | ch, 763 | use_checkpoint=use_checkpoint, 764 | num_heads=num_heads, 765 | num_head_channels=num_head_channels, 766 | use_new_attention_order=use_new_attention_order, 767 | ) 768 | ) 769 | self.input_blocks.append(TimestepEmbedSequential(*layers)) 770 | self._feature_size += ch 771 | input_block_chans.append(ch) 772 | if level != len(channel_mult) - 1: 773 | out_ch = ch 774 | self.input_blocks.append( 775 | TimestepEmbedSequential( 776 | ResBlock( 777 | ch, 778 | time_embed_dim, 779 | dropout, 780 | out_channels=out_ch, 781 | dims=dims, 782 | use_checkpoint=use_checkpoint, 783 | use_scale_shift_norm=use_scale_shift_norm, 784 | down=True, 785 | ) 786 | if resblock_updown 787 | else Downsample( 788 | ch, conv_resample, dims=dims, out_channels=out_ch 789 | ) 790 | ) 791 | ) 792 | ch = out_ch 793 | input_block_chans.append(ch) 794 | ds *= 2 795 | self._feature_size += ch 796 | 797 | self.middle_block = TimestepEmbedSequential( 798 | ResBlock( 799 | ch, 800 | time_embed_dim, 801 | dropout, 802 | dims=dims, 803 | use_checkpoint=use_checkpoint, 804 | use_scale_shift_norm=use_scale_shift_norm, 805 | ), 806 | AttentionBlock( 807 | ch, 808 | use_checkpoint=use_checkpoint, 809 | num_heads=num_heads, 810 | num_head_channels=num_head_channels, 811 | use_new_attention_order=use_new_attention_order, 812 | ), 813 | ResBlock( 814 | ch, 815 | time_embed_dim, 816 | dropout, 817 | dims=dims, 818 | use_checkpoint=use_checkpoint, 819 | use_scale_shift_norm=use_scale_shift_norm, 820 | ), 821 | ) 822 | self._feature_size += ch 823 | self.pool = pool 824 | if pool == "adaptive": 825 | self.out = nn.Sequential( 826 | normalization(ch), 827 | nn.SiLU(), 828 | nn.AdaptiveAvgPool2d((1, 1)), 829 | zero_module(conv_nd(dims, ch, out_channels, 1)), 830 | nn.Flatten(), 831 | ) 832 | elif pool == "attention": 833 | assert num_head_channels != -1 834 | self.out = nn.Sequential( 835 | normalization(ch), 836 | nn.SiLU(), 837 | AttentionPool2d( 838 | (image_size // ds), ch, num_head_channels, out_channels 839 | ), 840 | ) 841 | elif pool == "spatial": 842 | self.out = nn.Sequential( 843 | nn.Linear(self._feature_size, 2048), 844 | nn.ReLU(), 845 | nn.Linear(2048, self.out_channels), 846 | ) 847 | elif pool == "spatial_v2": 848 | self.out = nn.Sequential( 849 | nn.Linear(self._feature_size, 2048), 850 | normalization(2048), 851 | nn.SiLU(), 852 | nn.Linear(2048, self.out_channels), 853 | ) 854 | else: 855 | raise NotImplementedError(f"Unexpected {pool} pooling") 856 | 857 | def convert_to_fp16(self): 858 | """ 859 | Convert the torso of the model to float16. 860 | """ 861 | self.input_blocks.apply(convert_module_to_f16) 862 | self.middle_block.apply(convert_module_to_f16) 863 | 864 | def convert_to_fp32(self): 865 | """ 866 | Convert the torso of the model to float32. 867 | """ 868 | self.input_blocks.apply(convert_module_to_f32) 869 | self.middle_block.apply(convert_module_to_f32) 870 | 871 | def forward(self, x, timesteps): 872 | """ 873 | Apply the model to an input batch. 874 | 875 | :param x: an [N x C x ...] Tensor of inputs. 876 | :param timesteps: a 1-D batch of timesteps. 877 | :return: an [N x K] Tensor of outputs. 878 | """ 879 | emb = self.time_embed(timestep_embedding(timesteps, self.model_channels)) 880 | 881 | results = [] 882 | h = x.type(self.dtype) 883 | for module in self.input_blocks: 884 | h = module(h, emb) 885 | if self.pool.startswith("spatial"): 886 | results.append(h.type(x.dtype).mean(dim=(2, 3))) 887 | h = self.middle_block(h, emb) 888 | if self.pool.startswith("spatial"): 889 | results.append(h.type(x.dtype).mean(dim=(2, 3))) 890 | h = th.cat(results, axis=-1) 891 | return self.out(h) 892 | else: 893 | h = h.type(x.dtype) 894 | return self.out(h) 895 | -------------------------------------------------------------------------------- /img/deep_ensemble.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/matthewachan/hyperdm/5428d9ab79b9e698b90b5c5dbc4c00d0a8f78937/img/deep_ensemble.png -------------------------------------------------------------------------------- /img/era5.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/matthewachan/hyperdm/5428d9ab79b9e698b90b5c5dbc4c00d0a8f78937/img/era5.png -------------------------------------------------------------------------------- /img/hyperdm.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/matthewachan/hyperdm/5428d9ab79b9e698b90b5c5dbc4c00d0a8f78937/img/hyperdm.png -------------------------------------------------------------------------------- /model/mlp.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | import torch as th 4 | from torch import nn 5 | 6 | 7 | class MLP(th.nn.Module): 8 | 9 | def __init__(self, layer_channels: List[int]): 10 | super(MLP, self).__init__() 11 | 12 | layers = [] 13 | for i in range(len(layer_channels) - 2): 14 | layers.append(nn.Linear(layer_channels[i], layer_channels[i + 1])) 15 | layers.append(nn.ReLU()) 16 | # Append output layer 17 | layers.append(nn.Linear(layer_channels[-2], layer_channels[-1])) 18 | self.mlp = nn.Sequential(*layers) 19 | 20 | def forward(self, x, timesteps=None, y=None): 21 | """ 22 | Apply the model to an input batch. 23 | 24 | :param x: a [B, 1, 1, 1] Tensor of inputs. 25 | :param timesteps: a 1-D batch of timesteps. 26 | :param y: a [B, 1, 1, 1] Tensor of conditions. 27 | :return: an [B, 1, 1, 1] Tensor of outputs. 28 | """ 29 | if not timesteps is None and not y is None: 30 | t = timesteps.reshape(x.shape) 31 | x = th.cat([x, t, y], dim=-1) 32 | return self.mlp(x) 33 | -------------------------------------------------------------------------------- /model/unet.py: -------------------------------------------------------------------------------- 1 | import math 2 | from collections import namedtuple 3 | 4 | import torch 5 | import torch.nn.functional as F 6 | from einops import rearrange 7 | from einops.layers.torch import Rearrange 8 | from torch import einsum, nn 9 | 10 | # constants 11 | ModelPrediction = namedtuple('ModelPrediction', ['pred_noise', 'pred_x_start']) 12 | 13 | 14 | # helpers functions 15 | def exists(x): 16 | return x is not None 17 | 18 | 19 | def default(val, d): 20 | if exists(val): 21 | return val 22 | return d() if callable(d) else d 23 | 24 | 25 | def identity(t, *args, **kwargs): 26 | return t 27 | 28 | 29 | def cycle(dl): 30 | while True: 31 | for data in dl: 32 | yield data 33 | 34 | 35 | def has_int_squareroot(num): 36 | return (math.sqrt(num)**2) == num 37 | 38 | 39 | def num_to_groups(num, divisor): 40 | groups = num // divisor 41 | remainder = num % divisor 42 | arr = [divisor] * groups 43 | if remainder > 0: 44 | arr.append(remainder) 45 | return arr 46 | 47 | 48 | def convert_image_to_fn(img_type, image): 49 | if image.mode != img_type: 50 | return image.convert(img_type) 51 | return image 52 | 53 | 54 | # normalization functions 55 | 56 | 57 | def normalize_to_neg_one_to_one(img): 58 | return img * 2 - 1 59 | 60 | 61 | def unnormalize_to_zero_to_one(t): 62 | return (t + 1) * 0.5 63 | 64 | 65 | # small helper modules 66 | 67 | 68 | class Residual(nn.Module): 69 | 70 | def __init__(self, fn): 71 | super().__init__() 72 | self.fn = fn 73 | 74 | def forward(self, x, *args, **kwargs): 75 | return self.fn(x, *args, **kwargs) + x 76 | 77 | 78 | def Upsample(dim, dim_out=None): 79 | return nn.Sequential(nn.Upsample(scale_factor=2, mode='nearest'), 80 | nn.Conv2d(dim, default(dim_out, dim), 3, padding=1)) 81 | 82 | 83 | def Downsample(dim, dim_out=None): 84 | return nn.Sequential( 85 | Rearrange('b c (h p1) (w p2) -> b (c p1 p2) h w', p1=2, p2=2), 86 | nn.Conv2d(dim * 4, default(dim_out, dim), 1)) 87 | 88 | 89 | class RMSNorm(nn.Module): 90 | 91 | def __init__(self, dim): 92 | super().__init__() 93 | self.g = nn.Parameter(torch.ones(1, dim, 1, 1)) 94 | 95 | def forward(self, x): 96 | return F.normalize(x, dim=1) * self.g * (x.shape[-1]**0.5) 97 | 98 | 99 | class PreNorm(nn.Module): 100 | 101 | def __init__(self, dim, fn): 102 | super().__init__() 103 | self.fn = fn 104 | self.norm = RMSNorm(dim) 105 | 106 | def forward(self, x): 107 | x = self.norm(x) 108 | return self.fn(x) 109 | 110 | 111 | # sinusoidal positional embeds 112 | 113 | 114 | class SinusoidalPosEmb(nn.Module): 115 | 116 | def __init__(self, dim): 117 | super().__init__() 118 | self.dim = dim 119 | 120 | def forward(self, x): 121 | device = x.device 122 | half_dim = self.dim // 2 123 | emb = math.log(10000) / (half_dim - 1) 124 | emb = torch.exp(torch.arange(half_dim, device=device) * -emb) 125 | emb = x[:, None] * emb[None, :] 126 | emb = torch.cat((emb.sin(), emb.cos()), dim=-1) 127 | return emb 128 | 129 | 130 | class RandomOrLearnedSinusoidalPosEmb(nn.Module): 131 | """ following @crowsonkb 's lead with random (learned optional) sinusoidal pos emb """ 132 | """ https://github.com/crowsonkb/v-diffusion-jax/blob/master/diffusion/models/danbooru_128.py#L8 """ 133 | 134 | def __init__(self, dim, is_random=False): 135 | super().__init__() 136 | assert (dim % 2) == 0 137 | half_dim = dim // 2 138 | self.weights = nn.Parameter(torch.randn(half_dim), 139 | requires_grad=not is_random) 140 | 141 | def forward(self, x): 142 | x = rearrange(x, 'b -> b 1') 143 | freqs = x * rearrange(self.weights, 'd -> 1 d') * 2 * math.pi 144 | fouriered = torch.cat((freqs.sin(), freqs.cos()), dim=-1) 145 | fouriered = torch.cat((x, fouriered), dim=-1) 146 | return fouriered 147 | 148 | 149 | # building block modules 150 | 151 | 152 | class Block(nn.Module): 153 | 154 | def __init__(self, dim, dim_out): 155 | super().__init__() 156 | self.proj = nn.Conv2d(dim, dim_out, 3, padding=1) 157 | self.norm = RMSNorm(dim_out) 158 | self.act = nn.SiLU() 159 | 160 | def forward(self, x, scale_shift=None): 161 | x = self.proj(x) 162 | x = self.norm(x) 163 | 164 | if exists(scale_shift): 165 | scale, shift = scale_shift 166 | x = x * (scale + 1) + shift 167 | 168 | x = self.act(x) 169 | return x 170 | 171 | 172 | class ResnetBlock(nn.Module): 173 | 174 | def __init__(self, dim, dim_out, *, time_emb_dim=None): 175 | super().__init__() 176 | self.mlp = nn.Sequential(nn.SiLU(), nn.Linear( 177 | time_emb_dim, dim_out * 2)) if exists(time_emb_dim) else None 178 | 179 | self.block1 = Block(dim, dim_out) 180 | self.block2 = Block(dim_out, dim_out) 181 | self.res_conv = nn.Conv2d(dim, dim_out, 182 | 1) if dim != dim_out else nn.Identity() 183 | 184 | def forward(self, x, time_emb=None): 185 | 186 | scale_shift = None 187 | if exists(self.mlp) and exists(time_emb): 188 | time_emb = self.mlp(time_emb) 189 | time_emb = rearrange(time_emb, 'b c -> b c 1 1') 190 | scale_shift = time_emb.chunk(2, dim=1) 191 | 192 | h = self.block1(x, scale_shift=scale_shift) 193 | 194 | h = self.block2(h) 195 | 196 | return h + self.res_conv(x) 197 | 198 | 199 | class LinearAttention(nn.Module): 200 | 201 | def __init__(self, dim, heads=4, dim_head=32): 202 | super().__init__() 203 | self.scale = dim_head**-0.5 204 | self.heads = heads 205 | hidden_dim = dim_head * heads 206 | self.to_qkv = nn.Conv2d(dim, hidden_dim * 3, 1, bias=False) 207 | 208 | self.to_out = nn.Sequential(nn.Conv2d(hidden_dim, dim, 1), 209 | RMSNorm(dim)) 210 | 211 | def forward(self, x): 212 | b, c, h, w = x.shape 213 | qkv = self.to_qkv(x).chunk(3, dim=1) 214 | q, k, v = map( 215 | lambda t: rearrange(t, 'b (h c) x y -> b h c (x y)', h=self.heads), 216 | qkv) 217 | 218 | q = q.softmax(dim=-2) 219 | k = k.softmax(dim=-1) 220 | 221 | q = q * self.scale 222 | 223 | context = torch.einsum('b h d n, b h e n -> b h d e', k, v) 224 | 225 | out = torch.einsum('b h d e, b h d n -> b h e n', context, q) 226 | out = rearrange(out, 227 | 'b h c (x y) -> b (h c) x y', 228 | h=self.heads, 229 | x=h, 230 | y=w) 231 | return self.to_out(out) 232 | 233 | 234 | class Attention(nn.Module): 235 | 236 | def __init__(self, dim, heads=4, dim_head=32): 237 | super().__init__() 238 | self.scale = dim_head**-0.5 239 | self.heads = heads 240 | hidden_dim = dim_head * heads 241 | 242 | self.to_qkv = nn.Conv2d(dim, hidden_dim * 3, 1, bias=False) 243 | self.to_out = nn.Conv2d(hidden_dim, dim, 1) 244 | 245 | def forward(self, x): 246 | b, c, h, w = x.shape 247 | qkv = self.to_qkv(x).chunk(3, dim=1) 248 | q, k, v = map( 249 | lambda t: rearrange(t, 'b (h c) x y -> b h c (x y)', h=self.heads), 250 | qkv) 251 | 252 | q = q * self.scale 253 | 254 | sim = einsum('b h d i, b h d j -> b h i j', q, k) 255 | attn = sim.softmax(dim=-1) 256 | out = einsum('b h i j, b h d j -> b h i d', attn, v) 257 | 258 | out = rearrange(out, 'b h (x y) d -> b (h d) x y', x=h, y=w) 259 | return self.to_out(out) 260 | 261 | 262 | # model 263 | 264 | 265 | class Unet(nn.Module): 266 | 267 | def __init__(self, 268 | dim, 269 | init_dim=None, 270 | out_dim=None, 271 | dim_mults=(1, 2, 4, 8), 272 | channels=3, 273 | self_condition=False, 274 | learned_variance=False, 275 | learned_sinusoidal_cond=False, 276 | random_fourier_features=False, 277 | learned_sinusoidal_dim=16): 278 | super().__init__() 279 | 280 | # determine dimensions 281 | 282 | self.channels = channels 283 | self.self_condition = self_condition 284 | input_channels = channels * (2 if self_condition else 1) 285 | 286 | init_dim = default(init_dim, dim) 287 | self.init_conv = nn.Conv2d(input_channels, init_dim, 7, padding=3) 288 | 289 | dims = [init_dim, *map(lambda m: dim * m, dim_mults)] 290 | in_out = list(zip(dims[:-1], dims[1:])) 291 | 292 | # time embeddings 293 | 294 | time_dim = dim * 4 295 | 296 | self.random_or_learned_sinusoidal_cond = learned_sinusoidal_cond or random_fourier_features 297 | 298 | if self.random_or_learned_sinusoidal_cond: 299 | sinu_pos_emb = RandomOrLearnedSinusoidalPosEmb( 300 | learned_sinusoidal_dim, random_fourier_features) 301 | fourier_dim = learned_sinusoidal_dim + 1 302 | else: 303 | sinu_pos_emb = SinusoidalPosEmb(dim) 304 | fourier_dim = dim 305 | 306 | self.time_mlp = nn.Sequential(sinu_pos_emb, 307 | nn.Linear(fourier_dim, time_dim), 308 | nn.GELU(), nn.Linear(time_dim, time_dim)) 309 | 310 | # layers 311 | 312 | self.downs = nn.ModuleList([]) 313 | self.ups = nn.ModuleList([]) 314 | num_resolutions = len(in_out) 315 | 316 | for ind, (dim_in, dim_out) in enumerate(in_out): 317 | is_last = ind >= (num_resolutions - 1) 318 | 319 | self.downs.append( 320 | nn.ModuleList([ 321 | ResnetBlock(dim_in, dim_in, time_emb_dim=time_dim), 322 | ResnetBlock(dim_in, dim_in, time_emb_dim=time_dim), 323 | Residual(PreNorm(dim_in, LinearAttention(dim_in))), 324 | Downsample(dim_in, dim_out) if not is_last else nn.Conv2d( 325 | dim_in, dim_out, 3, padding=1) 326 | ])) 327 | 328 | mid_dim = dims[-1] 329 | self.mid_block1 = ResnetBlock(mid_dim, mid_dim, time_emb_dim=time_dim) 330 | self.mid_attn = Residual(PreNorm(mid_dim, Attention(mid_dim))) 331 | self.mid_block2 = ResnetBlock(mid_dim, mid_dim, time_emb_dim=time_dim) 332 | 333 | for ind, (dim_in, dim_out) in enumerate(reversed(in_out)): 334 | is_last = ind == (len(in_out) - 1) 335 | 336 | self.ups.append( 337 | nn.ModuleList([ 338 | ResnetBlock(dim_out + dim_in, 339 | dim_out, 340 | time_emb_dim=time_dim), 341 | ResnetBlock(dim_out + dim_in, 342 | dim_out, 343 | time_emb_dim=time_dim), 344 | Residual(PreNorm(dim_out, LinearAttention(dim_out))), 345 | Upsample(dim_out, dim_in) if not is_last else nn.Conv2d( 346 | dim_out, dim_in, 3, padding=1) 347 | ])) 348 | 349 | default_out_dim = channels * (1 if not learned_variance else 2) 350 | self.out_dim = default(out_dim, default_out_dim) 351 | 352 | self.final_res_block = ResnetBlock(dim * 2, dim, time_emb_dim=time_dim) 353 | self.final_conv = nn.Conv2d(dim, self.out_dim, 1) 354 | 355 | def forward(self, x, time, y=None): 356 | if self.self_condition: 357 | assert x.shape == y.shape, f"shape mismatch {x.shape}, {y.shape}" 358 | # y = default(y, lambda: torch.zeros_like(x)) 359 | x = torch.cat((x, y), dim=1) 360 | 361 | x = self.init_conv(x) 362 | r = x.clone() 363 | 364 | t = self.time_mlp(time) 365 | 366 | h = [] 367 | 368 | for block1, block2, attn, downsample in self.downs: 369 | x = block1(x, t) 370 | h.append(x) 371 | 372 | x = block2(x, t) 373 | x = attn(x) 374 | h.append(x) 375 | 376 | x = downsample(x) 377 | 378 | x = self.mid_block1(x, t) 379 | x = self.mid_attn(x) 380 | x = self.mid_block2(x, t) 381 | 382 | for block1, block2, attn, upsample in self.ups: 383 | x = torch.cat((x, h.pop()), dim=1) 384 | x = block1(x, t) 385 | 386 | x = torch.cat((x, h.pop()), dim=1) 387 | x = block2(x, t) 388 | x = attn(x) 389 | 390 | x = upsample(x) 391 | 392 | x = torch.cat((x, r), dim=1) 393 | 394 | x = self.final_res_block(x, t) 395 | return self.final_conv(x) 396 | 397 | 398 | # gaussian diffusion trainer class 399 | 400 | 401 | def extract(a, t, x_shape): 402 | b, *_ = t.shape 403 | out = a.gather(-1, t) 404 | return out.reshape(b, *((1, ) * (len(x_shape) - 1))) 405 | 406 | 407 | def linear_beta_schedule(timesteps): 408 | """ 409 | linear schedule, proposed in original ddpm paper 410 | """ 411 | scale = 1000 / timesteps 412 | beta_start = scale * 0.0001 413 | beta_end = scale * 0.02 414 | return torch.linspace(beta_start, beta_end, timesteps, dtype=torch.float64) 415 | 416 | 417 | def cosine_beta_schedule(timesteps, s=0.008): 418 | """ 419 | cosine schedule 420 | as proposed in https://openreview.net/forum?id=-NEXDKk8gZ 421 | """ 422 | steps = timesteps + 1 423 | t = torch.linspace(0, timesteps, steps, dtype=torch.float64) / timesteps 424 | alphas_cumprod = torch.cos((t + s) / (1 + s) * math.pi * 0.5)**2 425 | alphas_cumprod = alphas_cumprod / alphas_cumprod[0] 426 | betas = 1 - (alphas_cumprod[1:] / alphas_cumprod[:-1]) 427 | return torch.clip(betas, 0, 0.999) 428 | 429 | 430 | def sigmoid_beta_schedule(timesteps, start=-3, end=3, tau=1, clamp_min=1e-5): 431 | """ 432 | sigmoid schedule 433 | proposed in https://arxiv.org/abs/2212.11972 - Figure 8 434 | better for images > 64x64, when used during training 435 | """ 436 | steps = timesteps + 1 437 | t = torch.linspace(0, timesteps, steps, dtype=torch.float64) / timesteps 438 | v_start = torch.tensor(start / tau).sigmoid() 439 | v_end = torch.tensor(end / tau).sigmoid() 440 | alphas_cumprod = (-( 441 | (t * 442 | (end - start) + start) / tau).sigmoid() + v_end) / (v_end - v_start) 443 | alphas_cumprod = alphas_cumprod / alphas_cumprod[0] 444 | betas = 1 - (alphas_cumprod[1:] / alphas_cumprod[:-1]) 445 | return torch.clip(betas, 0, 0.999) 446 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | asttokens==2.4.1 2 | attrs==24.2.0 3 | blobfile==3.0.0 4 | cads-api-client==1.5.0 5 | cdsapi==0.7.4 6 | certifi==2024.8.30 7 | cffi==1.17.1 8 | cfgrib==0.9.14.1 9 | charset-normalizer==3.4.0 10 | click==8.1.7 11 | comm==0.2.2 12 | contourpy==1.3.0 13 | cycler==0.12.1 14 | debugpy==1.8.7 15 | decorator==5.1.1 16 | eccodes==1.3.1 17 | ecmwflibs==0.6.3 18 | einops==0.8.0 19 | executing==2.1.0 20 | filelock==3.13.1 21 | findlibs==0.0.5 22 | fonttools==4.54.1 23 | fsspec==2024.2.0 24 | idna==3.10 25 | ipykernel==6.29.5 26 | ipython==8.29.0 27 | jedi==0.19.1 28 | Jinja2==3.1.3 29 | jupyter_client==8.6.3 30 | jupyter_core==5.7.2 31 | kiwisolver==1.4.7 32 | lxml==5.3.0 33 | MarkupSafe==2.1.5 34 | matplotlib==3.9.2 35 | matplotlib-inline==0.1.7 36 | mpmath==1.3.0 37 | multiurl==0.3.2 38 | nest-asyncio==1.6.0 39 | networkx==3.2.1 40 | numpy==2.1.3 41 | nvidia-cublas-cu11==11.11.3.6 42 | nvidia-cuda-cupti-cu11==11.8.87 43 | nvidia-cuda-nvrtc-cu11==11.8.89 44 | nvidia-cuda-runtime-cu11==11.8.89 45 | nvidia-cudnn-cu11==9.1.0.70 46 | nvidia-cufft-cu11==10.9.0.58 47 | nvidia-curand-cu11==10.3.0.86 48 | nvidia-cusolver-cu11==11.4.1.48 49 | nvidia-cusparse-cu11==11.7.5.86 50 | nvidia-nccl-cu11==2.21.5 51 | nvidia-nvtx-cu11==11.8.86 52 | opencv-python==4.10.0.84 53 | packaging==24.1 54 | pandas==2.2.3 55 | parso==0.8.4 56 | pexpect==4.9.0 57 | pillow==10.2.0 58 | platformdirs==4.3.6 59 | prompt_toolkit==3.0.48 60 | psutil==6.1.0 61 | ptyprocess==0.7.0 62 | pure_eval==0.2.3 63 | pycparser==2.22 64 | pycryptodomex==3.21.0 65 | Pygments==2.18.0 66 | pyparsing==3.2.0 67 | python-dateutil==2.9.0.post0 68 | pytz==2024.2 69 | pyzmq==26.2.0 70 | requests==2.32.3 71 | six==1.16.0 72 | stack-data==0.6.3 73 | sympy==1.13.1 74 | torch==2.5.1+cu118 75 | torchaudio==2.5.1+cu118 76 | torchvision==0.20.1+cu118 77 | tornado==6.4.1 78 | tqdm==4.66.6 79 | traitlets==5.14.3 80 | triton==3.1.0 81 | typing_extensions==4.9.0 82 | tzdata==2024.2 83 | urllib3==2.2.3 84 | wcwidth==0.2.13 85 | xarray==2024.10.0 -------------------------------------------------------------------------------- /src/hyperdm.py: -------------------------------------------------------------------------------- 1 | from functools import partial 2 | 3 | import torch as th 4 | from tqdm import tqdm 5 | from typing import List 6 | 7 | from guided_diffusion.gaussian_diffusion import GaussianDiffusion 8 | from model.mlp import MLP 9 | 10 | 11 | class HyperDM(th.nn.Module): 12 | 13 | def __init__(self, primary_net: th.nn.Module, hyper_net_dims: List[int], 14 | diffusion: GaussianDiffusion): 15 | """ 16 | Initialize the hyper-diffusion model class. 17 | 18 | :param primary_net: diffusion model 19 | :param hyper_net_dims: hyper-network layer dimensions 20 | :param diffusion: Gaussian diffusion process 21 | """ 22 | super().__init__() 23 | self.primary_net = primary_net 24 | self.primary_params = sum(p.numel() 25 | for p in self.primary_net.parameters()) 26 | # Freeze primary network weights 27 | for param in primary_net.parameters(): 28 | param.requires_grad = False 29 | 30 | hyper_net_dims.append(self.primary_params) 31 | self.hyper_net_input_dim = hyper_net_dims[0] 32 | self.hyper_net = MLP(hyper_net_dims) 33 | self.hyper_net = self.hyper_net 34 | self.hyper_params = sum(p.numel() for p in self.hyper_net.parameters()) 35 | 36 | self.diffusion = diffusion 37 | 38 | def print_stats(self): 39 | print("# of params (primary):", self.primary_params) 40 | print("# of params (hyper):", self.hyper_params) 41 | 42 | def get_mean_variance(self, 43 | M: int, 44 | N: int, 45 | condition: th.Tensor, 46 | device=None, 47 | progress=False): 48 | """ 49 | Sample the predictive distribution mean and variance. In the paper this is \mathbb{E}_{\hat{x} \sim p(x|y,\phi)}\[\hat{x}\] and \text{Var}_{\hat{x} \sim p(x|y,\phi)}\[\hat{x}\]. 50 | 51 | :param M: number of network weights to sample 52 | :param N: number of predictions to sample per network weight 53 | :param condition: input condition to sample with 54 | :param device: device to run on 55 | :return: mean and variance of the predictive distribution 56 | """ 57 | _, C, H, W = condition.shape 58 | mean = th.zeros([M, C, H, W]) 59 | var = th.zeros([M, C, H, W]) 60 | Ms = tqdm(range(M)) if progress else range(M) 61 | for i in Ms: 62 | net = self.sample_network(device) 63 | 64 | y = condition.repeat(N, 1, 1, 1).to(device) 65 | with th.no_grad(): 66 | preds = self.diffusion.ddim_sample_loop(net, 67 | y.shape, 68 | model_kwargs={"y": y}, 69 | device=device) 70 | mean[i] = preds.mean(dim=0) 71 | var[i] = preds.var(dim=0) 72 | return mean, var 73 | 74 | def sample_network(self, device=None): 75 | """ 76 | Sample a network with weights from a Bayesian hyper-network. 77 | 78 | :param device: device to run on 79 | :return: callable primary network with weights sampled from the hyper-network 80 | """ 81 | # Sample noise 82 | z = th.randn(self.hyper_net_input_dim).to(device) 83 | 84 | # Compute weights 85 | weights = self.hyper_net(z) 86 | weights = weights.ravel() 87 | assert ( 88 | len(weights) == self.primary_params 89 | ), f"# of generated weights {len(weights)} must match # of parameters {self.primary_params}!" 90 | # Format weights 91 | i = 0 92 | weight_dict = dict() 93 | for k, v in self.primary_net.state_dict().items(): 94 | weight_dict[k] = weights[i:i + v.numel()].view(v.shape) 95 | i += v.numel() 96 | 97 | return partial(th.func.functional_call, self.primary_net, weight_dict) 98 | -------------------------------------------------------------------------------- /src/test.py: -------------------------------------------------------------------------------- 1 | import matplotlib.pyplot as plt 2 | import numpy as np 3 | import torch as th 4 | from tqdm import tqdm 5 | 6 | from data.dataset import Dataset 7 | from data.era5 import ERA5 8 | from data.toy import ToyDataset 9 | from guided_diffusion.script_util import create_gaussian_diffusion 10 | from model.mlp import MLP 11 | from model.unet import Unet 12 | from src.hyperdm import HyperDM 13 | from src.util import circular_mask, normalize_range, parse_test_args 14 | 15 | 16 | def toy_test(args): 17 | device = "cuda" if th.cuda.is_available() else "cpu" 18 | primary_net = MLP([3, 8, 16, 8, 1]) 19 | diffusion = create_gaussian_diffusion(steps=args.diffusion_steps, 20 | predict_xstart=True, 21 | timestep_respacing="ddim10") 22 | hyperdm = HyperDM(primary_net, args.hyper_net_dims, diffusion).to(device) 23 | hyperdm.load_state_dict(th.load(args.checkpoint, weights_only=True)) 24 | hyperdm.print_stats() 25 | hyperdm.eval() 26 | 27 | eu = [] 28 | au = [] 29 | pred = [] 30 | xs = th.linspace(-1.0, 1.0, 1000) 31 | for i in tqdm(xs): 32 | y = th.tensor([i]).reshape(1, 1, 1, 1) 33 | mean, var = hyperdm.get_mean_variance(M=args.M, 34 | N=args.N, 35 | condition=y, 36 | device=device) 37 | eu.append(mean.var()) 38 | au.append(var.mean()) 39 | pred.append(mean.mean()) 40 | eu = th.vstack(eu).ravel() 41 | au = th.vstack(au).ravel() 42 | pred = th.vstack(pred).ravel() 43 | 44 | # Normalize uncertainty for visualization purposes 45 | eu_norm = normalize_range(eu, low=0, high=1) 46 | au_norm = normalize_range(au, low=0, high=1) 47 | 48 | dataset = ToyDataset(args.dataset_size, split="train") 49 | plt.scatter(x=dataset.x, 50 | y=dataset.y, 51 | s=5, 52 | c="gray", 53 | label="Train Data", 54 | alpha=0.5) 55 | plt.plot(xs, pred, c='black', label="Prediction") 56 | plt.fill_between(xs, 57 | pred - au_norm, 58 | pred + au_norm, 59 | color='lightsalmon', 60 | alpha=0.4, 61 | label="AU") 62 | plt.fill_between(xs, 63 | pred - eu_norm, 64 | pred + eu_norm, 65 | color='lightskyblue', 66 | alpha=0.4, 67 | label="EU") 68 | plt.legend() 69 | plt.title("HyperDM") 70 | plt.savefig("toy_result.pdf") 71 | 72 | def era5_test(args): 73 | device = "cuda" if th.cuda.is_available() else "cpu" 74 | primary_net = Unet(dim=16, 75 | dim_mults=(1, 2, 4, 8), 76 | channels=1, 77 | self_condition=True) 78 | dataset = ERA5(args.image_size, split="test", download=args.download) 79 | 80 | # Initialize network 81 | diffusion = create_gaussian_diffusion(steps=args.diffusion_steps, 82 | predict_xstart=True, 83 | timestep_respacing="ddim25") 84 | hyperdm = HyperDM(primary_net, args.hyper_net_dims, diffusion).to(device) 85 | hyperdm.load_state_dict(th.load(args.checkpoint, weights_only=True)) 86 | hyperdm.print_stats() 87 | hyperdm.eval() 88 | random_idx = np.random.choice(range(len(dataset))) 89 | x, y = dataset[random_idx] 90 | 91 | # Create out-of-distribution image 92 | ood = y.squeeze().clone() 93 | mask = circular_mask( 94 | *ood.shape, 95 | center=[int(.88 * args.image_size), 96 | int(.1 * args.image_size)], 97 | radius=int(.03 * args.image_size)) 98 | ood[mask] = 1 99 | ood = ood.reshape(1, 1, *ood.shape).to(device) 100 | mean, var = hyperdm.get_mean_variance(M=args.M, 101 | N=args.N, 102 | condition=ood, 103 | device=device, 104 | progress=True) 105 | pred = mean.mean(dim=0).squeeze() 106 | eu = mean.var(dim=0).squeeze() 107 | au = var.mean(dim=0).squeeze() 108 | 109 | _, axs = plt.subplots(1, 4, figsize=(25, 6)) 110 | axs[0].imshow(pred, cmap="gray") 111 | axs[1].imshow(ood.squeeze().cpu(), cmap="gray") 112 | axs[2].imshow(eu, cmap="gray") 113 | axs[3].imshow(au, cmap="gray") 114 | axs[0].set_title("Prediction") 115 | axs[1].set_title("Anomalous Input") 116 | axs[2].set_title("EU") 117 | axs[3].set_title("AU") 118 | for ax in axs: 119 | ax.axis('off') 120 | plt.savefig("era5_result.pdf") 121 | 122 | 123 | if __name__ == "__main__": 124 | args = parse_test_args() 125 | print(args) 126 | plt.rcParams['text.usetex'] = True 127 | 128 | if args.seed: 129 | rng = th.manual_seed(args.seed) 130 | np.random.seed(args.seed) 131 | 132 | if args.dataset == Dataset.TOY: 133 | toy_test(args) 134 | elif args.dataset == Dataset.ERA5: 135 | era5_test(args) 136 | else: 137 | raise NotImplementedError() 138 | -------------------------------------------------------------------------------- /src/toy_baseline.py: -------------------------------------------------------------------------------- 1 | from functools import partial 2 | 3 | import matplotlib.pyplot as plt 4 | import numpy as np 5 | import torch as th 6 | from torch.func import functional_call 7 | from torch.utils.data import DataLoader 8 | from tqdm import tqdm 9 | 10 | from data.toy import ToyDataset 11 | from guided_diffusion.script_util import create_gaussian_diffusion 12 | from model.mlp import MLP 13 | from src.util import normalize_range 14 | 15 | 16 | def get_mean_variance(M, 17 | N, 18 | models, 19 | diffusion, 20 | condition, 21 | device=None, 22 | progress=False): 23 | """ 24 | Sample the predictive distribution mean and variance. In the paper this is \mathbb{E}_{\hat{x} \sim p(x|y,\phi)}\[\hat{x}\] and \text{Var}_{\hat{x} \sim p(x|y,\phi)}\[\hat{x}\]. 25 | 26 | :param M: number of network weights to sample 27 | :param N: number of predictions to sample per network weight 28 | :param condition: input condition to sample with 29 | :param device: device to run on 30 | :return: mean and variance of the predictive distribution 31 | """ 32 | _, C, H, W = condition.shape 33 | mean = th.zeros([M, C, H, W]) 34 | var = th.zeros([M, C, H, W]) 35 | Ms = tqdm(range(M)) if progress else range(M) 36 | for i in Ms: 37 | net = partial(functional_call, models[i], 38 | dict(models[i].named_parameters())) 39 | 40 | y = condition.repeat(N, 1, 1, 1).to(device) 41 | with th.no_grad(): 42 | preds = diffusion.ddim_sample_loop(net, 43 | y.shape, 44 | model_kwargs={"y": y}, 45 | device=device) 46 | mean[i] = preds.mean(dim=0) 47 | var[i] = preds.var(dim=0) 48 | return mean, var 49 | 50 | 51 | if __name__ == "__main__": 52 | M = 10 53 | # Seed for reproducible results. 54 | rng = th.manual_seed(1) 55 | np.random.seed(1) 56 | 57 | device = "cuda" if th.cuda.is_available() else "cpu" 58 | 59 | dataset = ToyDataset(10000, split="train") 60 | dataloader = DataLoader(dataset, 64, shuffle=True, pin_memory=True) 61 | 62 | # Initialize network 63 | diffusion = create_gaussian_diffusion(steps=1000, predict_xstart=True) 64 | 65 | # Training loop 66 | models = [] 67 | for i in tqdm(range(M)): 68 | primary_net = MLP([3, 8, 16, 8, 1]).to(device) 69 | primary_net.train() 70 | optimizer = th.optim.AdamW(primary_net.parameters(), 1e-2) 71 | prog_bar = tqdm(range(100)) 72 | for step in prog_bar: 73 | for (x, y) in dataloader: 74 | x = x.to(device) 75 | y = y.to(device) 76 | t = th.randint(0, 1000, (len(x), ), device=device) 77 | net = partial(functional_call, primary_net, 78 | dict(primary_net.named_parameters())) 79 | loss = diffusion.training_losses( 80 | net, x, t, model_kwargs={"y": y})["loss"].mean() 81 | optimizer.zero_grad() 82 | loss.backward() 83 | optimizer.step() 84 | prog_bar.set_description(f"loss={loss.item():.4f}") 85 | models.append(primary_net) 86 | 87 | diffusion = create_gaussian_diffusion(steps=1000, 88 | predict_xstart=True, 89 | timestep_respacing="ddim10") 90 | # Testing 91 | eu = [] 92 | au = [] 93 | pred = [] 94 | xs = th.linspace(-1.0, 1.0, 1000) 95 | for i in tqdm(xs): 96 | y = th.tensor([i]).reshape(1, 1, 1, 1) 97 | mean, var = get_mean_variance(M, 98 | 100, 99 | models, 100 | diffusion, 101 | y, 102 | device=device) 103 | eu.append(mean.var()) 104 | au.append(var.mean()) 105 | pred.append(mean.mean()) 106 | eu = th.vstack(eu).ravel() 107 | au = th.vstack(au).ravel() 108 | pred = th.vstack(pred).ravel() 109 | 110 | eu_norm = normalize_range(eu, low=0, high=1) 111 | au_norm = normalize_range(au, low=0, high=1) 112 | 113 | plt.rcParams['text.usetex'] = True 114 | plt.scatter(x=dataset.x, 115 | y=dataset.y, 116 | s=5, 117 | c="gray", 118 | label="Train Data", 119 | alpha=0.5) 120 | plt.plot(xs, pred, c='black', label="Prediction") 121 | plt.fill_between(xs, 122 | pred - au_norm, 123 | pred + au_norm, 124 | color='lightsalmon', 125 | alpha=0.4, 126 | label="AU") 127 | plt.fill_between(xs, 128 | pred - eu_norm, 129 | pred + eu_norm, 130 | color='lightskyblue', 131 | alpha=0.4, 132 | label="EU") 133 | plt.legend() 134 | plt.title("Deep Ensemble") 135 | plt.savefig("toy_baseline.pdf") 136 | -------------------------------------------------------------------------------- /src/train.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import torch as th 3 | from torch.utils.data import DataLoader, Subset 4 | from tqdm import tqdm 5 | 6 | from data.dataset import Dataset 7 | from data.era5 import ERA5 8 | from data.toy import ToyDataset 9 | from guided_diffusion.script_util import create_gaussian_diffusion 10 | from model.mlp import MLP 11 | from model.unet import Unet 12 | from src.hyperdm import HyperDM 13 | from src.util import parse_train_args 14 | 15 | if __name__ == "__main__": 16 | args = parse_train_args() 17 | print(args) 18 | 19 | # Seed for reproducible results. 20 | if not args.seed is None: 21 | rng = th.manual_seed(args.seed) 22 | np.random.seed(args.seed) 23 | 24 | device = "cuda" if th.cuda.is_available() else "cpu" 25 | 26 | if args.dataset == Dataset.TOY: 27 | primary_net = MLP([3, 8, 16, 8, 1]) 28 | dataset = ToyDataset(args.dataset_size, split="train") 29 | elif args.dataset == Dataset.ERA5: 30 | primary_net = Unet(dim=16, 31 | dim_mults=(1, 2, 4, 8), 32 | channels=1, 33 | self_condition=True) 34 | dataset = ERA5(args.image_size, split="train", download=args.download) 35 | dataset = Subset(dataset, range(args.dataset_size)) 36 | else: 37 | raise NotImplementedError() 38 | 39 | # Initialize network 40 | diffusion = create_gaussian_diffusion(steps=args.diffusion_steps, 41 | predict_xstart=True) 42 | hyperdm = HyperDM(primary_net, args.hyper_net_dims, diffusion).to(device) 43 | hyperdm.print_stats() 44 | hyperdm.train() 45 | optimizer = th.optim.AdamW(hyperdm.parameters(), args.lr) 46 | 47 | # Training loop 48 | dataloader = DataLoader(dataset, 49 | args.batch_size, 50 | shuffle=True, 51 | pin_memory=True) 52 | prog_bar = tqdm(range(args.num_epochs)) 53 | for step in prog_bar: 54 | for (x, y) in dataloader: 55 | x = x.to(device) 56 | y = y.to(device) 57 | t = th.randint(0, args.diffusion_steps, (len(x), ), device=device) 58 | 59 | net = hyperdm.sample_network(device) 60 | loss = hyperdm.diffusion.training_losses( 61 | net, x, t, model_kwargs={"y": y})["loss"].mean() 62 | 63 | optimizer.zero_grad() 64 | loss.backward() 65 | optimizer.step() 66 | prog_bar.set_description(f"loss={loss.item():.4f}") 67 | 68 | th.save(hyperdm.state_dict(), args.checkpoint) 69 | -------------------------------------------------------------------------------- /src/util.py: -------------------------------------------------------------------------------- 1 | from argparse import ArgumentParser, BooleanOptionalAction 2 | 3 | import numpy as np 4 | 5 | from data.dataset import Dataset 6 | 7 | 8 | def normalize_range(x, low=-1, high=1): 9 | """ 10 | Normalizes values to a specified range. 11 | :param x: input value 12 | :param low: low end of the range 13 | :param high: high end of the range 14 | :return: normalized value 15 | """ 16 | x = (x - x.min()) / (x.max() - x.min()) 17 | x = ((high - low) * x) + low 18 | return x 19 | 20 | 21 | def circular_mask(h: int, w: int, center: tuple, radius: int): 22 | """ 23 | Creates a circular mask. 24 | :param h: target mask height 25 | :param w: target mask weight 26 | :param center: circle center 27 | :param radius: circle radius 28 | :return: circle mask 29 | """ 30 | Y, X = np.ogrid[:h, :w] 31 | dist = np.sqrt((X - center[0])**2 + (Y - center[1])**2) 32 | mask = dist <= radius 33 | return mask 34 | 35 | 36 | 37 | def parse_train_args(): 38 | parser = ArgumentParser() 39 | parser.add_argument("--seed", type=int) 40 | parser.add_argument("--dataset", type=Dataset, choices=list(Dataset)) 41 | parser.add_argument("--dataset_size", type=int, default=1000) 42 | parser.add_argument('--download', action=BooleanOptionalAction) 43 | parser.add_argument("--image_size", type=int, default=256) 44 | parser.add_argument("--checkpoint", type=str, default="model.pt") 45 | parser.add_argument("--num_epochs", type=int, default=100) 46 | parser.add_argument("--lr", type=float, default=1e-3) 47 | parser.add_argument("--batch_size", type=int, default=64) 48 | parser.add_argument("--diffusion_steps", type=int, default=1000) 49 | parser.add_argument("--hyper_net_dims", type=int, nargs="+") 50 | return parser.parse_args() 51 | 52 | 53 | def parse_test_args(): 54 | parser = ArgumentParser() 55 | parser.add_argument("--seed", type=int) 56 | parser.add_argument("--dataset", type=Dataset, choices=list(Dataset)) 57 | parser.add_argument("--dataset_size", type=int, default=1000) 58 | parser.add_argument('--download', action=BooleanOptionalAction) 59 | parser.add_argument("--image_size", type=int, default=256) 60 | parser.add_argument("--checkpoint", type=str, default="model.pt") 61 | parser.add_argument("--M", type=int, default=100) 62 | parser.add_argument("--N", type=int, default=100) 63 | parser.add_argument("--diffusion_steps", type=int, default=1000) 64 | parser.add_argument("--hyper_net_dims", type=int, nargs="+") 65 | return parser.parse_args() 66 | --------------------------------------------------------------------------------