├── .gitignore ├── ComfyUI-PMRF-Workflow.json ├── ComfyUI-PMRF-Workflow.png ├── LICENSE ├── README.md ├── __init__.py ├── arch ├── __init__.py ├── hourglass │ ├── __init__.py │ ├── axial_rope.py │ ├── flags.py │ ├── flops.py │ └── image_transformer_v2.py └── swinir │ ├── __init__.py │ └── swinir.py ├── lightning_models └── mmse_rectified_flow.py ├── nodes.py ├── prestartup_script.py └── utils ├── __init__.py └── create_arch.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 | -------------------------------------------------------------------------------- /ComfyUI-PMRF-Workflow.json: -------------------------------------------------------------------------------- 1 | { 2 | "last_node_id": 16, 3 | "last_link_id": 17, 4 | "nodes": [ 5 | { 6 | "id": 12, 7 | "type": "SaveImage", 8 | "pos": { 9 | "0": 1076, 10 | "1": 177 11 | }, 12 | "size": { 13 | "0": 588.0836181640625, 14 | "1": 630.0543212890625 15 | }, 16 | "flags": {}, 17 | "order": 2, 18 | "mode": 0, 19 | "inputs": [ 20 | { 21 | "name": "images", 22 | "type": "IMAGE", 23 | "link": 17 24 | } 25 | ], 26 | "outputs": [], 27 | "properties": {}, 28 | "widgets_values": [ 29 | "ComfyUI" 30 | ] 31 | }, 32 | { 33 | "id": 10, 34 | "type": "LoadImage", 35 | "pos": { 36 | "0": 105, 37 | "1": 178 38 | }, 39 | "size": { 40 | "0": 537.6058959960938, 41 | "1": 637.7671508789062 42 | }, 43 | "flags": {}, 44 | "order": 0, 45 | "mode": 0, 46 | "inputs": [], 47 | "outputs": [ 48 | { 49 | "name": "IMAGE", 50 | "type": "IMAGE", 51 | "links": [ 52 | 16 53 | ], 54 | "slot_index": 0 55 | }, 56 | { 57 | "name": "MASK", 58 | "type": "MASK", 59 | "links": null 60 | } 61 | ], 62 | "properties": { 63 | "Node name for S&R": "LoadImage" 64 | }, 65 | "widgets_values": [ 66 | "00000055.png", 67 | "image" 68 | ] 69 | }, 70 | { 71 | "id": 16, 72 | "type": "PMRF", 73 | "pos": { 74 | "0": 711, 75 | "1": 179 76 | }, 77 | "size": { 78 | "0": 315, 79 | "1": 154 80 | }, 81 | "flags": {}, 82 | "order": 1, 83 | "mode": 0, 84 | "inputs": [ 85 | { 86 | "name": "images", 87 | "type": "IMAGE", 88 | "link": 16 89 | } 90 | ], 91 | "outputs": [ 92 | { 93 | "name": "images", 94 | "type": "IMAGE", 95 | "links": [ 96 | 17 97 | ], 98 | "slot_index": 0 99 | } 100 | ], 101 | "properties": { 102 | "Node name for S&R": "PMRF" 103 | }, 104 | "widgets_values": [ 105 | 2, 106 | 25, 107 | 42, 108 | "randomize", 109 | "lanczos4" 110 | ] 111 | } 112 | ], 113 | "links": [ 114 | [ 115 | 16, 116 | 10, 117 | 0, 118 | 16, 119 | 0, 120 | "IMAGE" 121 | ], 122 | [ 123 | 17, 124 | 16, 125 | 0, 126 | 12, 127 | 0, 128 | "IMAGE" 129 | ] 130 | ], 131 | "groups": [], 132 | "config": {}, 133 | "extra": { 134 | "ds": { 135 | "scale": 0.751314800901578, 136 | "offset": [ 137 | -27.85560710141621, 138 | -28.96510744938352 139 | ] 140 | } 141 | }, 142 | "version": 0.4 143 | } -------------------------------------------------------------------------------- /ComfyUI-PMRF-Workflow.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/2kpr/ComfyUI-PMRF/e105c042161785b6fbbae840e70817896c1eebf4/ComfyUI-PMRF-Workflow.png -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU AFFERO GENERAL PUBLIC LICENSE 2 | Version 3, 19 November 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 Affero General Public License is a free, copyleft license for 11 | software and other kinds of works, specifically designed to ensure 12 | cooperation with the community in the case of network server software. 13 | 14 | The licenses for most software and other practical works are designed 15 | to take away your freedom to share and change the works. By contrast, 16 | our General Public Licenses are intended to guarantee your freedom to 17 | share and change all versions of a program--to make sure it remains free 18 | software for all its users. 19 | 20 | When we speak of free software, we are referring to freedom, not 21 | price. Our General Public Licenses are designed to make sure that you 22 | have the freedom to distribute copies of free software (and charge for 23 | them if you wish), that you receive source code or can get it if you 24 | want it, that you can change the software or use pieces of it in new 25 | free programs, and that you know you can do these things. 26 | 27 | Developers that use our General Public Licenses protect your rights 28 | with two steps: (1) assert copyright on the software, and (2) offer 29 | you this License which gives you legal permission to copy, distribute 30 | and/or modify the software. 31 | 32 | A secondary benefit of defending all users' freedom is that 33 | improvements made in alternate versions of the program, if they 34 | receive widespread use, become available for other developers to 35 | incorporate. Many developers of free software are heartened and 36 | encouraged by the resulting cooperation. However, in the case of 37 | software used on network servers, this result may fail to come about. 38 | The GNU General Public License permits making a modified version and 39 | letting the public access it on a server without ever releasing its 40 | source code to the public. 41 | 42 | The GNU Affero General Public License is designed specifically to 43 | ensure that, in such cases, the modified source code becomes available 44 | to the community. It requires the operator of a network server to 45 | provide the source code of the modified version running there to the 46 | users of that server. Therefore, public use of a modified version, on 47 | a publicly accessible server, gives the public access to the source 48 | code of the modified version. 49 | 50 | An older license, called the Affero General Public License and 51 | published by Affero, was designed to accomplish similar goals. This is 52 | a different license, not a version of the Affero GPL, but Affero has 53 | released a new version of the Affero GPL which permits relicensing under 54 | this license. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | TERMS AND CONDITIONS 60 | 61 | 0. Definitions. 62 | 63 | "This License" refers to version 3 of the GNU Affero General Public License. 64 | 65 | "Copyright" also means copyright-like laws that apply to other kinds of 66 | works, such as semiconductor masks. 67 | 68 | "The Program" refers to any copyrightable work licensed under this 69 | License. Each licensee is addressed as "you". "Licensees" and 70 | "recipients" may be individuals or organizations. 71 | 72 | To "modify" a work means to copy from or adapt all or part of the work 73 | in a fashion requiring copyright permission, other than the making of an 74 | exact copy. The resulting work is called a "modified version" of the 75 | earlier work or a work "based on" the earlier work. 76 | 77 | A "covered work" means either the unmodified Program or a work based 78 | on the Program. 79 | 80 | To "propagate" a work means to do anything with it that, without 81 | permission, would make you directly or secondarily liable for 82 | infringement under applicable copyright law, except executing it on a 83 | computer or modifying a private copy. Propagation includes copying, 84 | distribution (with or without modification), making available to the 85 | public, and in some countries other activities as well. 86 | 87 | To "convey" a work means any kind of propagation that enables other 88 | parties to make or receive copies. Mere interaction with a user through 89 | a computer network, with no transfer of a copy, is not conveying. 90 | 91 | An interactive user interface displays "Appropriate Legal Notices" 92 | to the extent that it includes a convenient and prominently visible 93 | feature that (1) displays an appropriate copyright notice, and (2) 94 | tells the user that there is no warranty for the work (except to the 95 | extent that warranties are provided), that licensees may convey the 96 | work under this License, and how to view a copy of this License. If 97 | the interface presents a list of user commands or options, such as a 98 | menu, a prominent item in the list meets this criterion. 99 | 100 | 1. Source Code. 101 | 102 | The "source code" for a work means the preferred form of the work 103 | for making modifications to it. "Object code" means any non-source 104 | form of a work. 105 | 106 | A "Standard Interface" means an interface that either is an official 107 | standard defined by a recognized standards body, or, in the case of 108 | interfaces specified for a particular programming language, one that 109 | is widely used among developers working in that language. 110 | 111 | The "System Libraries" of an executable work include anything, other 112 | than the work as a whole, that (a) is included in the normal form of 113 | packaging a Major Component, but which is not part of that Major 114 | Component, and (b) serves only to enable use of the work with that 115 | Major Component, or to implement a Standard Interface for which an 116 | implementation is available to the public in source code form. A 117 | "Major Component", in this context, means a major essential component 118 | (kernel, window system, and so on) of the specific operating system 119 | (if any) on which the executable work runs, or a compiler used to 120 | produce the work, or an object code interpreter used to run it. 121 | 122 | The "Corresponding Source" for a work in object code form means all 123 | the source code needed to generate, install, and (for an executable 124 | work) run the object code and to modify the work, including scripts to 125 | control those activities. However, it does not include the work's 126 | System Libraries, or general-purpose tools or generally available free 127 | programs which are used unmodified in performing those activities but 128 | which are not part of the work. For example, Corresponding Source 129 | includes interface definition files associated with source files for 130 | the work, and the source code for shared libraries and dynamically 131 | linked subprograms that the work is specifically designed to require, 132 | such as by intimate data communication or control flow between those 133 | subprograms and other parts of the work. 134 | 135 | The Corresponding Source need not include anything that users 136 | can regenerate automatically from other parts of the Corresponding 137 | Source. 138 | 139 | The Corresponding Source for a work in source code form is that 140 | same work. 141 | 142 | 2. Basic Permissions. 143 | 144 | All rights granted under this License are granted for the term of 145 | copyright on the Program, and are irrevocable provided the stated 146 | conditions are met. This License explicitly affirms your unlimited 147 | permission to run the unmodified Program. The output from running a 148 | covered work is covered by this License only if the output, given its 149 | content, constitutes a covered work. This License acknowledges your 150 | rights of fair use or other equivalent, as provided by copyright law. 151 | 152 | You may make, run and propagate covered works that you do not 153 | convey, without conditions so long as your license otherwise remains 154 | in force. You may convey covered works to others for the sole purpose 155 | of having them make modifications exclusively for you, or provide you 156 | with facilities for running those works, provided that you comply with 157 | the terms of this License in conveying all material for which you do 158 | not control copyright. Those thus making or running the covered works 159 | for you must do so exclusively on your behalf, under your direction 160 | and control, on terms that prohibit them from making any copies of 161 | your copyrighted material outside their relationship with you. 162 | 163 | Conveying under any other circumstances is permitted solely under 164 | the conditions stated below. Sublicensing is not allowed; section 10 165 | makes it unnecessary. 166 | 167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 168 | 169 | No covered work shall be deemed part of an effective technological 170 | measure under any applicable law fulfilling obligations under article 171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 172 | similar laws prohibiting or restricting circumvention of such 173 | measures. 174 | 175 | When you convey a covered work, you waive any legal power to forbid 176 | circumvention of technological measures to the extent such circumvention 177 | is effected by exercising rights under this License with respect to 178 | the covered work, and you disclaim any intention to limit operation or 179 | modification of the work as a means of enforcing, against the work's 180 | users, your or third parties' legal rights to forbid circumvention of 181 | technological measures. 182 | 183 | 4. Conveying Verbatim Copies. 184 | 185 | You may convey verbatim copies of the Program's source code as you 186 | receive it, in any medium, provided that you conspicuously and 187 | appropriately publish on each copy an appropriate copyright notice; 188 | keep intact all notices stating that this License and any 189 | non-permissive terms added in accord with section 7 apply to the code; 190 | keep intact all notices of the absence of any warranty; and give all 191 | recipients a copy of this License along with the Program. 192 | 193 | You may charge any price or no price for each copy that you convey, 194 | and you may offer support or warranty protection for a fee. 195 | 196 | 5. Conveying Modified Source Versions. 197 | 198 | You may convey a work based on the Program, or the modifications to 199 | produce it from the Program, in the form of source code under the 200 | terms of section 4, provided that you also meet all of these conditions: 201 | 202 | a) The work must carry prominent notices stating that you modified 203 | it, and giving a relevant date. 204 | 205 | b) The work must carry prominent notices stating that it is 206 | released under this License and any conditions added under section 207 | 7. This requirement modifies the requirement in section 4 to 208 | "keep intact all notices". 209 | 210 | c) You must license the entire work, as a whole, under this 211 | License to anyone who comes into possession of a copy. This 212 | License will therefore apply, along with any applicable section 7 213 | additional terms, to the whole of the work, and all its parts, 214 | regardless of how they are packaged. This License gives no 215 | permission to license the work in any other way, but it does not 216 | invalidate such permission if you have separately received it. 217 | 218 | d) If the work has interactive user interfaces, each must display 219 | Appropriate Legal Notices; however, if the Program has interactive 220 | interfaces that do not display Appropriate Legal Notices, your 221 | work need not make them do so. 222 | 223 | A compilation of a covered work with other separate and independent 224 | works, which are not by their nature extensions of the covered work, 225 | and which are not combined with it such as to form a larger program, 226 | in or on a volume of a storage or distribution medium, is called an 227 | "aggregate" if the compilation and its resulting copyright are not 228 | used to limit the access or legal rights of the compilation's users 229 | beyond what the individual works permit. Inclusion of a covered work 230 | in an aggregate does not cause this License to apply to the other 231 | parts of the aggregate. 232 | 233 | 6. Conveying Non-Source Forms. 234 | 235 | You may convey a covered work in object code form under the terms 236 | of sections 4 and 5, provided that you also convey the 237 | machine-readable Corresponding Source under the terms of this License, 238 | in one of these ways: 239 | 240 | a) Convey the object code in, or embodied in, a physical product 241 | (including a physical distribution medium), accompanied by the 242 | Corresponding Source fixed on a durable physical medium 243 | customarily used for software interchange. 244 | 245 | b) Convey the object code in, or embodied in, a physical product 246 | (including a physical distribution medium), accompanied by a 247 | written offer, valid for at least three years and valid for as 248 | long as you offer spare parts or customer support for that product 249 | model, to give anyone who possesses the object code either (1) a 250 | copy of the Corresponding Source for all the software in the 251 | product that is covered by this License, on a durable physical 252 | medium customarily used for software interchange, for a price no 253 | more than your reasonable cost of physically performing this 254 | conveying of source, or (2) access to copy the 255 | Corresponding Source from a network server at no charge. 256 | 257 | c) Convey individual copies of the object code with a copy of the 258 | written offer to provide the Corresponding Source. This 259 | alternative is allowed only occasionally and noncommercially, and 260 | only if you received the object code with such an offer, in accord 261 | with subsection 6b. 262 | 263 | d) Convey the object code by offering access from a designated 264 | place (gratis or for a charge), and offer equivalent access to the 265 | Corresponding Source in the same way through the same place at no 266 | further charge. You need not require recipients to copy the 267 | Corresponding Source along with the object code. If the place to 268 | copy the object code is a network server, the Corresponding Source 269 | may be on a different server (operated by you or a third party) 270 | that supports equivalent copying facilities, provided you maintain 271 | clear directions next to the object code saying where to find the 272 | Corresponding Source. Regardless of what server hosts the 273 | Corresponding Source, you remain obligated to ensure that it is 274 | available for as long as needed to satisfy these requirements. 275 | 276 | e) Convey the object code using peer-to-peer transmission, provided 277 | you inform other peers where the object code and Corresponding 278 | Source of the work are being offered to the general public at no 279 | charge under subsection 6d. 280 | 281 | A separable portion of the object code, whose source code is excluded 282 | from the Corresponding Source as a System Library, need not be 283 | included in conveying the object code work. 284 | 285 | A "User Product" is either (1) a "consumer product", which means any 286 | tangible personal property which is normally used for personal, family, 287 | or household purposes, or (2) anything designed or sold for incorporation 288 | into a dwelling. In determining whether a product is a consumer product, 289 | doubtful cases shall be resolved in favor of coverage. For a particular 290 | product received by a particular user, "normally used" refers to a 291 | typical or common use of that class of product, regardless of the status 292 | of the particular user or of the way in which the particular user 293 | actually uses, or expects or is expected to use, the product. A product 294 | is a consumer product regardless of whether the product has substantial 295 | commercial, industrial or non-consumer uses, unless such uses represent 296 | the only significant mode of use of the product. 297 | 298 | "Installation Information" for a User Product means any methods, 299 | procedures, authorization keys, or other information required to install 300 | and execute modified versions of a covered work in that User Product from 301 | a modified version of its Corresponding Source. The information must 302 | suffice to ensure that the continued functioning of the modified object 303 | code is in no case prevented or interfered with solely because 304 | modification has been made. 305 | 306 | If you convey an object code work under this section in, or with, or 307 | specifically for use in, a User Product, and the conveying occurs as 308 | part of a transaction in which the right of possession and use of the 309 | User Product is transferred to the recipient in perpetuity or for a 310 | fixed term (regardless of how the transaction is characterized), the 311 | Corresponding Source conveyed under this section must be accompanied 312 | by the Installation Information. But this requirement does not apply 313 | if neither you nor any third party retains the ability to install 314 | modified object code on the User Product (for example, the work has 315 | been installed in ROM). 316 | 317 | The requirement to provide Installation Information does not include a 318 | requirement to continue to provide support service, warranty, or updates 319 | for a work that has been modified or installed by the recipient, or for 320 | the User Product in which it has been modified or installed. Access to a 321 | network may be denied when the modification itself materially and 322 | adversely affects the operation of the network or violates the rules and 323 | protocols for communication across the network. 324 | 325 | Corresponding Source conveyed, and Installation Information provided, 326 | in accord with this section must be in a format that is publicly 327 | documented (and with an implementation available to the public in 328 | source code form), and must require no special password or key for 329 | unpacking, reading or copying. 330 | 331 | 7. Additional Terms. 332 | 333 | "Additional permissions" are terms that supplement the terms of this 334 | License by making exceptions from one or more of its conditions. 335 | Additional permissions that are applicable to the entire Program shall 336 | be treated as though they were included in this License, to the extent 337 | that they are valid under applicable law. If additional permissions 338 | apply only to part of the Program, that part may be used separately 339 | under those permissions, but the entire Program remains governed by 340 | this License without regard to the additional permissions. 341 | 342 | When you convey a copy of a covered work, you may at your option 343 | remove any additional permissions from that copy, or from any part of 344 | it. (Additional permissions may be written to require their own 345 | removal in certain cases when you modify the work.) You may place 346 | additional permissions on material, added by you to a covered work, 347 | for which you have or can give appropriate copyright permission. 348 | 349 | Notwithstanding any other provision of this License, for material you 350 | add to a covered work, you may (if authorized by the copyright holders of 351 | that material) supplement the terms of this License with terms: 352 | 353 | a) Disclaiming warranty or limiting liability differently from the 354 | terms of sections 15 and 16 of this License; or 355 | 356 | b) Requiring preservation of specified reasonable legal notices or 357 | author attributions in that material or in the Appropriate Legal 358 | Notices displayed by works containing it; or 359 | 360 | c) Prohibiting misrepresentation of the origin of that material, or 361 | requiring that modified versions of such material be marked in 362 | reasonable ways as different from the original version; or 363 | 364 | d) Limiting the use for publicity purposes of names of licensors or 365 | authors of the material; or 366 | 367 | e) Declining to grant rights under trademark law for use of some 368 | trade names, trademarks, or service marks; or 369 | 370 | f) Requiring indemnification of licensors and authors of that 371 | material by anyone who conveys the material (or modified versions of 372 | it) with contractual assumptions of liability to the recipient, for 373 | any liability that these contractual assumptions directly impose on 374 | those licensors and authors. 375 | 376 | All other non-permissive additional terms are considered "further 377 | restrictions" within the meaning of section 10. If the Program as you 378 | received it, or any part of it, contains a notice stating that it is 379 | governed by this License along with a term that is a further 380 | restriction, you may remove that term. If a license document contains 381 | a further restriction but permits relicensing or conveying under this 382 | License, you may add to a covered work material governed by the terms 383 | of that license document, provided that the further restriction does 384 | not survive such relicensing or conveying. 385 | 386 | If you add terms to a covered work in accord with this section, you 387 | must place, in the relevant source files, a statement of the 388 | additional terms that apply to those files, or a notice indicating 389 | where to find the applicable terms. 390 | 391 | Additional terms, permissive or non-permissive, may be stated in the 392 | form of a separately written license, or stated as exceptions; 393 | the above requirements apply either way. 394 | 395 | 8. Termination. 396 | 397 | You may not propagate or modify a covered work except as expressly 398 | provided under this License. Any attempt otherwise to propagate or 399 | modify it is void, and will automatically terminate your rights under 400 | this License (including any patent licenses granted under the third 401 | paragraph of section 11). 402 | 403 | However, if you cease all violation of this License, then your 404 | license from a particular copyright holder is reinstated (a) 405 | provisionally, unless and until the copyright holder explicitly and 406 | finally terminates your license, and (b) permanently, if the copyright 407 | holder fails to notify you of the violation by some reasonable means 408 | prior to 60 days after the cessation. 409 | 410 | Moreover, your license from a particular copyright holder is 411 | reinstated permanently if the copyright holder notifies you of the 412 | violation by some reasonable means, this is the first time you have 413 | received notice of violation of this License (for any work) from that 414 | copyright holder, and you cure the violation prior to 30 days after 415 | your receipt of the notice. 416 | 417 | Termination of your rights under this section does not terminate the 418 | licenses of parties who have received copies or rights from you under 419 | this License. If your rights have been terminated and not permanently 420 | reinstated, you do not qualify to receive new licenses for the same 421 | material under section 10. 422 | 423 | 9. Acceptance Not Required for Having Copies. 424 | 425 | You are not required to accept this License in order to receive or 426 | run a copy of the Program. Ancillary propagation of a covered work 427 | occurring solely as a consequence of using peer-to-peer transmission 428 | to receive a copy likewise does not require acceptance. However, 429 | nothing other than this License grants you permission to propagate or 430 | modify any covered work. These actions infringe copyright if you do 431 | not accept this License. Therefore, by modifying or propagating a 432 | covered work, you indicate your acceptance of this License to do so. 433 | 434 | 10. Automatic Licensing of Downstream Recipients. 435 | 436 | Each time you convey a covered work, the recipient automatically 437 | receives a license from the original licensors, to run, modify and 438 | propagate that work, subject to this License. You are not responsible 439 | for enforcing compliance by third parties with this License. 440 | 441 | An "entity transaction" is a transaction transferring control of an 442 | organization, or substantially all assets of one, or subdividing an 443 | organization, or merging organizations. If propagation of a covered 444 | work results from an entity transaction, each party to that 445 | transaction who receives a copy of the work also receives whatever 446 | licenses to the work the party's predecessor in interest had or could 447 | give under the previous paragraph, plus a right to possession of the 448 | Corresponding Source of the work from the predecessor in interest, if 449 | the predecessor has it or can get it with reasonable efforts. 450 | 451 | You may not impose any further restrictions on the exercise of the 452 | rights granted or affirmed under this License. For example, you may 453 | not impose a license fee, royalty, or other charge for exercise of 454 | rights granted under this License, and you may not initiate litigation 455 | (including a cross-claim or counterclaim in a lawsuit) alleging that 456 | any patent claim is infringed by making, using, selling, offering for 457 | sale, or importing the Program or any portion of it. 458 | 459 | 11. Patents. 460 | 461 | A "contributor" is a copyright holder who authorizes use under this 462 | License of the Program or a work on which the Program is based. The 463 | work thus licensed is called the contributor's "contributor version". 464 | 465 | A contributor's "essential patent claims" are all patent claims 466 | owned or controlled by the contributor, whether already acquired or 467 | hereafter acquired, that would be infringed by some manner, permitted 468 | by this License, of making, using, or selling its contributor version, 469 | but do not include claims that would be infringed only as a 470 | consequence of further modification of the contributor version. For 471 | purposes of this definition, "control" includes the right to grant 472 | patent sublicenses in a manner consistent with the requirements of 473 | this License. 474 | 475 | Each contributor grants you a non-exclusive, worldwide, royalty-free 476 | patent license under the contributor's essential patent claims, to 477 | make, use, sell, offer for sale, import and otherwise run, modify and 478 | propagate the contents of its contributor version. 479 | 480 | In the following three paragraphs, a "patent license" is any express 481 | agreement or commitment, however denominated, not to enforce a patent 482 | (such as an express permission to practice a patent or covenant not to 483 | sue for patent infringement). To "grant" such a patent license to a 484 | party means to make such an agreement or commitment not to enforce a 485 | patent against the party. 486 | 487 | If you convey a covered work, knowingly relying on a patent license, 488 | and the Corresponding Source of the work is not available for anyone 489 | to copy, free of charge and under the terms of this License, through a 490 | publicly available network server or other readily accessible means, 491 | then you must either (1) cause the Corresponding Source to be so 492 | available, or (2) arrange to deprive yourself of the benefit of the 493 | patent license for this particular work, or (3) arrange, in a manner 494 | consistent with the requirements of this License, to extend the patent 495 | license to downstream recipients. "Knowingly relying" means you have 496 | actual knowledge that, but for the patent license, your conveying the 497 | covered work in a country, or your recipient's use of the covered work 498 | in a country, would infringe one or more identifiable patents in that 499 | country that you have reason to believe are valid. 500 | 501 | If, pursuant to or in connection with a single transaction or 502 | arrangement, you convey, or propagate by procuring conveyance of, a 503 | covered work, and grant a patent license to some of the parties 504 | receiving the covered work authorizing them to use, propagate, modify 505 | or convey a specific copy of the covered work, then the patent license 506 | you grant is automatically extended to all recipients of the covered 507 | work and works based on it. 508 | 509 | A patent license is "discriminatory" if it does not include within 510 | the scope of its coverage, prohibits the exercise of, or is 511 | conditioned on the non-exercise of one or more of the rights that are 512 | specifically granted under this License. You may not convey a covered 513 | work if you are a party to an arrangement with a third party that is 514 | in the business of distributing software, under which you make payment 515 | to the third party based on the extent of your activity of conveying 516 | the work, and under which the third party grants, to any of the 517 | parties who would receive the covered work from you, a discriminatory 518 | patent license (a) in connection with copies of the covered work 519 | conveyed by you (or copies made from those copies), or (b) primarily 520 | for and in connection with specific products or compilations that 521 | contain the covered work, unless you entered into that arrangement, 522 | or that patent license was granted, prior to 28 March 2007. 523 | 524 | Nothing in this License shall be construed as excluding or limiting 525 | any implied license or other defenses to infringement that may 526 | otherwise be available to you under applicable patent law. 527 | 528 | 12. No Surrender of Others' Freedom. 529 | 530 | If conditions are imposed on you (whether by court order, agreement or 531 | otherwise) that contradict the conditions of this License, they do not 532 | excuse you from the conditions of this License. If you cannot convey a 533 | covered work so as to satisfy simultaneously your obligations under this 534 | License and any other pertinent obligations, then as a consequence you may 535 | not convey it at all. For example, if you agree to terms that obligate you 536 | to collect a royalty for further conveying from those to whom you convey 537 | the Program, the only way you could satisfy both those terms and this 538 | License would be to refrain entirely from conveying the Program. 539 | 540 | 13. Remote Network Interaction; Use with the GNU General Public License. 541 | 542 | Notwithstanding any other provision of this License, if you modify the 543 | Program, your modified version must prominently offer all users 544 | interacting with it remotely through a computer network (if your version 545 | supports such interaction) an opportunity to receive the Corresponding 546 | Source of your version by providing access to the Corresponding Source 547 | from a network server at no charge, through some standard or customary 548 | means of facilitating copying of software. This Corresponding Source 549 | shall include the Corresponding Source for any work covered by version 3 550 | of the GNU General Public License that is incorporated pursuant to the 551 | following paragraph. 552 | 553 | Notwithstanding any other provision of this License, you have 554 | permission to link or combine any covered work with a work licensed 555 | under version 3 of the GNU General Public License into a single 556 | combined work, and to convey the resulting work. The terms of this 557 | License will continue to apply to the part which is the covered work, 558 | but the work with which it is combined will remain governed by version 559 | 3 of the GNU General Public License. 560 | 561 | 14. Revised Versions of this License. 562 | 563 | The Free Software Foundation may publish revised and/or new versions of 564 | the GNU Affero General Public License from time to time. Such new versions 565 | will be similar in spirit to the present version, but may differ in detail to 566 | address new problems or concerns. 567 | 568 | Each version is given a distinguishing version number. If the 569 | Program specifies that a certain numbered version of the GNU Affero General 570 | Public License "or any later version" applies to it, you have the 571 | option of following the terms and conditions either of that numbered 572 | version or of any later version published by the Free Software 573 | Foundation. If the Program does not specify a version number of the 574 | GNU Affero General Public License, you may choose any version ever published 575 | by the Free Software Foundation. 576 | 577 | If the Program specifies that a proxy can decide which future 578 | versions of the GNU Affero General Public License can be used, that proxy's 579 | public statement of acceptance of a version permanently authorizes you 580 | to choose that version for the Program. 581 | 582 | Later license versions may give you additional or different 583 | permissions. However, no additional obligations are imposed on any 584 | author or copyright holder as a result of your choosing to follow a 585 | later version. 586 | 587 | 15. Disclaimer of Warranty. 588 | 589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 597 | 598 | 16. Limitation of Liability. 599 | 600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 608 | SUCH DAMAGES. 609 | 610 | 17. Interpretation of Sections 15 and 16. 611 | 612 | If the disclaimer of warranty and limitation of liability provided 613 | above cannot be given local legal effect according to their terms, 614 | reviewing courts shall apply local law that most closely approximates 615 | an absolute waiver of all civil liability in connection with the 616 | Program, unless a warranty or assumption of liability accompanies a 617 | copy of the Program in return for a fee. 618 | 619 | END OF TERMS AND CONDITIONS 620 | 621 | How to Apply These Terms to Your New Programs 622 | 623 | If you develop a new program, and you want it to be of the greatest 624 | possible use to the public, the best way to achieve this is to make it 625 | free software which everyone can redistribute and change under these terms. 626 | 627 | To do so, attach the following notices to the program. It is safest 628 | to attach them to the start of each source file to most effectively 629 | state the exclusion of warranty; and each file should have at least 630 | the "copyright" line and a pointer to where the full notice is found. 631 | 632 | 633 | Copyright (C) 634 | 635 | This program is free software: you can redistribute it and/or modify 636 | it under the terms of the GNU Affero General Public License as published 637 | by the Free Software Foundation, either version 3 of the License, or 638 | (at your option) any later version. 639 | 640 | This program is distributed in the hope that it will be useful, 641 | but WITHOUT ANY WARRANTY; without even the implied warranty of 642 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 643 | GNU Affero General Public License for more details. 644 | 645 | You should have received a copy of the GNU Affero General Public License 646 | along with this program. If not, see . 647 | 648 | Also add information on how to contact you by electronic and paper mail. 649 | 650 | If your software can interact with users remotely through a computer 651 | network, you should also make sure that it provides a way for users to 652 | get its source. For example, if your program is a web application, its 653 | interface could display a "Source" link that leads users to an archive 654 | of the code. There are many ways you could offer source, and different 655 | solutions will be better for different programs; see section 13 for the 656 | specific requirements. 657 | 658 | You should also get your employer (if you work as a programmer) or school, 659 | if any, to sign a "copyright disclaimer" for the program, if necessary. 660 | For more information on this, and how to apply and follow the GNU AGPL, see 661 | . 662 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # ComfyUI-PMRF 2 | 3 | ### ComfyUI node for [PMRF](https://github.com/ohayonguy/PMRF) 4 | 5 | ![ComfyUI-PMRF](https://github.com/user-attachments/assets/c6692669-7335-424b-8377-b9aa85ac258c) 6 | 7 | Install by git cloning this repo to your ComfyUI custom_nodes directory and then restarting ComfyUI, after which all the PMRF models will be downloaded and necessary packages like NATTEN will be automatically installed for you... 8 | ``` 9 | from your main ComfyUI dir: 10 | cd custom_nodes 11 | git clone https://github.com/2kpr/ComfyUI-PMRF 12 | ``` 13 | 14 |
15 | 16 | PMRF uses [NATTEN](https://shi-labs.com/natten/), which requires matching its builds to your ComfyUI's venv/conda environment's CUDA and Torch versions. 17 | 18 | This isn't a problem on linux as there are ample builds available for CUDA 11.8 to 12.4 and Torch 2.1 to 2.4, but if you are on Windows it is another story. NATTEN doesn't provide any Windows builds, just a means to [build/install NATTEN on Windows yourself](https://github.com/SHI-Labs/NATTEN/blob/main/docs/install.md#build-with-msvc) if you have MSVC and the CUDA toolkit installed, etc. 19 | 20 | Therefore to make this ComfyUI-PMRF node a bit more accessible to Windows users I have spent the time to build 3 variants of NATTEN for Windows which are located here: [https://huggingface.co/2kpr/NATTEN-Windows](https://huggingface.co/2kpr/NATTEN-Windows). These 3 variants are for python 3.10, 3.11, and 3.12, each tied to CUDA 12.4 and Torch 2.4. 21 | 22 | So, if you are on Windows and you meet those specs then NATTEN will be automatically installed for you from one of those 3 variant builds and there is nothing you need to do extra, but if you happen to be on Windows and have a python version below 3.10 or above 3.12 and/or you don't have both CUDA 12.4 and Torch 2.4 installed in your ComfyUI's venv/conda environment, then you will have to [build/install NATTEN on Windows yourself](https://github.com/SHI-Labs/NATTEN/blob/main/docs/install.md#build-with-msvc). 23 | 24 |
25 | 26 | ### PMRF Links: 27 | https://pmrf-ml.github.io/
28 | https://github.com/ohayonguy/PMRF
29 | https://arxiv.org/abs/2410.00418
30 | https://huggingface.co/spaces/ohayonguy/PMRF
31 | -------------------------------------------------------------------------------- /__init__.py: -------------------------------------------------------------------------------- 1 | from .nodes import NODE_CLASS_MAPPINGS, NODE_DISPLAY_NAME_MAPPINGS 2 | 3 | __all__ = ["NODE_CLASS_MAPPINGS", "NODE_DISPLAY_NAME_MAPPINGS"] -------------------------------------------------------------------------------- /arch/__init__.py: -------------------------------------------------------------------------------- 1 | from .hourglass.image_transformer_v2 import ImageTransformerDenoiserModelV2 2 | from .swinir.swinir import SwinIR 3 | -------------------------------------------------------------------------------- /arch/hourglass/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/2kpr/ComfyUI-PMRF/e105c042161785b6fbbae840e70817896c1eebf4/arch/hourglass/__init__.py -------------------------------------------------------------------------------- /arch/hourglass/axial_rope.py: -------------------------------------------------------------------------------- 1 | """k-diffusion transformer diffusion models, version 2. 2 | Codes adopted from https://github.com/crowsonkb/k-diffusion 3 | """ 4 | 5 | import math 6 | 7 | import torch 8 | import torch._dynamo 9 | from torch import nn 10 | 11 | from . import flags 12 | 13 | if flags.get_use_compile(): 14 | torch._dynamo.config.suppress_errors = True 15 | 16 | 17 | def rotate_half(x): 18 | x1, x2 = x[..., 0::2], x[..., 1::2] 19 | x = torch.stack((-x2, x1), dim=-1) 20 | *shape, d, r = x.shape 21 | return x.view(*shape, d * r) 22 | 23 | 24 | def apply_rotary_emb(freqs, t, start_index=0, scale=1.0): 25 | freqs = freqs.to(t) 26 | rot_dim = freqs.shape[-1] 27 | end_index = start_index + rot_dim 28 | assert rot_dim <= t.shape[-1], f"feature dimension {t.shape[-1]} is not of sufficient size to rotate in all the positions {rot_dim}" 29 | t_left, t, t_right = t[..., :start_index], t[..., start_index:end_index], t[..., end_index:] 30 | t = (t * freqs.cos() * scale) + (rotate_half(t) * freqs.sin() * scale) 31 | return torch.cat((t_left, t, t_right), dim=-1) 32 | 33 | 34 | def centers(start, stop, num, dtype=None, device=None): 35 | edges = torch.linspace(start, stop, num + 1, dtype=dtype, device=device) 36 | return (edges[:-1] + edges[1:]) / 2 37 | 38 | 39 | def make_grid(h_pos, w_pos): 40 | grid = torch.stack(torch.meshgrid(h_pos, w_pos, indexing='ij'), dim=-1) 41 | h, w, d = grid.shape 42 | return grid.view(h * w, d) 43 | 44 | 45 | def bounding_box(h, w, pixel_aspect_ratio=1.0): 46 | # Adjusted dimensions 47 | w_adj = w 48 | h_adj = h * pixel_aspect_ratio 49 | 50 | # Adjusted aspect ratio 51 | ar_adj = w_adj / h_adj 52 | 53 | # Determine bounding box based on the adjusted aspect ratio 54 | y_min, y_max, x_min, x_max = -1.0, 1.0, -1.0, 1.0 55 | if ar_adj > 1: 56 | y_min, y_max = -1 / ar_adj, 1 / ar_adj 57 | elif ar_adj < 1: 58 | x_min, x_max = -ar_adj, ar_adj 59 | 60 | return y_min, y_max, x_min, x_max 61 | 62 | 63 | def make_axial_pos(h, w, pixel_aspect_ratio=1.0, align_corners=False, dtype=None, device=None): 64 | y_min, y_max, x_min, x_max = bounding_box(h, w, pixel_aspect_ratio) 65 | if align_corners: 66 | h_pos = torch.linspace(y_min, y_max, h, dtype=dtype, device=device) 67 | w_pos = torch.linspace(x_min, x_max, w, dtype=dtype, device=device) 68 | else: 69 | h_pos = centers(y_min, y_max, h, dtype=dtype, device=device) 70 | w_pos = centers(x_min, x_max, w, dtype=dtype, device=device) 71 | return make_grid(h_pos, w_pos) 72 | 73 | 74 | def freqs_pixel(max_freq=10.0): 75 | def init(shape): 76 | freqs = torch.linspace(1.0, max_freq / 2, shape[-1]) * math.pi 77 | return freqs.log().expand(shape) 78 | return init 79 | 80 | 81 | def freqs_pixel_log(max_freq=10.0): 82 | def init(shape): 83 | log_min = math.log(math.pi) 84 | log_max = math.log(max_freq * math.pi / 2) 85 | return torch.linspace(log_min, log_max, shape[-1]).expand(shape) 86 | return init 87 | 88 | 89 | class AxialRoPE(nn.Module): 90 | def __init__(self, dim, n_heads, start_index=0, freqs_init=freqs_pixel_log(max_freq=10.0)): 91 | super().__init__() 92 | self.n_heads = n_heads 93 | self.start_index = start_index 94 | log_freqs = freqs_init((n_heads, dim // 4)) 95 | self.freqs_h = nn.Parameter(log_freqs.clone()) 96 | self.freqs_w = nn.Parameter(log_freqs.clone()) 97 | 98 | def extra_repr(self): 99 | dim = (self.freqs_h.shape[-1] + self.freqs_w.shape[-1]) * 2 100 | return f"dim={dim}, n_heads={self.n_heads}, start_index={self.start_index}" 101 | 102 | def get_freqs(self, pos): 103 | if pos.shape[-1] != 2: 104 | raise ValueError("input shape must be (..., 2)") 105 | freqs_h = pos[..., None, None, 0] * self.freqs_h.exp() 106 | freqs_w = pos[..., None, None, 1] * self.freqs_w.exp() 107 | freqs = torch.cat((freqs_h, freqs_w), dim=-1).repeat_interleave(2, dim=-1) 108 | return freqs.transpose(-2, -3) 109 | 110 | def forward(self, x, pos): 111 | freqs = self.get_freqs(pos) 112 | return apply_rotary_emb(freqs, x, self.start_index) -------------------------------------------------------------------------------- /arch/hourglass/flags.py: -------------------------------------------------------------------------------- 1 | """k-diffusion transformer diffusion models, version 2. 2 | Codes adopted from https://github.com/crowsonkb/k-diffusion 3 | """ 4 | 5 | from contextlib import contextmanager 6 | from functools import update_wrapper 7 | import os 8 | import threading 9 | 10 | import torch 11 | 12 | 13 | def get_use_compile(): 14 | return os.environ.get("K_DIFFUSION_USE_COMPILE", "1") == "1" 15 | 16 | 17 | def get_use_flash_attention_2(): 18 | return os.environ.get("K_DIFFUSION_USE_FLASH_2", "1") == "1" 19 | 20 | 21 | state = threading.local() 22 | state.checkpointing = False 23 | 24 | 25 | @contextmanager 26 | def checkpointing(enable=True): 27 | try: 28 | old_checkpointing, state.checkpointing = state.checkpointing, enable 29 | yield 30 | finally: 31 | state.checkpointing = old_checkpointing 32 | 33 | 34 | def get_checkpointing(): 35 | return getattr(state, "checkpointing", False) 36 | 37 | 38 | class compile_wrap: 39 | def __init__(self, function, *args, **kwargs): 40 | self.function = function 41 | self.args = args 42 | self.kwargs = kwargs 43 | self._compiled_function = None 44 | update_wrapper(self, function) 45 | 46 | @property 47 | def compiled_function(self): 48 | if self._compiled_function is not None: 49 | return self._compiled_function 50 | if get_use_compile(): 51 | try: 52 | self._compiled_function = torch.compile(self.function, *self.args, **self.kwargs) 53 | except RuntimeError: 54 | self._compiled_function = self.function 55 | else: 56 | self._compiled_function = self.function 57 | return self._compiled_function 58 | 59 | def __call__(self, *args, **kwargs): 60 | return self.compiled_function(*args, **kwargs) -------------------------------------------------------------------------------- /arch/hourglass/flops.py: -------------------------------------------------------------------------------- 1 | """k-diffusion transformer diffusion models, version 2. 2 | Codes adopted from https://github.com/crowsonkb/k-diffusion 3 | """ 4 | 5 | from contextlib import contextmanager 6 | import math 7 | import threading 8 | 9 | 10 | state = threading.local() 11 | state.flop_counter = None 12 | 13 | 14 | @contextmanager 15 | def flop_counter(enable=True): 16 | try: 17 | old_flop_counter = state.flop_counter 18 | state.flop_counter = FlopCounter() if enable else None 19 | yield state.flop_counter 20 | finally: 21 | state.flop_counter = old_flop_counter 22 | 23 | 24 | class FlopCounter: 25 | def __init__(self): 26 | self.ops = [] 27 | 28 | def op(self, op, *args, **kwargs): 29 | self.ops.append((op, args, kwargs)) 30 | 31 | @property 32 | def flops(self): 33 | flops = 0 34 | for op, args, kwargs in self.ops: 35 | flops += op(*args, **kwargs) 36 | return flops 37 | 38 | 39 | def op(op, *args, **kwargs): 40 | if getattr(state, "flop_counter", None): 41 | state.flop_counter.op(op, *args, **kwargs) 42 | 43 | 44 | def op_linear(x, weight): 45 | return math.prod(x) * weight[0] 46 | 47 | 48 | def op_attention(q, k, v): 49 | *b, s_q, d_q = q 50 | *b, s_k, d_k = k 51 | *b, s_v, d_v = v 52 | return math.prod(b) * s_q * s_k * (d_q + d_v) 53 | 54 | 55 | def op_natten(q, k, v, kernel_size): 56 | *q_rest, d_q = q 57 | *_, d_v = v 58 | return math.prod(q_rest) * (d_q + d_v) * kernel_size**2 -------------------------------------------------------------------------------- /arch/hourglass/image_transformer_v2.py: -------------------------------------------------------------------------------- 1 | """k-diffusion transformer diffusion models, version 2. 2 | Codes adopted from https://github.com/crowsonkb/k-diffusion 3 | """ 4 | 5 | from dataclasses import dataclass 6 | from functools import lru_cache, reduce 7 | import math 8 | from typing import Union 9 | 10 | from einops import rearrange 11 | import torch 12 | from torch import nn 13 | import torch._dynamo 14 | from torch.nn import functional as F 15 | 16 | from . import flags, flops 17 | from .axial_rope import make_axial_pos 18 | 19 | 20 | try: 21 | import natten 22 | except ImportError: 23 | natten = None 24 | 25 | try: 26 | import flash_attn 27 | except ImportError: 28 | flash_attn = None 29 | 30 | 31 | if flags.get_use_compile(): 32 | torch._dynamo.config.cache_size_limit = max(64, torch._dynamo.config.cache_size_limit) 33 | torch._dynamo.config.suppress_errors = True 34 | 35 | 36 | # Helpers 37 | 38 | def zero_init(layer): 39 | nn.init.zeros_(layer.weight) 40 | if layer.bias is not None: 41 | nn.init.zeros_(layer.bias) 42 | return layer 43 | 44 | 45 | def checkpoint(function, *args, **kwargs): 46 | if flags.get_checkpointing(): 47 | kwargs.setdefault("use_reentrant", True) 48 | return torch.utils.checkpoint.checkpoint(function, *args, **kwargs) 49 | else: 50 | return function(*args, **kwargs) 51 | 52 | 53 | def downscale_pos(pos): 54 | pos = rearrange(pos, "... (h nh) (w nw) e -> ... h w (nh nw) e", nh=2, nw=2) 55 | return torch.mean(pos, dim=-2) 56 | 57 | 58 | # Param tags 59 | 60 | def tag_param(param, tag): 61 | if not hasattr(param, "_tags"): 62 | param._tags = set([tag]) 63 | else: 64 | param._tags.add(tag) 65 | return param 66 | 67 | 68 | def tag_module(module, tag): 69 | for param in module.parameters(): 70 | tag_param(param, tag) 71 | return module 72 | 73 | 74 | def apply_wd(module): 75 | for name, param in module.named_parameters(): 76 | if name.endswith("weight"): 77 | tag_param(param, "wd") 78 | return module 79 | 80 | 81 | def filter_params(function, module): 82 | for param in module.parameters(): 83 | tags = getattr(param, "_tags", set()) 84 | if function(tags): 85 | yield param 86 | 87 | 88 | # Kernels 89 | 90 | def linear_geglu(x, weight, bias=None): 91 | x = x @ weight.mT 92 | if bias is not None: 93 | x = x + bias 94 | x, gate = x.chunk(2, dim=-1) 95 | return x * F.gelu(gate) 96 | 97 | 98 | def rms_norm(x, scale, eps): 99 | dtype = reduce(torch.promote_types, (x.dtype, scale.dtype, torch.float32)) 100 | mean_sq = torch.mean(x.to(dtype)**2, dim=-1, keepdim=True) 101 | scale = scale.to(dtype) * torch.rsqrt(mean_sq + eps) 102 | return x * scale.to(x.dtype) 103 | 104 | 105 | def scale_for_cosine_sim(q, k, scale, eps): 106 | dtype = reduce(torch.promote_types, (q.dtype, k.dtype, scale.dtype, torch.float32)) 107 | sum_sq_q = torch.sum(q.to(dtype)**2, dim=-1, keepdim=True) 108 | sum_sq_k = torch.sum(k.to(dtype)**2, dim=-1, keepdim=True) 109 | sqrt_scale = torch.sqrt(scale.to(dtype)) 110 | scale_q = sqrt_scale * torch.rsqrt(sum_sq_q + eps) 111 | scale_k = sqrt_scale * torch.rsqrt(sum_sq_k + eps) 112 | return q * scale_q.to(q.dtype), k * scale_k.to(k.dtype) 113 | 114 | 115 | def scale_for_cosine_sim_qkv(qkv, scale, eps): 116 | q, k, v = qkv.unbind(2) 117 | q, k = scale_for_cosine_sim(q, k, scale[:, None], eps) 118 | return torch.stack((q, k, v), dim=2) 119 | 120 | 121 | # Layers 122 | 123 | class Linear(nn.Linear): 124 | def forward(self, x): 125 | flops.op(flops.op_linear, x.shape, self.weight.shape) 126 | return super().forward(x) 127 | 128 | 129 | class LinearGEGLU(nn.Linear): 130 | def __init__(self, in_features, out_features, bias=True): 131 | super().__init__(in_features, out_features * 2, bias=bias) 132 | self.out_features = out_features 133 | 134 | def forward(self, x): 135 | flops.op(flops.op_linear, x.shape, self.weight.shape) 136 | return linear_geglu(x, self.weight, self.bias) 137 | 138 | 139 | class FourierFeatures(nn.Module): 140 | def __init__(self, in_features, out_features, std=1.): 141 | super().__init__() 142 | assert out_features % 2 == 0 143 | self.register_buffer('weight', torch.randn([out_features // 2, in_features]) * std) 144 | 145 | def forward(self, input): 146 | f = 2 * math.pi * input @ self.weight.T 147 | return torch.cat([f.cos(), f.sin()], dim=-1) 148 | 149 | class RMSNorm(nn.Module): 150 | def __init__(self, shape, eps=1e-6): 151 | super().__init__() 152 | self.eps = eps 153 | self.scale = nn.Parameter(torch.ones(shape)) 154 | 155 | def extra_repr(self): 156 | return f"shape={tuple(self.scale.shape)}, eps={self.eps}" 157 | 158 | def forward(self, x): 159 | return rms_norm(x, self.scale, self.eps) 160 | 161 | 162 | class AdaRMSNorm(nn.Module): 163 | def __init__(self, features, cond_features, eps=1e-6): 164 | super().__init__() 165 | self.eps = eps 166 | self.linear = apply_wd(zero_init(Linear(cond_features, features, bias=False))) 167 | tag_module(self.linear, "mapping") 168 | 169 | def extra_repr(self): 170 | return f"eps={self.eps}," 171 | 172 | def forward(self, x, cond): 173 | return rms_norm(x, self.linear(cond)[:, None, None, :] + 1, self.eps) 174 | 175 | 176 | # Rotary position embeddings 177 | 178 | def apply_rotary_emb(x, theta, conj=False): 179 | out_dtype = x.dtype 180 | dtype = reduce(torch.promote_types, (x.dtype, theta.dtype, torch.float32)) 181 | d = theta.shape[-1] 182 | assert d * 2 <= x.shape[-1] 183 | x1, x2, x3 = x[..., :d], x[..., d : d * 2], x[..., d * 2 :] 184 | x1, x2, theta = x1.to(dtype), x2.to(dtype), theta.to(dtype) 185 | cos, sin = torch.cos(theta), torch.sin(theta) 186 | sin = -sin if conj else sin 187 | y1 = x1 * cos - x2 * sin 188 | y2 = x2 * cos + x1 * sin 189 | y1, y2 = y1.to(out_dtype), y2.to(out_dtype) 190 | return torch.cat((y1, y2, x3), dim=-1) 191 | 192 | 193 | def _apply_rotary_emb_inplace(x, theta, conj): 194 | dtype = reduce(torch.promote_types, (x.dtype, theta.dtype, torch.float32)) 195 | d = theta.shape[-1] 196 | assert d * 2 <= x.shape[-1] 197 | x1, x2 = x[..., :d], x[..., d : d * 2] 198 | x1_, x2_, theta = x1.to(dtype), x2.to(dtype), theta.to(dtype) 199 | cos, sin = torch.cos(theta), torch.sin(theta) 200 | sin = -sin if conj else sin 201 | y1 = x1_ * cos - x2_ * sin 202 | y2 = x2_ * cos + x1_ * sin 203 | x1.copy_(y1) 204 | x2.copy_(y2) 205 | 206 | 207 | class ApplyRotaryEmbeddingInplace(torch.autograd.Function): 208 | @staticmethod 209 | def forward(x, theta, conj): 210 | _apply_rotary_emb_inplace(x, theta, conj=conj) 211 | return x 212 | 213 | @staticmethod 214 | def setup_context(ctx, inputs, output): 215 | _, theta, conj = inputs 216 | ctx.save_for_backward(theta) 217 | ctx.conj = conj 218 | 219 | @staticmethod 220 | def backward(ctx, grad_output): 221 | theta, = ctx.saved_tensors 222 | _apply_rotary_emb_inplace(grad_output, theta, conj=not ctx.conj) 223 | return grad_output, None, None 224 | 225 | 226 | def apply_rotary_emb_(x, theta): 227 | return ApplyRotaryEmbeddingInplace.apply(x, theta, False) 228 | 229 | 230 | class AxialRoPE(nn.Module): 231 | def __init__(self, dim, n_heads): 232 | super().__init__() 233 | log_min = math.log(math.pi) 234 | log_max = math.log(10.0 * math.pi) 235 | freqs = torch.linspace(log_min, log_max, n_heads * dim // 4 + 1)[:-1].exp() 236 | self.register_buffer("freqs", freqs.view(dim // 4, n_heads).T.contiguous()) 237 | 238 | def extra_repr(self): 239 | return f"dim={self.freqs.shape[1] * 4}, n_heads={self.freqs.shape[0]}" 240 | 241 | def forward(self, pos): 242 | theta_h = pos[..., None, 0:1] * self.freqs.to(pos.dtype) 243 | theta_w = pos[..., None, 1:2] * self.freqs.to(pos.dtype) 244 | return torch.cat((theta_h, theta_w), dim=-1) 245 | 246 | 247 | # Shifted window attention 248 | 249 | def window(window_size, x): 250 | *b, h, w, c = x.shape 251 | x = torch.reshape( 252 | x, 253 | (*b, h // window_size, window_size, w // window_size, window_size, c), 254 | ) 255 | x = torch.permute( 256 | x, 257 | (*range(len(b)), -5, -3, -4, -2, -1), 258 | ) 259 | return x 260 | 261 | 262 | def unwindow(x): 263 | *b, h, w, wh, ww, c = x.shape 264 | x = torch.permute(x, (*range(len(b)), -5, -3, -4, -2, -1)) 265 | x = torch.reshape(x, (*b, h * wh, w * ww, c)) 266 | return x 267 | 268 | 269 | def shifted_window(window_size, window_shift, x): 270 | x = torch.roll(x, shifts=(window_shift, window_shift), dims=(-2, -3)) 271 | windows = window(window_size, x) 272 | return windows 273 | 274 | 275 | def shifted_unwindow(window_shift, x): 276 | x = unwindow(x) 277 | x = torch.roll(x, shifts=(-window_shift, -window_shift), dims=(-2, -3)) 278 | return x 279 | 280 | 281 | @lru_cache 282 | def make_shifted_window_masks(n_h_w, n_w_w, w_h, w_w, shift, device=None): 283 | ph_coords = torch.arange(n_h_w, device=device) 284 | pw_coords = torch.arange(n_w_w, device=device) 285 | h_coords = torch.arange(w_h, device=device) 286 | w_coords = torch.arange(w_w, device=device) 287 | patch_h, patch_w, q_h, q_w, k_h, k_w = torch.meshgrid( 288 | ph_coords, 289 | pw_coords, 290 | h_coords, 291 | w_coords, 292 | h_coords, 293 | w_coords, 294 | indexing="ij", 295 | ) 296 | is_top_patch = patch_h == 0 297 | is_left_patch = patch_w == 0 298 | q_above_shift = q_h < shift 299 | k_above_shift = k_h < shift 300 | q_left_of_shift = q_w < shift 301 | k_left_of_shift = k_w < shift 302 | m_corner = ( 303 | is_left_patch 304 | & is_top_patch 305 | & (q_left_of_shift == k_left_of_shift) 306 | & (q_above_shift == k_above_shift) 307 | ) 308 | m_left = is_left_patch & ~is_top_patch & (q_left_of_shift == k_left_of_shift) 309 | m_top = ~is_left_patch & is_top_patch & (q_above_shift == k_above_shift) 310 | m_rest = ~is_left_patch & ~is_top_patch 311 | m = m_corner | m_left | m_top | m_rest 312 | return m 313 | 314 | 315 | def apply_window_attention(window_size, window_shift, q, k, v, scale=None): 316 | # prep windows and masks 317 | q_windows = shifted_window(window_size, window_shift, q) 318 | k_windows = shifted_window(window_size, window_shift, k) 319 | v_windows = shifted_window(window_size, window_shift, v) 320 | b, heads, h, w, wh, ww, d_head = q_windows.shape 321 | mask = make_shifted_window_masks(h, w, wh, ww, window_shift, device=q.device) 322 | q_seqs = torch.reshape(q_windows, (b, heads, h, w, wh * ww, d_head)) 323 | k_seqs = torch.reshape(k_windows, (b, heads, h, w, wh * ww, d_head)) 324 | v_seqs = torch.reshape(v_windows, (b, heads, h, w, wh * ww, d_head)) 325 | mask = torch.reshape(mask, (h, w, wh * ww, wh * ww)) 326 | 327 | # do the attention here 328 | flops.op(flops.op_attention, q_seqs.shape, k_seqs.shape, v_seqs.shape) 329 | qkv = F.scaled_dot_product_attention(q_seqs, k_seqs, v_seqs, mask, scale=scale) 330 | 331 | # unwindow 332 | qkv = torch.reshape(qkv, (b, heads, h, w, wh, ww, d_head)) 333 | return shifted_unwindow(window_shift, qkv) 334 | 335 | 336 | # Transformer layers 337 | 338 | 339 | def use_flash_2(x): 340 | if not flags.get_use_flash_attention_2(): 341 | return False 342 | if flash_attn is None: 343 | return False 344 | if x.device.type != "cuda": 345 | return False 346 | if x.dtype not in (torch.float16, torch.bfloat16): 347 | return False 348 | return True 349 | 350 | 351 | class SelfAttentionBlock(nn.Module): 352 | def __init__(self, d_model, d_head, cond_features, dropout=0.0): 353 | super().__init__() 354 | self.d_head = d_head 355 | self.n_heads = d_model // d_head 356 | self.norm = AdaRMSNorm(d_model, cond_features) 357 | self.qkv_proj = apply_wd(Linear(d_model, d_model * 3, bias=False)) 358 | self.scale = nn.Parameter(torch.full([self.n_heads], 10.0)) 359 | self.pos_emb = AxialRoPE(d_head // 2, self.n_heads) 360 | self.dropout = nn.Dropout(dropout) 361 | self.out_proj = apply_wd(zero_init(Linear(d_model, d_model, bias=False))) 362 | 363 | def extra_repr(self): 364 | return f"d_head={self.d_head}," 365 | 366 | def forward(self, x, pos, cond): 367 | skip = x 368 | x = self.norm(x, cond) 369 | qkv = self.qkv_proj(x) 370 | pos = rearrange(pos, "... h w e -> ... (h w) e").to(qkv.dtype) 371 | theta = self.pos_emb(pos) 372 | if use_flash_2(qkv): 373 | qkv = rearrange(qkv, "n h w (t nh e) -> n (h w) t nh e", t=3, e=self.d_head) 374 | qkv = scale_for_cosine_sim_qkv(qkv, self.scale, 1e-6) 375 | theta = torch.stack((theta, theta, torch.zeros_like(theta)), dim=-3) 376 | qkv = apply_rotary_emb_(qkv, theta) 377 | flops_shape = qkv.shape[-5], qkv.shape[-2], qkv.shape[-4], qkv.shape[-1] 378 | flops.op(flops.op_attention, flops_shape, flops_shape, flops_shape) 379 | x = flash_attn.flash_attn_qkvpacked_func(qkv, softmax_scale=1.0) 380 | x = rearrange(x, "n (h w) nh e -> n h w (nh e)", h=skip.shape[-3], w=skip.shape[-2]) 381 | else: 382 | q, k, v = rearrange(qkv, "n h w (t nh e) -> t n nh (h w) e", t=3, e=self.d_head) 383 | q, k = scale_for_cosine_sim(q, k, self.scale[:, None, None], 1e-6) 384 | theta = theta.movedim(-2, -3) 385 | q = apply_rotary_emb_(q, theta) 386 | k = apply_rotary_emb_(k, theta) 387 | flops.op(flops.op_attention, q.shape, k.shape, v.shape) 388 | x = F.scaled_dot_product_attention(q, k, v, scale=1.0) 389 | x = rearrange(x, "n nh (h w) e -> n h w (nh e)", h=skip.shape[-3], w=skip.shape[-2]) 390 | x = self.dropout(x) 391 | x = self.out_proj(x) 392 | return x + skip 393 | 394 | 395 | class NeighborhoodSelfAttentionBlock(nn.Module): 396 | def __init__(self, d_model, d_head, cond_features, kernel_size, dropout=0.0): 397 | super().__init__() 398 | self.d_head = d_head 399 | self.n_heads = d_model // d_head 400 | self.kernel_size = kernel_size 401 | self.norm = AdaRMSNorm(d_model, cond_features) 402 | self.qkv_proj = apply_wd(Linear(d_model, d_model * 3, bias=False)) 403 | self.scale = nn.Parameter(torch.full([self.n_heads], 10.0)) 404 | self.pos_emb = AxialRoPE(d_head // 2, self.n_heads) 405 | self.dropout = nn.Dropout(dropout) 406 | self.out_proj = apply_wd(zero_init(Linear(d_model, d_model, bias=False))) 407 | 408 | def extra_repr(self): 409 | return f"d_head={self.d_head}, kernel_size={self.kernel_size}" 410 | 411 | def forward(self, x, pos, cond): 412 | skip = x 413 | x = self.norm(x, cond) 414 | qkv = self.qkv_proj(x) 415 | if natten is None: 416 | raise ModuleNotFoundError("natten is required for neighborhood attention") 417 | if natten.has_fused_na(): 418 | q, k, v = rearrange(qkv, "n h w (t nh e) -> t n h w nh e", t=3, e=self.d_head) 419 | q, k = scale_for_cosine_sim(q, k, self.scale[:, None], 1e-6) 420 | theta = self.pos_emb(pos) 421 | q = apply_rotary_emb_(q, theta) 422 | k = apply_rotary_emb_(k, theta) 423 | flops.op(flops.op_natten, q.shape, k.shape, v.shape, self.kernel_size) 424 | x = natten.functional.na2d(q, k, v, self.kernel_size, scale=1.0) 425 | x = rearrange(x, "n h w nh e -> n h w (nh e)") 426 | else: 427 | q, k, v = rearrange(qkv, "n h w (t nh e) -> t n nh h w e", t=3, e=self.d_head) 428 | q, k = scale_for_cosine_sim(q, k, self.scale[:, None, None, None], 1e-6) 429 | theta = self.pos_emb(pos).movedim(-2, -4) 430 | q = apply_rotary_emb_(q, theta) 431 | k = apply_rotary_emb_(k, theta) 432 | flops.op(flops.op_natten, q.shape, k.shape, v.shape, self.kernel_size) 433 | qk = natten.functional.na2d_qk(q, k, self.kernel_size) 434 | a = torch.softmax(qk, dim=-1).to(v.dtype) 435 | x = natten.functional.na2d_av(a, v, self.kernel_size) 436 | x = rearrange(x, "n nh h w e -> n h w (nh e)") 437 | x = self.dropout(x) 438 | x = self.out_proj(x) 439 | return x + skip 440 | 441 | 442 | class ShiftedWindowSelfAttentionBlock(nn.Module): 443 | def __init__(self, d_model, d_head, cond_features, window_size, window_shift, dropout=0.0): 444 | super().__init__() 445 | self.d_head = d_head 446 | self.n_heads = d_model // d_head 447 | self.window_size = window_size 448 | self.window_shift = window_shift 449 | self.norm = AdaRMSNorm(d_model, cond_features) 450 | self.qkv_proj = apply_wd(Linear(d_model, d_model * 3, bias=False)) 451 | self.scale = nn.Parameter(torch.full([self.n_heads], 10.0)) 452 | self.pos_emb = AxialRoPE(d_head // 2, self.n_heads) 453 | self.dropout = nn.Dropout(dropout) 454 | self.out_proj = apply_wd(zero_init(Linear(d_model, d_model, bias=False))) 455 | 456 | def extra_repr(self): 457 | return f"d_head={self.d_head}, window_size={self.window_size}, window_shift={self.window_shift}" 458 | 459 | def forward(self, x, pos, cond): 460 | skip = x 461 | x = self.norm(x, cond) 462 | qkv = self.qkv_proj(x) 463 | q, k, v = rearrange(qkv, "n h w (t nh e) -> t n nh h w e", t=3, e=self.d_head) 464 | q, k = scale_for_cosine_sim(q, k, self.scale[:, None, None, None], 1e-6) 465 | theta = self.pos_emb(pos).movedim(-2, -4) 466 | q = apply_rotary_emb_(q, theta) 467 | k = apply_rotary_emb_(k, theta) 468 | x = apply_window_attention(self.window_size, self.window_shift, q, k, v, scale=1.0) 469 | x = rearrange(x, "n nh h w e -> n h w (nh e)") 470 | x = self.dropout(x) 471 | x = self.out_proj(x) 472 | return x + skip 473 | 474 | 475 | class FeedForwardBlock(nn.Module): 476 | def __init__(self, d_model, d_ff, cond_features, dropout=0.0): 477 | super().__init__() 478 | self.norm = AdaRMSNorm(d_model, cond_features) 479 | self.up_proj = apply_wd(LinearGEGLU(d_model, d_ff, bias=False)) 480 | self.dropout = nn.Dropout(dropout) 481 | self.down_proj = apply_wd(zero_init(Linear(d_ff, d_model, bias=False))) 482 | 483 | def forward(self, x, cond): 484 | skip = x 485 | x = self.norm(x, cond) 486 | x = self.up_proj(x) 487 | x = self.dropout(x) 488 | x = self.down_proj(x) 489 | return x + skip 490 | 491 | 492 | class GlobalTransformerLayer(nn.Module): 493 | def __init__(self, d_model, d_ff, d_head, cond_features, dropout=0.0): 494 | super().__init__() 495 | self.self_attn = SelfAttentionBlock(d_model, d_head, cond_features, dropout=dropout) 496 | self.ff = FeedForwardBlock(d_model, d_ff, cond_features, dropout=dropout) 497 | 498 | def forward(self, x, pos, cond): 499 | x = checkpoint(self.self_attn, x, pos, cond) 500 | x = checkpoint(self.ff, x, cond) 501 | return x 502 | 503 | 504 | class NeighborhoodTransformerLayer(nn.Module): 505 | def __init__(self, d_model, d_ff, d_head, cond_features, kernel_size, dropout=0.0): 506 | super().__init__() 507 | self.self_attn = NeighborhoodSelfAttentionBlock(d_model, d_head, cond_features, kernel_size, dropout=dropout) 508 | self.ff = FeedForwardBlock(d_model, d_ff, cond_features, dropout=dropout) 509 | 510 | def forward(self, x, pos, cond): 511 | x = checkpoint(self.self_attn, x, pos, cond) 512 | x = checkpoint(self.ff, x, cond) 513 | return x 514 | 515 | 516 | class ShiftedWindowTransformerLayer(nn.Module): 517 | def __init__(self, d_model, d_ff, d_head, cond_features, window_size, index, dropout=0.0): 518 | super().__init__() 519 | window_shift = window_size // 2 if index % 2 == 1 else 0 520 | self.self_attn = ShiftedWindowSelfAttentionBlock(d_model, d_head, cond_features, window_size, window_shift, dropout=dropout) 521 | self.ff = FeedForwardBlock(d_model, d_ff, cond_features, dropout=dropout) 522 | 523 | def forward(self, x, pos, cond): 524 | x = checkpoint(self.self_attn, x, pos, cond) 525 | x = checkpoint(self.ff, x, cond) 526 | return x 527 | 528 | 529 | class NoAttentionTransformerLayer(nn.Module): 530 | def __init__(self, d_model, d_ff, cond_features, dropout=0.0): 531 | super().__init__() 532 | self.ff = FeedForwardBlock(d_model, d_ff, cond_features, dropout=dropout) 533 | 534 | def forward(self, x, pos, cond): 535 | x = checkpoint(self.ff, x, cond) 536 | return x 537 | 538 | 539 | class Level(nn.ModuleList): 540 | def forward(self, x, *args, **kwargs): 541 | for layer in self: 542 | x = layer(x, *args, **kwargs) 543 | return x 544 | 545 | 546 | # Mapping network 547 | 548 | class MappingFeedForwardBlock(nn.Module): 549 | def __init__(self, d_model, d_ff, dropout=0.0): 550 | super().__init__() 551 | self.norm = RMSNorm(d_model) 552 | self.up_proj = apply_wd(LinearGEGLU(d_model, d_ff, bias=False)) 553 | self.dropout = nn.Dropout(dropout) 554 | self.down_proj = apply_wd(zero_init(Linear(d_ff, d_model, bias=False))) 555 | 556 | def forward(self, x): 557 | skip = x 558 | x = self.norm(x) 559 | x = self.up_proj(x) 560 | x = self.dropout(x) 561 | x = self.down_proj(x) 562 | return x + skip 563 | 564 | 565 | class MappingNetwork(nn.Module): 566 | def __init__(self, n_layers, d_model, d_ff, dropout=0.0): 567 | super().__init__() 568 | self.in_norm = RMSNorm(d_model) 569 | self.blocks = nn.ModuleList([MappingFeedForwardBlock(d_model, d_ff, dropout=dropout) for _ in range(n_layers)]) 570 | self.out_norm = RMSNorm(d_model) 571 | 572 | def forward(self, x): 573 | x = self.in_norm(x) 574 | for block in self.blocks: 575 | x = block(x) 576 | x = self.out_norm(x) 577 | return x 578 | 579 | 580 | # Token merging and splitting 581 | 582 | class TokenMerge(nn.Module): 583 | def __init__(self, in_features, out_features, patch_size=(2, 2)): 584 | super().__init__() 585 | self.h = patch_size[0] 586 | self.w = patch_size[1] 587 | self.proj = apply_wd(Linear(in_features * self.h * self.w, out_features, bias=False)) 588 | 589 | def forward(self, x): 590 | x = rearrange(x, "... (h nh) (w nw) e -> ... h w (nh nw e)", nh=self.h, nw=self.w) 591 | return self.proj(x) 592 | 593 | 594 | class TokenSplitWithoutSkip(nn.Module): 595 | def __init__(self, in_features, out_features, patch_size=(2, 2)): 596 | super().__init__() 597 | self.h = patch_size[0] 598 | self.w = patch_size[1] 599 | self.proj = apply_wd(Linear(in_features, out_features * self.h * self.w, bias=False)) 600 | 601 | def forward(self, x): 602 | x = self.proj(x) 603 | return rearrange(x, "... h w (nh nw e) -> ... (h nh) (w nw) e", nh=self.h, nw=self.w) 604 | 605 | 606 | class TokenSplit(nn.Module): 607 | def __init__(self, in_features, out_features, patch_size=(2, 2)): 608 | super().__init__() 609 | self.h = patch_size[0] 610 | self.w = patch_size[1] 611 | self.proj = apply_wd(Linear(in_features, out_features * self.h * self.w, bias=False)) 612 | self.fac = nn.Parameter(torch.ones(1) * 0.5) 613 | 614 | def forward(self, x, skip): 615 | x = self.proj(x) 616 | x = rearrange(x, "... h w (nh nw e) -> ... (h nh) (w nw) e", nh=self.h, nw=self.w) 617 | return torch.lerp(skip, x, self.fac.to(x.dtype)) 618 | 619 | 620 | # Configuration 621 | 622 | @dataclass 623 | class GlobalAttentionSpec: 624 | d_head: int 625 | 626 | 627 | @dataclass 628 | class NeighborhoodAttentionSpec: 629 | d_head: int 630 | kernel_size: int 631 | 632 | 633 | @dataclass 634 | class ShiftedWindowAttentionSpec: 635 | d_head: int 636 | window_size: int 637 | 638 | 639 | @dataclass 640 | class NoAttentionSpec: 641 | pass 642 | 643 | 644 | @dataclass 645 | class LevelSpec: 646 | depth: int 647 | width: int 648 | d_ff: int 649 | self_attn: Union[GlobalAttentionSpec, NeighborhoodAttentionSpec, ShiftedWindowAttentionSpec, NoAttentionSpec] 650 | dropout: float 651 | 652 | 653 | @dataclass 654 | class MappingSpec: 655 | depth: int 656 | width: int 657 | d_ff: int 658 | dropout: float 659 | 660 | 661 | # Model class 662 | 663 | class ImageTransformerDenoiserModelV2(nn.Module): 664 | def __init__(self, levels, mapping, in_channels, out_channels, patch_size, num_classes=0, mapping_cond_dim=0, degradation_params_dim=None): 665 | super().__init__() 666 | self.num_classes = num_classes 667 | self.patch_in = TokenMerge(in_channels, levels[0].width, patch_size) 668 | self.mapping_width = mapping.width 669 | self.time_emb = FourierFeatures(1, mapping.width) 670 | self.time_in_proj = Linear(mapping.width, mapping.width, bias=False) 671 | self.aug_emb = FourierFeatures(9, mapping.width) 672 | self.aug_in_proj = Linear(mapping.width, mapping.width, bias=False) 673 | self.degradation_proj = Linear(degradation_params_dim, mapping.width, bias=False) if degradation_params_dim else None 674 | self.class_emb = nn.Embedding(num_classes, mapping.width) if num_classes else None 675 | self.mapping_cond_in_proj = Linear(mapping_cond_dim, mapping.width, bias=False) if mapping_cond_dim else None 676 | self.mapping = tag_module(MappingNetwork(mapping.depth, mapping.width, mapping.d_ff, dropout=mapping.dropout), "mapping") 677 | 678 | self.down_levels, self.up_levels = nn.ModuleList(), nn.ModuleList() 679 | for i, spec in enumerate(levels): 680 | if isinstance(spec.self_attn, GlobalAttentionSpec): 681 | layer_factory = lambda _: GlobalTransformerLayer(spec.width, spec.d_ff, spec.self_attn.d_head, mapping.width, dropout=spec.dropout) 682 | elif isinstance(spec.self_attn, NeighborhoodAttentionSpec): 683 | layer_factory = lambda _: NeighborhoodTransformerLayer(spec.width, spec.d_ff, spec.self_attn.d_head, mapping.width, spec.self_attn.kernel_size, dropout=spec.dropout) 684 | elif isinstance(spec.self_attn, ShiftedWindowAttentionSpec): 685 | layer_factory = lambda i: ShiftedWindowTransformerLayer(spec.width, spec.d_ff, spec.self_attn.d_head, mapping.width, spec.self_attn.window_size, i, dropout=spec.dropout) 686 | elif isinstance(spec.self_attn, NoAttentionSpec): 687 | layer_factory = lambda _: NoAttentionTransformerLayer(spec.width, spec.d_ff, mapping.width, dropout=spec.dropout) 688 | else: 689 | raise ValueError(f"unsupported self attention spec {spec.self_attn}") 690 | 691 | if i < len(levels) - 1: 692 | self.down_levels.append(Level([layer_factory(i) for i in range(spec.depth)])) 693 | self.up_levels.append(Level([layer_factory(i + spec.depth) for i in range(spec.depth)])) 694 | else: 695 | self.mid_level = Level([layer_factory(i) for i in range(spec.depth)]) 696 | 697 | self.merges = nn.ModuleList([TokenMerge(spec_1.width, spec_2.width) for spec_1, spec_2 in zip(levels[:-1], levels[1:])]) 698 | self.splits = nn.ModuleList([TokenSplit(spec_2.width, spec_1.width) for spec_1, spec_2 in zip(levels[:-1], levels[1:])]) 699 | 700 | self.out_norm = RMSNorm(levels[0].width) 701 | self.patch_out = TokenSplitWithoutSkip(levels[0].width, out_channels, patch_size) 702 | nn.init.zeros_(self.patch_out.proj.weight) 703 | 704 | def param_groups(self, base_lr=5e-4, mapping_lr_scale=1 / 3): 705 | wd = filter_params(lambda tags: "wd" in tags and "mapping" not in tags, self) 706 | no_wd = filter_params(lambda tags: "wd" not in tags and "mapping" not in tags, self) 707 | mapping_wd = filter_params(lambda tags: "wd" in tags and "mapping" in tags, self) 708 | mapping_no_wd = filter_params(lambda tags: "wd" not in tags and "mapping" in tags, self) 709 | groups = [ 710 | {"params": list(wd), "lr": base_lr}, 711 | {"params": list(no_wd), "lr": base_lr, "weight_decay": 0.0}, 712 | {"params": list(mapping_wd), "lr": base_lr * mapping_lr_scale}, 713 | {"params": list(mapping_no_wd), "lr": base_lr * mapping_lr_scale, "weight_decay": 0.0} 714 | ] 715 | return groups 716 | 717 | def forward(self, x, sigma=None, aug_cond=None, class_cond=None, mapping_cond=None, degradation_params=None): 718 | # Patching 719 | x = x.movedim(-3, -1) 720 | x = self.patch_in(x) 721 | # TODO: pixel aspect ratio for nonsquare patches 722 | pos = make_axial_pos(x.shape[-3], x.shape[-2], device=x.device).view(x.shape[-3], x.shape[-2], 2) 723 | 724 | # Mapping network 725 | if class_cond is None and self.class_emb is not None: 726 | raise ValueError("class_cond must be specified if num_classes > 0") 727 | if mapping_cond is None and self.mapping_cond_in_proj is not None: 728 | raise ValueError("mapping_cond must be specified if mapping_cond_dim > 0") 729 | 730 | # c_noise = torch.log(sigma) / 4 731 | # c_noise = (sigma * 2.0 - 1.0) 732 | # c_noise = sigma * 2 - 1 733 | if sigma is not None: 734 | time_emb = self.time_in_proj(self.time_emb(sigma[..., None])) 735 | else: 736 | time_emb = self.time_in_proj(torch.ones(1, 1, device=x.device, dtype=x.dtype).expand(x.shape[0], self.mapping_width)) 737 | # time_emb = self.time_in_proj(sigma[..., None]) 738 | 739 | aug_cond = x.new_zeros([x.shape[0], 9]) if aug_cond is None else aug_cond 740 | aug_emb = self.aug_in_proj(self.aug_emb(aug_cond)) 741 | class_emb = self.class_emb(class_cond) if self.class_emb is not None else 0 742 | mapping_emb = self.mapping_cond_in_proj(mapping_cond) if self.mapping_cond_in_proj is not None else 0 743 | degradation_emb = self.degradation_proj(degradation_params) if degradation_params is not None else 0 744 | cond = self.mapping(time_emb + aug_emb + class_emb + mapping_emb + degradation_emb) 745 | 746 | # Hourglass transformer 747 | skips, poses = [], [] 748 | for down_level, merge in zip(self.down_levels, self.merges): 749 | x = down_level(x, pos, cond) 750 | skips.append(x) 751 | poses.append(pos) 752 | x = merge(x) 753 | pos = downscale_pos(pos) 754 | 755 | x = self.mid_level(x, pos, cond) 756 | 757 | for up_level, split, skip, pos in reversed(list(zip(self.up_levels, self.splits, skips, poses))): 758 | x = split(x, skip) 759 | x = up_level(x, pos, cond) 760 | 761 | # Unpatching 762 | x = self.out_norm(x) 763 | x = self.patch_out(x) 764 | x = x.movedim(-1, -3) 765 | 766 | return x -------------------------------------------------------------------------------- /arch/swinir/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/2kpr/ComfyUI-PMRF/e105c042161785b6fbbae840e70817896c1eebf4/arch/swinir/__init__.py -------------------------------------------------------------------------------- /arch/swinir/swinir.py: -------------------------------------------------------------------------------- 1 | # ----------------------------------------------------------------------------------- 2 | # SwinIR: Image Restoration Using Swin Transformer, https://arxiv.org/abs/2108.10257 3 | # Originally Written by Ze Liu, Modified by Jingyun Liang. 4 | # ----------------------------------------------------------------------------------- 5 | # Borrowed from DifFace (https://github.com/zsyOAOA/DifFace/blob/master/models/swinir.py) 6 | 7 | import math 8 | from typing import Set 9 | 10 | import torch 11 | import torch.nn as nn 12 | import torch.nn.functional as F 13 | import torch.utils.checkpoint as checkpoint 14 | from timm.models.layers import DropPath, to_2tuple, trunc_normal_ 15 | 16 | 17 | class Mlp(nn.Module): 18 | def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, drop=0.): 19 | super().__init__() 20 | out_features = out_features or in_features 21 | hidden_features = hidden_features or in_features 22 | self.fc1 = nn.Linear(in_features, hidden_features) 23 | self.act = act_layer() 24 | self.fc2 = nn.Linear(hidden_features, out_features) 25 | self.drop = nn.Dropout(drop) 26 | 27 | def forward(self, x): 28 | x = self.fc1(x) 29 | x = self.act(x) 30 | x = self.drop(x) 31 | x = self.fc2(x) 32 | x = self.drop(x) 33 | return x 34 | 35 | 36 | def window_partition(x, window_size): 37 | """ 38 | Args: 39 | x: (B, H, W, C) 40 | window_size (int): window size 41 | 42 | Returns: 43 | windows: (num_windows*B, window_size, window_size, C) 44 | """ 45 | B, H, W, C = x.shape 46 | x = x.view(B, H // window_size, window_size, W // window_size, window_size, C) 47 | windows = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(-1, window_size, window_size, C) 48 | return windows 49 | 50 | 51 | def window_reverse(windows, window_size, H, W): 52 | """ 53 | Args: 54 | windows: (num_windows*B, window_size, window_size, C) 55 | window_size (int): Window size 56 | H (int): Height of image 57 | W (int): Width of image 58 | 59 | Returns: 60 | x: (B, H, W, C) 61 | """ 62 | B = int(windows.shape[0] / (H * W / window_size / window_size)) 63 | x = windows.view(B, H // window_size, W // window_size, window_size, window_size, -1) 64 | x = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(B, H, W, -1) 65 | return x 66 | 67 | 68 | class WindowAttention(nn.Module): 69 | r""" Window based multi-head self attention (W-MSA) module with relative position bias. 70 | It supports both of shifted and non-shifted window. 71 | 72 | Args: 73 | dim (int): Number of input channels. 74 | window_size (tuple[int]): The height and width of the window. 75 | num_heads (int): Number of attention heads. 76 | qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True 77 | qk_scale (float | None, optional): Override default qk scale of head_dim ** -0.5 if set 78 | attn_drop (float, optional): Dropout ratio of attention weight. Default: 0.0 79 | proj_drop (float, optional): Dropout ratio of output. Default: 0.0 80 | """ 81 | 82 | def __init__(self, dim, window_size, num_heads, qkv_bias=True, qk_scale=None, attn_drop=0., proj_drop=0.): 83 | 84 | super().__init__() 85 | self.dim = dim 86 | self.window_size = window_size # Wh, Ww 87 | self.num_heads = num_heads 88 | head_dim = dim // num_heads 89 | self.scale = qk_scale or head_dim ** -0.5 90 | 91 | # define a parameter table of relative position bias 92 | self.relative_position_bias_table = nn.Parameter( 93 | torch.zeros((2 * window_size[0] - 1) * (2 * window_size[1] - 1), num_heads)) # 2*Wh-1 * 2*Ww-1, nH 94 | 95 | # get pair-wise relative position index for each token inside the window 96 | coords_h = torch.arange(self.window_size[0]) 97 | coords_w = torch.arange(self.window_size[1]) 98 | # coords = torch.stack(torch.meshgrid([coords_h, coords_w])) # 2, Wh, Ww 99 | # Fix: Pass indexing="ij" to avoid warning 100 | coords = torch.stack(torch.meshgrid([coords_h, coords_w], indexing="ij")) # 2, Wh, Ww 101 | coords_flatten = torch.flatten(coords, 1) # 2, Wh*Ww 102 | relative_coords = coords_flatten[:, :, None] - coords_flatten[:, None, :] # 2, Wh*Ww, Wh*Ww 103 | relative_coords = relative_coords.permute(1, 2, 0).contiguous() # Wh*Ww, Wh*Ww, 2 104 | relative_coords[:, :, 0] += self.window_size[0] - 1 # shift to start from 0 105 | relative_coords[:, :, 1] += self.window_size[1] - 1 106 | relative_coords[:, :, 0] *= 2 * self.window_size[1] - 1 107 | relative_position_index = relative_coords.sum(-1) # Wh*Ww, Wh*Ww 108 | self.register_buffer("relative_position_index", relative_position_index) 109 | 110 | self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias) 111 | self.attn_drop = nn.Dropout(attn_drop) 112 | self.proj = nn.Linear(dim, dim) 113 | 114 | self.proj_drop = nn.Dropout(proj_drop) 115 | 116 | trunc_normal_(self.relative_position_bias_table, std=.02) 117 | self.softmax = nn.Softmax(dim=-1) 118 | 119 | def forward(self, x, mask=None): 120 | """ 121 | Args: 122 | x: input features with shape of (num_windows*B, N, C) 123 | mask: (0/-inf) mask with shape of (num_windows, Wh*Ww, Wh*Ww) or None 124 | """ 125 | B_, N, C = x.shape 126 | qkv = self.qkv(x).reshape(B_, N, 3, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4) 127 | q, k, v = qkv[0], qkv[1], qkv[2] # make torchscript happy (cannot use tensor as tuple) 128 | 129 | q = q * self.scale 130 | attn = (q @ k.transpose(-2, -1)) 131 | 132 | relative_position_bias = self.relative_position_bias_table[self.relative_position_index.view(-1)].view( 133 | self.window_size[0] * self.window_size[1], self.window_size[0] * self.window_size[1], -1) # Wh*Ww,Wh*Ww,nH 134 | relative_position_bias = relative_position_bias.permute(2, 0, 1).contiguous() # nH, Wh*Ww, Wh*Ww 135 | attn = attn + relative_position_bias.unsqueeze(0) 136 | 137 | if mask is not None: 138 | nW = mask.shape[0] 139 | attn = attn.view(B_ // nW, nW, self.num_heads, N, N) + mask.unsqueeze(1).unsqueeze(0) 140 | attn = attn.view(-1, self.num_heads, N, N) 141 | attn = self.softmax(attn) 142 | else: 143 | attn = self.softmax(attn) 144 | 145 | attn = self.attn_drop(attn) 146 | 147 | x = (attn @ v).transpose(1, 2).reshape(B_, N, C) 148 | x = self.proj(x) 149 | x = self.proj_drop(x) 150 | return x 151 | 152 | def extra_repr(self) -> str: 153 | return f'dim={self.dim}, window_size={self.window_size}, num_heads={self.num_heads}' 154 | 155 | def flops(self, N): 156 | # calculate flops for 1 window with token length of N 157 | flops = 0 158 | # qkv = self.qkv(x) 159 | flops += N * self.dim * 3 * self.dim 160 | # attn = (q @ k.transpose(-2, -1)) 161 | flops += self.num_heads * N * (self.dim // self.num_heads) * N 162 | # x = (attn @ v) 163 | flops += self.num_heads * N * N * (self.dim // self.num_heads) 164 | # x = self.proj(x) 165 | flops += N * self.dim * self.dim 166 | return flops 167 | 168 | 169 | class SwinTransformerBlock(nn.Module): 170 | r""" Swin Transformer Block. 171 | 172 | Args: 173 | dim (int): Number of input channels. 174 | input_resolution (tuple[int]): Input resulotion. 175 | num_heads (int): Number of attention heads. 176 | window_size (int): Window size. 177 | shift_size (int): Shift size for SW-MSA. 178 | mlp_ratio (float): Ratio of mlp hidden dim to embedding dim. 179 | qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True 180 | qk_scale (float | None, optional): Override default qk scale of head_dim ** -0.5 if set. 181 | drop (float, optional): Dropout rate. Default: 0.0 182 | attn_drop (float, optional): Attention dropout rate. Default: 0.0 183 | drop_path (float, optional): Stochastic depth rate. Default: 0.0 184 | act_layer (nn.Module, optional): Activation layer. Default: nn.GELU 185 | norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm 186 | """ 187 | 188 | def __init__(self, dim, input_resolution, num_heads, window_size=7, shift_size=0, 189 | mlp_ratio=4., qkv_bias=True, qk_scale=None, drop=0., attn_drop=0., drop_path=0., 190 | act_layer=nn.GELU, norm_layer=nn.LayerNorm): 191 | super().__init__() 192 | self.dim = dim 193 | self.input_resolution = input_resolution 194 | self.num_heads = num_heads 195 | self.window_size = window_size 196 | self.shift_size = shift_size 197 | self.mlp_ratio = mlp_ratio 198 | if min(self.input_resolution) <= self.window_size: 199 | # if window size is larger than input resolution, we don't partition windows 200 | self.shift_size = 0 201 | self.window_size = min(self.input_resolution) 202 | assert 0 <= self.shift_size < self.window_size, "shift_size must in 0-window_size" 203 | 204 | self.norm1 = norm_layer(dim) 205 | self.attn = WindowAttention( 206 | dim, window_size=to_2tuple(self.window_size), num_heads=num_heads, 207 | qkv_bias=qkv_bias, qk_scale=qk_scale, attn_drop=attn_drop, proj_drop=drop) 208 | 209 | self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity() 210 | self.norm2 = norm_layer(dim) 211 | mlp_hidden_dim = int(dim * mlp_ratio) 212 | self.mlp = Mlp(in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, drop=drop) 213 | 214 | if self.shift_size > 0: 215 | attn_mask = self.calculate_mask(self.input_resolution) 216 | else: 217 | attn_mask = None 218 | 219 | self.register_buffer("attn_mask", attn_mask) 220 | 221 | def calculate_mask(self, x_size): 222 | # calculate attention mask for SW-MSA 223 | H, W = x_size 224 | img_mask = torch.zeros((1, H, W, 1)) # 1 H W 1 225 | h_slices = (slice(0, -self.window_size), 226 | slice(-self.window_size, -self.shift_size), 227 | slice(-self.shift_size, None)) 228 | w_slices = (slice(0, -self.window_size), 229 | slice(-self.window_size, -self.shift_size), 230 | slice(-self.shift_size, None)) 231 | cnt = 0 232 | for h in h_slices: 233 | for w in w_slices: 234 | img_mask[:, h, w, :] = cnt 235 | cnt += 1 236 | 237 | mask_windows = window_partition(img_mask, self.window_size) # nW, window_size, window_size, 1 238 | mask_windows = mask_windows.view(-1, self.window_size * self.window_size) 239 | attn_mask = mask_windows.unsqueeze(1) - mask_windows.unsqueeze(2) 240 | attn_mask = attn_mask.masked_fill(attn_mask != 0, float(-100.0)).masked_fill(attn_mask == 0, float(0.0)) 241 | 242 | return attn_mask 243 | 244 | def forward(self, x, x_size): 245 | H, W = x_size 246 | B, L, C = x.shape 247 | # assert L == H * W, "input feature has wrong size" 248 | 249 | shortcut = x 250 | x = self.norm1(x) 251 | x = x.view(B, H, W, C) 252 | 253 | # cyclic shift 254 | if self.shift_size > 0: 255 | shifted_x = torch.roll(x, shifts=(-self.shift_size, -self.shift_size), dims=(1, 2)) 256 | else: 257 | shifted_x = x 258 | 259 | # partition windows 260 | x_windows = window_partition(shifted_x, self.window_size) # nW*B, window_size, window_size, C 261 | x_windows = x_windows.view(-1, self.window_size * self.window_size, C) # nW*B, window_size*window_size, C 262 | 263 | # W-MSA/SW-MSA (to be compatible for testing on images whose shapes are the multiple of window size 264 | if self.input_resolution == x_size: 265 | attn_windows = self.attn(x_windows, mask=self.attn_mask) # nW*B, window_size*window_size, C 266 | else: 267 | attn_windows = self.attn(x_windows, mask=self.calculate_mask(x_size).to(x.device)) 268 | 269 | # merge windows 270 | attn_windows = attn_windows.view(-1, self.window_size, self.window_size, C) 271 | shifted_x = window_reverse(attn_windows, self.window_size, H, W) # B H' W' C 272 | 273 | # reverse cyclic shift 274 | if self.shift_size > 0: 275 | x = torch.roll(shifted_x, shifts=(self.shift_size, self.shift_size), dims=(1, 2)) 276 | else: 277 | x = shifted_x 278 | x = x.view(B, H * W, C) 279 | 280 | # FFN 281 | x = shortcut + self.drop_path(x) 282 | x = x + self.drop_path(self.mlp(self.norm2(x))) 283 | 284 | return x 285 | 286 | def extra_repr(self) -> str: 287 | return f"dim={self.dim}, input_resolution={self.input_resolution}, num_heads={self.num_heads}, " \ 288 | f"window_size={self.window_size}, shift_size={self.shift_size}, mlp_ratio={self.mlp_ratio}" 289 | 290 | def flops(self): 291 | flops = 0 292 | H, W = self.input_resolution 293 | # norm1 294 | flops += self.dim * H * W 295 | # W-MSA/SW-MSA 296 | nW = H * W / self.window_size / self.window_size 297 | flops += nW * self.attn.flops(self.window_size * self.window_size) 298 | # mlp 299 | flops += 2 * H * W * self.dim * self.dim * self.mlp_ratio 300 | # norm2 301 | flops += self.dim * H * W 302 | return flops 303 | 304 | 305 | class PatchMerging(nn.Module): 306 | r""" Patch Merging Layer. 307 | 308 | Args: 309 | input_resolution (tuple[int]): Resolution of input feature. 310 | dim (int): Number of input channels. 311 | norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm 312 | """ 313 | 314 | def __init__(self, input_resolution, dim, norm_layer=nn.LayerNorm): 315 | super().__init__() 316 | self.input_resolution = input_resolution 317 | self.dim = dim 318 | self.reduction = nn.Linear(4 * dim, 2 * dim, bias=False) 319 | self.norm = norm_layer(4 * dim) 320 | 321 | def forward(self, x): 322 | """ 323 | x: B, H*W, C 324 | """ 325 | H, W = self.input_resolution 326 | B, L, C = x.shape 327 | assert L == H * W, "input feature has wrong size" 328 | assert H % 2 == 0 and W % 2 == 0, f"x size ({H}*{W}) are not even." 329 | 330 | x = x.view(B, H, W, C) 331 | 332 | x0 = x[:, 0::2, 0::2, :] # B H/2 W/2 C 333 | x1 = x[:, 1::2, 0::2, :] # B H/2 W/2 C 334 | x2 = x[:, 0::2, 1::2, :] # B H/2 W/2 C 335 | x3 = x[:, 1::2, 1::2, :] # B H/2 W/2 C 336 | x = torch.cat([x0, x1, x2, x3], -1) # B H/2 W/2 4*C 337 | x = x.view(B, -1, 4 * C) # B H/2*W/2 4*C 338 | 339 | x = self.norm(x) 340 | x = self.reduction(x) 341 | 342 | return x 343 | 344 | def extra_repr(self) -> str: 345 | return f"input_resolution={self.input_resolution}, dim={self.dim}" 346 | 347 | def flops(self): 348 | H, W = self.input_resolution 349 | flops = H * W * self.dim 350 | flops += (H // 2) * (W // 2) * 4 * self.dim * 2 * self.dim 351 | return flops 352 | 353 | 354 | class BasicLayer(nn.Module): 355 | """ A basic Swin Transformer layer for one stage. 356 | 357 | Args: 358 | dim (int): Number of input channels. 359 | input_resolution (tuple[int]): Input resolution. 360 | depth (int): Number of blocks. 361 | num_heads (int): Number of attention heads. 362 | window_size (int): Local window size. 363 | mlp_ratio (float): Ratio of mlp hidden dim to embedding dim. 364 | qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True 365 | qk_scale (float | None, optional): Override default qk scale of head_dim ** -0.5 if set. 366 | drop (float, optional): Dropout rate. Default: 0.0 367 | attn_drop (float, optional): Attention dropout rate. Default: 0.0 368 | drop_path (float | tuple[float], optional): Stochastic depth rate. Default: 0.0 369 | norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm 370 | downsample (nn.Module | None, optional): Downsample layer at the end of the layer. Default: None 371 | use_checkpoint (bool): Whether to use checkpointing to save memory. Default: False. 372 | """ 373 | 374 | def __init__(self, dim, input_resolution, depth, num_heads, window_size, 375 | mlp_ratio=4., qkv_bias=True, qk_scale=None, drop=0., attn_drop=0., 376 | drop_path=0., norm_layer=nn.LayerNorm, downsample=None, use_checkpoint=False): 377 | 378 | super().__init__() 379 | self.dim = dim 380 | self.input_resolution = input_resolution 381 | self.depth = depth 382 | self.use_checkpoint = use_checkpoint 383 | 384 | # build blocks 385 | self.blocks = nn.ModuleList([ 386 | SwinTransformerBlock(dim=dim, input_resolution=input_resolution, 387 | num_heads=num_heads, window_size=window_size, 388 | shift_size=0 if (i % 2 == 0) else window_size // 2, 389 | mlp_ratio=mlp_ratio, 390 | qkv_bias=qkv_bias, qk_scale=qk_scale, 391 | drop=drop, attn_drop=attn_drop, 392 | drop_path=drop_path[i] if isinstance(drop_path, list) else drop_path, 393 | norm_layer=norm_layer) 394 | for i in range(depth)]) 395 | 396 | # patch merging layer 397 | if downsample is not None: 398 | self.downsample = downsample(input_resolution, dim=dim, norm_layer=norm_layer) 399 | else: 400 | self.downsample = None 401 | 402 | def forward(self, x, x_size): 403 | for blk in self.blocks: 404 | if self.use_checkpoint: 405 | x = checkpoint.checkpoint(blk, x, x_size) 406 | else: 407 | x = blk(x, x_size) 408 | if self.downsample is not None: 409 | x = self.downsample(x) 410 | return x 411 | 412 | def extra_repr(self) -> str: 413 | return f"dim={self.dim}, input_resolution={self.input_resolution}, depth={self.depth}" 414 | 415 | def flops(self): 416 | flops = 0 417 | for blk in self.blocks: 418 | flops += blk.flops() 419 | if self.downsample is not None: 420 | flops += self.downsample.flops() 421 | return flops 422 | 423 | 424 | class RSTB(nn.Module): 425 | """Residual Swin Transformer Block (RSTB). 426 | 427 | Args: 428 | dim (int): Number of input channels. 429 | input_resolution (tuple[int]): Input resolution. 430 | depth (int): Number of blocks. 431 | num_heads (int): Number of attention heads. 432 | window_size (int): Local window size. 433 | mlp_ratio (float): Ratio of mlp hidden dim to embedding dim. 434 | qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True 435 | qk_scale (float | None, optional): Override default qk scale of head_dim ** -0.5 if set. 436 | drop (float, optional): Dropout rate. Default: 0.0 437 | attn_drop (float, optional): Attention dropout rate. Default: 0.0 438 | drop_path (float | tuple[float], optional): Stochastic depth rate. Default: 0.0 439 | norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm 440 | downsample (nn.Module | None, optional): Downsample layer at the end of the layer. Default: None 441 | use_checkpoint (bool): Whether to use checkpointing to save memory. Default: False. 442 | img_size: Input image size. 443 | patch_size: Patch size. 444 | resi_connection: The convolutional block before residual connection. 445 | """ 446 | 447 | def __init__(self, dim, input_resolution, depth, num_heads, window_size, 448 | mlp_ratio=4., qkv_bias=True, qk_scale=None, drop=0., attn_drop=0., 449 | drop_path=0., norm_layer=nn.LayerNorm, downsample=None, use_checkpoint=False, 450 | img_size=224, patch_size=4, resi_connection='1conv'): 451 | super(RSTB, self).__init__() 452 | 453 | self.dim = dim 454 | self.input_resolution = input_resolution 455 | 456 | self.residual_group = BasicLayer(dim=dim, 457 | input_resolution=input_resolution, 458 | depth=depth, 459 | num_heads=num_heads, 460 | window_size=window_size, 461 | mlp_ratio=mlp_ratio, 462 | qkv_bias=qkv_bias, qk_scale=qk_scale, 463 | drop=drop, attn_drop=attn_drop, 464 | drop_path=drop_path, 465 | norm_layer=norm_layer, 466 | downsample=downsample, 467 | use_checkpoint=use_checkpoint) 468 | 469 | if resi_connection == '1conv': 470 | self.conv = nn.Conv2d(dim, dim, 3, 1, 1) 471 | elif resi_connection == '3conv': 472 | # to save parameters and memory 473 | self.conv = nn.Sequential(nn.Conv2d(dim, dim // 4, 3, 1, 1), nn.LeakyReLU(negative_slope=0.2, inplace=True), 474 | nn.Conv2d(dim // 4, dim // 4, 1, 1, 0), 475 | nn.LeakyReLU(negative_slope=0.2, inplace=True), 476 | nn.Conv2d(dim // 4, dim, 3, 1, 1)) 477 | 478 | self.patch_embed = PatchEmbed( 479 | img_size=img_size, patch_size=patch_size, in_chans=0, embed_dim=dim, 480 | norm_layer=None) 481 | 482 | self.patch_unembed = PatchUnEmbed( 483 | img_size=img_size, patch_size=patch_size, in_chans=0, embed_dim=dim, 484 | norm_layer=None) 485 | 486 | def forward(self, x, x_size): 487 | return self.patch_embed(self.conv(self.patch_unembed(self.residual_group(x, x_size), x_size))) + x 488 | 489 | def flops(self): 490 | flops = 0 491 | flops += self.residual_group.flops() 492 | H, W = self.input_resolution 493 | flops += H * W * self.dim * self.dim * 9 494 | flops += self.patch_embed.flops() 495 | flops += self.patch_unembed.flops() 496 | 497 | return flops 498 | 499 | 500 | class PatchEmbed(nn.Module): 501 | r""" Image to Patch Embedding 502 | 503 | Args: 504 | img_size (int): Image size. Default: 224. 505 | patch_size (int): Patch token size. Default: 4. 506 | in_chans (int): Number of input image channels. Default: 3. 507 | embed_dim (int): Number of linear projection output channels. Default: 96. 508 | norm_layer (nn.Module, optional): Normalization layer. Default: None 509 | """ 510 | 511 | def __init__(self, img_size=224, patch_size=4, in_chans=3, embed_dim=96, norm_layer=None): 512 | super().__init__() 513 | img_size = to_2tuple(img_size) 514 | patch_size = to_2tuple(patch_size) 515 | patches_resolution = [img_size[0] // patch_size[0], img_size[1] // patch_size[1]] 516 | self.img_size = img_size 517 | self.patch_size = patch_size 518 | self.patches_resolution = patches_resolution 519 | self.num_patches = patches_resolution[0] * patches_resolution[1] 520 | 521 | self.in_chans = in_chans 522 | self.embed_dim = embed_dim 523 | 524 | if norm_layer is not None: 525 | self.norm = norm_layer(embed_dim) 526 | else: 527 | self.norm = None 528 | 529 | def forward(self, x): 530 | x = x.flatten(2).transpose(1, 2) # B Ph*Pw C 531 | if self.norm is not None: 532 | x = self.norm(x) 533 | return x 534 | 535 | def flops(self): 536 | flops = 0 537 | H, W = self.img_size 538 | if self.norm is not None: 539 | flops += H * W * self.embed_dim 540 | return flops 541 | 542 | 543 | class PatchUnEmbed(nn.Module): 544 | r""" Image to Patch Unembedding 545 | 546 | Args: 547 | img_size (int): Image size. Default: 224. 548 | patch_size (int): Patch token size. Default: 4. 549 | in_chans (int): Number of input image channels. Default: 3. 550 | embed_dim (int): Number of linear projection output channels. Default: 96. 551 | norm_layer (nn.Module, optional): Normalization layer. Default: None 552 | """ 553 | 554 | def __init__(self, img_size=224, patch_size=4, in_chans=3, embed_dim=96, norm_layer=None): 555 | super().__init__() 556 | img_size = to_2tuple(img_size) 557 | patch_size = to_2tuple(patch_size) 558 | patches_resolution = [img_size[0] // patch_size[0], img_size[1] // patch_size[1]] 559 | self.img_size = img_size 560 | self.patch_size = patch_size 561 | self.patches_resolution = patches_resolution 562 | self.num_patches = patches_resolution[0] * patches_resolution[1] 563 | 564 | self.in_chans = in_chans 565 | self.embed_dim = embed_dim 566 | 567 | def forward(self, x, x_size): 568 | B, HW, C = x.shape 569 | x = x.transpose(1, 2).view(B, self.embed_dim, x_size[0], x_size[1]) # B Ph*Pw C 570 | return x 571 | 572 | def flops(self): 573 | flops = 0 574 | return flops 575 | 576 | 577 | class Upsample(nn.Sequential): 578 | """Upsample module. 579 | 580 | Args: 581 | scale (int): Scale factor. Supported scales: 2^n and 3. 582 | num_feat (int): Channel number of intermediate features. 583 | """ 584 | 585 | def __init__(self, scale, num_feat): 586 | m = [] 587 | if (scale & (scale - 1)) == 0: # scale = 2^n 588 | for _ in range(int(math.log(scale, 2))): 589 | m.append(nn.Conv2d(num_feat, 4 * num_feat, 3, 1, 1)) 590 | m.append(nn.PixelShuffle(2)) 591 | elif scale == 3: 592 | m.append(nn.Conv2d(num_feat, 9 * num_feat, 3, 1, 1)) 593 | m.append(nn.PixelShuffle(3)) 594 | else: 595 | raise ValueError(f'scale {scale} is not supported. ' 'Supported scales: 2^n and 3.') 596 | super(Upsample, self).__init__(*m) 597 | 598 | 599 | class UpsampleOneStep(nn.Sequential): 600 | """UpsampleOneStep module (the difference with Upsample is that it always only has 1conv + 1pixelshuffle) 601 | Used in lightweight SR to save parameters. 602 | 603 | Args: 604 | scale (int): Scale factor. Supported scales: 2^n and 3. 605 | num_feat (int): Channel number of intermediate features. 606 | 607 | """ 608 | 609 | def __init__(self, scale, num_feat, num_out_ch, input_resolution=None): 610 | self.num_feat = num_feat 611 | self.input_resolution = input_resolution 612 | m = [] 613 | m.append(nn.Conv2d(num_feat, (scale ** 2) * num_out_ch, 3, 1, 1)) 614 | m.append(nn.PixelShuffle(scale)) 615 | super(UpsampleOneStep, self).__init__(*m) 616 | 617 | def flops(self): 618 | H, W = self.input_resolution 619 | flops = H * W * self.num_feat * 3 * 9 620 | return flops 621 | 622 | 623 | class SwinIR(nn.Module): 624 | r""" SwinIR 625 | A PyTorch impl of : `SwinIR: Image Restoration Using Swin Transformer`, based on Swin Transformer. 626 | 627 | Args: 628 | img_size (int | tuple(int)): Input image size. Default 64 629 | patch_size (int | tuple(int)): Patch size. Default: 1 630 | in_chans (int): Number of input image channels. Default: 3 631 | embed_dim (int): Patch embedding dimension. Default: 96 632 | depths (tuple(int)): Depth of each Swin Transformer layer. 633 | num_heads (tuple(int)): Number of attention heads in different layers. 634 | window_size (int): Window size. Default: 7 635 | mlp_ratio (float): Ratio of mlp hidden dim to embedding dim. Default: 4 636 | qkv_bias (bool): If True, add a learnable bias to query, key, value. Default: True 637 | qk_scale (float): Override default qk scale of head_dim ** -0.5 if set. Default: None 638 | drop_rate (float): Dropout rate. Default: 0 639 | attn_drop_rate (float): Attention dropout rate. Default: 0 640 | drop_path_rate (float): Stochastic depth rate. Default: 0.1 641 | norm_layer (nn.Module): Normalization layer. Default: nn.LayerNorm. 642 | ape (bool): If True, add absolute position embedding to the patch embedding. Default: False 643 | patch_norm (bool): If True, add normalization after patch embedding. Default: True 644 | use_checkpoint (bool): Whether to use checkpointing to save memory. Default: False 645 | sf: Upscale factor. 2/3/4/8 for image SR, 1 for denoising and compress artifact reduction 646 | img_range: Image range. 1. or 255. 647 | upsampler: The reconstruction reconstruction module. 'pixelshuffle'/'pixelshuffledirect'/'nearest+conv'/None 648 | resi_connection: The convolutional block before residual connection. '1conv'/'3conv' 649 | """ 650 | 651 | def __init__( 652 | self, 653 | img_size=64, 654 | patch_size=1, 655 | in_chans=3, 656 | num_out_ch=3, 657 | embed_dim=96, 658 | depths=[6, 6, 6, 6], 659 | num_heads=[6, 6, 6, 6], 660 | window_size=7, 661 | mlp_ratio=4., 662 | qkv_bias=True, 663 | qk_scale=None, 664 | drop_rate=0., 665 | attn_drop_rate=0., 666 | drop_path_rate=0.1, 667 | norm_layer=nn.LayerNorm, 668 | ape=False, 669 | patch_norm=True, 670 | use_checkpoint=False, 671 | sf=4, 672 | img_range=1., 673 | upsampler='', 674 | resi_connection='1conv', 675 | unshuffle=False, 676 | unshuffle_scale=None, 677 | hq_key: str = "jpg", 678 | lq_key: str = "hint", 679 | learning_rate: float = None, 680 | weight_decay: float = None 681 | ) -> "SwinIR": 682 | super(SwinIR, self).__init__() 683 | num_in_ch = in_chans * (unshuffle_scale ** 2) if unshuffle else in_chans 684 | num_feat = 64 685 | self.img_range = img_range 686 | if in_chans == 3: 687 | rgb_mean = (0.4488, 0.4371, 0.4040) 688 | self.mean = torch.Tensor(rgb_mean).view(1, 3, 1, 1) 689 | else: 690 | self.mean = torch.zeros(1, 1, 1, 1) 691 | self.upscale = sf 692 | self.upsampler = upsampler 693 | self.window_size = window_size 694 | self.unshuffle_scale = unshuffle_scale 695 | self.unshuffle = unshuffle 696 | 697 | ##################################################################################################### 698 | ################################### 1, shallow feature extraction ################################### 699 | if unshuffle: 700 | assert unshuffle_scale is not None 701 | self.conv_first = nn.Sequential( 702 | nn.PixelUnshuffle(sf), 703 | nn.Conv2d(num_in_ch, embed_dim, 3, 1, 1), 704 | ) 705 | else: 706 | self.conv_first = nn.Conv2d(num_in_ch, embed_dim, 3, 1, 1) 707 | 708 | ##################################################################################################### 709 | ################################### 2, deep feature extraction ###################################### 710 | self.num_layers = len(depths) 711 | self.embed_dim = embed_dim 712 | self.ape = ape 713 | self.patch_norm = patch_norm 714 | self.num_features = embed_dim 715 | self.mlp_ratio = mlp_ratio 716 | 717 | # split image into non-overlapping patches 718 | self.patch_embed = PatchEmbed( 719 | img_size=img_size, patch_size=patch_size, in_chans=embed_dim, embed_dim=embed_dim, 720 | norm_layer=norm_layer if self.patch_norm else None 721 | ) 722 | num_patches = self.patch_embed.num_patches 723 | patches_resolution = self.patch_embed.patches_resolution 724 | self.patches_resolution = patches_resolution 725 | 726 | # merge non-overlapping patches into image 727 | self.patch_unembed = PatchUnEmbed( 728 | img_size=img_size, patch_size=patch_size, in_chans=embed_dim, embed_dim=embed_dim, 729 | norm_layer=norm_layer if self.patch_norm else None 730 | ) 731 | 732 | # absolute position embedding 733 | if self.ape: 734 | self.absolute_pos_embed = nn.Parameter(torch.zeros(1, num_patches, embed_dim)) 735 | trunc_normal_(self.absolute_pos_embed, std=.02) 736 | 737 | self.pos_drop = nn.Dropout(p=drop_rate) 738 | 739 | # stochastic depth 740 | dpr = [x.item() for x in torch.linspace(0, drop_path_rate, sum(depths))] # stochastic depth decay rule 741 | 742 | # build Residual Swin Transformer blocks (RSTB) 743 | self.layers = nn.ModuleList() 744 | for i_layer in range(self.num_layers): 745 | layer = RSTB( 746 | dim=embed_dim, 747 | input_resolution=(patches_resolution[0], patches_resolution[1]), 748 | depth=depths[i_layer], 749 | num_heads=num_heads[i_layer], 750 | window_size=window_size, 751 | mlp_ratio=self.mlp_ratio, 752 | qkv_bias=qkv_bias, qk_scale=qk_scale, 753 | drop=drop_rate, attn_drop=attn_drop_rate, 754 | drop_path=dpr[sum(depths[:i_layer]):sum(depths[:i_layer + 1])], # no impact on SR results 755 | norm_layer=norm_layer, 756 | downsample=None, 757 | use_checkpoint=use_checkpoint, 758 | img_size=img_size, 759 | patch_size=patch_size, 760 | resi_connection=resi_connection 761 | ) 762 | self.layers.append(layer) 763 | self.norm = norm_layer(self.num_features) 764 | 765 | # build the last conv layer in deep feature extraction 766 | if resi_connection == '1conv': 767 | self.conv_after_body = nn.Conv2d(embed_dim, embed_dim, 3, 1, 1) 768 | elif resi_connection == '3conv': 769 | # to save parameters and memory 770 | self.conv_after_body = nn.Sequential( 771 | nn.Conv2d(embed_dim, embed_dim // 4, 3, 1, 1), 772 | nn.LeakyReLU(negative_slope=0.2, inplace=True), 773 | nn.Conv2d(embed_dim // 4, embed_dim // 4, 1, 1, 0), 774 | nn.LeakyReLU(negative_slope=0.2, inplace=True), 775 | nn.Conv2d(embed_dim // 4, embed_dim, 3, 1, 1) 776 | ) 777 | 778 | ##################################################################################################### 779 | ################################ 3, high quality image reconstruction ################################ 780 | if self.upsampler == 'pixelshuffle': 781 | # for classical SR 782 | self.conv_before_upsample = nn.Sequential( 783 | nn.Conv2d(embed_dim, num_feat, 3, 1, 1), 784 | nn.LeakyReLU(inplace=True) 785 | ) 786 | self.upsample = Upsample(sf, num_feat) 787 | self.conv_last = nn.Conv2d(num_feat, num_out_ch, 3, 1, 1) 788 | elif self.upsampler == 'pixelshuffledirect': 789 | # for lightweight SR (to save parameters) 790 | self.upsample = UpsampleOneStep( 791 | sf, embed_dim, num_out_ch, 792 | (patches_resolution[0], patches_resolution[1]) 793 | ) 794 | elif self.upsampler == 'nearest+conv': 795 | # for real-world SR (less artifacts) 796 | self.conv_before_upsample = nn.Sequential( 797 | nn.Conv2d(embed_dim, num_feat, 3, 1, 1), 798 | nn.LeakyReLU(inplace=True) 799 | ) 800 | self.conv_up1 = nn.Conv2d(num_feat, num_feat, 3, 1, 1) 801 | if self.upscale == 4: 802 | self.conv_up2 = nn.Conv2d(num_feat, num_feat, 3, 1, 1) 803 | elif self.upscale == 8: 804 | self.conv_up2 = nn.Conv2d(num_feat, num_feat, 3, 1, 1) 805 | self.conv_up3 = nn.Conv2d(num_feat, num_feat, 3, 1, 1) 806 | self.conv_hr = nn.Conv2d(num_feat, num_feat, 3, 1, 1) 807 | self.conv_last = nn.Conv2d(num_feat, num_out_ch, 3, 1, 1) 808 | self.lrelu = nn.LeakyReLU(negative_slope=0.2, inplace=True) 809 | else: 810 | # for image denoising and JPEG compression artifact reduction 811 | self.conv_last = nn.Conv2d(embed_dim, num_out_ch, 3, 1, 1) 812 | 813 | self.apply(self._init_weights) 814 | 815 | def _init_weights(self, m: nn.Module) -> None: 816 | if isinstance(m, nn.Linear): 817 | trunc_normal_(m.weight, std=.02) 818 | if isinstance(m, nn.Linear) and m.bias is not None: 819 | nn.init.constant_(m.bias, 0) 820 | elif isinstance(m, nn.LayerNorm): 821 | nn.init.constant_(m.bias, 0) 822 | nn.init.constant_(m.weight, 1.0) 823 | 824 | # TODO: What's this ? 825 | @torch.jit.ignore 826 | def no_weight_decay(self) -> Set[str]: 827 | return {'absolute_pos_embed'} 828 | 829 | @torch.jit.ignore 830 | def no_weight_decay_keywords(self) -> Set[str]: 831 | return {'relative_position_bias_table'} 832 | 833 | def check_image_size(self, x: torch.Tensor) -> torch.Tensor: 834 | _, _, h, w = x.size() 835 | mod_pad_h = (self.window_size - h % self.window_size) % self.window_size 836 | mod_pad_w = (self.window_size - w % self.window_size) % self.window_size 837 | x = F.pad(x, (0, mod_pad_w, 0, mod_pad_h), 'reflect') 838 | return x 839 | 840 | def forward_features(self, x: torch.Tensor) -> torch.Tensor: 841 | x_size = (x.shape[2], x.shape[3]) 842 | x = self.patch_embed(x) 843 | if self.ape: 844 | x = x + self.absolute_pos_embed 845 | x = self.pos_drop(x) 846 | 847 | for layer in self.layers: 848 | x = layer(x, x_size) 849 | 850 | x = self.norm(x) # B L C 851 | x = self.patch_unembed(x, x_size) 852 | 853 | return x 854 | 855 | def forward(self, x: torch.Tensor) -> torch.Tensor: 856 | H, W = x.shape[2:] 857 | x = self.check_image_size(x) 858 | 859 | self.mean = self.mean.type_as(x) 860 | x = (x - self.mean) * self.img_range 861 | 862 | if self.upsampler == 'pixelshuffle': 863 | # for classical SR 864 | x = self.conv_first(x) 865 | x = self.conv_after_body(self.forward_features(x)) + x 866 | x = self.conv_before_upsample(x) 867 | x = self.conv_last(self.upsample(x)) 868 | elif self.upsampler == 'pixelshuffledirect': 869 | # for lightweight SR 870 | x = self.conv_first(x) 871 | x = self.conv_after_body(self.forward_features(x)) + x 872 | x = self.upsample(x) 873 | elif self.upsampler == 'nearest+conv': 874 | # for real-world SR 875 | x = self.conv_first(x) 876 | x = self.conv_after_body(self.forward_features(x)) + x 877 | x = self.conv_before_upsample(x) 878 | x = self.lrelu(self.conv_up1(torch.nn.functional.interpolate(x, scale_factor=2, mode='nearest'))) 879 | if self.upscale == 4: 880 | x = self.lrelu(self.conv_up2(torch.nn.functional.interpolate(x, scale_factor=2, mode='nearest'))) 881 | elif self.upscale == 8: 882 | x = self.lrelu(self.conv_up2(torch.nn.functional.interpolate(x, scale_factor=2, mode='nearest'))) 883 | x = self.lrelu(self.conv_up3(torch.nn.functional.interpolate(x, scale_factor=2, mode='nearest'))) 884 | x = self.conv_last(self.lrelu(self.conv_hr(x))) 885 | else: 886 | # for image denoising and JPEG compression artifact reduction 887 | x_first = self.conv_first(x) 888 | res = self.conv_after_body(self.forward_features(x_first)) + x_first 889 | x = x + self.conv_last(res) 890 | 891 | x = x / self.img_range + self.mean 892 | 893 | return x[:, :, :H * self.upscale, :W * self.upscale] 894 | 895 | def flops(self) -> int: 896 | flops = 0 897 | H, W = self.patches_resolution 898 | flops += H * W * 3 * self.embed_dim * 9 899 | flops += self.patch_embed.flops() 900 | for i, layer in enumerate(self.layers): 901 | flops += layer.flops() 902 | flops += H * W * 3 * self.embed_dim * self.embed_dim 903 | flops += self.upsample.flops() 904 | return flops 905 | -------------------------------------------------------------------------------- /lightning_models/mmse_rectified_flow.py: -------------------------------------------------------------------------------- 1 | import os 2 | from contextlib import contextmanager, nullcontext 3 | 4 | import torch 5 | #import wandb 6 | from pytorch_lightning import LightningModule 7 | from torch.nn.functional import mse_loss 8 | from torch.nn.functional import sigmoid 9 | from torch.optim import AdamW 10 | from torch_ema import ExponentialMovingAverage as EMA 11 | from torchmetrics.image.fid import FrechetInceptionDistance 12 | from torchmetrics.image.inception import InceptionScore 13 | from torchvision.transforms.functional import to_pil_image 14 | from torchvision.utils import save_image 15 | from ..utils.create_arch import create_arch 16 | from huggingface_hub import PyTorchModelHubMixin 17 | 18 | 19 | 20 | class MMSERectifiedFlow(LightningModule, 21 | PyTorchModelHubMixin, 22 | pipeline_tag="image-to-image", 23 | license="mit", 24 | ): 25 | def __init__(self, 26 | stage, 27 | arch, 28 | conditional=False, 29 | mmse_model_ckpt_path=None, 30 | mmse_model_arch=None, 31 | lr=5e-4, 32 | weight_decay=1e-3, 33 | betas=(0.9, 0.95), 34 | mmse_noise_std=0.1, 35 | num_flow_steps=50, 36 | ema_decay=0.9999, 37 | eps=0.0, 38 | t_schedule='stratified_uniform', 39 | *args, 40 | **kwargs 41 | ): 42 | super().__init__() 43 | self.save_hyperparameters(logger=False) 44 | 45 | if stage == 'flow': 46 | if conditional: 47 | condition_channels = 3 48 | else: 49 | condition_channels = 0 50 | if mmse_model_arch is None and 'colorization' in kwargs and kwargs['colorization']: 51 | condition_channels //= 3 52 | self.model = create_arch(arch, condition_channels) 53 | self.mmse_model = create_arch(mmse_model_arch, 0) if mmse_model_arch is not None else None 54 | if mmse_model_ckpt_path is not None: 55 | ckpt = torch.load(mmse_model_ckpt_path, map_location="cpu") 56 | if mmse_model_arch is None: 57 | mmse_model_arch = ckpt['hyper_parameters']['arch'] 58 | self.mmse_model = create_arch(mmse_model_arch, 0) 59 | if 'ema' in ckpt: 60 | # ema_decay doesn't affect anything here, because we are doing load_state_dict 61 | mmse_ema = EMA(self.mmse_model.parameters(), decay=ema_decay) 62 | mmse_ema.load_state_dict(ckpt['ema']) 63 | mmse_ema.copy_to() 64 | elif 'params_ema' in ckpt: 65 | self.mmse_model.load_state_dict(ckpt['params_ema']) 66 | else: 67 | state_dict = ckpt['state_dict'] 68 | state_dict = {layer_name.replace('model.', ''): weights for layer_name, weights in 69 | state_dict.items()} 70 | state_dict = {layer_name.replace('module.', ''): weights for layer_name, weights in 71 | state_dict.items()} 72 | self.mmse_model.load_state_dict(state_dict) 73 | for param in self.mmse_model.parameters(): 74 | param.requires_grad = False 75 | self.mmse_model.eval() 76 | else: 77 | assert stage == 'mmse' or stage == 'naive_flow' 78 | assert not conditional 79 | self.model = create_arch(arch, 0) 80 | self.mmse_model = None 81 | if 'flow' in stage: 82 | self.fid = FrechetInceptionDistance(reset_real_features=True, normalize=True) 83 | self.inception_score = InceptionScore(normalize=True) 84 | 85 | self.ema = EMA(self.model.parameters(), decay=ema_decay) if self.ema_wanted else None 86 | self.test_results_path = None 87 | 88 | @property 89 | def ema_wanted(self): 90 | return self.hparams.ema_decay != -1 91 | 92 | def on_save_checkpoint(self, checkpoint: dict) -> None: 93 | if self.ema_wanted: 94 | checkpoint['ema'] = self.ema.state_dict() 95 | return super().on_save_checkpoint(checkpoint) 96 | 97 | def on_load_checkpoint(self, checkpoint: dict) -> None: 98 | if self.ema_wanted: 99 | self.ema.load_state_dict(checkpoint['ema']) 100 | return super().on_load_checkpoint(checkpoint) 101 | 102 | def on_before_zero_grad(self, optimizer) -> None: 103 | if self.ema_wanted: 104 | self.ema.update(self.model.parameters()) 105 | return super().on_before_zero_grad(optimizer) 106 | 107 | def to(self, *args, **kwargs): 108 | if self.ema_wanted: 109 | self.ema.to(*args, **kwargs) 110 | return super().to(*args, **kwargs) 111 | 112 | # This will use the contextmanager of ema, to copy the EMA weights to the flow model during validation, and then restore them for training. 113 | @contextmanager 114 | def maybe_ema(self): 115 | ema = self.ema 116 | ctx = nullcontext if ema is None else ema.average_parameters 117 | yield ctx 118 | 119 | def forward_mmse(self, y): 120 | return self.model(y).clip(0, 1) 121 | 122 | def forward_flow(self, x_t, t, y=None): 123 | if self.hparams.conditional: 124 | if self.mmse_model is not None: 125 | with torch.no_grad(): 126 | self.mmse_model.eval() 127 | condition = self.mmse_model(y).clip(0, 1) 128 | else: 129 | condition = y 130 | x_t = torch.cat((x_t, condition), dim=1) 131 | return self.model(x_t, t) 132 | 133 | def forward(self, x_t, t, y): 134 | if 'flow' in self.hparams.stage: 135 | return self.forward_flow(x_t, t, y) 136 | else: 137 | return self.forward_mmse(y) 138 | 139 | @torch.no_grad() 140 | def create_source_distribution_samples(self, x, y, non_noisy_z0): 141 | with torch.no_grad(): 142 | if self.hparams.conditional: 143 | source_dist_samples = torch.randn_like(x) 144 | else: 145 | if self.hparams.stage == 'flow': 146 | if non_noisy_z0 is None: 147 | self.mmse_model.eval() 148 | non_noisy_z0 = self.mmse_model(y).clip(0, 1) 149 | source_dist_samples = non_noisy_z0 + torch.randn_like(non_noisy_z0) * self.hparams.mmse_noise_std 150 | else: 151 | assert self.hparams.stage == 'naive_flow' 152 | if non_noisy_z0 is not None: 153 | source_dist_samples = non_noisy_z0 154 | else: 155 | source_dist_samples = y 156 | if source_dist_samples.shape[1] != x.shape[1]: 157 | assert source_dist_samples.shape[1] == 1 # Colorization 158 | source_dist_samples = source_dist_samples.expand(-1, x.shape[1], -1, -1) 159 | if self.hparams.mmse_noise_std is not None: 160 | source_dist_samples = source_dist_samples + torch.randn_like(source_dist_samples) * self.hparams.mmse_noise_std 161 | return source_dist_samples 162 | 163 | @staticmethod 164 | def stratified_uniform(bs, group=0, groups=1, dtype=None, device=None): 165 | if groups <= 0: 166 | raise ValueError(f"groups must be positive, got {groups}") 167 | if group < 0 or group >= groups: 168 | raise ValueError(f"group must be in [0, {groups})") 169 | n = bs * groups 170 | offsets = torch.arange(group, n, groups, dtype=dtype, device=device) 171 | u = torch.rand(bs, dtype=dtype, device=device) 172 | return ((offsets + u) / n).view(bs, 1, 1, 1) 173 | 174 | def generate_random_t(self, bs, dtype=None): 175 | if self.hparams.t_schedule == 'logit-normal': 176 | return sigmoid(torch.randn(bs, 1, 1, 1, device=self.device)) * (1.0 - self.hparams.eps) + self.hparams.eps 177 | elif self.hparams.t_schedule == 'uniform': 178 | return torch.rand(bs, 1, 1, 1, device=self.device) * (1.0 - self.hparams.eps) + self.hparams.eps 179 | elif self.hparams.t_schedule == 'stratified_uniform': 180 | return self.stratified_uniform(bs, self.trainer.global_rank, self.trainer.world_size, dtype=dtype, 181 | device=self.device) * (1.0 - self.hparams.eps) + self.hparams.eps 182 | else: 183 | raise NotImplementedError() 184 | 185 | def training_step(self, batch, batch_idx): 186 | x = batch['x'] 187 | y = batch['y'] 188 | non_noisy_z0 = batch['non_noisy_z0'] if 'non_noisy_z0' in batch else None 189 | if 'flow' in self.hparams.stage: 190 | with torch.no_grad(): 191 | t = self.generate_random_t(x.shape[0], dtype=x.dtype) 192 | source_dist_samples = self.create_source_distribution_samples(x, y, non_noisy_z0) 193 | x_t = t * x + (1.0 - t) * source_dist_samples 194 | v_t = self(x_t, t.squeeze(), y) 195 | loss = mse_loss(v_t, x - source_dist_samples) 196 | else: 197 | xhat = self(x_t=None, t=None, y=y) 198 | loss = mse_loss(xhat, x) 199 | self.log("train/loss", loss) 200 | return loss 201 | 202 | @torch.no_grad() 203 | def generate_reconstructions(self, x, y, non_noisy_z0, num_flow_steps, result_device): 204 | with self.maybe_ema(): 205 | if 'flow' in self.hparams.stage: 206 | source_dist_samples = self.create_source_distribution_samples(x, y, non_noisy_z0) 207 | 208 | dt = (1.0 / num_flow_steps) * (1.0 - self.hparams.eps) 209 | x_t_next = source_dist_samples.clone() 210 | x_t_seq = [x_t_next] 211 | t_one = torch.ones(x.shape[0], device=self.device) 212 | for i in range(num_flow_steps): 213 | num_t = (i / num_flow_steps) * (1.0 - self.hparams.eps) + self.hparams.eps 214 | v_t_next = self(x_t=x_t_next, t=t_one * num_t, y=y).to(x_t_next.dtype) 215 | x_t_next = x_t_next.clone() + v_t_next * dt 216 | x_t_seq.append(x_t_next.to(result_device)) 217 | 218 | xhat = x_t_seq[-1].clip(0, 1).to(torch.float32) 219 | source_dist_samples = source_dist_samples.to(result_device) 220 | else: 221 | xhat = self(x_t=None, t=None, y=y).to(torch.float32) 222 | x_t_seq = None 223 | source_dist_samples = None 224 | return xhat.to(result_device), x_t_seq, source_dist_samples 225 | 226 | def validation_step(self, batch, batch_idx): 227 | x = batch['x'] 228 | y = batch['y'] 229 | non_noisy_z0 = batch['non_noisy_z0'] if 'non_noisy_z0' in batch else None 230 | xhat, x_t_seq, source_dist_samples = self.generate_reconstructions(x, y, non_noisy_z0, self.hparams.num_flow_steps, 231 | self.device) 232 | x = x.to(torch.float32) 233 | y = y.to(torch.float32) 234 | self.log_dict({"val_metrics/mse": ((x - xhat) ** 2).mean()}, on_step=False, on_epoch=True, sync_dist=True, 235 | batch_size=x.shape[0]) 236 | 237 | if 'flow' in self.hparams.stage: 238 | self.fid.update(x, real=True) 239 | self.fid.update(xhat, real=False) 240 | self.inception_score.update(xhat) 241 | 242 | if batch_idx == 0: 243 | ''' 244 | wandb_logger = self.logger.experiment 245 | wandb_logger.log({'val_images/x': [wandb.Image(to_pil_image(create_grid(x)))], 246 | 'val_images/y': [wandb.Image(to_pil_image(create_grid(y.clip(0, 1))))], 247 | 'val_images/xhat': [wandb.Image(to_pil_image(create_grid(xhat)))], }) 248 | if 'flow' in self.hparams.stage: 249 | wandb_logger.log({'val_images/x_t_seq': [wandb.Image(to_pil_image(create_grid( 250 | torch.cat([elem[0].unsqueeze(0).to(torch.float32) for elem in x_t_seq], dim=0).clip(0, 1), 251 | num_images=len(x_t_seq))))], 'val_images/source_distribution_samples': [ 252 | wandb.Image(to_pil_image(create_grid(source_dist_samples.clip(0, 1).to(torch.float32))))]}) 253 | if self.mmse_model is not None: 254 | xhat_mmse = self.mmse_model(y).clip(0, 1) 255 | wandb_logger.log({'val_images/xhat_mmse': [ 256 | wandb.Image(to_pil_image(create_grid(xhat_mmse.to(torch.float32))))]}) 257 | ''' 258 | 259 | def on_validation_epoch_end(self): 260 | if 'flow' in self.hparams.stage: 261 | inception_score_mean, inception_score_std = self.inception_score.compute() 262 | self.log_dict( 263 | {'val_metrics/fid': self.fid.compute(), 264 | 'val_metrics/inception_score_mean': inception_score_mean, 265 | 'val_metrics/inception_score_std': inception_score_std}, 266 | on_epoch=True, on_step=False, sync_dist=True, 267 | batch_size=1) 268 | self.fid.reset() 269 | self.inception_score.reset() 270 | 271 | def test_step(self, batch, batch_idx): 272 | assert self.test_results_path is not None, "Please set test_results_path before testing." 273 | assert os.path.isdir(self.test_results_path), 'Please make sure the test_result_path dir exists.' 274 | 275 | def save_image_batch(images, folder, image_file_names): 276 | os.makedirs(folder, exist_ok=True) 277 | for i, img in enumerate(images): 278 | save_image(images[i].clip(0, 1), os.path.join(folder, image_file_names[i])) 279 | 280 | os.makedirs(self.test_results_path, exist_ok=True) 281 | x = batch['x'] 282 | y = batch['y'] 283 | non_noisy_z0 = batch['non_noisy_z0'] if 'non_noisy_z0' in batch else None 284 | y_path = os.path.join(self.test_results_path, 'y') 285 | save_image_batch(y, y_path, batch['img_file_name']) 286 | 287 | if 'flow' in self.hparams.stage: 288 | source_dist_samples_to_save = None 289 | 290 | for num_flow_steps in self.num_test_flow_steps: 291 | xhat, x_t_seq, source_dist_samples = self.generate_reconstructions(x, y, non_noisy_z0, num_flow_steps, 292 | torch.device("cpu")) 293 | xhat_path = os.path.join(self.test_results_path, f"num_flow_steps={num_flow_steps}", 'xhat') 294 | save_image_batch(xhat, xhat_path, batch['img_file_name']) 295 | if source_dist_samples_to_save is None: 296 | source_dist_samples_to_save = source_dist_samples 297 | 298 | source_distribution_samples_path = os.path.join(self.test_results_path, 'source_distribution_samples') 299 | save_image_batch(source_dist_samples_to_save, source_distribution_samples_path, batch['img_file_name']) 300 | if self.mmse_model is not None: 301 | mmse_estimates = self.mmse_model(y).clip(0, 1) 302 | mmse_samples_path = os.path.join(self.test_results_path, 'mmse_samples') 303 | save_image_batch(mmse_estimates, mmse_samples_path, batch['img_file_name']) 304 | 305 | 306 | else: 307 | xhat, _, _ = self.generate_reconstructions(x, y, non_noisy_z0, None, torch.device('cpu')) 308 | xhat_path = os.path.join(self.test_results_path, 'xhat') 309 | save_image_batch(xhat, xhat_path, batch['img_file_name']) 310 | 311 | def configure_optimizers(self): 312 | # Add here a learning rate scheduler if you wish to do so. 313 | optimizer = AdamW(self.model.parameters(), 314 | betas=self.hparams.betas, 315 | eps=1e-8, 316 | lr=self.hparams.lr, 317 | weight_decay=self.hparams.weight_decay) 318 | return optimizer 319 | -------------------------------------------------------------------------------- /nodes.py: -------------------------------------------------------------------------------- 1 | # Code from https://huggingface.co/spaces/ohayonguy/PMRF/blob/main/app.py 2 | # Some of the implementations below are adopted from 3 | # https://huggingface.co/spaces/sczhou/CodeFormer and https://huggingface.co/spaces/wzhouxiff/RestoreFormerPlusPlus 4 | import cv2 5 | from tqdm import tqdm 6 | import torch 7 | from basicsr.archs.rrdbnet_arch import RRDBNet 8 | from basicsr.utils import img2tensor, tensor2img 9 | from facexlib.utils.face_restoration_helper import FaceRestoreHelper 10 | from realesrgan.utils import RealESRGANer 11 | from .lightning_models.mmse_rectified_flow import MMSERectifiedFlow 12 | import torchvision 13 | import numpy as np 14 | from PIL import Image 15 | import os 16 | import folder_paths 17 | 18 | device = torch.device("cuda" if torch.cuda.is_available() else "cpu") 19 | 20 | def set_realesrgan(): 21 | use_half = False 22 | if torch.cuda.is_available(): # set False in CPU/MPS mode 23 | no_half_gpu_list = ["1650", "1660"] # set False for GPUs that don't support f16 24 | if not True in [ 25 | gpu in torch.cuda.get_device_name(0) for gpu in no_half_gpu_list 26 | ]: 27 | use_half = True 28 | 29 | model = RRDBNet( 30 | num_in_ch=3, num_out_ch=3, num_feat=64, num_block=23, num_grow_ch=32, scale=2, 31 | ) 32 | upscale_models_path = os.path.join(folder_paths.models_dir, "upscale_models") 33 | realesrgan_path = os.path.join(upscale_models_path, "RealESRGAN_x2plus.pth") 34 | upsampler = RealESRGANer( 35 | scale=2, 36 | model_path=realesrgan_path, 37 | model=model, 38 | tile=400, 39 | tile_pad=40, 40 | pre_pad=0, 41 | half=use_half, 42 | ) 43 | return upsampler 44 | 45 | pmrf_path = os.path.join(folder_paths.models_dir, "pmrf") 46 | upsampler = set_realesrgan() 47 | pmrf = MMSERectifiedFlow.from_pretrained(pmrf_path).to(device=device) 48 | 49 | def generate_reconstructions(pmrf_model, x, y, non_noisy_z0, num_flow_steps, device): 50 | source_dist_samples = pmrf_model.create_source_distribution_samples( 51 | x, y, non_noisy_z0 52 | ) 53 | dt = (1.0 / num_flow_steps) * (1.0 - pmrf_model.hparams.eps) 54 | x_t_next = source_dist_samples.clone() 55 | t_one = torch.ones(x.shape[0], device=device) 56 | for i in tqdm(range(num_flow_steps)): 57 | num_t = (i / num_flow_steps) * ( 58 | 1.0 - pmrf_model.hparams.eps 59 | ) + pmrf_model.hparams.eps 60 | v_t_next = pmrf_model(x_t=x_t_next, t=t_one * num_t, y=y).to(x_t_next.dtype) 61 | x_t_next = x_t_next.clone() + v_t_next * dt 62 | return x_t_next.clip(0, 1) 63 | 64 | def resize(img, size, interpolation): 65 | # From https://github.com/sczhou/CodeFormer/blob/master/facelib/utils/face_restoration_helper.py 66 | h, w = img.shape[0:2] 67 | scale = float(size) / float(min(h, w)) 68 | h, w = int(round(h * scale)), int(round(w * scale)) 69 | return cv2.resize(img, (w, h), interpolation=interpolation) 70 | 71 | @torch.inference_mode() 72 | def enhance_face(img, face_helper, num_flow_steps, scale=2, interpolation=cv2.INTER_LANCZOS4): 73 | face_helper.clean_all() 74 | face_helper.read_image(img) 75 | face_helper.input_img = resize(face_helper.input_img, 640, interpolation) 76 | face_helper.get_face_landmarks_5(only_center_face=False, eye_dist_threshold=5) 77 | face_helper.align_warp_face() 78 | 79 | # face restoration 80 | for i, cropped_face in tqdm(enumerate(face_helper.cropped_faces)): 81 | cropped_face_t = img2tensor(cropped_face / 255.0, bgr2rgb=True, float32=True) 82 | cropped_face_t = cropped_face_t.unsqueeze(0).to(device) 83 | 84 | output = generate_reconstructions( 85 | pmrf, 86 | torch.zeros_like(cropped_face_t), 87 | cropped_face_t, 88 | None, 89 | num_flow_steps, 90 | device, 91 | ) 92 | restored_face = tensor2img( 93 | output.to(torch.float32).squeeze(0), rgb2bgr=True, min_max=(0, 1) 94 | ) 95 | restored_face = restored_face.astype("uint8") 96 | face_helper.add_restored_face(restored_face) 97 | 98 | # upsample the background 99 | # Now only support RealESRGAN for upsampling background 100 | bg_img = upsampler.enhance(img, outscale=scale)[0] 101 | face_helper.get_inverse_affine(None) 102 | # paste each restored face to the input image 103 | restored_img = face_helper.paste_faces_to_input_image(upsample_img=bg_img) 104 | return face_helper.cropped_faces, face_helper.restored_faces, restored_img 105 | 106 | @torch.inference_mode() 107 | def inference( 108 | imgs, 109 | scale, 110 | num_flow_steps, 111 | seed, 112 | interpolation, 113 | ): 114 | torch.manual_seed(seed) 115 | if interpolation == "lanczos4": 116 | interpolation = cv2.INTER_LANCZOS4 117 | elif interpolation == "nearest": 118 | interpolation = cv2.INTER_NEAREST 119 | elif interpolation == "linear": 120 | interpolation = cv2.INTER_LINEAR 121 | elif interpolation == "cubic": 122 | interpolation = cv2.INTER_CUBIC 123 | elif interpolation == "area": 124 | interpolation = cv2.INTER_AREA 125 | elif interpolation == "linear_exact": 126 | interpolation = cv2.INTER_LINEAR_EXACT 127 | elif interpolation == "nearest_exact": 128 | interpolation = cv2.INTER_NEAREST_EXACT 129 | imgs_output = [] 130 | for img in imgs: 131 | img = img.permute(2, 0, 1) 132 | img = torchvision.transforms.functional.to_pil_image(img.clamp(0, 1)).convert("RGB") 133 | img = np.array(img) 134 | img = img[:, :, ::-1].copy() 135 | h, w = img.shape[0:2] 136 | size = min(h, w) 137 | 138 | face_scale = scale*(size/640) 139 | face_scale = face_scale if face_scale < scale else scale 140 | face_scale = face_scale if face_scale > 1.0 else 1.0 141 | 142 | face_helper = FaceRestoreHelper( 143 | face_scale, 144 | face_size=512, 145 | crop_ratio=(1, 1), 146 | det_model="retinaface_resnet50", 147 | save_ext="png", 148 | use_parse=True, 149 | device=device, 150 | model_rootpath=None, 151 | ) 152 | 153 | cropped_face, restored_faces, restored_img = enhance_face( 154 | img, 155 | face_helper, 156 | num_flow_steps=num_flow_steps, 157 | scale=face_scale, 158 | interpolation=interpolation, 159 | ) 160 | 161 | output = restored_img 162 | output = cv2.cvtColor(output, cv2.COLOR_BGR2RGB) 163 | output = resize(output, size*scale, interpolation) 164 | 165 | torch.cuda.empty_cache() 166 | output = torchvision.transforms.functional.pil_to_tensor(Image.fromarray(output)).to(torch.float32) / 255.0 167 | output = output.permute(1, 2, 0) 168 | imgs_output.append(output[None,]) 169 | return (torch.cat(tuple(imgs_output), dim=0),) 170 | 171 | class PMRF: 172 | @classmethod 173 | def INPUT_TYPES(s): 174 | return { 175 | "required": { 176 | "images": ("IMAGE",), 177 | "scale": ("FLOAT", {"default": 1.0, "min": 1.0, "max": 40.0, "step": 0.1}), 178 | "num_steps": ("INT", {"default": 25, "min": 1, "max": 400, "step": 1}), 179 | "seed": ("INT", {"default": 123, "min": 0, "max": 2**32, "step": 1}), 180 | "interpolation": (["lanczos4", "nearest", "linear", "cubic", "area", "linear_exact", "nearest_exact"],) 181 | }, 182 | } 183 | 184 | RETURN_TYPES = ("IMAGE",) 185 | RETURN_NAMES = ("images", ) 186 | FUNCTION = "pmrf" 187 | CATEGORY = "PMRF" 188 | 189 | def pmrf(self, images, scale, num_steps, seed, interpolation): 190 | return inference(images, scale, num_steps, seed, interpolation) 191 | 192 | NODE_CLASS_MAPPINGS = { 193 | "PMRF": PMRF, 194 | } 195 | NODE_DISPLAY_NAME_MAPPINGS = { 196 | "PMRF": "PMRF", 197 | } 198 | -------------------------------------------------------------------------------- /prestartup_script.py: -------------------------------------------------------------------------------- 1 | import pkg_resources 2 | import subprocess 3 | import sys 4 | import huggingface_hub 5 | import importlib.util 6 | import importlib.metadata 7 | import folder_paths 8 | import os 9 | import pathlib 10 | from packaging.version import Version 11 | import time 12 | 13 | pmrf_path = os.path.join(folder_paths.models_dir, "pmrf") 14 | pmrf_model_path = os.path.join(pmrf_path, "model.safetensors") 15 | pmrf_model_json_path = os.path.join(pmrf_path, "config.json") 16 | if not (os.path.exists(pmrf_model_path) and os.path.exists(pmrf_model_json_path)): 17 | print("Downloading PMRF model from ohayonguy/PMRF_blind_face_image_restoration...") 18 | if not os.path.exists(pmrf_path): 19 | os.makedirs(pmrf_path) 20 | huggingface_hub.snapshot_download( 21 | repo_id="ohayonguy/PMRF_blind_face_image_restoration", 22 | local_dir=pmrf_path, 23 | ) 24 | upscale_models_path = os.path.join(folder_paths.models_dir, "upscale_models") 25 | models = ["RealESRGAN_x2plus.pth", "RealESRGAN_x4plus.pth"] 26 | for model in models: 27 | realesrgan_path = os.path.join(upscale_models_path, model) 28 | if not os.path.exists(realesrgan_path): 29 | print(f"Downloading {model} model from 2kpr/Real-ESRGAN...") 30 | huggingface_hub.snapshot_download( 31 | repo_id="2kpr/Real-ESRGAN", 32 | allow_patterns=model, 33 | local_dir=upscale_models_path, 34 | ) 35 | 36 | packages = [ 37 | {"name": "realesrgan", "version": "0.2.5"}, 38 | {"name": "torchvision", "version": "0.19.0"}, 39 | {"name": "torch_fidelity", "version": "0.3.0"}, 40 | {"name": "torch_ema", "version": "0.3"}, 41 | {"name": "pytorch_lightning", "version": "2.4.0"}, 42 | {"name": "timm", "version": "1.0.7"}, 43 | ] 44 | 45 | for package in packages: 46 | if importlib.util.find_spec(package["name"]): 47 | #print(f'Found package {package["name"]}') 48 | #print(f'Version: {package["version"]}') 49 | #print(f'Version: {importlib.metadata.version(package["name"])}') 50 | if Version(package["version"]) > Version(importlib.metadata.version(package["name"])): 51 | print(f'Updating {package["name"]} for PMRF...') 52 | subprocess.check_call([sys.executable, "-m", "pip", "install", f'{package["name"]}>={package["version"]}', "--upgrade"]) 53 | else: 54 | print(f'Installing {package["name"]} for PMRF...') 55 | subprocess.check_call([sys.executable, "-m", "pip", "install", f'{package["name"]}>={package["version"]}', "--upgrade"]) 56 | 57 | if importlib.util.find_spec("basicsr"): 58 | path = pathlib.Path(importlib.util.find_spec("basicsr").origin).parent.joinpath("data/degradations.py") 59 | if os.path.exists(path): 60 | with open(path, "r", encoding="utf-8") as f: 61 | content = f.read() 62 | if "from torchvision.transforms.functional_tensor import rgb_to_grayscale" in content: 63 | print(f"Patching basicsr with fix from https://github.com/XPixelGroup/BasicSR/pull/650 for PMRF...") 64 | content = content.replace( 65 | "from torchvision.transforms.functional_tensor import rgb_to_grayscale", 66 | "from torchvision.transforms.functional import rgb_to_grayscale", 67 | ) 68 | with open(path, "w", encoding="utf-8") as f: 69 | f.write(content) 70 | 71 | if not importlib.util.find_spec("natten"): 72 | print(f'Installing natten for PMRF...') 73 | cuda_version = "" 74 | torch_version = "" 75 | print("Searching for CUDA and Torch versions for installing atten needed by PMRF...") 76 | for p in pkg_resources.working_set: 77 | if p.project_name.startswith("nvidia-cuda-runtime"): 78 | if p.version.startswith("12.4"): 79 | cuda_version = "cu124" 80 | print("- Found CUDA 12.4") 81 | elif p.version.startswith("12.1"): 82 | cuda_version = "cu121" 83 | print("- Found CUDA 12.1") 84 | elif p.version.startswith("11.8"): 85 | cuda_version = "cu118" 86 | print("- Found CUDA 11.8") 87 | elif p.project_name == "torch": 88 | if p.version.startswith("2.4"): 89 | torch_version = "torch240" 90 | print("- Found Torch 2.4") 91 | elif p.version.startswith("2.3"): 92 | torch_version = "torch230" 93 | print("- Found Torch 2.3") 94 | elif p.version.startswith("2.2"): 95 | torch_version = "torch220" 96 | print("- Found Torch 2.2") 97 | elif p.version.startswith("2.1"): 98 | torch_version = "torch210" 99 | print("- Found Torch 2.1") 100 | if cuda_version == "": 101 | py_path = os.path.join(folder_paths.temp_directory, "torchcudaversion.py") 102 | if not os.path.exists(py_path): 103 | if not os.path.exists(folder_paths.temp_directory): 104 | os.makedirs(folder_paths.temp_directory) 105 | with open(py_path, "w", encoding="utf-8") as f: 106 | f.write("import torch\nprint(torch.version.cuda)") 107 | cuda_version = subprocess.check_output([sys.executable, f"{py_path}"]).decode().strip() 108 | if cuda_version == "12.4": 109 | cuda_version = "cu124" 110 | print("- Found CUDA 12.4") 111 | elif cuda_version == "12.1": 112 | cuda_version = "cu121" 113 | print("- Found CUDA 12.1") 114 | elif cuda_version == "11.8": 115 | cuda_version = "cu118" 116 | print("- Found CUDA 11.8") 117 | if cuda_version == "": 118 | print("************************************") 119 | print("Error: Can't find CUDA runtime version, can't install natten") 120 | print(" PMRF will not work until natten is installed, see https://github.com/SHI-Labs/NATTEN for help in installing natten.") 121 | print("************************************") 122 | time.sleep(4) 123 | elif torch_version == "": 124 | print("************************************") 125 | print("Error: Can't find torch version, can't install natten") 126 | print(" PMRF will not work until natten is installed, see https://github.com/SHI-Labs/NATTEN for help in installing natten.") 127 | print("************************************") 128 | time.sleep(4) 129 | elif cuda_version == "cu124" and torch_version != "torch240": 130 | print("************************************") 131 | print("Error: Can't install natten, which is needed by PMRF since CUDA runtime version is 12.4 but torch is not version 2.4") 132 | print(" PMRF will not work until natten is installed, see https://github.com/SHI-Labs/NATTEN for help in installing natten.") 133 | print("************************************") 134 | time.sleep(4) 135 | elif os.name == "nt" and cuda_version != "cu124": 136 | print("************************************") 137 | print("Error: Can't install natten on windows if CUDA runtime version is not 12.4 unless you build natten yourself, see https://github.com/SHI-Labs/NATTEN/blob/main/docs/install.md#build-with-msvc") 138 | print(" PMRF will not work until natten is installed, see https://github.com/SHI-Labs/NATTEN for help in installing natten.") 139 | print("************************************") 140 | time.sleep(4) 141 | elif os.name == "nt" and torch_version != "torch240": 142 | print("************************************") 143 | print("Error: Can't install natten on windows if torch version is not 2.4 unless you build natten yourself, see https://github.com/SHI-Labs/NATTEN/blob/main/docs/install.md#build-with-msvc") 144 | print(" PMRF will not work until natten is installed, see https://github.com/SHI-Labs/NATTEN for help in installing natten.") 145 | print("************************************") 146 | time.sleep(4) 147 | elif os.name == "nt" and (sys.version_info[1] < 10 or sys.version_info[1] > 12): 148 | print("************************************") 149 | print("Error: Can't install natten on windows if python version isn't 3.10, 3.11, or 3.12, unless you build natten yourself, see https://github.com/SHI-Labs/NATTEN/blob/main/docs/install.md#build-with-msvc") 150 | print(" PMRF will not work until natten is installed, see https://github.com/SHI-Labs/NATTEN for help in installing natten.") 151 | print("************************************") 152 | time.sleep(4) 153 | elif os.name == "nt": 154 | if sys.version_info[1] == 10: 155 | whl = "natten-0.17.2.dev0-py310-none-win_amd64.whl" 156 | elif sys.version_info[1] == 11: 157 | whl = "natten-0.17.2.dev0-py311-none-win_amd64.whl" 158 | elif sys.version_info[1] == 12: 159 | whl = "natten-0.17.2.dev0-py312-none-win_amd64.whl" 160 | whl_path = os.path.join(folder_paths.temp_directory, whl) 161 | if not os.path.exists(whl_path): 162 | if not os.path.exists(folder_paths.temp_directory): 163 | os.makedirs(folder_paths.temp_directory) 164 | print(f"Downloading {whl} from 2kpr/NATTEN-Windows...") 165 | huggingface_hub.snapshot_download( 166 | repo_id="2kpr/NATTEN-Windows", 167 | allow_patterns=whl, 168 | local_dir=folder_paths.temp_directory, 169 | ) 170 | subprocess.check_call([sys.executable, "-m", "pip", "install", f"{whl_path}"]) 171 | else: 172 | subprocess.check_call([sys.executable, "-m", "pip", "install", f"natten==0.17.1+{torch_version}{cuda_version}", "-f", "https://shi-labs.com/natten/wheels/"]) -------------------------------------------------------------------------------- /utils/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/2kpr/ComfyUI-PMRF/e105c042161785b6fbbae840e70817896c1eebf4/utils/__init__.py -------------------------------------------------------------------------------- /utils/create_arch.py: -------------------------------------------------------------------------------- 1 | from ..arch.hourglass import image_transformer_v2 as itv2 2 | from ..arch.hourglass.image_transformer_v2 import ImageTransformerDenoiserModelV2 3 | from ..arch.swinir.swinir import SwinIR 4 | 5 | 6 | def create_arch(arch, condition_channels=0): 7 | # arch should be, e.g., swinir_XL, or hdit_XL 8 | arch_name, arch_size = arch.split('_') 9 | arch_config = arch_configs[arch_name][arch_size].copy() 10 | arch_config['in_channels'] += condition_channels 11 | return arch_name_to_object[arch_name](**arch_config) 12 | 13 | 14 | arch_configs = { 15 | 'hdit': { 16 | "ImageNet256Sp4": { 17 | 'in_channels': 3, 18 | 'out_channels': 3, 19 | 'widths': [256, 512, 1024], 20 | 'depths': [2, 2, 8], 21 | 'patch_size': [4, 4], 22 | 'self_attns': [ 23 | {"type": "neighborhood", "d_head": 64, "kernel_size": 7}, 24 | {"type": "neighborhood", "d_head": 64, "kernel_size": 7}, 25 | {"type": "global", "d_head": 64} 26 | ], 27 | 'mapping_depth': 2, 28 | 'mapping_width': 768, 29 | 'dropout_rate': [0, 0, 0], 30 | 'mapping_dropout_rate': 0.0 31 | }, 32 | "XL2": { 33 | 'in_channels': 3, 34 | 'out_channels': 3, 35 | 'widths': [384, 768], 36 | 'depths': [2, 11], 37 | 'patch_size': [4, 4], 38 | 'self_attns': [ 39 | {"type": "neighborhood", "d_head": 64, "kernel_size": 7}, 40 | {"type": "global", "d_head": 64} 41 | ], 42 | 'mapping_depth': 2, 43 | 'mapping_width': 768, 44 | 'dropout_rate': [0, 0], 45 | 'mapping_dropout_rate': 0.0 46 | } 47 | 48 | }, 49 | 'swinir': { 50 | "M": { 51 | 'in_channels': 3, 52 | 'out_channels': 3, 53 | 'embed_dim': 120, 54 | 'depths': [6, 6, 6, 6, 6], 55 | 'num_heads': [6, 6, 6, 6, 6], 56 | 'resi_connection': '1conv', 57 | 'sf': 8 58 | 59 | }, 60 | "L": { 61 | 'in_channels': 3, 62 | 'out_channels': 3, 63 | 'embed_dim': 180, 64 | 'depths': [6, 6, 6, 6, 6, 6, 6, 6], 65 | 'num_heads': [6, 6, 6, 6, 6, 6, 6, 6], 66 | 'resi_connection': '1conv', 67 | 'sf': 8 68 | }, 69 | }, 70 | } 71 | 72 | 73 | def create_swinir_model(in_channels, out_channels, embed_dim, depths, num_heads, resi_connection, 74 | sf): 75 | return SwinIR( 76 | img_size=64, 77 | patch_size=1, 78 | in_chans=in_channels, 79 | num_out_ch=out_channels, 80 | embed_dim=embed_dim, 81 | depths=depths, 82 | num_heads=num_heads, 83 | window_size=8, 84 | mlp_ratio=2, 85 | sf=sf, 86 | img_range=1.0, 87 | upsampler="nearest+conv", 88 | resi_connection=resi_connection, 89 | unshuffle=True, 90 | unshuffle_scale=8 91 | ) 92 | 93 | 94 | def create_hdit_model(widths, 95 | depths, 96 | self_attns, 97 | dropout_rate, 98 | mapping_depth, 99 | mapping_width, 100 | mapping_dropout_rate, 101 | in_channels, 102 | out_channels, 103 | patch_size 104 | ): 105 | assert len(widths) == len(depths) 106 | assert len(widths) == len(self_attns) 107 | assert len(widths) == len(dropout_rate) 108 | mapping_d_ff = mapping_width * 3 109 | d_ffs = [] 110 | for width in widths: 111 | d_ffs.append(width * 3) 112 | 113 | levels = [] 114 | for depth, width, d_ff, self_attn, dropout in zip(depths, widths, d_ffs, self_attns, dropout_rate): 115 | if self_attn['type'] == 'global': 116 | self_attn = itv2.GlobalAttentionSpec(self_attn.get('d_head', 64)) 117 | elif self_attn['type'] == 'neighborhood': 118 | self_attn = itv2.NeighborhoodAttentionSpec(self_attn.get('d_head', 64), self_attn.get('kernel_size', 7)) 119 | elif self_attn['type'] == 'shifted-window': 120 | self_attn = itv2.ShiftedWindowAttentionSpec(self_attn.get('d_head', 64), self_attn['window_size']) 121 | elif self_attn['type'] == 'none': 122 | self_attn = itv2.NoAttentionSpec() 123 | else: 124 | raise ValueError(f'unsupported self attention type {self_attn["type"]}') 125 | levels.append(itv2.LevelSpec(depth, width, d_ff, self_attn, dropout)) 126 | mapping = itv2.MappingSpec(mapping_depth, mapping_width, mapping_d_ff, mapping_dropout_rate) 127 | model = ImageTransformerDenoiserModelV2( 128 | levels=levels, 129 | mapping=mapping, 130 | in_channels=in_channels, 131 | out_channels=out_channels, 132 | patch_size=patch_size, 133 | num_classes=0, 134 | mapping_cond_dim=0, 135 | ) 136 | 137 | return model 138 | 139 | 140 | arch_name_to_object = { 141 | 'hdit': create_hdit_model, 142 | 'swinir': create_swinir_model, 143 | } 144 | --------------------------------------------------------------------------------