├── .gitignore ├── LICENSE ├── README.md ├── benchmarking ├── __pycache__ │ ├── calc_inception.cpython-37.pyc │ ├── calc_inception.cpython-38.pyc │ ├── inception.cpython-37.pyc │ └── inception.cpython-38.pyc ├── benchmark.py ├── calc_inception.py ├── fid.py └── inception.py ├── diffaug.py ├── docker ├── Dockerfile.cpu ├── Dockerfile.gpu ├── build-and-push.sh └── infer.sh ├── eval.py ├── lpips ├── __init__.py ├── __pycache__ │ ├── __init__.cpython-37.pyc │ ├── __init__.cpython-38.pyc │ ├── base_model.cpython-37.pyc │ ├── base_model.cpython-38.pyc │ ├── dist_model.cpython-37.pyc │ ├── dist_model.cpython-38.pyc │ ├── networks_basic.cpython-37.pyc │ ├── networks_basic.cpython-38.pyc │ ├── pretrained_networks.cpython-37.pyc │ └── pretrained_networks.cpython-38.pyc ├── base_model.py ├── dist_model.py ├── networks_basic.py ├── pretrained_networks.py └── weights │ ├── v0.0 │ ├── alex.pth │ ├── squeeze.pth │ └── vgg.pth │ └── v0.1 │ ├── alex.pth │ ├── squeeze.pth │ └── vgg.pth ├── models.py ├── operation.py ├── requirements.txt ├── scripts ├── find_nearest_neighbor.py ├── generate_video.py ├── style_mix.py ├── train_backtracking_all.py └── train_backtracking_one.py └── train.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 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow 98 | __pypackages__/ 99 | 100 | # Celery stuff 101 | celerybeat-schedule 102 | celerybeat.pid 103 | 104 | # SageMath parsed files 105 | *.sage.py 106 | 107 | # Environments 108 | .env 109 | .venv 110 | env/ 111 | venv/ 112 | ENV/ 113 | env.bak/ 114 | venv.bak/ 115 | 116 | # Spyder project settings 117 | .spyderproject 118 | .spyproject 119 | 120 | # Rope project settings 121 | .ropeproject 122 | 123 | # mkdocs documentation 124 | /site 125 | 126 | # mypy 127 | .mypy_cache/ 128 | .dmypy.json 129 | dmypy.json 130 | 131 | # Pyre type checker 132 | .pyre/ 133 | 134 | # pytype static type analyzer 135 | .pytype/ 136 | 137 | # Cython debug symbols 138 | cython_debug/ 139 | storage/* 140 | train_results/* -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # A Fast and Stable GAN for Small and High Resolution Imagesets - pytorch 2 | The official pytorch implementation of the paper "Towards Faster and Stabilized GAN Training for High-fidelity Few-shot Image Synthesis", the paper can be found [here](https://arxiv.org/abs/2101.04775). 3 | 4 | ## 0. Data 5 | The datasets used in the paper can be found at [link](https://drive.google.com/file/d/1aAJCZbXNHyraJ6Mi13dSbe7pTyfPXha0/view?usp=sharing). 6 | 7 | After testing on over 20 datasets with each has less than 100 images, this GAN converges on 80% of them. 8 | I still cannot summarize an obvious pattern of the "good properties" for a dataset which this GAN can converge on, please feel free to try with your own datasets. 9 | 10 | 11 | ## 1. Description 12 | The code is structured as follows: 13 | * models.py: all the models' structure definition. 14 | 15 | * operation.py: the helper functions and data loading methods during training. 16 | 17 | * train.py: the main entry of the code, execute this file to train the model, the intermediate results and checkpoints will be automatically saved periodically into a folder "train_results". 18 | 19 | * eval.py: generates images from a trained generator into a folder, which can be used to calculate FID score. 20 | 21 | * benchmarking: the functions we used to compute FID are located here, it automatically downloads the pytorch official inception model. 22 | 23 | * lpips: this folder contains the code to compute the LPIPS score, the inception model is also automatically download from official location. 24 | 25 | * scripts: this folder contains many scripts you can use to play around the trained model. Including: 26 | 1. style_mix.py: style-mixing as introduced in the paper; 27 | 2. generate_video.py: generating a continuous video from the interpolation of generated images; 28 | 3. find_nearest_neighbor.py: given a generated image, find the closest real-image from the training set; 29 | 4. train_backtracking_one.py: given a real-image, find the latent vector of this image from a trained Generator. 30 | 31 | ## 2. How to run 32 | Place all your training images in a folder, and simply call 33 | ``` 34 | python train.py --path /path/to/RGB-image-folder --output_path /path/to/the/output 35 | ``` 36 | You can also see all the training options by: 37 | ``` 38 | python train.py --help 39 | ``` 40 | The code will automatically create a new folder (you have to specify the name of the folder using --name option) to store the trained checkpoints and intermediate synthesis results. 41 | 42 | Once finish training, you can generate 100 images (or as many as you want) by: 43 | ``` 44 | cd ./train_results/name_of_your_training/ 45 | python eval.py --n_sample 100 46 | ``` 47 | 48 | ## 3. Pre-trained models 49 | The pre-trained models and the respective code of each model are shared [here](https://drive.google.com/drive/folders/1nCpr84nKkrs9-aVMET5h8gqFbUYJRPLR?usp=sharing). 50 | 51 | You can also use FastGAN to generate images with a pre-packaged Docker image, hosted on the Replicate registry: https://beta.replicate.ai/odegeasslbc/FastGAN 52 | 53 | ## 4. Important notes 54 | 1. The provided code is for research use only. 55 | 2. Different model and training configurations are needed on different datasets. You may have to tune the hyper-parameters to get the best results on your own datasets. 56 | 57 | 2.1. The hyper-parameters includes: the augmentation options, the model depth (how many layers), the model width (channel numbers of each layer). To change these, you have to change the code in models.py and train.py directly. 58 | 59 | 2.2. Please check the code in the shared pre-trained models on how each of them are configured differently on different datasets. Especially, compare the models.py for ffhq and art datasets, you will get an idea on what chages could be made on different datasets. 60 | 61 | ## 5. Other notes 62 | 1. The provided scripts are not well organized, contributions are welcomed to clean them. 63 | 2. An third-party implementation of this paper can be found [here](https://github.com/lucidrains/lightweight-gan), where some other techniques are included. I suggest you try both implementation if you find one of them does not work. 64 | -------------------------------------------------------------------------------- /benchmarking/__pycache__/calc_inception.cpython-37.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/odegeasslbc/FastGAN-pytorch/1a848e5bce265c50e0ee38c932c256d5aa6f9880/benchmarking/__pycache__/calc_inception.cpython-37.pyc -------------------------------------------------------------------------------- /benchmarking/__pycache__/calc_inception.cpython-38.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/odegeasslbc/FastGAN-pytorch/1a848e5bce265c50e0ee38c932c256d5aa6f9880/benchmarking/__pycache__/calc_inception.cpython-38.pyc -------------------------------------------------------------------------------- /benchmarking/__pycache__/inception.cpython-37.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/odegeasslbc/FastGAN-pytorch/1a848e5bce265c50e0ee38c932c256d5aa6f9880/benchmarking/__pycache__/inception.cpython-37.pyc -------------------------------------------------------------------------------- /benchmarking/__pycache__/inception.cpython-38.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/odegeasslbc/FastGAN-pytorch/1a848e5bce265c50e0ee38c932c256d5aa6f9880/benchmarking/__pycache__/inception.cpython-38.pyc -------------------------------------------------------------------------------- /benchmarking/benchmark.py: -------------------------------------------------------------------------------- 1 | import torch 2 | import torch.nn as nn 3 | import torch.nn.functional as F 4 | from torchvision import models 5 | from torchvision.models import inception_v3, Inception3 6 | from torchvision.utils import save_image 7 | 8 | try: 9 | from torchvision.models.utils import load_state_dict_from_url 10 | except ImportError: 11 | from torch.utils.model_zoo import load_url as load_state_dict_from_url 12 | 13 | import numpy as np 14 | from scipy import linalg 15 | from tqdm import tqdm 16 | import pickle 17 | import os 18 | 19 | # Inception weights ported to Pytorch from 20 | # http://download.tensorflow.org/models/image/imagenet/inception-2015-12-05.tgz 21 | FID_WEIGHTS_URL = 'https://github.com/mseitzer/pytorch-fid/releases/download/fid_weights/pt_inception-2015-12-05-6726825d.pth' 22 | 23 | 24 | class InceptionV3(nn.Module): 25 | """Pretrained InceptionV3 network returning feature maps""" 26 | 27 | # Index of default block of inception to return, 28 | # corresponds to output of final average pooling 29 | DEFAULT_BLOCK_INDEX = 3 30 | 31 | # Maps feature dimensionality to their output blocks indices 32 | BLOCK_INDEX_BY_DIM = { 33 | 64: 0, # First max pooling features 34 | 192: 1, # Second max pooling featurs 35 | 768: 2, # Pre-aux classifier features 36 | 2048: 3 # Final average pooling features 37 | } 38 | 39 | def __init__(self, 40 | output_blocks=[DEFAULT_BLOCK_INDEX], 41 | resize_input=True, 42 | normalize_input=True, 43 | requires_grad=False, 44 | use_fid_inception=True): 45 | """Build pretrained InceptionV3 46 | Parameters 47 | ---------- 48 | output_blocks : list of int 49 | Indices of blocks to return features of. Possible values are: 50 | - 0: corresponds to output of first max pooling 51 | - 1: corresponds to output of second max pooling 52 | - 2: corresponds to output which is fed to aux classifier 53 | - 3: corresponds to output of final average pooling 54 | resize_input : bool 55 | If true, bilinearly resizes input to width and height 299 before 56 | feeding input to model. As the network without fully connected 57 | layers is fully convolutional, it should be able to handle inputs 58 | of arbitrary size, so resizing might not be strictly needed 59 | normalize_input : bool 60 | If true, scales the input from range (0, 1) to the range the 61 | pretrained Inception network expects, namely (-1, 1) 62 | requires_grad : bool 63 | If true, parameters of the model require gradients. Possibly useful 64 | for finetuning the network 65 | use_fid_inception : bool 66 | If true, uses the pretrained Inception model used in Tensorflow's 67 | FID implementation. If false, uses the pretrained Inception model 68 | available in torchvision. The FID Inception model has different 69 | weights and a slightly different structure from torchvision's 70 | Inception model. If you want to compute FID scores, you are 71 | strongly advised to set this parameter to true to get comparable 72 | results. 73 | """ 74 | super(InceptionV3, self).__init__() 75 | 76 | self.resize_input = resize_input 77 | self.normalize_input = normalize_input 78 | self.output_blocks = sorted(output_blocks) 79 | self.last_needed_block = max(output_blocks) 80 | 81 | assert self.last_needed_block <= 3, \ 82 | 'Last possible output block index is 3' 83 | 84 | self.blocks = nn.ModuleList() 85 | 86 | if use_fid_inception: 87 | inception = fid_inception_v3() 88 | else: 89 | inception = models.inception_v3(pretrained=True) 90 | 91 | # Block 0: input to maxpool1 92 | block0 = [ 93 | inception.Conv2d_1a_3x3, 94 | inception.Conv2d_2a_3x3, 95 | inception.Conv2d_2b_3x3, 96 | nn.MaxPool2d(kernel_size=3, stride=2) 97 | ] 98 | self.blocks.append(nn.Sequential(*block0)) 99 | 100 | # Block 1: maxpool1 to maxpool2 101 | if self.last_needed_block >= 1: 102 | block1 = [ 103 | inception.Conv2d_3b_1x1, 104 | inception.Conv2d_4a_3x3, 105 | nn.MaxPool2d(kernel_size=3, stride=2) 106 | ] 107 | self.blocks.append(nn.Sequential(*block1)) 108 | 109 | # Block 2: maxpool2 to aux classifier 110 | if self.last_needed_block >= 2: 111 | block2 = [ 112 | inception.Mixed_5b, 113 | inception.Mixed_5c, 114 | inception.Mixed_5d, 115 | inception.Mixed_6a, 116 | inception.Mixed_6b, 117 | inception.Mixed_6c, 118 | inception.Mixed_6d, 119 | inception.Mixed_6e, 120 | ] 121 | self.blocks.append(nn.Sequential(*block2)) 122 | 123 | # Block 3: aux classifier to final avgpool 124 | if self.last_needed_block >= 3: 125 | block3 = [ 126 | inception.Mixed_7a, 127 | inception.Mixed_7b, 128 | inception.Mixed_7c, 129 | nn.AdaptiveAvgPool2d(output_size=(1, 1)) 130 | ] 131 | self.blocks.append(nn.Sequential(*block3)) 132 | 133 | for param in self.parameters(): 134 | param.requires_grad = requires_grad 135 | 136 | def forward(self, inp): 137 | """Get Inception feature maps 138 | Parameters 139 | ---------- 140 | inp : torch.autograd.Variable 141 | Input tensor of shape Bx3xHxW. Values are expected to be in 142 | range (0, 1) 143 | Returns 144 | ------- 145 | List of torch.autograd.Variable, corresponding to the selected output 146 | block, sorted ascending by index 147 | """ 148 | outp = [] 149 | x = inp 150 | 151 | if self.resize_input: 152 | x = F.interpolate(x, 153 | size=(299, 299), 154 | mode='bilinear', 155 | align_corners=False) 156 | 157 | if self.normalize_input: 158 | x = 2 * x - 1 # Scale from range (0, 1) to range (-1, 1) 159 | 160 | for idx, block in enumerate(self.blocks): 161 | x = block(x) 162 | if idx in self.output_blocks: 163 | outp.append(x) 164 | 165 | if idx == self.last_needed_block: 166 | break 167 | 168 | return outp 169 | 170 | 171 | def fid_inception_v3(): 172 | """Build pretrained Inception model for FID computation 173 | The Inception model for FID computation uses a different set of weights 174 | and has a slightly different structure than torchvision's Inception. 175 | This method first constructs torchvision's Inception and then patches the 176 | necessary parts that are different in the FID Inception model. 177 | """ 178 | inception = models.inception_v3(num_classes=1008, 179 | aux_logits=False, 180 | pretrained=False) 181 | inception.Mixed_5b = FIDInceptionA(192, pool_features=32) 182 | inception.Mixed_5c = FIDInceptionA(256, pool_features=64) 183 | inception.Mixed_5d = FIDInceptionA(288, pool_features=64) 184 | inception.Mixed_6b = FIDInceptionC(768, channels_7x7=128) 185 | inception.Mixed_6c = FIDInceptionC(768, channels_7x7=160) 186 | inception.Mixed_6d = FIDInceptionC(768, channels_7x7=160) 187 | inception.Mixed_6e = FIDInceptionC(768, channels_7x7=192) 188 | inception.Mixed_7b = FIDInceptionE_1(1280) 189 | inception.Mixed_7c = FIDInceptionE_2(2048) 190 | 191 | state_dict = load_state_dict_from_url(FID_WEIGHTS_URL, progress=True) 192 | inception.load_state_dict(state_dict) 193 | return inception 194 | 195 | 196 | class FIDInceptionA(models.inception.InceptionA): 197 | """InceptionA block patched for FID computation""" 198 | def __init__(self, in_channels, pool_features): 199 | super(FIDInceptionA, self).__init__(in_channels, pool_features) 200 | 201 | def forward(self, x): 202 | branch1x1 = self.branch1x1(x) 203 | 204 | branch5x5 = self.branch5x5_1(x) 205 | branch5x5 = self.branch5x5_2(branch5x5) 206 | 207 | branch3x3dbl = self.branch3x3dbl_1(x) 208 | branch3x3dbl = self.branch3x3dbl_2(branch3x3dbl) 209 | branch3x3dbl = self.branch3x3dbl_3(branch3x3dbl) 210 | 211 | # Patch: Tensorflow's average pool does not use the padded zero's in 212 | # its average calculation 213 | branch_pool = F.avg_pool2d(x, kernel_size=3, stride=1, padding=1, 214 | count_include_pad=False) 215 | branch_pool = self.branch_pool(branch_pool) 216 | 217 | outputs = [branch1x1, branch5x5, branch3x3dbl, branch_pool] 218 | return torch.cat(outputs, 1) 219 | 220 | 221 | class FIDInceptionC(models.inception.InceptionC): 222 | """InceptionC block patched for FID computation""" 223 | def __init__(self, in_channels, channels_7x7): 224 | super(FIDInceptionC, self).__init__(in_channels, channels_7x7) 225 | 226 | def forward(self, x): 227 | branch1x1 = self.branch1x1(x) 228 | 229 | branch7x7 = self.branch7x7_1(x) 230 | branch7x7 = self.branch7x7_2(branch7x7) 231 | branch7x7 = self.branch7x7_3(branch7x7) 232 | 233 | branch7x7dbl = self.branch7x7dbl_1(x) 234 | branch7x7dbl = self.branch7x7dbl_2(branch7x7dbl) 235 | branch7x7dbl = self.branch7x7dbl_3(branch7x7dbl) 236 | branch7x7dbl = self.branch7x7dbl_4(branch7x7dbl) 237 | branch7x7dbl = self.branch7x7dbl_5(branch7x7dbl) 238 | 239 | # Patch: Tensorflow's average pool does not use the padded zero's in 240 | # its average calculation 241 | branch_pool = F.avg_pool2d(x, kernel_size=3, stride=1, padding=1, 242 | count_include_pad=False) 243 | branch_pool = self.branch_pool(branch_pool) 244 | 245 | outputs = [branch1x1, branch7x7, branch7x7dbl, branch_pool] 246 | return torch.cat(outputs, 1) 247 | 248 | 249 | class FIDInceptionE_1(models.inception.InceptionE): 250 | """First InceptionE block patched for FID computation""" 251 | def __init__(self, in_channels): 252 | super(FIDInceptionE_1, self).__init__(in_channels) 253 | 254 | def forward(self, x): 255 | branch1x1 = self.branch1x1(x) 256 | 257 | branch3x3 = self.branch3x3_1(x) 258 | branch3x3 = [ 259 | self.branch3x3_2a(branch3x3), 260 | self.branch3x3_2b(branch3x3), 261 | ] 262 | branch3x3 = torch.cat(branch3x3, 1) 263 | 264 | branch3x3dbl = self.branch3x3dbl_1(x) 265 | branch3x3dbl = self.branch3x3dbl_2(branch3x3dbl) 266 | branch3x3dbl = [ 267 | self.branch3x3dbl_3a(branch3x3dbl), 268 | self.branch3x3dbl_3b(branch3x3dbl), 269 | ] 270 | branch3x3dbl = torch.cat(branch3x3dbl, 1) 271 | 272 | # Patch: Tensorflow's average pool does not use the padded zero's in 273 | # its average calculation 274 | branch_pool = F.avg_pool2d(x, kernel_size=3, stride=1, padding=1, 275 | count_include_pad=False) 276 | branch_pool = self.branch_pool(branch_pool) 277 | 278 | outputs = [branch1x1, branch3x3, branch3x3dbl, branch_pool] 279 | return torch.cat(outputs, 1) 280 | 281 | 282 | class FIDInceptionE_2(models.inception.InceptionE): 283 | """Second InceptionE block patched for FID computation""" 284 | def __init__(self, in_channels): 285 | super(FIDInceptionE_2, self).__init__(in_channels) 286 | 287 | def forward(self, x): 288 | branch1x1 = self.branch1x1(x) 289 | 290 | branch3x3 = self.branch3x3_1(x) 291 | branch3x3 = [ 292 | self.branch3x3_2a(branch3x3), 293 | self.branch3x3_2b(branch3x3), 294 | ] 295 | branch3x3 = torch.cat(branch3x3, 1) 296 | 297 | branch3x3dbl = self.branch3x3dbl_1(x) 298 | branch3x3dbl = self.branch3x3dbl_2(branch3x3dbl) 299 | branch3x3dbl = [ 300 | self.branch3x3dbl_3a(branch3x3dbl), 301 | self.branch3x3dbl_3b(branch3x3dbl), 302 | ] 303 | branch3x3dbl = torch.cat(branch3x3dbl, 1) 304 | 305 | # Patch: The FID Inception model uses max pooling instead of average 306 | # pooling. This is likely an error in this specific Inception 307 | # implementation, as other Inception models use average pooling here 308 | # (which matches the description in the paper). 309 | branch_pool = F.max_pool2d(x, kernel_size=3, stride=1, padding=1) 310 | branch_pool = self.branch_pool(branch_pool) 311 | 312 | outputs = [branch1x1, branch3x3, branch3x3dbl, branch_pool] 313 | return torch.cat(outputs, 1) 314 | 315 | 316 | class Inception3Feature(Inception3): 317 | def forward(self, x): 318 | if x.shape[2] != 299 or x.shape[3] != 299: 319 | x = F.interpolate(x, size=(299, 299), mode='bilinear', align_corners=True) 320 | 321 | x = self.Conv2d_1a_3x3(x) # 299 x 299 x 3 322 | x = self.Conv2d_2a_3x3(x) # 149 x 149 x 32 323 | x = self.Conv2d_2b_3x3(x) # 147 x 147 x 32 324 | x = F.max_pool2d(x, kernel_size=3, stride=2) # 147 x 147 x 64 325 | 326 | x = self.Conv2d_3b_1x1(x) # 73 x 73 x 64 327 | x = self.Conv2d_4a_3x3(x) # 73 x 73 x 80 328 | x = F.max_pool2d(x, kernel_size=3, stride=2) # 71 x 71 x 192 329 | 330 | x = self.Mixed_5b(x) # 35 x 35 x 192 331 | x = self.Mixed_5c(x) # 35 x 35 x 256 332 | x = self.Mixed_5d(x) # 35 x 35 x 288 333 | 334 | x = self.Mixed_6a(x) # 35 x 35 x 288 335 | x = self.Mixed_6b(x) # 17 x 17 x 768 336 | x = self.Mixed_6c(x) # 17 x 17 x 768 337 | x = self.Mixed_6d(x) # 17 x 17 x 768 338 | x = self.Mixed_6e(x) # 17 x 17 x 768 339 | 340 | x = self.Mixed_7a(x) # 17 x 17 x 768 341 | x = self.Mixed_7b(x) # 8 x 8 x 1280 342 | x = self.Mixed_7c(x) # 8 x 8 x 2048 343 | 344 | x = F.avg_pool2d(x, kernel_size=8) # 8 x 8 x 2048 345 | 346 | return x.view(x.shape[0], x.shape[1]) # 1 x 1 x 2048 347 | 348 | 349 | def load_patched_inception_v3(): 350 | # inception = inception_v3(pretrained=True) 351 | # inception_feat = Inception3Feature() 352 | # inception_feat.load_state_dict(inception.state_dict()) 353 | inception_feat = InceptionV3([3], normalize_input=False) 354 | 355 | return inception_feat 356 | 357 | 358 | @torch.no_grad() 359 | def extract_features(loader, inception, device): 360 | pbar = tqdm(loader) 361 | 362 | feature_list = [] 363 | 364 | for img in pbar: 365 | img = img.to(device) 366 | feature = inception(img)[0].view(img.shape[0], -1) 367 | feature_list.append(feature.to('cpu')) 368 | 369 | features = torch.cat(feature_list, 0) 370 | 371 | return features 372 | 373 | 374 | 375 | @torch.no_grad() 376 | def extract_feature_from_samples(generator, inception, device='cuda'): 377 | n_batch = n_sample // batch_size 378 | resid = n_sample - (n_batch * batch_size) 379 | batch_sizes = [batch_size] * n_batch + [resid] 380 | features = [] 381 | 382 | for batch in tqdm(batch_sizes): 383 | latent = torch.randn(batch, 512, device=device) 384 | img, _ = g([latent], truncation=truncation, truncation_latent=truncation_latent) 385 | feat = inception(img)[0].view(img.shape[0], -1) 386 | features.append(feat.to('cpu')) 387 | 388 | features = torch.cat(features, 0) 389 | 390 | return features 391 | 392 | 393 | @torch.no_grad() 394 | def extract_feature_from_generator_fn(generator_fn, inception, device='cuda', total=1000): 395 | features = [] 396 | for batch in tqdm(generator_fn, total=total): 397 | feat = inception(batch)[0].view(batch.shape[0], -1) 398 | features.append(feat.to('cpu')) 399 | 400 | features = torch.cat(features, 0).detach() 401 | return features.numpy() 402 | 403 | 404 | def calc_fid(sample_features, real_features=None, real_mean=None, real_cov=None, eps=1e-6): 405 | sample_mean = np.mean(sample_features, 0) 406 | sample_cov = np.cov(sample_features, rowvar=False) 407 | 408 | if real_features is not None: 409 | real_mean = np.mean(real_features, 0) 410 | real_cov = np.cov(real_features, rowvar=False) 411 | 412 | cov_sqrt, _ = linalg.sqrtm(sample_cov @ real_cov, disp=False) 413 | 414 | if not np.isfinite(cov_sqrt).all(): 415 | print('product of cov matrices is singular') 416 | offset = np.eye(sample_cov.shape[0]) * eps 417 | cov_sqrt = linalg.sqrtm((sample_cov + offset) @ (real_cov + offset)) 418 | 419 | if np.iscomplexobj(cov_sqrt): 420 | if not np.allclose(np.diagonal(cov_sqrt).imag, 0, atol=1e-3): 421 | m = np.max(np.abs(cov_sqrt.imag)) 422 | 423 | raise ValueError(f'Imaginary component {m}') 424 | 425 | cov_sqrt = cov_sqrt.real 426 | 427 | mean_diff = sample_mean - real_mean 428 | mean_norm = mean_diff @ mean_diff 429 | 430 | trace = np.trace(sample_cov) + np.trace(real_cov) - 2 * np.trace(cov_sqrt) 431 | 432 | fid = mean_norm + trace 433 | 434 | return fid 435 | 436 | 437 | if __name__ == "__main__": 438 | #from utils import PairedMultiDataset, InfiniteSamplerWrapper, make_folders, AverageMeter 439 | from torch.utils.data import DataLoader 440 | from torchvision import utils as vutils 441 | 442 | IM_SIZE = 1024 443 | BATCH_SIZE = 16 444 | DATALOADER_WORKERS = 8 445 | NBR_CLS = 2000 446 | TRIAL_NAME = 'trial_vae_512_1' 447 | SAVE_FOLDER = './' 448 | 449 | from torchvision.datasets import ImageFolder 450 | 451 | ''' 452 | data_root_colorful = '../images/celebA/CelebA_512/img' 453 | data_root_sketch_1 = './sketch_simplification/vggadin_iter_700' 454 | data_root_sketch_2 = './sketch_simplification/vggadin_iter_1900' 455 | data_root_sketch_3 = './sketch_simplification/vggadin_iter_2300' 456 | 457 | dataset = PairedMultiDataset(data_root_colorful, data_root_sketch_1, data_root_sketch_2, data_root_sketch_3, im_size=IM_SIZE, rand_crop=False) 458 | dataloader = iter(DataLoader(dataset, BATCH_SIZE, shuffle=False, num_workers=DATALOADER_WORKERS, pin_memory=True)) 459 | 460 | 461 | from pretrain_ae import StyleEncoder, ContentEncoder, Decoder 462 | import pickle 463 | from refine_ae_as_gan import AE, RefineGenerator 464 | from utils import load_params 465 | 466 | net_ig = RefineGenerator().cuda() 467 | net_ig = nn.DataParallel(net_ig) 468 | 469 | ckpt = './train_results/trial_refine_ae_as_gan_1024_2/models/4.pth' 470 | if ckpt is not None: 471 | ckpt = torch.load(ckpt) 472 | #net_ig.load_state_dict(ckpt['ig']) 473 | #net_id.load_state_dict(ckpt['id']) 474 | net_ig_ema = ckpt['ig_ema'] 475 | load_params(net_ig, net_ig_ema) 476 | net_ig = net_ig.module 477 | #net_ig.eval() 478 | 479 | net_ae = AE() 480 | net_ae.load_state_dicts('./train_results/trial_vae_512_1/models/176000.pth') 481 | net_ae.cuda() 482 | net_ae.eval() 483 | 484 | #style_encoder = StyleEncoder(nbr_cls=NBR_CLS).cuda() 485 | #content_encoder = ContentEncoder().cuda() 486 | #decoder = Decoder().cuda() 487 | ''' 488 | 489 | def real_image_loader(dataloader, n_batches=10): 490 | counter = 0 491 | while counter < n_batches: 492 | counter += 1 493 | rgb_img, _ = next(dataloader) 494 | if counter == 1: 495 | vutils.save_image(0.5*(rgb_img+1), 'tmp_real.jpg') 496 | yield rgb_img.cuda() 497 | 498 | ''' 499 | @torch.no_grad() 500 | def image_generator_1(dataloader, n_batches=10): 501 | counter = 0 502 | while counter < n_batches: 503 | counter += 1 504 | rgb_img, _, _, skt_img = next(dataloader) 505 | rgb_img = rgb_img.cuda() 506 | skt_img = skt_img.cuda() 507 | 508 | style_feat, _ = style_encoder(rgb_img) 509 | content_feats = content_encoder( F.interpolate( skt_img , size=512 ) ) 510 | gimg = decoder(content_feats, style_feat) 511 | 512 | vutils.save_image(0.5*(gimg+1), 'tmp.jpg') 513 | yield gimg 514 | 515 | from utils import true_randperm 516 | @torch.no_grad() 517 | def image_generator(dataset, net_ae, net_ig, n_batches=500): 518 | counter = 0 519 | dataloader = iter(DataLoader(dataset, BATCH_SIZE, shuffle=False, num_workers=DATALOADER_WORKERS, pin_memory=False)) 520 | 521 | while counter < n_batches: 522 | counter += 1 523 | rgb_img, _, _, skt_img = next(dataloader) 524 | rgb_img = F.interpolate( rgb_img, size=512 ).cuda() 525 | skt_img = F.interpolate( skt_img, size=512 ).cuda() 526 | 527 | #perm = true_randperm(rgb_img.shape[0], device=rgb_img.device) 528 | 529 | gimg_ae, style_feat = net_ae(skt_img, rgb_img) 530 | g_image = net_ig(gimg_ae, style_feat, skt_img) 531 | if counter == 1: 532 | vutils.save_image(0.5*(g_image+1), 'tmp.jpg') 533 | yield g_image 534 | ''' 535 | inception = load_patched_inception_v3().cuda() 536 | inception.eval() 537 | 538 | path_a = '../../../database/images/celebaMask/CelebA_1024' 539 | path_b = '../../stylegan/celebahq_samples' 540 | 541 | from torchvision import transforms 542 | 543 | transform = transforms.Compose( 544 | [ 545 | transforms.Resize( (299, 299) ), 546 | #transforms.RandomHorizontalFlip(p=0.5 if args.flip else 0), 547 | transforms.ToTensor(), 548 | transforms.Normalize([0.5, 0.5, 0.5], [0.5, 0.5, 0.5]), 549 | ] 550 | ) 551 | 552 | dset_a = ImageFolder(path_a, transform) 553 | loader_a = iter(DataLoader(dset_a, batch_size=16, num_workers=4)) 554 | 555 | real_features = extract_feature_from_generator_fn( 556 | real_image_loader(loader_a, n_batches=900), inception ) 557 | real_mean = np.mean(real_features, 0) 558 | real_cov = np.cov(real_features, rowvar=False) 559 | 560 | #pickle.dump({'feats': real_features, 'mean': real_mean, 'cov': real_cov}, open('celeba_fid_feats.npy','wb') ) 561 | 562 | #real_features = pickle.load( open('celeba_fid_feats.npy', 'rb') ) 563 | #real_mean = real_features['mean'] 564 | #real_cov = real_features['cov'] 565 | #sample_features = extract_feature_from_generator_fn( real_image_loader(dataloader, n_batches=100), inception ) 566 | 567 | dset_b = ImageFolder(path_b, transform) 568 | loader_b = iter(DataLoader(dset_b, batch_size=16, num_workers=4)) 569 | 570 | sample_features = extract_feature_from_generator_fn( 571 | real_image_loader(loader_b, n_batches=900), inception ) 572 | #sample_features = extract_feature_from_generator_fn( 573 | # image_generator(dataset, net_ae, net_ig, n_batches=1800), inception, 574 | # total=1800 ) 575 | 576 | #fid = calc_fid(sample_features, real_mean=real_features['mean'], real_cov=real_features['cov']) 577 | fid = calc_fid(sample_features, real_mean=real_mean, real_cov=real_cov) 578 | 579 | print(fid) -------------------------------------------------------------------------------- /benchmarking/calc_inception.py: -------------------------------------------------------------------------------- 1 | import argparse 2 | import pickle 3 | import os 4 | 5 | import torch 6 | from torch import nn 7 | from torch.nn import functional as F 8 | from torch.utils.data import DataLoader 9 | from torchvision import transforms 10 | from torchvision.models import inception_v3, Inception3 11 | import numpy as np 12 | from tqdm import tqdm 13 | 14 | from inception import InceptionV3 15 | from torchvision.datasets import ImageFolder 16 | 17 | class Inception3Feature(Inception3): 18 | def forward(self, x): 19 | if x.shape[2] != 299 or x.shape[3] != 299: 20 | x = F.interpolate(x, size=(299, 299), mode='bilinear', align_corners=True) 21 | 22 | x = self.Conv2d_1a_3x3(x) # 299 x 299 x 3 23 | x = self.Conv2d_2a_3x3(x) # 149 x 149 x 32 24 | x = self.Conv2d_2b_3x3(x) # 147 x 147 x 32 25 | x = F.max_pool2d(x, kernel_size=3, stride=2) # 147 x 147 x 64 26 | 27 | x = self.Conv2d_3b_1x1(x) # 73 x 73 x 64 28 | x = self.Conv2d_4a_3x3(x) # 73 x 73 x 80 29 | x = F.max_pool2d(x, kernel_size=3, stride=2) # 71 x 71 x 192 30 | 31 | x = self.Mixed_5b(x) # 35 x 35 x 192 32 | x = self.Mixed_5c(x) # 35 x 35 x 256 33 | x = self.Mixed_5d(x) # 35 x 35 x 288 34 | 35 | x = self.Mixed_6a(x) # 35 x 35 x 288 36 | x = self.Mixed_6b(x) # 17 x 17 x 768 37 | x = self.Mixed_6c(x) # 17 x 17 x 768 38 | x = self.Mixed_6d(x) # 17 x 17 x 768 39 | x = self.Mixed_6e(x) # 17 x 17 x 768 40 | 41 | x = self.Mixed_7a(x) # 17 x 17 x 768 42 | x = self.Mixed_7b(x) # 8 x 8 x 1280 43 | x = self.Mixed_7c(x) # 8 x 8 x 2048 44 | 45 | x = F.avg_pool2d(x, kernel_size=8) # 8 x 8 x 2048 46 | 47 | return x.view(x.shape[0], x.shape[1]) # 1 x 1 x 2048 48 | 49 | 50 | def load_patched_inception_v3(): 51 | # inception = inception_v3(pretrained=True) 52 | # inception_feat = Inception3Feature() 53 | # inception_feat.load_state_dict(inception.state_dict()) 54 | inception_feat = InceptionV3([3], normalize_input=False) 55 | 56 | return inception_feat 57 | 58 | 59 | @torch.no_grad() 60 | def extract_features(loader, inception, device): 61 | pbar = tqdm(loader) 62 | 63 | feature_list = [] 64 | 65 | for img,_ in pbar: 66 | img = img.to(device) 67 | feature = inception(img)[0].view(img.shape[0], -1) 68 | feature_list.append(feature.to('cpu')) 69 | 70 | features = torch.cat(feature_list, 0) 71 | 72 | return features 73 | 74 | 75 | if __name__ == '__main__': 76 | device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') 77 | 78 | parser = argparse.ArgumentParser( 79 | description='Calculate Inception v3 features for datasets' 80 | ) 81 | parser.add_argument('--size', type=int, default=256) 82 | parser.add_argument('--batch', default=64, type=int, help='batch size') 83 | parser.add_argument('--n_sample', type=int, default=50000) 84 | parser.add_argument('--flip', action='store_true') 85 | parser.add_argument('path', metavar='PATH', help='path to datset lmdb file') 86 | 87 | args = parser.parse_args() 88 | 89 | inception = load_patched_inception_v3().eval().to(device) 90 | 91 | transform = transforms.Compose( 92 | [ 93 | transforms.Resize( (args.size, args.size) ), 94 | transforms.RandomHorizontalFlip(p=0.5 if args.flip else 0), 95 | transforms.ToTensor(), 96 | transforms.Normalize([0.5, 0.5, 0.5], [0.5, 0.5, 0.5]), 97 | ] 98 | ) 99 | 100 | dset = ImageFolder(args.path, transform) 101 | loader = DataLoader(dset, batch_size=args.batch, num_workers=4) 102 | 103 | features = extract_features(loader, inception, device).numpy() 104 | 105 | features = features[: args.n_sample] 106 | 107 | print(f'extracted {features.shape[0]} features') 108 | 109 | mean = np.mean(features, 0) 110 | cov = np.cov(features, rowvar=False) 111 | 112 | name = os.path.splitext(os.path.basename(args.path))[0] 113 | 114 | print({'mean': mean.mean(), 'cov': cov.mean()}) 115 | with open(f'inception_{name}.pkl', 'wb') as f: 116 | pickle.dump({'mean': mean, 'cov': cov, 'size': args.size, 'path': args.path}, f) 117 | -------------------------------------------------------------------------------- /benchmarking/fid.py: -------------------------------------------------------------------------------- 1 | import argparse 2 | import pickle 3 | 4 | import torch 5 | from torch import nn 6 | import numpy as np 7 | from scipy import linalg 8 | from tqdm import tqdm 9 | 10 | from torchvision import transforms 11 | from torchvision.datasets import ImageFolder 12 | from torch.utils.data import DataLoader 13 | 14 | from calc_inception import load_patched_inception_v3 15 | import os 16 | 17 | @torch.no_grad() 18 | def extract_features(loader, inception, device): 19 | pbar = tqdm(loader) 20 | 21 | feature_list = [] 22 | 23 | for img,_ in pbar: 24 | img = img.to(device) 25 | feature = inception(img)[0].view(img.shape[0], -1) 26 | feature_list.append(feature.to('cpu')) 27 | 28 | features = torch.cat(feature_list, 0) 29 | 30 | return features 31 | 32 | 33 | def calc_fid(sample_mean, sample_cov, real_mean, real_cov, eps=1e-6): 34 | cov_sqrt, _ = linalg.sqrtm(sample_cov @ real_cov, disp=False) 35 | 36 | if not np.isfinite(cov_sqrt).all(): 37 | print('product of cov matrices is singular') 38 | offset = np.eye(sample_cov.shape[0]) * eps 39 | cov_sqrt = linalg.sqrtm((sample_cov + offset) @ (real_cov + offset)) 40 | 41 | if np.iscomplexobj(cov_sqrt): 42 | if not np.allclose(np.diagonal(cov_sqrt).imag, 0, atol=1e-3): 43 | m = np.max(np.abs(cov_sqrt.imag)) 44 | 45 | raise ValueError(f'Imaginary component {m}') 46 | 47 | cov_sqrt = cov_sqrt.real 48 | 49 | mean_diff = sample_mean - real_mean 50 | mean_norm = mean_diff @ mean_diff 51 | 52 | trace = np.trace(sample_cov) + np.trace(real_cov) - 2 * np.trace(cov_sqrt) 53 | 54 | fid = mean_norm + trace 55 | 56 | return fid 57 | 58 | 59 | if __name__ == '__main__': 60 | device = 'cuda' 61 | 62 | parser = argparse.ArgumentParser() 63 | 64 | parser.add_argument('--batch', type=int, default=64) 65 | parser.add_argument('--size', type=int, default=256) 66 | parser.add_argument('--path_a', type=str) 67 | parser.add_argument('--path_b', type=str) 68 | parser.add_argument('--iter', type=int, default=3) 69 | parser.add_argument('--end', type=int, default=13) 70 | 71 | args = parser.parse_args() 72 | 73 | inception = load_patched_inception_v3().eval().to(device) 74 | 75 | transform = transforms.Compose( 76 | [ 77 | transforms.Resize( (args.size, args.size) ), 78 | #transforms.RandomHorizontalFlip(p=0.5 if args.flip else 0), 79 | transforms.ToTensor(), 80 | transforms.Normalize([0.5, 0.5, 0.5], [0.5, 0.5, 0.5]), 81 | ] 82 | ) 83 | 84 | dset_a = ImageFolder(args.path_a, transform) 85 | loader_a = DataLoader(dset_a, batch_size=args.batch, num_workers=4) 86 | 87 | features_a = extract_features(loader_a, inception, device).numpy() 88 | print(f'extracted {features_a.shape[0]} features') 89 | 90 | real_mean = np.mean(features_a, 0) 91 | real_cov = np.cov(features_a, rowvar=False) 92 | 93 | #for folder in os.listdir(args.path_b): 94 | for folder in range(args.iter,args.end+1): 95 | folder = 'eval_%d'%(folder*10000) 96 | if os.path.exists(os.path.join( args.path_b, folder )): 97 | print(folder) 98 | dset_b = ImageFolder( os.path.join( args.path_b, folder ), transform) 99 | loader_b = DataLoader(dset_b, batch_size=args.batch, num_workers=4) 100 | 101 | features_b = extract_features(loader_b, inception, device).numpy() 102 | print(f'extracted {features_b.shape[0]} features') 103 | 104 | sample_mean = np.mean(features_b, 0) 105 | sample_cov = np.cov(features_b, rowvar=False) 106 | 107 | fid = calc_fid(sample_mean, sample_cov, real_mean, real_cov) 108 | 109 | print(folder, ' fid:', fid) 110 | -------------------------------------------------------------------------------- /benchmarking/inception.py: -------------------------------------------------------------------------------- 1 | import torch 2 | import torch.nn as nn 3 | import torch.nn.functional as F 4 | from torchvision import models 5 | 6 | try: 7 | from torchvision.models.utils import load_state_dict_from_url 8 | except ImportError: 9 | from torch.utils.model_zoo import load_url as load_state_dict_from_url 10 | 11 | # Inception weights ported to Pytorch from 12 | # http://download.tensorflow.org/models/image/imagenet/inception-2015-12-05.tgz 13 | FID_WEIGHTS_URL = 'https://github.com/mseitzer/pytorch-fid/releases/download/fid_weights/pt_inception-2015-12-05-6726825d.pth' 14 | 15 | 16 | class InceptionV3(nn.Module): 17 | """Pretrained InceptionV3 network returning feature maps""" 18 | 19 | # Index of default block of inception to return, 20 | # corresponds to output of final average pooling 21 | DEFAULT_BLOCK_INDEX = 3 22 | 23 | # Maps feature dimensionality to their output blocks indices 24 | BLOCK_INDEX_BY_DIM = { 25 | 64: 0, # First max pooling features 26 | 192: 1, # Second max pooling featurs 27 | 768: 2, # Pre-aux classifier features 28 | 2048: 3 # Final average pooling features 29 | } 30 | 31 | def __init__(self, 32 | output_blocks=[DEFAULT_BLOCK_INDEX], 33 | resize_input=True, 34 | normalize_input=True, 35 | requires_grad=False, 36 | use_fid_inception=True): 37 | """Build pretrained InceptionV3 38 | 39 | Parameters 40 | ---------- 41 | output_blocks : list of int 42 | Indices of blocks to return features of. Possible values are: 43 | - 0: corresponds to output of first max pooling 44 | - 1: corresponds to output of second max pooling 45 | - 2: corresponds to output which is fed to aux classifier 46 | - 3: corresponds to output of final average pooling 47 | resize_input : bool 48 | If true, bilinearly resizes input to width and height 299 before 49 | feeding input to model. As the network without fully connected 50 | layers is fully convolutional, it should be able to handle inputs 51 | of arbitrary size, so resizing might not be strictly needed 52 | normalize_input : bool 53 | If true, scales the input from range (0, 1) to the range the 54 | pretrained Inception network expects, namely (-1, 1) 55 | requires_grad : bool 56 | If true, parameters of the model require gradients. Possibly useful 57 | for finetuning the network 58 | use_fid_inception : bool 59 | If true, uses the pretrained Inception model used in Tensorflow's 60 | FID implementation. If false, uses the pretrained Inception model 61 | available in torchvision. The FID Inception model has different 62 | weights and a slightly different structure from torchvision's 63 | Inception model. If you want to compute FID scores, you are 64 | strongly advised to set this parameter to true to get comparable 65 | results. 66 | """ 67 | super(InceptionV3, self).__init__() 68 | 69 | self.resize_input = resize_input 70 | self.normalize_input = normalize_input 71 | self.output_blocks = sorted(output_blocks) 72 | self.last_needed_block = max(output_blocks) 73 | 74 | assert self.last_needed_block <= 3, \ 75 | 'Last possible output block index is 3' 76 | 77 | self.blocks = nn.ModuleList() 78 | 79 | if use_fid_inception: 80 | inception = fid_inception_v3() 81 | else: 82 | inception = models.inception_v3(pretrained=True) 83 | 84 | # Block 0: input to maxpool1 85 | block0 = [ 86 | inception.Conv2d_1a_3x3, 87 | inception.Conv2d_2a_3x3, 88 | inception.Conv2d_2b_3x3, 89 | nn.MaxPool2d(kernel_size=3, stride=2) 90 | ] 91 | self.blocks.append(nn.Sequential(*block0)) 92 | 93 | # Block 1: maxpool1 to maxpool2 94 | if self.last_needed_block >= 1: 95 | block1 = [ 96 | inception.Conv2d_3b_1x1, 97 | inception.Conv2d_4a_3x3, 98 | nn.MaxPool2d(kernel_size=3, stride=2) 99 | ] 100 | self.blocks.append(nn.Sequential(*block1)) 101 | 102 | # Block 2: maxpool2 to aux classifier 103 | if self.last_needed_block >= 2: 104 | block2 = [ 105 | inception.Mixed_5b, 106 | inception.Mixed_5c, 107 | inception.Mixed_5d, 108 | inception.Mixed_6a, 109 | inception.Mixed_6b, 110 | inception.Mixed_6c, 111 | inception.Mixed_6d, 112 | inception.Mixed_6e, 113 | ] 114 | self.blocks.append(nn.Sequential(*block2)) 115 | 116 | # Block 3: aux classifier to final avgpool 117 | if self.last_needed_block >= 3: 118 | block3 = [ 119 | inception.Mixed_7a, 120 | inception.Mixed_7b, 121 | inception.Mixed_7c, 122 | nn.AdaptiveAvgPool2d(output_size=(1, 1)) 123 | ] 124 | self.blocks.append(nn.Sequential(*block3)) 125 | 126 | for param in self.parameters(): 127 | param.requires_grad = requires_grad 128 | 129 | def forward(self, inp): 130 | """Get Inception feature maps 131 | 132 | Parameters 133 | ---------- 134 | inp : torch.autograd.Variable 135 | Input tensor of shape Bx3xHxW. Values are expected to be in 136 | range (0, 1) 137 | 138 | Returns 139 | ------- 140 | List of torch.autograd.Variable, corresponding to the selected output 141 | block, sorted ascending by index 142 | """ 143 | outp = [] 144 | x = inp 145 | 146 | if self.resize_input: 147 | x = F.interpolate(x, 148 | size=(299, 299), 149 | mode='bilinear', 150 | align_corners=False) 151 | 152 | if self.normalize_input: 153 | x = 2 * x - 1 # Scale from range (0, 1) to range (-1, 1) 154 | 155 | for idx, block in enumerate(self.blocks): 156 | x = block(x) 157 | if idx in self.output_blocks: 158 | outp.append(x) 159 | 160 | if idx == self.last_needed_block: 161 | break 162 | 163 | return outp 164 | 165 | 166 | def fid_inception_v3(): 167 | """Build pretrained Inception model for FID computation 168 | 169 | The Inception model for FID computation uses a different set of weights 170 | and has a slightly different structure than torchvision's Inception. 171 | 172 | This method first constructs torchvision's Inception and then patches the 173 | necessary parts that are different in the FID Inception model. 174 | """ 175 | inception = models.inception_v3(num_classes=1008, 176 | aux_logits=False, 177 | pretrained=False) 178 | inception.Mixed_5b = FIDInceptionA(192, pool_features=32) 179 | inception.Mixed_5c = FIDInceptionA(256, pool_features=64) 180 | inception.Mixed_5d = FIDInceptionA(288, pool_features=64) 181 | inception.Mixed_6b = FIDInceptionC(768, channels_7x7=128) 182 | inception.Mixed_6c = FIDInceptionC(768, channels_7x7=160) 183 | inception.Mixed_6d = FIDInceptionC(768, channels_7x7=160) 184 | inception.Mixed_6e = FIDInceptionC(768, channels_7x7=192) 185 | inception.Mixed_7b = FIDInceptionE_1(1280) 186 | inception.Mixed_7c = FIDInceptionE_2(2048) 187 | 188 | state_dict = load_state_dict_from_url(FID_WEIGHTS_URL, progress=True) 189 | inception.load_state_dict(state_dict) 190 | return inception 191 | 192 | 193 | class FIDInceptionA(models.inception.InceptionA): 194 | """InceptionA block patched for FID computation""" 195 | def __init__(self, in_channels, pool_features): 196 | super(FIDInceptionA, self).__init__(in_channels, pool_features) 197 | 198 | def forward(self, x): 199 | branch1x1 = self.branch1x1(x) 200 | 201 | branch5x5 = self.branch5x5_1(x) 202 | branch5x5 = self.branch5x5_2(branch5x5) 203 | 204 | branch3x3dbl = self.branch3x3dbl_1(x) 205 | branch3x3dbl = self.branch3x3dbl_2(branch3x3dbl) 206 | branch3x3dbl = self.branch3x3dbl_3(branch3x3dbl) 207 | 208 | # Patch: Tensorflow's average pool does not use the padded zero's in 209 | # its average calculation 210 | branch_pool = F.avg_pool2d(x, kernel_size=3, stride=1, padding=1, 211 | count_include_pad=False) 212 | branch_pool = self.branch_pool(branch_pool) 213 | 214 | outputs = [branch1x1, branch5x5, branch3x3dbl, branch_pool] 215 | return torch.cat(outputs, 1) 216 | 217 | 218 | class FIDInceptionC(models.inception.InceptionC): 219 | """InceptionC block patched for FID computation""" 220 | def __init__(self, in_channels, channels_7x7): 221 | super(FIDInceptionC, self).__init__(in_channels, channels_7x7) 222 | 223 | def forward(self, x): 224 | branch1x1 = self.branch1x1(x) 225 | 226 | branch7x7 = self.branch7x7_1(x) 227 | branch7x7 = self.branch7x7_2(branch7x7) 228 | branch7x7 = self.branch7x7_3(branch7x7) 229 | 230 | branch7x7dbl = self.branch7x7dbl_1(x) 231 | branch7x7dbl = self.branch7x7dbl_2(branch7x7dbl) 232 | branch7x7dbl = self.branch7x7dbl_3(branch7x7dbl) 233 | branch7x7dbl = self.branch7x7dbl_4(branch7x7dbl) 234 | branch7x7dbl = self.branch7x7dbl_5(branch7x7dbl) 235 | 236 | # Patch: Tensorflow's average pool does not use the padded zero's in 237 | # its average calculation 238 | branch_pool = F.avg_pool2d(x, kernel_size=3, stride=1, padding=1, 239 | count_include_pad=False) 240 | branch_pool = self.branch_pool(branch_pool) 241 | 242 | outputs = [branch1x1, branch7x7, branch7x7dbl, branch_pool] 243 | return torch.cat(outputs, 1) 244 | 245 | 246 | class FIDInceptionE_1(models.inception.InceptionE): 247 | """First InceptionE block patched for FID computation""" 248 | def __init__(self, in_channels): 249 | super(FIDInceptionE_1, self).__init__(in_channels) 250 | 251 | def forward(self, x): 252 | branch1x1 = self.branch1x1(x) 253 | 254 | branch3x3 = self.branch3x3_1(x) 255 | branch3x3 = [ 256 | self.branch3x3_2a(branch3x3), 257 | self.branch3x3_2b(branch3x3), 258 | ] 259 | branch3x3 = torch.cat(branch3x3, 1) 260 | 261 | branch3x3dbl = self.branch3x3dbl_1(x) 262 | branch3x3dbl = self.branch3x3dbl_2(branch3x3dbl) 263 | branch3x3dbl = [ 264 | self.branch3x3dbl_3a(branch3x3dbl), 265 | self.branch3x3dbl_3b(branch3x3dbl), 266 | ] 267 | branch3x3dbl = torch.cat(branch3x3dbl, 1) 268 | 269 | # Patch: Tensorflow's average pool does not use the padded zero's in 270 | # its average calculation 271 | branch_pool = F.avg_pool2d(x, kernel_size=3, stride=1, padding=1, 272 | count_include_pad=False) 273 | branch_pool = self.branch_pool(branch_pool) 274 | 275 | outputs = [branch1x1, branch3x3, branch3x3dbl, branch_pool] 276 | return torch.cat(outputs, 1) 277 | 278 | 279 | class FIDInceptionE_2(models.inception.InceptionE): 280 | """Second InceptionE block patched for FID computation""" 281 | def __init__(self, in_channels): 282 | super(FIDInceptionE_2, self).__init__(in_channels) 283 | 284 | def forward(self, x): 285 | branch1x1 = self.branch1x1(x) 286 | 287 | branch3x3 = self.branch3x3_1(x) 288 | branch3x3 = [ 289 | self.branch3x3_2a(branch3x3), 290 | self.branch3x3_2b(branch3x3), 291 | ] 292 | branch3x3 = torch.cat(branch3x3, 1) 293 | 294 | branch3x3dbl = self.branch3x3dbl_1(x) 295 | branch3x3dbl = self.branch3x3dbl_2(branch3x3dbl) 296 | branch3x3dbl = [ 297 | self.branch3x3dbl_3a(branch3x3dbl), 298 | self.branch3x3dbl_3b(branch3x3dbl), 299 | ] 300 | branch3x3dbl = torch.cat(branch3x3dbl, 1) 301 | 302 | # Patch: The FID Inception model uses max pooling instead of average 303 | # pooling. This is likely an error in this specific Inception 304 | # implementation, as other Inception models use average pooling here 305 | # (which matches the description in the paper). 306 | branch_pool = F.max_pool2d(x, kernel_size=3, stride=1, padding=1) 307 | branch_pool = self.branch_pool(branch_pool) 308 | 309 | outputs = [branch1x1, branch3x3, branch3x3dbl, branch_pool] 310 | return torch.cat(outputs, 1) 311 | -------------------------------------------------------------------------------- /diffaug.py: -------------------------------------------------------------------------------- 1 | # Differentiable Augmentation for Data-Efficient GAN Training 2 | # Shengyu Zhao, Zhijian Liu, Ji Lin, Jun-Yan Zhu, and Song Han 3 | # https://arxiv.org/pdf/2006.10738 4 | 5 | import torch 6 | import torch.nn.functional as F 7 | 8 | 9 | def DiffAugment(x, policy='', channels_first=True): 10 | if policy: 11 | if not channels_first: 12 | x = x.permute(0, 3, 1, 2) 13 | for p in policy.split(','): 14 | for f in AUGMENT_FNS[p]: 15 | x = f(x) 16 | if not channels_first: 17 | x = x.permute(0, 2, 3, 1) 18 | x = x.contiguous() 19 | return x 20 | 21 | 22 | def rand_brightness(x): 23 | x = x + (torch.rand(x.size(0), 1, 1, 1, dtype=x.dtype, device=x.device) - 0.5) 24 | return x 25 | 26 | 27 | def rand_saturation(x): 28 | x_mean = x.mean(dim=1, keepdim=True) 29 | x = (x - x_mean) * (torch.rand(x.size(0), 1, 1, 1, dtype=x.dtype, device=x.device) * 2) + x_mean 30 | return x 31 | 32 | 33 | def rand_contrast(x): 34 | x_mean = x.mean(dim=[1, 2, 3], keepdim=True) 35 | x = (x - x_mean) * (torch.rand(x.size(0), 1, 1, 1, dtype=x.dtype, device=x.device) + 0.5) + x_mean 36 | return x 37 | 38 | 39 | def rand_translation(x, ratio=0.125): 40 | shift_x, shift_y = int(x.size(2) * ratio + 0.5), int(x.size(3) * ratio + 0.5) 41 | translation_x = torch.randint(-shift_x, shift_x + 1, size=[x.size(0), 1, 1], device=x.device) 42 | translation_y = torch.randint(-shift_y, shift_y + 1, size=[x.size(0), 1, 1], device=x.device) 43 | grid_batch, grid_x, grid_y = torch.meshgrid( 44 | torch.arange(x.size(0), dtype=torch.long, device=x.device), 45 | torch.arange(x.size(2), dtype=torch.long, device=x.device), 46 | torch.arange(x.size(3), dtype=torch.long, device=x.device), 47 | ) 48 | grid_x = torch.clamp(grid_x + translation_x + 1, 0, x.size(2) + 1) 49 | grid_y = torch.clamp(grid_y + translation_y + 1, 0, x.size(3) + 1) 50 | x_pad = F.pad(x, [1, 1, 1, 1, 0, 0, 0, 0]) 51 | x = x_pad.permute(0, 2, 3, 1).contiguous()[grid_batch, grid_x, grid_y].permute(0, 3, 1, 2) 52 | return x 53 | 54 | 55 | def rand_cutout(x, ratio=0.5): 56 | cutout_size = int(x.size(2) * ratio + 0.5), int(x.size(3) * ratio + 0.5) 57 | offset_x = torch.randint(0, x.size(2) + (1 - cutout_size[0] % 2), size=[x.size(0), 1, 1], device=x.device) 58 | offset_y = torch.randint(0, x.size(3) + (1 - cutout_size[1] % 2), size=[x.size(0), 1, 1], device=x.device) 59 | grid_batch, grid_x, grid_y = torch.meshgrid( 60 | torch.arange(x.size(0), dtype=torch.long, device=x.device), 61 | torch.arange(cutout_size[0], dtype=torch.long, device=x.device), 62 | torch.arange(cutout_size[1], dtype=torch.long, device=x.device), 63 | ) 64 | grid_x = torch.clamp(grid_x + offset_x - cutout_size[0] // 2, min=0, max=x.size(2) - 1) 65 | grid_y = torch.clamp(grid_y + offset_y - cutout_size[1] // 2, min=0, max=x.size(3) - 1) 66 | mask = torch.ones(x.size(0), x.size(2), x.size(3), dtype=x.dtype, device=x.device) 67 | mask[grid_batch, grid_x, grid_y] = 0 68 | x = x * mask.unsqueeze(1) 69 | return x 70 | 71 | 72 | AUGMENT_FNS = { 73 | 'color': [rand_brightness, rand_saturation, rand_contrast], 74 | 'translation': [rand_translation], 75 | 'cutout': [rand_cutout], 76 | } -------------------------------------------------------------------------------- /docker/Dockerfile.cpu: -------------------------------------------------------------------------------- 1 | FROM python:3.8-buster 2 | 3 | ENV DEBIAN_FRONTEND=noninteractive 4 | SHELL ["/bin/bash", "-c"] 5 | 6 | RUN apt-get update && apt-get install -y unzip 7 | 8 | RUN pip install gdown 9 | RUN mkdir /code 10 | WORKDIR /code 11 | 12 | # Download pre-trained models and remove all but the latest 13 | # checkpoint for each model to save space 14 | 15 | RUN gdown -O trial_shell.zip "https://drive.google.com/uc?id=1plZ72wC1u8jX12PD3FaMzV5Z06XUuLj-" && \ 16 | unzip trial_shell.zip && \ 17 | rm trial_shell.zip && \ 18 | rm trial_shell/models/{all_10000.pth,all_20000.pth,10000.pth,20000.pth,30000.pth} && \ 19 | mv trial_shell/models/all_30000.pth trial_shell/models/30000.pth 20 | RUN gdown -O trial_skull.zip "https://drive.google.com/uc?id=1MVHSnf3Z42ZcRPk-29qXfjYgS1CKPuhm" && \ 21 | unzip trial_skull.zip && \ 22 | rm trial_skull.zip && \ 23 | rm trial_skull/models/{30000.pth,40000.pth} 24 | RUN gdown -O trial_dog.zip "https://drive.google.com/uc?id=1iHdCRXG_Y7Z_fTwFPMHAnHYGcmNpaHVn" && \ 25 | unzip trial_dog.zip && \ 26 | rm trial_dog.zip && \ 27 | rm trial_dog/models/{40000.pth,60000.pth} 28 | RUN gdown -O trial_panda.zip "https://drive.google.com/uc?id=1p1oRxpljgc2_M4NfaRrxmfNeC8RWAw8V" && \ 29 | unzip trial_panda.zip && \ 30 | rm trial_panda.zip && \ 31 | rm trial_panda/models/30000.pth 32 | RUN gdown -O good_ffhq_full_512.zip "https://drive.google.com/uc?id=1oBxHC16Vpm-_9xWkuM43MHGQMMVijyJA" && \ 33 | unzip good_ffhq_full_512.zip && \ 34 | rm good_ffhq_full_512.zip && \ 35 | mv good_ffhq_full_512/models/all_100000.pth good_ffhq_full_512/models/100000.pth 36 | RUN gdown -O good_art_1k_512.zip "https://drive.google.com/uc?id=1RHTmh0dWM0Mg-S8_maKv5Up3m6wuwY08" && \ 37 | unzip good_art_1k_512.zip && \ 38 | rm good_art_1k_512.zip && \ 39 | mv good_art_1k_512/models/all_50000.pth good_art_1k_512/models/50000.pth 40 | 41 | RUN pip install \ 42 | tqdm==4.56.0 \ 43 | scipy==1.6.0 \ 44 | scikit-image==0.18.1 \ 45 | ipdb==0.13.4 \ 46 | pandas==1.2.1 \ 47 | lmdb==1.0.0 \ 48 | opencv-python==4.5.1.48 \ 49 | easing-functions==1.0.4 \ 50 | torch==1.7.0 \ 51 | torchvision==0.8.0 52 | 53 | # Make the models work on cpu 54 | RUN for model in *; do sed -i "s/torch.device('cuda:%d'%(args.cuda))/torch.device('cpu')/" $model/eval.py; done 55 | 56 | COPY docker/infer.sh infer.sh 57 | RUN chmod +x infer.sh 58 | ENTRYPOINT ["./infer.sh"] 59 | -------------------------------------------------------------------------------- /docker/Dockerfile.gpu: -------------------------------------------------------------------------------- 1 | FROM docker.io/pytorch/pytorch:1.7.0-cuda11.0-cudnn8-devel 2 | 3 | SHELL ["/bin/bash", "-c"] 4 | 5 | RUN apt-get update && apt-get install -y unzip 6 | 7 | RUN pip install gdown 8 | RUN mkdir /code 9 | WORKDIR /code 10 | 11 | # Download pre-trained models and remove all but the latest 12 | # checkpoint for each model to save space 13 | 14 | RUN gdown -O trial_shell.zip "https://drive.google.com/uc?id=1plZ72wC1u8jX12PD3FaMzV5Z06XUuLj-" && \ 15 | unzip trial_shell.zip && \ 16 | rm trial_shell.zip && \ 17 | rm trial_shell/models/{all_10000.pth,all_20000.pth,10000.pth,20000.pth,30000.pth} && \ 18 | mv trial_shell/models/all_30000.pth trial_shell/models/30000.pth 19 | RUN gdown -O trial_skull.zip "https://drive.google.com/uc?id=1MVHSnf3Z42ZcRPk-29qXfjYgS1CKPuhm" && \ 20 | unzip trial_skull.zip && \ 21 | rm trial_skull.zip && \ 22 | rm trial_skull/models/{30000.pth,40000.pth} 23 | RUN gdown -O trial_dog.zip "https://drive.google.com/uc?id=1iHdCRXG_Y7Z_fTwFPMHAnHYGcmNpaHVn" && \ 24 | unzip trial_dog.zip && \ 25 | rm trial_dog.zip && \ 26 | rm trial_dog/models/{40000.pth,60000.pth} 27 | RUN gdown -O trial_panda.zip "https://drive.google.com/uc?id=1p1oRxpljgc2_M4NfaRrxmfNeC8RWAw8V" && \ 28 | unzip trial_panda.zip && \ 29 | rm trial_panda.zip && \ 30 | rm trial_panda/models/30000.pth 31 | RUN gdown -O good_ffhq_full_512.zip "https://drive.google.com/uc?id=1oBxHC16Vpm-_9xWkuM43MHGQMMVijyJA" && \ 32 | unzip good_ffhq_full_512.zip && \ 33 | rm good_ffhq_full_512.zip && \ 34 | mv good_ffhq_full_512/models/all_100000.pth good_ffhq_full_512/models/100000.pth 35 | RUN gdown -O good_art_1k_512.zip "https://drive.google.com/uc?id=1RHTmh0dWM0Mg-S8_maKv5Up3m6wuwY08" && \ 36 | unzip good_art_1k_512.zip && \ 37 | rm good_art_1k_512.zip && \ 38 | mv good_art_1k_512/models/all_50000.pth good_art_1k_512/models/50000.pth 39 | 40 | RUN pip install \ 41 | tqdm==4.56.0 \ 42 | scipy==1.6.0 \ 43 | scikit-image==0.18.1 \ 44 | ipdb==0.13.4 \ 45 | pandas==1.2.1 \ 46 | lmdb==1.0.0 \ 47 | opencv-python==4.5.1.48 \ 48 | easing-functions==1.0.4 49 | 50 | COPY docker/infer.sh infer.sh 51 | RUN chmod +x infer.sh 52 | ENTRYPOINT ["./infer.sh"] 53 | -------------------------------------------------------------------------------- /docker/build-and-push.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash -eux 2 | 3 | # Run this script from the repo's root folder 4 | # 5 | # $ ./docker/build-and-push.sh 6 | 7 | # 1. Build Docker images for CPU and GPU 8 | 9 | image="us-docker.pkg.dev/replicate/odegeasslbc/fastgan" 10 | cpu_tag="$image:cpu" 11 | gpu_tag="$image:gpu" 12 | 13 | docker build -f docker/Dockerfile.cpu --tag "$cpu_tag" . 14 | docker build -f docker/Dockerfile.gpu --tag "$gpu_tag" . 15 | 16 | # 2. Test Docker images 17 | 18 | test_output_folder=/tmp/test-chromagan/output 19 | 20 | docker run -it --rm \ 21 | -v $test_output_folder/cpu:/outputs \ 22 | $cpu_tag \ 23 | art --n_sample=20 24 | 25 | [ -f $test_output_folder/cpu/0.png ] || exit 1 26 | [ -f $test_output_folder/cpu/9.png ] || exit 1 27 | 28 | docker run --gpus all -it --rm \ 29 | -v $test_output_folder/gpu:/outputs \ 30 | $gpu_tag \ 31 | art --n_sample=20 32 | 33 | [ -f $test_output_folder/gpu/0.png ] || exit 1 34 | [ -f $test_output_folder/gpu/9.png ] || exit 1 35 | 36 | sudo rm -rf "$test_output_folder" 37 | 38 | # 3. Push Docker images 39 | 40 | docker push $cpu_tag 41 | docker push $gpu_tag 42 | -------------------------------------------------------------------------------- /docker/infer.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash -eu 2 | 3 | # The eval.py scripts in the various pre-trained model folders differ slightly. 4 | # * The model iteration is different 5 | # * The range() statement that selects the checkpoint iteration sometimes includes +1 on end_iter, sometimes not 6 | # * The image size differs 7 | # * The batch size differs 8 | 9 | case $1 in 10 | 11 | shell) 12 | model="trial_shell" 13 | start_iter=3 14 | end_iter=4 15 | size=1024 16 | batch_size=8 17 | ;; 18 | 19 | skull) 20 | model="trial_skull" 21 | start_iter=5 22 | end_iter=6 23 | size=1024 24 | batch_size=8 25 | ;; 26 | 27 | dog) 28 | model="trial_dog" 29 | start_iter=8 30 | end_iter=8 31 | size=256 32 | batch_size=8 33 | ;; 34 | 35 | art) 36 | model="good_art_1k_512" 37 | start_iter=5 38 | end_iter=5 39 | size=512 40 | batch_size=12 41 | ;; 42 | 43 | face) 44 | model="good_ffhq_full_512" 45 | start_iter=10 46 | end_iter=10 47 | size=512 48 | batch_size=16 49 | ;; 50 | 51 | *) 52 | echo "Unknown model '$1', valid options are: 'art', 'face', 'shell', 'skull', 'dog'." 53 | exit 1 54 | ;; 55 | esac 56 | 57 | shift 1 58 | 59 | cd $model 60 | python eval.py --start_iter=$start_iter --end_iter=$end_iter --im_size=$size --size=$size --batch=$batch_size $@ 61 | mv eval_${start_iter}0000/img/* /outputs/ 62 | -------------------------------------------------------------------------------- /eval.py: -------------------------------------------------------------------------------- 1 | import torch 2 | from torch import nn 3 | from torch import optim 4 | import torch.nn.functional as F 5 | from torchvision.datasets import ImageFolder 6 | from torch.utils.data import DataLoader 7 | from torchvision import utils as vutils 8 | 9 | import os 10 | import random 11 | import argparse 12 | from tqdm import tqdm 13 | 14 | from models import Generator 15 | 16 | 17 | def load_params(model, new_param): 18 | for p, new_p in zip(model.parameters(), new_param): 19 | p.data.copy_(new_p) 20 | 21 | def resize(img,size=256): 22 | return F.interpolate(img, size=size) 23 | 24 | def batch_generate(zs, netG, batch=8): 25 | g_images = [] 26 | with torch.no_grad(): 27 | for i in range(len(zs)//batch): 28 | g_images.append( netG(zs[i*batch:(i+1)*batch]).cpu() ) 29 | if len(zs)%batch>0: 30 | g_images.append( netG(zs[-(len(zs)%batch):]).cpu() ) 31 | return torch.cat(g_images) 32 | 33 | def batch_save(images, folder_name): 34 | if not os.path.exists(folder_name): 35 | os.mkdir(folder_name) 36 | for i, image in enumerate(images): 37 | vutils.save_image(image.add(1).mul(0.5), folder_name+'/%d.jpg'%i) 38 | 39 | 40 | if __name__ == "__main__": 41 | parser = argparse.ArgumentParser( 42 | description='generate images' 43 | ) 44 | parser.add_argument('--ckpt', type=str) 45 | parser.add_argument('--artifacts', type=str, default=".", help='path to artifacts.') 46 | parser.add_argument('--cuda', type=int, default=0, help='index of gpu to use') 47 | parser.add_argument('--start_iter', type=int, default=6) 48 | parser.add_argument('--end_iter', type=int, default=10) 49 | 50 | parser.add_argument('--dist', type=str, default='.') 51 | parser.add_argument('--size', type=int, default=256) 52 | parser.add_argument('--batch', default=16, type=int, help='batch size') 53 | parser.add_argument('--n_sample', type=int, default=2000) 54 | parser.add_argument('--big', action='store_true') 55 | parser.add_argument('--im_size', type=int, default=1024) 56 | parser.add_argument('--multiplier', type=int, default=10000, help='multiplier for model number') 57 | parser.set_defaults(big=False) 58 | args = parser.parse_args() 59 | 60 | noise_dim = 256 61 | device = torch.device('cuda:%d'%(args.cuda)) 62 | 63 | net_ig = Generator( ngf=64, nz=noise_dim, nc=3, im_size=args.im_size)#, big=args.big ) 64 | net_ig.to(device) 65 | 66 | for epoch in [args.multiplier*i for i in range(args.start_iter, args.end_iter+1)]: 67 | ckpt = f"{args.artifacts}/models/{epoch}.pth" 68 | checkpoint = torch.load(ckpt, map_location=lambda a,b: a) 69 | # Remove prefix `module`. 70 | checkpoint['g'] = {k.replace('module.', ''): v for k, v in checkpoint['g'].items()} 71 | net_ig.load_state_dict(checkpoint['g']) 72 | #load_params(net_ig, checkpoint['g_ema']) 73 | 74 | #net_ig.eval() 75 | print('load checkpoint success, epoch %d'%epoch) 76 | 77 | net_ig.to(device) 78 | 79 | del checkpoint 80 | 81 | dist = 'eval_%d'%(epoch) 82 | dist = os.path.join(dist, 'img') 83 | os.makedirs(dist, exist_ok=True) 84 | 85 | with torch.no_grad(): 86 | for i in tqdm(range(args.n_sample//args.batch)): 87 | noise = torch.randn(args.batch, noise_dim).to(device) 88 | g_imgs = net_ig(noise)[0] 89 | g_imgs = resize(g_imgs,args.im_size) # resize the image using given dimension 90 | for j, g_img in enumerate( g_imgs ): 91 | vutils.save_image(g_img.add(1).mul(0.5), 92 | os.path.join(dist, '%d.png'%(i*args.batch+j)))#, normalize=True, range=(-1,1)) 93 | -------------------------------------------------------------------------------- /lpips/__init__.py: -------------------------------------------------------------------------------- 1 | 2 | from __future__ import absolute_import 3 | from __future__ import division 4 | from __future__ import print_function 5 | 6 | import numpy as np 7 | import skimage 8 | import torch 9 | from torch.autograd import Variable 10 | 11 | from lpips import dist_model 12 | 13 | 14 | if skimage.__version__ == '0.14.3': 15 | from skimage.measure import compare_ssim 16 | else: 17 | from skimage.metrics import structural_similarity as compare_ssim 18 | 19 | 20 | 21 | class PerceptualLoss(torch.nn.Module): 22 | def __init__(self, model='net-lin', net='alex', colorspace='rgb', spatial=False, use_gpu=True, gpu_ids=[0]): # VGG using our perceptually-learned weights (LPIPS metric) 23 | # def __init__(self, model='net', net='vgg', use_gpu=True): # "default" way of using VGG as a perceptual loss 24 | super(PerceptualLoss, self).__init__() 25 | print('Setting up Perceptual loss...') 26 | self.use_gpu = use_gpu 27 | self.spatial = spatial 28 | self.gpu_ids = gpu_ids 29 | self.model = dist_model.DistModel() 30 | self.model.initialize(model=model, net=net, use_gpu=use_gpu, colorspace=colorspace, spatial=self.spatial, gpu_ids=gpu_ids) 31 | print('...[%s] initialized'%self.model.name()) 32 | print('...Done') 33 | 34 | def forward(self, pred, target, normalize=False): 35 | """ 36 | Pred and target are Variables. 37 | If normalize is True, assumes the images are between [0,1] and then scales them between [-1,+1] 38 | If normalize is False, assumes the images are already between [-1,+1] 39 | 40 | Inputs pred and target are Nx3xHxW 41 | Output pytorch Variable N long 42 | """ 43 | 44 | if normalize: 45 | target = 2 * target - 1 46 | pred = 2 * pred - 1 47 | 48 | return self.model.forward(target, pred) 49 | 50 | def normalize_tensor(in_feat,eps=1e-10): 51 | norm_factor = torch.sqrt(torch.sum(in_feat**2,dim=1,keepdim=True)) 52 | return in_feat/(norm_factor+eps) 53 | 54 | def l2(p0, p1, range=255.): 55 | return .5*np.mean((p0 / range - p1 / range)**2) 56 | 57 | def psnr(p0, p1, peak=255.): 58 | return 10*np.log10(peak**2/np.mean((1.*p0-1.*p1)**2)) 59 | 60 | def dssim(p0, p1, range=255.): 61 | return (1 - compare_ssim(p0, p1, data_range=range, multichannel=True)) / 2. 62 | 63 | def rgb2lab(in_img,mean_cent=False): 64 | from skimage import color 65 | img_lab = color.rgb2lab(in_img) 66 | if(mean_cent): 67 | img_lab[:,:,0] = img_lab[:,:,0]-50 68 | return img_lab 69 | 70 | def tensor2np(tensor_obj): 71 | # change dimension of a tensor object into a numpy array 72 | return tensor_obj[0].cpu().float().numpy().transpose((1,2,0)) 73 | 74 | def np2tensor(np_obj): 75 | # change dimenion of np array into tensor array 76 | return torch.Tensor(np_obj[:, :, :, np.newaxis].transpose((3, 2, 0, 1))) 77 | 78 | def tensor2tensorlab(image_tensor,to_norm=True,mc_only=False): 79 | # image tensor to lab tensor 80 | from skimage import color 81 | 82 | img = tensor2im(image_tensor) 83 | img_lab = color.rgb2lab(img) 84 | if(mc_only): 85 | img_lab[:,:,0] = img_lab[:,:,0]-50 86 | if(to_norm and not mc_only): 87 | img_lab[:,:,0] = img_lab[:,:,0]-50 88 | img_lab = img_lab/100. 89 | 90 | return np2tensor(img_lab) 91 | 92 | def tensorlab2tensor(lab_tensor,return_inbnd=False): 93 | from skimage import color 94 | import warnings 95 | warnings.filterwarnings("ignore") 96 | 97 | lab = tensor2np(lab_tensor)*100. 98 | lab[:,:,0] = lab[:,:,0]+50 99 | 100 | rgb_back = 255.*np.clip(color.lab2rgb(lab.astype('float')),0,1) 101 | if(return_inbnd): 102 | # convert back to lab, see if we match 103 | lab_back = color.rgb2lab(rgb_back.astype('uint8')) 104 | mask = 1.*np.isclose(lab_back,lab,atol=2.) 105 | mask = np2tensor(np.prod(mask,axis=2)[:,:,np.newaxis]) 106 | return (im2tensor(rgb_back),mask) 107 | else: 108 | return im2tensor(rgb_back) 109 | 110 | def rgb2lab(input): 111 | from skimage import color 112 | return color.rgb2lab(input / 255.) 113 | 114 | def tensor2im(image_tensor, imtype=np.uint8, cent=1., factor=255./2.): 115 | image_numpy = image_tensor[0].cpu().float().numpy() 116 | image_numpy = (np.transpose(image_numpy, (1, 2, 0)) + cent) * factor 117 | return image_numpy.astype(imtype) 118 | 119 | def im2tensor(image, imtype=np.uint8, cent=1., factor=255./2.): 120 | return torch.Tensor((image / factor - cent) 121 | [:, :, :, np.newaxis].transpose((3, 2, 0, 1))) 122 | 123 | def tensor2vec(vector_tensor): 124 | return vector_tensor.data.cpu().numpy()[:, :, 0, 0] 125 | 126 | def voc_ap(rec, prec, use_07_metric=False): 127 | """ ap = voc_ap(rec, prec, [use_07_metric]) 128 | Compute VOC AP given precision and recall. 129 | If use_07_metric is true, uses the 130 | VOC 07 11 point method (default:False). 131 | """ 132 | if use_07_metric: 133 | # 11 point metric 134 | ap = 0. 135 | for t in np.arange(0., 1.1, 0.1): 136 | if np.sum(rec >= t) == 0: 137 | p = 0 138 | else: 139 | p = np.max(prec[rec >= t]) 140 | ap = ap + p / 11. 141 | else: 142 | # correct AP calculation 143 | # first append sentinel values at the end 144 | mrec = np.concatenate(([0.], rec, [1.])) 145 | mpre = np.concatenate(([0.], prec, [0.])) 146 | 147 | # compute the precision envelope 148 | for i in range(mpre.size - 1, 0, -1): 149 | mpre[i - 1] = np.maximum(mpre[i - 1], mpre[i]) 150 | 151 | # to calculate area under PR curve, look for points 152 | # where X axis (recall) changes value 153 | i = np.where(mrec[1:] != mrec[:-1])[0] 154 | 155 | # and sum (\Delta recall) * prec 156 | ap = np.sum((mrec[i + 1] - mrec[i]) * mpre[i + 1]) 157 | return ap 158 | 159 | def tensor2im(image_tensor, imtype=np.uint8, cent=1., factor=255./2.): 160 | # def tensor2im(image_tensor, imtype=np.uint8, cent=1., factor=1.): 161 | image_numpy = image_tensor[0].cpu().float().numpy() 162 | image_numpy = (np.transpose(image_numpy, (1, 2, 0)) + cent) * factor 163 | return image_numpy.astype(imtype) 164 | 165 | def im2tensor(image, imtype=np.uint8, cent=1., factor=255./2.): 166 | # def im2tensor(image, imtype=np.uint8, cent=1., factor=1.): 167 | return torch.Tensor((image / factor - cent) 168 | [:, :, :, np.newaxis].transpose((3, 2, 0, 1))) 169 | -------------------------------------------------------------------------------- /lpips/__pycache__/__init__.cpython-37.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/odegeasslbc/FastGAN-pytorch/1a848e5bce265c50e0ee38c932c256d5aa6f9880/lpips/__pycache__/__init__.cpython-37.pyc -------------------------------------------------------------------------------- /lpips/__pycache__/__init__.cpython-38.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/odegeasslbc/FastGAN-pytorch/1a848e5bce265c50e0ee38c932c256d5aa6f9880/lpips/__pycache__/__init__.cpython-38.pyc -------------------------------------------------------------------------------- /lpips/__pycache__/base_model.cpython-37.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/odegeasslbc/FastGAN-pytorch/1a848e5bce265c50e0ee38c932c256d5aa6f9880/lpips/__pycache__/base_model.cpython-37.pyc -------------------------------------------------------------------------------- /lpips/__pycache__/base_model.cpython-38.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/odegeasslbc/FastGAN-pytorch/1a848e5bce265c50e0ee38c932c256d5aa6f9880/lpips/__pycache__/base_model.cpython-38.pyc -------------------------------------------------------------------------------- /lpips/__pycache__/dist_model.cpython-37.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/odegeasslbc/FastGAN-pytorch/1a848e5bce265c50e0ee38c932c256d5aa6f9880/lpips/__pycache__/dist_model.cpython-37.pyc -------------------------------------------------------------------------------- /lpips/__pycache__/dist_model.cpython-38.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/odegeasslbc/FastGAN-pytorch/1a848e5bce265c50e0ee38c932c256d5aa6f9880/lpips/__pycache__/dist_model.cpython-38.pyc -------------------------------------------------------------------------------- /lpips/__pycache__/networks_basic.cpython-37.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/odegeasslbc/FastGAN-pytorch/1a848e5bce265c50e0ee38c932c256d5aa6f9880/lpips/__pycache__/networks_basic.cpython-37.pyc -------------------------------------------------------------------------------- /lpips/__pycache__/networks_basic.cpython-38.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/odegeasslbc/FastGAN-pytorch/1a848e5bce265c50e0ee38c932c256d5aa6f9880/lpips/__pycache__/networks_basic.cpython-38.pyc -------------------------------------------------------------------------------- /lpips/__pycache__/pretrained_networks.cpython-37.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/odegeasslbc/FastGAN-pytorch/1a848e5bce265c50e0ee38c932c256d5aa6f9880/lpips/__pycache__/pretrained_networks.cpython-37.pyc -------------------------------------------------------------------------------- /lpips/__pycache__/pretrained_networks.cpython-38.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/odegeasslbc/FastGAN-pytorch/1a848e5bce265c50e0ee38c932c256d5aa6f9880/lpips/__pycache__/pretrained_networks.cpython-38.pyc -------------------------------------------------------------------------------- /lpips/base_model.py: -------------------------------------------------------------------------------- 1 | import os 2 | import torch 3 | from torch.autograd import Variable 4 | from pdb import set_trace as st 5 | from IPython import embed 6 | 7 | class BaseModel(): 8 | def __init__(self): 9 | pass; 10 | 11 | def name(self): 12 | return 'BaseModel' 13 | 14 | def initialize(self, use_gpu=True, gpu_ids=[0]): 15 | self.use_gpu = use_gpu 16 | self.gpu_ids = gpu_ids 17 | 18 | def forward(self): 19 | pass 20 | 21 | def get_image_paths(self): 22 | pass 23 | 24 | def optimize_parameters(self): 25 | pass 26 | 27 | def get_current_visuals(self): 28 | return self.input 29 | 30 | def get_current_errors(self): 31 | return {} 32 | 33 | def save(self, label): 34 | pass 35 | 36 | # helper saving function that can be used by subclasses 37 | def save_network(self, network, path, network_label, epoch_label): 38 | save_filename = '%s_net_%s.pth' % (epoch_label, network_label) 39 | save_path = os.path.join(path, save_filename) 40 | torch.save(network.state_dict(), save_path) 41 | 42 | # helper loading function that can be used by subclasses 43 | def load_network(self, network, network_label, epoch_label): 44 | save_filename = '%s_net_%s.pth' % (epoch_label, network_label) 45 | save_path = os.path.join(self.save_dir, save_filename) 46 | print('Loading network from %s'%save_path) 47 | network.load_state_dict(torch.load(save_path)) 48 | 49 | def update_learning_rate(): 50 | pass 51 | 52 | def get_image_paths(self): 53 | return self.image_paths 54 | 55 | def save_done(self, flag=False): 56 | np.save(os.path.join(self.save_dir, 'done_flag'),flag) 57 | np.savetxt(os.path.join(self.save_dir, 'done_flag'),[flag,],fmt='%i') 58 | 59 | -------------------------------------------------------------------------------- /lpips/dist_model.py: -------------------------------------------------------------------------------- 1 | 2 | from __future__ import absolute_import 3 | 4 | import sys 5 | import numpy as np 6 | import torch 7 | from torch import nn 8 | import os 9 | from collections import OrderedDict 10 | from torch.autograd import Variable 11 | import itertools 12 | from .base_model import BaseModel 13 | from scipy.ndimage import zoom 14 | import fractions 15 | import functools 16 | import skimage.transform 17 | from tqdm import tqdm 18 | 19 | from IPython import embed 20 | 21 | from . import networks_basic as networks 22 | import lpips as util 23 | 24 | class DistModel(BaseModel): 25 | def name(self): 26 | return self.model_name 27 | 28 | def initialize(self, model='net-lin', net='alex', colorspace='Lab', pnet_rand=False, pnet_tune=False, model_path=None, 29 | use_gpu=True, printNet=False, spatial=False, 30 | is_train=False, lr=.0001, beta1=0.5, version='0.1', gpu_ids=[0]): 31 | ''' 32 | INPUTS 33 | model - ['net-lin'] for linearly calibrated network 34 | ['net'] for off-the-shelf network 35 | ['L2'] for L2 distance in Lab colorspace 36 | ['SSIM'] for ssim in RGB colorspace 37 | net - ['squeeze','alex','vgg'] 38 | model_path - if None, will look in weights/[NET_NAME].pth 39 | colorspace - ['Lab','RGB'] colorspace to use for L2 and SSIM 40 | use_gpu - bool - whether or not to use a GPU 41 | printNet - bool - whether or not to print network architecture out 42 | spatial - bool - whether to output an array containing varying distances across spatial dimensions 43 | spatial_shape - if given, output spatial shape. if None then spatial shape is determined automatically via spatial_factor (see below). 44 | spatial_factor - if given, specifies upsampling factor relative to the largest spatial extent of a convolutional layer. if None then resized to size of input images. 45 | spatial_order - spline order of filter for upsampling in spatial mode, by default 1 (bilinear). 46 | is_train - bool - [True] for training mode 47 | lr - float - initial learning rate 48 | beta1 - float - initial momentum term for adam 49 | version - 0.1 for latest, 0.0 was original (with a bug) 50 | gpu_ids - int array - [0] by default, gpus to use 51 | ''' 52 | BaseModel.initialize(self, use_gpu=use_gpu, gpu_ids=gpu_ids) 53 | 54 | self.model = model 55 | self.net = net 56 | self.is_train = is_train 57 | self.spatial = spatial 58 | self.gpu_ids = gpu_ids 59 | self.model_name = '%s [%s]'%(model,net) 60 | 61 | if(self.model == 'net-lin'): # pretrained net + linear layer 62 | self.net = networks.PNetLin(pnet_rand=pnet_rand, pnet_tune=pnet_tune, pnet_type=net, 63 | use_dropout=True, spatial=spatial, version=version, lpips=True) 64 | kw = {} 65 | if not use_gpu: 66 | kw['map_location'] = 'cpu' 67 | if(model_path is None): 68 | import inspect 69 | model_path = os.path.abspath(os.path.join(inspect.getfile(self.initialize), '..', 'weights/v%s/%s.pth'%(version,net))) 70 | 71 | if(not is_train): 72 | print('Loading model from: %s'%model_path) 73 | self.net.load_state_dict(torch.load(model_path, **kw), strict=False) 74 | 75 | elif(self.model=='net'): # pretrained network 76 | self.net = networks.PNetLin(pnet_rand=pnet_rand, pnet_type=net, lpips=False) 77 | elif(self.model in ['L2','l2']): 78 | self.net = networks.L2(use_gpu=use_gpu,colorspace=colorspace) # not really a network, only for testing 79 | self.model_name = 'L2' 80 | elif(self.model in ['DSSIM','dssim','SSIM','ssim']): 81 | self.net = networks.DSSIM(use_gpu=use_gpu,colorspace=colorspace) 82 | self.model_name = 'SSIM' 83 | else: 84 | raise ValueError("Model [%s] not recognized." % self.model) 85 | 86 | self.parameters = list(self.net.parameters()) 87 | 88 | if self.is_train: # training mode 89 | # extra network on top to go from distances (d0,d1) => predicted human judgment (h*) 90 | self.rankLoss = networks.BCERankingLoss() 91 | self.parameters += list(self.rankLoss.net.parameters()) 92 | self.lr = lr 93 | self.old_lr = lr 94 | self.optimizer_net = torch.optim.Adam(self.parameters, lr=lr, betas=(beta1, 0.999)) 95 | else: # test mode 96 | self.net.eval() 97 | 98 | if(use_gpu): 99 | self.net.to(gpu_ids[0]) 100 | self.net = torch.nn.DataParallel(self.net, device_ids=gpu_ids) 101 | if(self.is_train): 102 | self.rankLoss = self.rankLoss.to(device=gpu_ids[0]) # just put this on GPU0 103 | 104 | if(printNet): 105 | print('---------- Networks initialized -------------') 106 | networks.print_network(self.net) 107 | print('-----------------------------------------------') 108 | 109 | def forward(self, in0, in1, retPerLayer=False): 110 | ''' Function computes the distance between image patches in0 and in1 111 | INPUTS 112 | in0, in1 - torch.Tensor object of shape Nx3xXxY - image patch scaled to [-1,1] 113 | OUTPUT 114 | computed distances between in0 and in1 115 | ''' 116 | 117 | return self.net.forward(in0, in1, retPerLayer=retPerLayer) 118 | 119 | # ***** TRAINING FUNCTIONS ***** 120 | def optimize_parameters(self): 121 | self.forward_train() 122 | self.optimizer_net.zero_grad() 123 | self.backward_train() 124 | self.optimizer_net.step() 125 | self.clamp_weights() 126 | 127 | def clamp_weights(self): 128 | for module in self.net.modules(): 129 | if(hasattr(module, 'weight') and module.kernel_size==(1,1)): 130 | module.weight.data = torch.clamp(module.weight.data,min=0) 131 | 132 | def set_input(self, data): 133 | self.input_ref = data['ref'] 134 | self.input_p0 = data['p0'] 135 | self.input_p1 = data['p1'] 136 | self.input_judge = data['judge'] 137 | 138 | if(self.use_gpu): 139 | self.input_ref = self.input_ref.to(device=self.gpu_ids[0]) 140 | self.input_p0 = self.input_p0.to(device=self.gpu_ids[0]) 141 | self.input_p1 = self.input_p1.to(device=self.gpu_ids[0]) 142 | self.input_judge = self.input_judge.to(device=self.gpu_ids[0]) 143 | 144 | self.var_ref = Variable(self.input_ref,requires_grad=True) 145 | self.var_p0 = Variable(self.input_p0,requires_grad=True) 146 | self.var_p1 = Variable(self.input_p1,requires_grad=True) 147 | 148 | def forward_train(self): # run forward pass 149 | # print(self.net.module.scaling_layer.shift) 150 | # print(torch.norm(self.net.module.net.slice1[0].weight).item(), torch.norm(self.net.module.lin0.model[1].weight).item()) 151 | 152 | self.d0 = self.forward(self.var_ref, self.var_p0) 153 | self.d1 = self.forward(self.var_ref, self.var_p1) 154 | self.acc_r = self.compute_accuracy(self.d0,self.d1,self.input_judge) 155 | 156 | self.var_judge = Variable(1.*self.input_judge).view(self.d0.size()) 157 | 158 | self.loss_total = self.rankLoss.forward(self.d0, self.d1, self.var_judge*2.-1.) 159 | 160 | return self.loss_total 161 | 162 | def backward_train(self): 163 | torch.mean(self.loss_total).backward() 164 | 165 | def compute_accuracy(self,d0,d1,judge): 166 | ''' d0, d1 are Variables, judge is a Tensor ''' 167 | d1_lt_d0 = (d1 %f' % (type,self.old_lr, lr)) 210 | self.old_lr = lr 211 | 212 | def score_2afc_dataset(data_loader, func, name=''): 213 | ''' Function computes Two Alternative Forced Choice (2AFC) score using 214 | distance function 'func' in dataset 'data_loader' 215 | INPUTS 216 | data_loader - CustomDatasetDataLoader object - contains a TwoAFCDataset inside 217 | func - callable distance function - calling d=func(in0,in1) should take 2 218 | pytorch tensors with shape Nx3xXxY, and return numpy array of length N 219 | OUTPUTS 220 | [0] - 2AFC score in [0,1], fraction of time func agrees with human evaluators 221 | [1] - dictionary with following elements 222 | d0s,d1s - N arrays containing distances between reference patch to perturbed patches 223 | gts - N array in [0,1], preferred patch selected by human evaluators 224 | (closer to "0" for left patch p0, "1" for right patch p1, 225 | "0.6" means 60pct people preferred right patch, 40pct preferred left) 226 | scores - N array in [0,1], corresponding to what percentage function agreed with humans 227 | CONSTS 228 | N - number of test triplets in data_loader 229 | ''' 230 | 231 | d0s = [] 232 | d1s = [] 233 | gts = [] 234 | 235 | for data in tqdm(data_loader.load_data(), desc=name): 236 | d0s+=func(data['ref'],data['p0']).data.cpu().numpy().flatten().tolist() 237 | d1s+=func(data['ref'],data['p1']).data.cpu().numpy().flatten().tolist() 238 | gts+=data['judge'].cpu().numpy().flatten().tolist() 239 | 240 | d0s = np.array(d0s) 241 | d1s = np.array(d1s) 242 | gts = np.array(gts) 243 | scores = (d0s 256: 150 | self.feat_512 = UpBlockComp(nfc[256], nfc[512]) 151 | self.se_512 = SEBlock(nfc[32], nfc[512]) 152 | if im_size > 512: 153 | self.feat_1024 = UpBlock(nfc[512], nfc[1024]) 154 | 155 | def forward(self, input): 156 | 157 | feat_4 = self.init(input) 158 | feat_8 = self.feat_8(feat_4) 159 | feat_16 = self.feat_16(feat_8) 160 | feat_32 = self.feat_32(feat_16) 161 | 162 | feat_64 = self.se_64( feat_4, self.feat_64(feat_32) ) 163 | 164 | feat_128 = self.se_128( feat_8, self.feat_128(feat_64) ) 165 | 166 | feat_256 = self.se_256( feat_16, self.feat_256(feat_128) ) 167 | 168 | if self.im_size == 256: 169 | return [self.to_big(feat_256), self.to_128(feat_128)] 170 | 171 | feat_512 = self.se_512( feat_32, self.feat_512(feat_256) ) 172 | if self.im_size == 512: 173 | return [self.to_big(feat_512), self.to_128(feat_128)] 174 | 175 | feat_1024 = self.feat_1024(feat_512) 176 | 177 | im_128 = torch.tanh(self.to_128(feat_128)) 178 | im_1024 = torch.tanh(self.to_big(feat_1024)) 179 | 180 | return [im_1024, im_128] 181 | 182 | 183 | class DownBlock(nn.Module): 184 | def __init__(self, in_planes, out_planes): 185 | super(DownBlock, self).__init__() 186 | 187 | self.main = nn.Sequential( 188 | conv2d(in_planes, out_planes, 4, 2, 1, bias=False), 189 | batchNorm2d(out_planes), nn.LeakyReLU(0.2, inplace=True), 190 | ) 191 | 192 | def forward(self, feat): 193 | return self.main(feat) 194 | 195 | 196 | class DownBlockComp(nn.Module): 197 | def __init__(self, in_planes, out_planes): 198 | super(DownBlockComp, self).__init__() 199 | 200 | self.main = nn.Sequential( 201 | conv2d(in_planes, out_planes, 4, 2, 1, bias=False), 202 | batchNorm2d(out_planes), nn.LeakyReLU(0.2, inplace=True), 203 | conv2d(out_planes, out_planes, 3, 1, 1, bias=False), 204 | batchNorm2d(out_planes), nn.LeakyReLU(0.2) 205 | ) 206 | 207 | self.direct = nn.Sequential( 208 | nn.AvgPool2d(2, 2), 209 | conv2d(in_planes, out_planes, 1, 1, 0, bias=False), 210 | batchNorm2d(out_planes), nn.LeakyReLU(0.2)) 211 | 212 | def forward(self, feat): 213 | return (self.main(feat) + self.direct(feat)) / 2 214 | 215 | 216 | class Discriminator(nn.Module): 217 | def __init__(self, ndf=64, nc=3, im_size=512): 218 | super(Discriminator, self).__init__() 219 | self.ndf = ndf 220 | self.im_size = im_size 221 | 222 | nfc_multi = {4:16, 8:16, 16:8, 32:4, 64:2, 128:1, 256:0.5, 512:0.25, 1024:0.125} 223 | nfc = {} 224 | for k, v in nfc_multi.items(): 225 | nfc[k] = int(v*ndf) 226 | 227 | if im_size == 1024: 228 | self.down_from_big = nn.Sequential( 229 | conv2d(nc, nfc[1024], 4, 2, 1, bias=False), 230 | nn.LeakyReLU(0.2, inplace=True), 231 | conv2d(nfc[1024], nfc[512], 4, 2, 1, bias=False), 232 | batchNorm2d(nfc[512]), 233 | nn.LeakyReLU(0.2, inplace=True)) 234 | elif im_size == 512: 235 | self.down_from_big = nn.Sequential( 236 | conv2d(nc, nfc[512], 4, 2, 1, bias=False), 237 | nn.LeakyReLU(0.2, inplace=True) ) 238 | elif im_size == 256: 239 | self.down_from_big = nn.Sequential( 240 | conv2d(nc, nfc[512], 3, 1, 1, bias=False), 241 | nn.LeakyReLU(0.2, inplace=True) ) 242 | 243 | self.down_4 = DownBlockComp(nfc[512], nfc[256]) 244 | self.down_8 = DownBlockComp(nfc[256], nfc[128]) 245 | self.down_16 = DownBlockComp(nfc[128], nfc[64]) 246 | self.down_32 = DownBlockComp(nfc[64], nfc[32]) 247 | self.down_64 = DownBlockComp(nfc[32], nfc[16]) 248 | 249 | self.rf_big = nn.Sequential( 250 | conv2d(nfc[16] , nfc[8], 1, 1, 0, bias=False), 251 | batchNorm2d(nfc[8]), nn.LeakyReLU(0.2, inplace=True), 252 | conv2d(nfc[8], 1, 4, 1, 0, bias=False)) 253 | 254 | self.se_2_16 = SEBlock(nfc[512], nfc[64]) 255 | self.se_4_32 = SEBlock(nfc[256], nfc[32]) 256 | self.se_8_64 = SEBlock(nfc[128], nfc[16]) 257 | 258 | self.down_from_small = nn.Sequential( 259 | conv2d(nc, nfc[256], 4, 2, 1, bias=False), 260 | nn.LeakyReLU(0.2, inplace=True), 261 | DownBlock(nfc[256], nfc[128]), 262 | DownBlock(nfc[128], nfc[64]), 263 | DownBlock(nfc[64], nfc[32]), ) 264 | 265 | self.rf_small = conv2d(nfc[32], 1, 4, 1, 0, bias=False) 266 | 267 | self.decoder_big = SimpleDecoder(nfc[16], nc) 268 | self.decoder_part = SimpleDecoder(nfc[32], nc) 269 | self.decoder_small = SimpleDecoder(nfc[32], nc) 270 | 271 | def forward(self, imgs, label, part=None): 272 | if type(imgs) is not list: 273 | imgs = [F.interpolate(imgs, size=self.im_size), F.interpolate(imgs, size=128)] 274 | 275 | feat_2 = self.down_from_big(imgs[0]) 276 | feat_4 = self.down_4(feat_2) 277 | feat_8 = self.down_8(feat_4) 278 | 279 | feat_16 = self.down_16(feat_8) 280 | feat_16 = self.se_2_16(feat_2, feat_16) 281 | 282 | feat_32 = self.down_32(feat_16) 283 | feat_32 = self.se_4_32(feat_4, feat_32) 284 | 285 | feat_last = self.down_64(feat_32) 286 | feat_last = self.se_8_64(feat_8, feat_last) 287 | 288 | #rf_0 = torch.cat([self.rf_big_1(feat_last).view(-1),self.rf_big_2(feat_last).view(-1)]) 289 | #rff_big = torch.sigmoid(self.rf_factor_big) 290 | rf_0 = self.rf_big(feat_last).view(-1) 291 | 292 | feat_small = self.down_from_small(imgs[1]) 293 | #rf_1 = torch.cat([self.rf_small_1(feat_small).view(-1),self.rf_small_2(feat_small).view(-1)]) 294 | rf_1 = self.rf_small(feat_small).view(-1) 295 | 296 | if label=='real': 297 | rec_img_big = self.decoder_big(feat_last) 298 | rec_img_small = self.decoder_small(feat_small) 299 | 300 | assert part is not None 301 | rec_img_part = None 302 | if part==0: 303 | rec_img_part = self.decoder_part(feat_32[:,:,:8,:8]) 304 | if part==1: 305 | rec_img_part = self.decoder_part(feat_32[:,:,:8,8:]) 306 | if part==2: 307 | rec_img_part = self.decoder_part(feat_32[:,:,8:,:8]) 308 | if part==3: 309 | rec_img_part = self.decoder_part(feat_32[:,:,8:,8:]) 310 | 311 | return torch.cat([rf_0, rf_1]) , [rec_img_big, rec_img_small, rec_img_part] 312 | 313 | return torch.cat([rf_0, rf_1]) 314 | 315 | 316 | class SimpleDecoder(nn.Module): 317 | """docstring for CAN_SimpleDecoder""" 318 | def __init__(self, nfc_in=64, nc=3): 319 | super(SimpleDecoder, self).__init__() 320 | 321 | nfc_multi = {4:16, 8:8, 16:4, 32:2, 64:2, 128:1, 256:0.5, 512:0.25, 1024:0.125} 322 | nfc = {} 323 | for k, v in nfc_multi.items(): 324 | nfc[k] = int(v*32) 325 | 326 | def upBlock(in_planes, out_planes): 327 | block = nn.Sequential( 328 | nn.Upsample(scale_factor=2, mode='nearest'), 329 | conv2d(in_planes, out_planes*2, 3, 1, 1, bias=False), 330 | batchNorm2d(out_planes*2), GLU()) 331 | return block 332 | 333 | self.main = nn.Sequential( nn.AdaptiveAvgPool2d(8), 334 | upBlock(nfc_in, nfc[16]) , 335 | upBlock(nfc[16], nfc[32]), 336 | upBlock(nfc[32], nfc[64]), 337 | upBlock(nfc[64], nfc[128]), 338 | conv2d(nfc[128], nc, 3, 1, 1, bias=False), 339 | nn.Tanh() ) 340 | 341 | def forward(self, input): 342 | # input shape: c x 4 x 4 343 | return self.main(input) 344 | 345 | from random import randint 346 | def random_crop(image, size): 347 | h, w = image.shape[2:] 348 | ch = randint(0, h-size-1) 349 | cw = randint(0, w-size-1) 350 | return image[:,:,ch:ch+size,cw:cw+size] 351 | 352 | class TextureDiscriminator(nn.Module): 353 | def __init__(self, ndf=64, nc=3, im_size=512): 354 | super(TextureDiscriminator, self).__init__() 355 | self.ndf = ndf 356 | self.im_size = im_size 357 | 358 | nfc_multi = {4:16, 8:8, 16:8, 32:4, 64:2, 128:1, 256:0.5, 512:0.25, 1024:0.125} 359 | nfc = {} 360 | for k, v in nfc_multi.items(): 361 | nfc[k] = int(v*ndf) 362 | 363 | self.down_from_small = nn.Sequential( 364 | conv2d(nc, nfc[256], 4, 2, 1, bias=False), 365 | nn.LeakyReLU(0.2, inplace=True), 366 | DownBlock(nfc[256], nfc[128]), 367 | DownBlock(nfc[128], nfc[64]), 368 | DownBlock(nfc[64], nfc[32]), ) 369 | self.rf_small = nn.Sequential( 370 | conv2d(nfc[16], 1, 4, 1, 0, bias=False)) 371 | 372 | self.decoder_small = SimpleDecoder(nfc[32], nc) 373 | 374 | def forward(self, img, label): 375 | img = random_crop(img, size=128) 376 | 377 | feat_small = self.down_from_small(img) 378 | rf = self.rf_small(feat_small).view(-1) 379 | 380 | if label=='real': 381 | rec_img_small = self.decoder_small(feat_small) 382 | 383 | return rf, rec_img_small, img 384 | 385 | return rf -------------------------------------------------------------------------------- /operation.py: -------------------------------------------------------------------------------- 1 | import os 2 | import numpy as np 3 | import torch 4 | import torch.utils.data as data 5 | from torch.utils.data import Dataset 6 | from PIL import Image 7 | from copy import deepcopy 8 | import shutil 9 | import json 10 | 11 | def InfiniteSampler(n): 12 | """Data sampler""" 13 | # check if the number of samples is valid 14 | if n <= 0: 15 | raise ValueError(f"Invalid number of samples: {n}.\nMake sure that images are present in the given path.") 16 | i = n - 1 17 | order = np.random.permutation(n) 18 | while True: 19 | yield order[i] 20 | i += 1 21 | if i >= n: 22 | np.random.seed() 23 | order = np.random.permutation(n) 24 | i = 0 25 | 26 | 27 | class InfiniteSamplerWrapper(data.sampler.Sampler): 28 | """Data sampler wrapper""" 29 | def __init__(self, data_source): 30 | self.num_samples = len(data_source) 31 | 32 | def __iter__(self): 33 | return iter(InfiniteSampler(self.num_samples)) 34 | 35 | def __len__(self): 36 | return 2 ** 31 37 | 38 | 39 | def copy_G_params(model): 40 | flatten = deepcopy(list(p.data for p in model.parameters())) 41 | return flatten 42 | 43 | 44 | def load_params(model, new_param): 45 | for p, new_p in zip(model.parameters(), new_param): 46 | p.data.copy_(new_p) 47 | 48 | 49 | def get_dir(args): 50 | 51 | if not os.path.exists(args.output_path): 52 | os.makedirs(args.output_path) 53 | 54 | task_name = os.path.join(args.output_path, 'train_results', args.name) 55 | saved_model_folder = os.path.join(task_name, 'models') 56 | saved_image_folder = os.path.join(task_name, 'images') 57 | 58 | os.makedirs(saved_model_folder, exist_ok=True) 59 | os.makedirs(saved_image_folder, exist_ok=True) 60 | 61 | for f in os.listdir('./'): 62 | if '.py' in f: 63 | shutil.copy(f, os.path.join(task_name, f)) 64 | 65 | with open(os.path.join(saved_model_folder, '../args.txt'), 'w') as f: 66 | json.dump(args.__dict__, f, indent=2) 67 | 68 | return saved_model_folder, saved_image_folder 69 | 70 | 71 | 72 | 73 | class ImageFolder(Dataset): 74 | """docstring for ArtDataset""" 75 | def __init__(self, root, transform=None): 76 | super( ImageFolder, self).__init__() 77 | self.root = root 78 | 79 | self.frame = self._parse_frame() 80 | self.transform = transform 81 | 82 | def _parse_frame(self): 83 | frame = [] 84 | img_names = os.listdir(self.root) 85 | img_names.sort() 86 | for i in range(len(img_names)): 87 | image_path = os.path.join(self.root, img_names[i]) 88 | if image_path[-4:] == '.jpg' or image_path[-4:] == '.png' or image_path[-5:] == '.jpeg': 89 | frame.append(image_path) 90 | return frame 91 | 92 | def __len__(self): 93 | return len(self.frame) 94 | 95 | def __getitem__(self, idx): 96 | file = self.frame[idx] 97 | img = Image.open(file).convert('RGB') 98 | 99 | if self.transform: 100 | img = self.transform(img) 101 | 102 | return img 103 | 104 | 105 | 106 | from io import BytesIO 107 | import lmdb 108 | from torch.utils.data import Dataset 109 | 110 | 111 | class MultiResolutionDataset(Dataset): 112 | def __init__(self, path, transform, resolution=256): 113 | self.env = lmdb.open( 114 | path, 115 | max_readers=32, 116 | readonly=True, 117 | lock=False, 118 | readahead=False, 119 | meminit=False, 120 | ) 121 | 122 | if not self.env: 123 | raise IOError('Cannot open lmdb dataset', path) 124 | 125 | with self.env.begin(write=False) as txn: 126 | self.length = int(txn.get('length'.encode('utf-8')).decode('utf-8')) 127 | 128 | self.resolution = resolution 129 | self.transform = transform 130 | 131 | def __len__(self): 132 | return self.length 133 | 134 | def __getitem__(self, index): 135 | with self.env.begin(write=False) as txn: 136 | key = f'{self.resolution}-{str(index).zfill(5)}'.encode('utf-8') 137 | img_bytes = txn.get(key) 138 | #key_asp = f'aspect_ratio-{str(index).zfill(5)}'.encode('utf-8') 139 | #aspect_ratio = float(txn.get(key_asp).decode()) 140 | 141 | buffer = BytesIO(img_bytes) 142 | img = Image.open(buffer) 143 | img = self.transform(img) 144 | 145 | return img 146 | 147 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | torch==2.0.0 2 | pandas==1.5.3 3 | numpy==1.23.5 4 | tqdm==4.64.1 5 | scipy==1.10.1 6 | scikit-image==0.20.0 7 | ipdb==0.13.3 8 | lmdb==1.4.1 9 | opencv-python==4.5.4.60 10 | easing-functions==1.0.4 11 | torchvision==0.15.1 12 | -------------------------------------------------------------------------------- /scripts/find_nearest_neighbor.py: -------------------------------------------------------------------------------- 1 | from eval import load_params 2 | import torch 3 | from torch import nn 4 | from torch import optim 5 | import torch.nn.functional as F 6 | from torchvision.datasets import ImageFolder 7 | from torch.utils.data import DataLoader 8 | from torchvision import utils as vutils 9 | from torchvision import transforms 10 | import os 11 | import random 12 | import argparse 13 | from tqdm import tqdm 14 | 15 | from models import Generator 16 | from operation import load_params, InfiniteSamplerWrapper 17 | 18 | noise_dim = 256 19 | device = torch.device('cuda:%d'%(0)) 20 | 21 | im_size = 512 22 | net_ig = Generator( ngf=64, nz=noise_dim, nc=3, im_size=im_size)#, big=args.big ) 23 | net_ig.to(device) 24 | 25 | epoch = 50000 26 | ckpt = './models/all_%d.pth'%(epoch) 27 | checkpoint = torch.load(ckpt, map_location=lambda a,b: a) 28 | net_ig.load_state_dict(checkpoint['g']) 29 | load_params(net_ig, checkpoint['g_ema']) 30 | 31 | batch = 8 32 | noise = torch.randn(batch, noise_dim).to(device) 33 | g_imgs = net_ig(noise)[0] 34 | 35 | vutils.save_image(g_imgs.add(1).mul(0.5), 36 | os.path.join('./', '%d.png'%(2))) 37 | 38 | 39 | transform_list = [ 40 | transforms.Resize((int(256),int(256))), 41 | transforms.ToTensor(), 42 | transforms.Normalize(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5]) 43 | ] 44 | trans = transforms.Compose(transform_list) 45 | data_root = '/media/database/images/first_1k' 46 | dataset = ImageFolder(root=data_root, transform=trans) 47 | 48 | import lpips 49 | percept = lpips.PerceptualLoss(model='net-lin', net='vgg', use_gpu=True) 50 | 51 | the_image = g_imgs[0].unsqueeze(0) 52 | def find_closest(the_image): 53 | the_image = F.interpolate(the_image, size=256) 54 | small = 100 55 | close_image = None 56 | for i in tqdm(range(len(dataset))): 57 | real_iamge = dataset[i][0].unsqueeze(0).to(device) 58 | 59 | dis = percept(the_image, real_iamge).sum() 60 | if dis < small: 61 | small = dis 62 | close_image = real_iamge 63 | return close_image, small 64 | 65 | all_dist = [] 66 | batch = 8 67 | result_path = 'nn_track' 68 | import os 69 | os.makedirs(result_path, exist_ok=True) 70 | for j in range(8): 71 | with torch.no_grad(): 72 | noise = torch.randn(batch, noise_dim).to(device) 73 | g_imgs = net_ig(noise)[0] 74 | 75 | for n in range(batch): 76 | the_image = g_imgs[n].unsqueeze(0) 77 | 78 | close_0, dis = find_closest(the_image) 79 | 80 | vutils.save_image(torch.cat([F.interpolate(the_image,256), close_0]).add(1).mul(0.5), \ 81 | result_path+'/nn_%d.jpg'%(j*batch+n)) 82 | all_dist.append(dis.view(1)) 83 | 84 | new_all_dist = [] 85 | for v in all_dist: 86 | new_all_dist.append(v.view(1)) 87 | print(torch.cat(new_all_dist).mean()) -------------------------------------------------------------------------------- /scripts/generate_video.py: -------------------------------------------------------------------------------- 1 | from easing_functions.easing import LinearInOut 2 | import torch 3 | import pandas as pd 4 | from torchvision import utils as vutils 5 | import os 6 | import cv2 7 | from tqdm import tqdm 8 | from scipy import io 9 | import numpy as np 10 | import argparse 11 | 12 | from easing_functions import QuadEaseInOut 13 | from easing_functions import SineEaseIn, SineEaseInOut, SineEaseOut 14 | from easing_functions import ElasticEaseIn, ElasticEaseInOut, ElasticEaseOut 15 | 16 | ease_fn_dict = {'QuadEaseInOut': QuadEaseInOut, 17 | 'SineEaseIn': SineEaseIn, 18 | 'SineEaseInOut': SineEaseInOut, 19 | 'SineEaseOut': SineEaseOut, 20 | 'ElasticEaseIn': ElasticEaseIn, 21 | 'ElasticEaseInOut': ElasticEaseInOut, 22 | 'ElasticEaseOut': ElasticEaseOut, 23 | 'Linear': LinearInOut} 24 | 25 | def interpolate(z1, z2, num_interp): 26 | # this is a "first frame included, last frame excluded" interpolation 27 | w = torch.linspace(0, 1, num_interp+1) 28 | interp_zs = [] 29 | for n in range(num_interp): 30 | interp_zs.append( (z2*w[n].item() + z1*(1-w[n].item())).unsqueeze(0) ) 31 | return torch.cat(interp_zs) 32 | 33 | 34 | 35 | def interpolate_ease_inout(z1, z2, num_interp, ease_fn, model_type='freeform'): 36 | # this is a "first frame included, last frame excluded" interpolation 37 | w = ease_fn(start=0, end=1, duration=num_interp+1) 38 | interp_zs = [] 39 | 40 | # just to make sure the latent vectors in the right shape 41 | if model_type == 'freeform': 42 | z1 = z1.view(1, -1) 43 | z2 = z2.view(1, -1) 44 | if model_type == 'stylegan2': 45 | if type(z1) is list: 46 | z1 = [z1[0].view(1, -1), z1[1].view(1, -1)] 47 | else: 48 | z1 = [z1.view(1, -1), z1.view(1, -1)] 49 | if type(z2) is list: 50 | z2 = [z2[0].view(1, -1), z2[1].view(1, -1)] 51 | else: 52 | z2 = [z2.view(1, -1), z2.view(1, -1)] 53 | 54 | for n in range(num_interp): 55 | if model_type == 'freeform': 56 | interp_zs.append( z2*w.ease(n) + z1*(1-w.ease(n)) ) 57 | if model_type == 'stylegan2': 58 | interp_zs.append( [ z2[0]*w.ease(n) + z1[0]*(1-w.ease(n)), 59 | z2[1]*w.ease(n) + z1[1]*(1-w.ease(n)) ] ) 60 | return interp_zs 61 | 62 | @torch.no_grad() 63 | def net_generate(netG, z, model_type='freeform', im_size=1024): 64 | 65 | if model_type == 'stylegan2': 66 | z_contents = [] 67 | z_styles = [] 68 | for zidx in range(len(z)): 69 | z_contents.append(z[zidx][0]) 70 | z_styles.append(z[zidx][1]) 71 | z = [ torch.cat(z_contents), torch.cat(z_styles) ] 72 | gimg = netG( z, inject_index=8, input_is_latent=True, randomize_noise=False )[0].cpu() 73 | elif model_type == 'freeform': 74 | z = torch.cat(z) 75 | gimg = netG(z)[0].cpu() 76 | 77 | return torch.nn.functional.interpolate(gimg, im_size) 78 | 79 | def batch_generate_and_save(netG, zs, folder_name, batch_size=8, model_type='freeform', im_size=1024): 80 | # zs is a list of vectors if model is freeform 81 | # zs is a list of lists, each list is 2 vectors, if model is stylegan 82 | t = 0 83 | num = 0 84 | if len(zs) < batch_size: 85 | gimgs = net_generate(netG, zs, model_type, im_size=im_size).cpu() 86 | for image in gimgs: 87 | vutils.save_image( image.add(1).mul(0.5), folder_name+"/%d.jpg"%(num) ) 88 | num += 1 89 | 90 | for k in tqdm(range(len(zs)//batch_size)): 91 | gimgs = net_generate(netG, zs[k*batch_size:(k+1)*batch_size], model_type, im_size=im_size) 92 | for image in gimgs: 93 | vutils.save_image( image.add(1).mul(0.5), folder_name+"/%d.jpg"%(num) ) 94 | num += 1 95 | t = k 96 | 97 | if len(zs)%batch_size>0: 98 | gimgs = net_generate(netG, zs[(t+1)*batch_size:], model_type, im_size=im_size) 99 | for image in gimgs: 100 | vutils.save_image( image.add(1).mul(0.5), folder_name+"/%d.jpg"%(num) ) 101 | num += 1 102 | 103 | 104 | 105 | def batch_save(images, folder_name, start_num=0): 106 | os.makedirs(folder_name, exist_ok=True) 107 | num = start_num 108 | for image in images: 109 | vutils.save_image( image.add(1).mul(0.5), folder_name+"/%d.jpg"%(num) ) 110 | num += 1 111 | 112 | 113 | def read_img_and_make_video(dist, video_name, fps): 114 | img_array = [] 115 | for i in tqdm(range(len(os.listdir(dist)))): 116 | try: 117 | filename = dist+'/%d.jpg'%(i) 118 | img = cv2.imread(filename) 119 | height, width, layers = img.shape 120 | size = (width,height) 121 | img_array.append(img) 122 | except: 123 | print('error at: %d'%i) 124 | 125 | if '.mp4' not in video_name: 126 | video_name += '.mp4' 127 | out = cv2.VideoWriter(video_name,cv2.VideoWriter_fourcc(*'mp4v'), fps, size) 128 | for i in range(len(img_array)): 129 | out.write(img_array[i]) 130 | out.release() 131 | 132 | from shutil import rmtree 133 | 134 | def make_video_from_latents(net, selected_latents, frames_dist_folder, video_name, fps, video_length, ease_fn, model_type, im_size=1024): 135 | # selected_latents: the latent noise of user selected key-frame images, it is a list 136 | # each item in the list is a vector if the model is freeform, 137 | # each item in the list is a list of two vectors if the model is stylegan2 138 | # frames_dist_folder: the folder path to save the generated images to make the video 139 | # fps: is the frames we generate per second 140 | # video_length: is the time of the video, in seconds. For example: 30 means a video length of 30 seconds 141 | # ease_fn: user selected type of transitions between each key-frame 142 | 143 | # first calculate how many images need to generate 144 | try: 145 | rmtree(frames_dist_folder) 146 | except: 147 | pass 148 | os.makedirs(frames_dist_folder, exist_ok=True) 149 | 150 | nbr_generate = fps*video_length 151 | nbr_keyframe = len(selected_latents) 152 | nbr_interpolation = 1 + nbr_generate // (nbr_keyframe - 1) 153 | 154 | 155 | main_zs = [] 156 | for idx in range(nbr_keyframe-1): 157 | main_zs += interpolate_ease_inout(selected_latents[idx], 158 | selected_latents[idx+1], nbr_interpolation, ease_fn, model_type) 159 | 160 | 161 | print('generating images ...') 162 | batch_generate_and_save(net, main_zs, folder_name=frames_dist_folder, batch_size=8, model_type=model_type, im_size=im_size) 163 | print('making videos ...') 164 | read_img_and_make_video(frames_dist_folder, video_name, fps=fps) 165 | 166 | 167 | if __name__ == "__main__": 168 | 169 | 170 | device = torch.device('cuda:%d'%(0)) 171 | 172 | load_model_err = 0 173 | 174 | from models import Generator as Generator_freeform 175 | 176 | frames_dist_folder = 'project_video_frames' # a folder to save generated images 177 | ckpt_path = './time_1024_1/models/180000.pth' # path to the checkpoint 178 | video_name = 'videl_keyframe_15' # name of the generated video 179 | 180 | model_type = 'freeform' 181 | net = Generator_freeform(ngf=64, nz=100) 182 | net.load_state_dict(torch.load(ckpt_path)['g']) 183 | net.to(device) 184 | net.eval() 185 | 186 | 187 | try: 188 | rmtree(frames_dist_folder) 189 | except: 190 | pass 191 | os.makedirs(frames_dist_folder, exist_ok=True) 192 | 193 | fps = 30 194 | minutes = 1 195 | im_size = 1024 196 | 197 | ease_fn=ease_fn_dict['SineEaseInOut'] 198 | 199 | init_kf_nbr = 15 200 | nbr_key_frames_per_minute = [init_kf_nbr-i for i in range(minutes)] 201 | nbr_key_frames_total = sum(nbr_key_frames_per_minute) 202 | noises = torch.randn( nbr_key_frames_total , 100).to(device) 203 | user_selected_noises = [n for n in noises] 204 | nbr_interpolation_list = [[fps*60//nbr_kf]*nbr_kf for nbr_kf in nbr_key_frames_per_minute] 205 | nbl = [] 206 | for nb in nbr_interpolation_list: 207 | nbl += nb 208 | 209 | print(len(nbl)) 210 | print(len(user_selected_noises))# , print("mismatch size") 211 | main_zs = [] 212 | for idx in range(len(user_selected_noises)-1): 213 | main_zs += interpolate_ease_inout(user_selected_noises[idx], 214 | user_selected_noises[idx+1], nbl[idx], ease_fn, model_type) 215 | for idx in range(100): 216 | main_zs.append(main_zs[-1]) 217 | print('generating images ...') 218 | batch_generate_and_save(net, main_zs, folder_name=frames_dist_folder, batch_size=8, model_type=model_type, im_size=im_size) 219 | print('making videos ...') 220 | read_img_and_make_video(frames_dist_folder, video_name, fps=fps) 221 | 222 | -------------------------------------------------------------------------------- /scripts/style_mix.py: -------------------------------------------------------------------------------- 1 | import torch 2 | from torch import nn 3 | import torch.optim as optim 4 | import torch.nn.functional as F 5 | from torch.utils.data.dataloader import DataLoader 6 | from torchvision import transforms 7 | from torchvision import utils as vutils 8 | 9 | import argparse 10 | from tqdm import tqdm 11 | 12 | from models import weights_init, Discriminator, Generator 13 | from operation import copy_G_params, load_params, get_dir 14 | from operation import ImageFolder, InfiniteSamplerWrapper 15 | from diffaug import DiffAugment 16 | 17 | 18 | 19 | ndf = 64 20 | ngf = 64 21 | nz = 256 22 | nlr = 0.0002 23 | nbeta1 = 0.5 24 | use_cuda = True 25 | multi_gpu = False 26 | dataloader_workers = 8 27 | current_iteration = 0 28 | save_interval = 100 29 | device = 'cuda:0' 30 | im_size = 256 31 | 32 | 33 | netG = Generator(ngf=ngf, nz=nz, im_size=im_size) 34 | netG.apply(weights_init) 35 | 36 | netD = Discriminator(ndf=ndf, im_size=im_size) 37 | netD.apply(weights_init) 38 | 39 | netG.to(device) 40 | netD.to(device) 41 | 42 | avg_param_G = copy_G_params(netG) 43 | 44 | fixed_noise = torch.FloatTensor(8, nz).normal_(0, 1).to(device) 45 | 46 | optimizerG = optim.Adam(netG.parameters(), lr=nlr, betas=(nbeta1, 0.999)) 47 | optimizerD = optim.Adam(netD.parameters(), lr=nlr, betas=(nbeta1, 0.999)) 48 | 49 | j = 4 50 | checkpoint = "./models/all_%d.pth"%(j*10000) 51 | ckpt = torch.load(checkpoint) 52 | netG.load_state_dict(ckpt['g']) 53 | netD.load_state_dict(ckpt['d']) 54 | avg_param_G = ckpt['g_ema'] 55 | load_params(netG, avg_param_G) 56 | 57 | bs = 8 58 | noise_a = torch.randn(bs, nz).to(device) 59 | noise_b = torch.randn(bs, nz).to(device) 60 | 61 | def get_early_features(net, noise): 62 | feat_4 = net.init(noise) 63 | feat_8 = net.feat_8(feat_4) 64 | feat_16 = net.feat_16(feat_8) 65 | feat_32 = net.feat_32(feat_16) 66 | feat_64 = net.feat_64(feat_32) 67 | return feat_8, feat_16, feat_32, feat_64 68 | 69 | def get_late_features(net, im_size, feat_64, feat_8, feat_16, feat_32): 70 | feat_128 = net.feat_128(feat_64) 71 | feat_128 = net.se_128(feat_8, feat_128) 72 | 73 | feat_256 = net.feat_256(feat_128) 74 | feat_256 = net.se_256(feat_16, feat_256) 75 | if im_size==256: 76 | return net.to_big(feat_256) 77 | 78 | feat_512 = net.feat_512(feat_256) 79 | feat_512 = net.se_512(feat_32, feat_512) 80 | if im_size==512: 81 | return net.to_big(feat_512) 82 | 83 | feat_1024 = net.feat_1024(feat_512) 84 | return net.to_big(feat_1024) 85 | 86 | 87 | feat_8_a, feat_16_a, feat_32_a, feat_64_a = get_early_features(netG, noise_a) 88 | feat_8_b, feat_16_b, feat_32_b, feat_64_b = get_early_features(netG, noise_b) 89 | 90 | images_b = get_late_features(netG, im_size, feat_64_b, feat_8_b, feat_16_b, feat_32_b) 91 | images_a = get_late_features(netG, im_size, feat_64_a, feat_8_a, feat_16_a, feat_32_a) 92 | 93 | imgs = [ torch.ones(1, 3, im_size, im_size) ] 94 | imgs.append(images_b.cpu()) 95 | for i in range(bs): 96 | imgs.append(images_a[i].unsqueeze(0).cpu()) 97 | 98 | gimgs = get_late_features(netG, im_size, feat_64_a[i].unsqueeze(0).repeat(bs, 1, 1, 1), feat_8_b, feat_16_b, feat_32_b) 99 | imgs.append(gimgs.cpu()) 100 | 101 | imgs = torch.cat(imgs) 102 | vutils.save_image(imgs.add(1).mul(0.5), 'style_mix_1.jpg', nrow=bs+1) -------------------------------------------------------------------------------- /scripts/train_backtracking_all.py: -------------------------------------------------------------------------------- 1 | import torch 2 | from torch import nn, real, select 3 | import torch.optim as optim 4 | import torch.nn.functional as F 5 | from torch.utils.data.dataloader import DataLoader 6 | from torchvision import transforms 7 | from torchvision import utils as vutils 8 | 9 | import argparse 10 | from tqdm import tqdm 11 | 12 | from models import weights_init, Discriminator, Generator, SimpleDecoder 13 | from operation import copy_G_params, load_params, get_dir 14 | from operation import ImageFolder, InfiniteSamplerWrapper 15 | from diffaug import DiffAugment 16 | policy = 'color,translation' 17 | import lpips 18 | percept = lpips.PerceptualLoss(model='net-lin', net='vgg', use_gpu=True) 19 | 20 | 21 | #torch.backends.cudnn.benchmark = True 22 | 23 | 24 | def crop_image_by_part(image, part): 25 | hw = image.shape[2]//2 26 | if part==0: 27 | return image[:,:,:hw,:hw] 28 | if part==1: 29 | return image[:,:,:hw,hw:] 30 | if part==2: 31 | return image[:,:,hw:,:hw] 32 | if part==3: 33 | return image[:,:,hw:,hw:] 34 | 35 | def train_d(net, data, label="real"): 36 | """Train function of discriminator""" 37 | if label=="real": 38 | #pred, [rec_all, rec_small, rec_part], part = net(data, label) 39 | pred = net(data, label) 40 | err = F.relu( torch.rand_like(pred) * 0.2 + 0.8 - pred).mean() #+ \ 41 | #percept( rec_all, F.interpolate(data, rec_all.shape[2]) ).sum() +\ 42 | #percept( rec_small, F.interpolate(data, rec_small.shape[2]) ).sum() +\ 43 | #percept( rec_part, F.interpolate(crop_image_by_part(data, part), rec_part.shape[2]) ).sum() 44 | err.backward() 45 | return pred.mean().item()#, rec_all, rec_small, rec_part 46 | else: 47 | pred = net(data, label) 48 | err = F.relu( torch.rand_like(pred) * 0.2 + 0.8 + pred).mean() 49 | err.backward() 50 | return pred.mean().item() 51 | 52 | @torch.no_grad() 53 | def interpolate(z1, z2, netG, img_name, step=8): 54 | z = [ a*z2 + (1-a)*z1 for a in torch.linspace(0, 1, steps=step) ] 55 | z = torch.cat(z).view(step, -1) 56 | g_image = netG(z)[0] 57 | vutils.save_image( g_image.add(1).mul(0.5), img_name , nrow=step) 58 | 59 | 60 | def train(args): 61 | 62 | data_root = args.path 63 | total_iterations = args.iter 64 | checkpoint = args.ckpt 65 | batch_size = args.batch_size 66 | im_size = args.im_size 67 | ndf = 64 68 | ngf = 64 69 | nz = 256 70 | nlr = 0.0002 71 | nbeta1 = 0.5 72 | use_cuda = True 73 | multi_gpu = False 74 | dataloader_workers = 8 75 | current_iteration = 0 76 | save_interval = 100 77 | saved_model_folder, saved_image_folder = get_dir(args) 78 | 79 | device = torch.device("cpu") 80 | if use_cuda: 81 | device = torch.device("cuda:0") 82 | 83 | transform_list = [ 84 | transforms.Resize((int(im_size),int(im_size))), 85 | transforms.RandomHorizontalFlip(), 86 | transforms.ToTensor(), 87 | transforms.Normalize(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5]) 88 | ] 89 | trans = transforms.Compose(transform_list) 90 | 91 | dataset = ImageFolder(root=data_root, transform=trans, return_idx=True) 92 | dataloader = iter(DataLoader(dataset, batch_size=batch_size, shuffle=False, 93 | sampler=InfiniteSamplerWrapper(dataset), num_workers=dataloader_workers, pin_memory=True)) 94 | 95 | total_iterations = int(len(dataset)*100/batch_size) 96 | 97 | netG = Generator(ngf=ngf, nz=nz, im_size=im_size) 98 | 99 | 100 | ckpt = torch.load(checkpoint) 101 | load_params( netG , ckpt['g_ema'] ) 102 | #netG.eval() 103 | netG.to(device) 104 | 105 | fixed_noise = torch.randn(len(dataset), nz, requires_grad=True, device=device) 106 | optimizerG = optim.Adam([fixed_noise], lr=0.1, betas=(nbeta1, 0.999)) 107 | 108 | log_rec_loss = 0 109 | 110 | 111 | for iteration in tqdm(range(current_iteration, total_iterations+1)): 112 | real_image, noise_idx = next(dataloader) 113 | real_image = real_image.to(device) 114 | 115 | optimizerG.zero_grad() 116 | 117 | select_noise = fixed_noise[noise_idx] 118 | g_image = netG(select_noise)[0] 119 | 120 | rec_loss = percept( F.avg_pool2d( g_image, 2, 2), F.avg_pool2d(real_image,2,2) ).sum() + 0.2*F.mse_loss(g_image, real_image) 121 | 122 | rec_loss.backward() 123 | 124 | optimizerG.step() 125 | 126 | log_rec_loss += rec_loss.item() 127 | 128 | if iteration % 100 == 0: 129 | print("lpips loss g: %.5f"%(log_rec_loss/100)) 130 | log_rec_loss = 0 131 | 132 | if iteration % (save_interval*10) == 0: 133 | 134 | with torch.no_grad(): 135 | vutils.save_image( torch.cat([ 136 | real_image, g_image]).add(1).mul(0.5), saved_image_folder+'/rec_%d.jpg'%iteration , nrow=batch_size) 137 | 138 | interpolate(fixed_noise[0], fixed_noise[1], netG, saved_image_folder+'/interpolate_0_1_%d.jpg'%iteration) 139 | 140 | if iteration % (save_interval*10) == 0 or iteration == total_iterations: 141 | torch.save(fixed_noise, saved_model_folder+'/%d.pth'%iteration) 142 | 143 | dataloader = DataLoader(dataset, batch_size=batch_size, shuffle=False, num_workers=dataloader_workers, pin_memory=True) 144 | 145 | mean_lpips = 0 146 | for idx, data in enumerate(dataloader): 147 | real_image, noise_idx = data 148 | real_image = real_image.to(device) 149 | 150 | select_noise = fixed_noise[noise_idx] 151 | g_image = netG(select_noise)[0] 152 | 153 | rec_loss = percept( F.avg_pool2d( g_image, 2, 2), F.avg_pool2d(real_image,2,2) ).sum() 154 | mean_lpips += rec_loss.sum() 155 | mean_lpips /= len(dataset) 156 | print(mean_lpips) 157 | 158 | 159 | if __name__ == "__main__": 160 | parser = argparse.ArgumentParser(description='region gan') 161 | 162 | parser.add_argument('--path', type=str, default='../lmdbs/art_landscape_1k', help='path of resource dataset, should be a folder that has one or many sub image folders inside') 163 | parser.add_argument('--cuda', type=int, default=0, help='index of gpu to use') 164 | parser.add_argument('--name', type=str, default='test1', help='experiment name') 165 | parser.add_argument('--iter', type=int, default=50000, help='number of iterations') 166 | parser.add_argument('--start_iter', type=int, default=0, help='the iteration to start training') 167 | parser.add_argument('--batch_size', type=int, default=4, help='mini batch number of images') 168 | parser.add_argument('--im_size', type=int, default=1024, help='image resolution') 169 | parser.add_argument('--ckpt', type=str, default='None', help='checkpoint weight path') 170 | 171 | 172 | args = parser.parse_args() 173 | print(args) 174 | 175 | train(args) -------------------------------------------------------------------------------- /scripts/train_backtracking_one.py: -------------------------------------------------------------------------------- 1 | import torch 2 | from torch import nn 3 | import torch.optim as optim 4 | import torch.nn.functional as F 5 | from torch.utils.data.dataloader import DataLoader 6 | from torchvision import transforms 7 | from torchvision import utils as vutils 8 | 9 | import argparse 10 | from tqdm import tqdm 11 | 12 | from models import weights_init, Discriminator, Generator, SimpleDecoder 13 | from operation import copy_G_params, load_params, get_dir 14 | from operation import ImageFolder, InfiniteSamplerWrapper 15 | from diffaug import DiffAugment 16 | policy = 'color,translation' 17 | import lpips 18 | percept = lpips.PerceptualLoss(model='net-lin', net='vgg', use_gpu=True) 19 | 20 | 21 | #torch.backends.cudnn.benchmark = True 22 | 23 | 24 | def crop_image_by_part(image, part): 25 | hw = image.shape[2]//2 26 | if part==0: 27 | return image[:,:,:hw,:hw] 28 | if part==1: 29 | return image[:,:,:hw,hw:] 30 | if part==2: 31 | return image[:,:,hw:,:hw] 32 | if part==3: 33 | return image[:,:,hw:,hw:] 34 | 35 | def train_d(net, data, label="real"): 36 | """Train function of discriminator""" 37 | if label=="real": 38 | #pred, [rec_all, rec_small, rec_part], part = net(data, label) 39 | pred = net(data, label) 40 | err = F.relu( torch.rand_like(pred) * 0.2 + 0.8 - pred).mean() #+ \ 41 | #percept( rec_all, F.interpolate(data, rec_all.shape[2]) ).sum() +\ 42 | #percept( rec_small, F.interpolate(data, rec_small.shape[2]) ).sum() +\ 43 | #percept( rec_part, F.interpolate(crop_image_by_part(data, part), rec_part.shape[2]) ).sum() 44 | err.backward() 45 | return pred.mean().item()#, rec_all, rec_small, rec_part 46 | else: 47 | pred = net(data, label) 48 | err = F.relu( torch.rand_like(pred) * 0.2 + 0.8 + pred).mean() 49 | err.backward() 50 | return pred.mean().item() 51 | 52 | @torch.no_grad() 53 | def interpolate(z1, z2, netG, img_name, step=8): 54 | z = [ a*z2 + (1-a)*z1 for a in torch.linspace(0, 1, steps=step) ] 55 | z = torch.cat(z).view(step, -1) 56 | g_image = netG(z)[0] 57 | vutils.save_image( g_image.add(1).mul(0.5), img_name , nrow=step) 58 | 59 | 60 | def train(args): 61 | 62 | data_root = args.path 63 | total_iterations = args.iter 64 | checkpoint = args.ckpt 65 | batch_size = args.batch_size 66 | im_size = args.im_size 67 | ndf = 64 68 | ngf = 64 69 | nz = 256 70 | nlr = 0.0002 71 | nbeta1 = 0.5 72 | use_cuda = True 73 | multi_gpu = False 74 | dataloader_workers = 8 75 | current_iteration = 0 76 | save_interval = 100 77 | saved_model_folder, saved_image_folder = get_dir(args) 78 | 79 | device = torch.device("cpu") 80 | if use_cuda: 81 | device = torch.device("cuda:0") 82 | 83 | transform_list = [ 84 | transforms.Resize((int(im_size),int(im_size))), 85 | transforms.RandomHorizontalFlip(), 86 | transforms.ToTensor(), 87 | transforms.Normalize(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5]) 88 | ] 89 | trans = transforms.Compose(transform_list) 90 | 91 | dataset = ImageFolder(root=data_root, transform=trans) 92 | dataloader = iter(DataLoader(dataset, batch_size=batch_size, shuffle=False, 93 | sampler=InfiniteSamplerWrapper(dataset), num_workers=dataloader_workers, pin_memory=True)) 94 | 95 | 96 | 97 | netG = Generator(ngf=ngf, nz=nz, im_size=im_size) 98 | 99 | 100 | ckpt = torch.load(checkpoint) 101 | load_params( netG , ckpt['g_ema'] ) 102 | #netG.eval() 103 | netG.to(device) 104 | 105 | fixed_noise = torch.randn(batch_size, nz, requires_grad=True, device=device) 106 | optimizerG = optim.Adam([fixed_noise], lr=0.1, betas=(nbeta1, 0.999)) 107 | 108 | real_image = next(dataloader).to(device) 109 | 110 | log_rec_loss = 0 111 | 112 | for iteration in tqdm(range(current_iteration, total_iterations+1)): 113 | 114 | optimizerG.zero_grad() 115 | 116 | g_image = netG(fixed_noise)[0] 117 | 118 | rec_loss = percept( F.avg_pool2d( g_image, 2, 2), F.avg_pool2d(real_image,2,2) ).sum() + 0.2*F.mse_loss(g_image, real_image) 119 | 120 | rec_loss.backward() 121 | 122 | optimizerG.step() 123 | 124 | log_rec_loss += rec_loss.item() 125 | 126 | if iteration % 100 == 0: 127 | print("lpips loss g: %.5f"%(log_rec_loss/100)) 128 | log_rec_loss = 0 129 | 130 | if iteration % (save_interval*2) == 0: 131 | 132 | with torch.no_grad(): 133 | vutils.save_image( torch.cat([ 134 | real_image, g_image]).add(1).mul(0.5), saved_image_folder+'/rec_%d.jpg'%iteration ) 135 | 136 | interpolate(fixed_noise[0], fixed_noise[1], netG, saved_image_folder+'/interpolate_0_1_%d.jpg'%iteration) 137 | 138 | if iteration % (save_interval*5) == 0 or iteration == total_iterations: 139 | torch.save(fixed_noise, saved_model_folder+'/%d.pth'%iteration) 140 | 141 | 142 | 143 | if __name__ == "__main__": 144 | parser = argparse.ArgumentParser(description='region gan') 145 | 146 | parser.add_argument('--path', type=str, default='../lmdbs/art_landscape_1k', help='path of resource dataset, should be a folder that has one or many sub image folders inside') 147 | parser.add_argument('--cuda', type=int, default=0, help='index of gpu to use') 148 | parser.add_argument('--name', type=str, default='test1', help='experiment name') 149 | parser.add_argument('--iter', type=int, default=50000, help='number of iterations') 150 | parser.add_argument('--start_iter', type=int, default=0, help='the iteration to start training') 151 | parser.add_argument('--batch_size', type=int, default=8, help='mini batch number of images') 152 | parser.add_argument('--im_size', type=int, default=1024, help='image resolution') 153 | parser.add_argument('--ckpt', type=str, default='None', help='checkpoint weight path') 154 | 155 | 156 | args = parser.parse_args() 157 | print(args) 158 | 159 | train(args) -------------------------------------------------------------------------------- /train.py: -------------------------------------------------------------------------------- 1 | import torch 2 | from torch import nn 3 | import torch.optim as optim 4 | import torch.nn.functional as F 5 | from torch.utils.data.dataloader import DataLoader 6 | from torchvision import transforms 7 | from torchvision import utils as vutils 8 | 9 | import argparse 10 | import random 11 | from tqdm import tqdm 12 | 13 | from models import weights_init, Discriminator, Generator 14 | from operation import copy_G_params, load_params, get_dir 15 | from operation import ImageFolder, InfiniteSamplerWrapper 16 | from diffaug import DiffAugment 17 | policy = 'color,translation' 18 | import lpips 19 | percept = lpips.PerceptualLoss(model='net-lin', net='vgg', use_gpu=True) 20 | 21 | 22 | #torch.backends.cudnn.benchmark = True 23 | 24 | def crop_image_by_part(image, part): 25 | hw = image.shape[2]//2 26 | if part==0: 27 | return image[:,:,:hw,:hw] 28 | if part==1: 29 | return image[:,:,:hw,hw:] 30 | if part==2: 31 | return image[:,:,hw:,:hw] 32 | if part==3: 33 | return image[:,:,hw:,hw:] 34 | 35 | def train_d(net, data, label="real"): 36 | """Train function of discriminator""" 37 | if label=="real": 38 | part = random.randint(0, 3) 39 | pred, [rec_all, rec_small, rec_part] = net(data, label, part=part) 40 | err = F.relu( torch.rand_like(pred) * 0.2 + 0.8 - pred).mean() + \ 41 | percept( rec_all, F.interpolate(data, rec_all.shape[2]) ).sum() +\ 42 | percept( rec_small, F.interpolate(data, rec_small.shape[2]) ).sum() +\ 43 | percept( rec_part, F.interpolate(crop_image_by_part(data, part), rec_part.shape[2]) ).sum() 44 | err.backward() 45 | return pred.mean().item(), rec_all, rec_small, rec_part 46 | else: 47 | pred = net(data, label) 48 | err = F.relu( torch.rand_like(pred) * 0.2 + 0.8 + pred).mean() 49 | err.backward() 50 | return pred.mean().item() 51 | 52 | 53 | def train(args): 54 | 55 | data_root = args.path 56 | total_iterations = args.iter 57 | checkpoint = args.ckpt 58 | batch_size = args.batch_size 59 | im_size = args.im_size 60 | ndf = 64 61 | ngf = 64 62 | nz = 256 63 | nlr = 0.0002 64 | nbeta1 = 0.5 65 | use_cuda = True 66 | multi_gpu = True 67 | dataloader_workers = args.workers 68 | current_iteration = args.start_iter 69 | save_interval = args.save_interval 70 | saved_model_folder, saved_image_folder = get_dir(args) 71 | 72 | 73 | device = torch.device("cpu") 74 | if use_cuda: 75 | device = torch.device("cuda:0") 76 | 77 | transform_list = [ 78 | transforms.Resize((int(im_size),int(im_size))), 79 | transforms.RandomHorizontalFlip(), 80 | transforms.ToTensor(), 81 | transforms.Normalize(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5]) 82 | ] 83 | trans = transforms.Compose(transform_list) 84 | 85 | if 'lmdb' in data_root: 86 | from operation import MultiResolutionDataset 87 | dataset = MultiResolutionDataset(data_root, trans, 1024) 88 | else: 89 | dataset = ImageFolder(root=data_root, transform=trans) 90 | 91 | 92 | dataloader = iter(DataLoader(dataset, batch_size=batch_size, shuffle=False, 93 | sampler=InfiniteSamplerWrapper(dataset), num_workers=dataloader_workers, pin_memory=True)) 94 | ''' 95 | loader = MultiEpochsDataLoader(dataset, batch_size=batch_size, 96 | shuffle=True, num_workers=dataloader_workers, 97 | pin_memory=True) 98 | dataloader = CudaDataLoader(loader, 'cuda') 99 | ''' 100 | 101 | 102 | #from model_s import Generator, Discriminator 103 | netG = Generator(ngf=ngf, nz=nz, im_size=im_size) 104 | netG.apply(weights_init) 105 | 106 | netD = Discriminator(ndf=ndf, im_size=im_size) 107 | netD.apply(weights_init) 108 | 109 | netG.to(device) 110 | netD.to(device) 111 | 112 | avg_param_G = copy_G_params(netG) 113 | 114 | fixed_noise = torch.FloatTensor(8, nz).normal_(0, 1).to(device) 115 | 116 | optimizerG = optim.Adam(netG.parameters(), lr=nlr, betas=(nbeta1, 0.999)) 117 | optimizerD = optim.Adam(netD.parameters(), lr=nlr, betas=(nbeta1, 0.999)) 118 | 119 | if checkpoint != 'None': 120 | ckpt = torch.load(checkpoint) 121 | netG.load_state_dict({k.replace('module.', ''): v for k, v in ckpt['g'].items()}) 122 | netD.load_state_dict({k.replace('module.', ''): v for k, v in ckpt['d'].items()}) 123 | avg_param_G = ckpt['g_ema'] 124 | optimizerG.load_state_dict(ckpt['opt_g']) 125 | optimizerD.load_state_dict(ckpt['opt_d']) 126 | current_iteration = int(checkpoint.split('_')[-1].split('.')[0]) 127 | del ckpt 128 | 129 | if multi_gpu: 130 | netG = nn.DataParallel(netG.to(device)) 131 | netD = nn.DataParallel(netD.to(device)) 132 | 133 | for iteration in tqdm(range(current_iteration, total_iterations+1)): 134 | real_image = next(dataloader) 135 | real_image = real_image.to(device) 136 | current_batch_size = real_image.size(0) 137 | noise = torch.Tensor(current_batch_size, nz).normal_(0, 1).to(device) 138 | 139 | fake_images = netG(noise) 140 | 141 | real_image = DiffAugment(real_image, policy=policy) 142 | fake_images = [DiffAugment(fake, policy=policy) for fake in fake_images] 143 | 144 | ## 2. train Discriminator 145 | netD.zero_grad() 146 | 147 | err_dr, rec_img_all, rec_img_small, rec_img_part = train_d(netD, real_image, label="real") 148 | train_d(netD, [fi.detach() for fi in fake_images], label="fake") 149 | optimizerD.step() 150 | 151 | ## 3. train Generator 152 | netG.zero_grad() 153 | pred_g = netD(fake_images, "fake") 154 | err_g = -pred_g.mean() 155 | 156 | err_g.backward() 157 | optimizerG.step() 158 | 159 | for p, avg_p in zip(netG.parameters(), avg_param_G): 160 | avg_p.mul_(0.999).add_(0.001 * p.data) 161 | 162 | if iteration % 100 == 0: 163 | print("GAN: loss d: %.5f loss g: %.5f"%(err_dr, -err_g.item())) 164 | 165 | if iteration % (save_interval*10) == 0: 166 | backup_para = copy_G_params(netG) 167 | load_params(netG, avg_param_G) 168 | with torch.no_grad(): 169 | vutils.save_image(netG(fixed_noise)[0].add(1).mul(0.5), saved_image_folder+'/%d.jpg'%iteration, nrow=4) 170 | vutils.save_image( torch.cat([ 171 | F.interpolate(real_image, 128), 172 | rec_img_all, rec_img_small, 173 | rec_img_part]).add(1).mul(0.5), saved_image_folder+'/rec_%d.jpg'%iteration ) 174 | load_params(netG, backup_para) 175 | 176 | if iteration % (save_interval*50) == 0 or iteration == total_iterations: 177 | backup_para = copy_G_params(netG) 178 | load_params(netG, avg_param_G) 179 | torch.save({'g':netG.state_dict(),'d':netD.state_dict()}, saved_model_folder+'/%d.pth'%iteration) 180 | load_params(netG, backup_para) 181 | torch.save({'g':netG.state_dict(), 182 | 'd':netD.state_dict(), 183 | 'g_ema': avg_param_G, 184 | 'opt_g': optimizerG.state_dict(), 185 | 'opt_d': optimizerD.state_dict()}, saved_model_folder+'/all_%d.pth'%iteration) 186 | 187 | if __name__ == "__main__": 188 | parser = argparse.ArgumentParser(description='region gan') 189 | 190 | parser.add_argument('--path', type=str, default='../lmdbs/art_landscape_1k', help='path of resource dataset, should be a folder that has one or many sub image folders inside') 191 | parser.add_argument('--output_path', type=str, default='./', help='Output path for the train results') 192 | parser.add_argument('--cuda', type=int, default=0, help='index of gpu to use') 193 | parser.add_argument('--name', type=str, default='test1', help='experiment name') 194 | parser.add_argument('--iter', type=int, default=50000, help='number of iterations') 195 | parser.add_argument('--start_iter', type=int, default=0, help='the iteration to start training') 196 | parser.add_argument('--batch_size', type=int, default=8, help='mini batch number of images') 197 | parser.add_argument('--im_size', type=int, default=1024, help='image resolution') 198 | parser.add_argument('--ckpt', type=str, default='None', help='checkpoint weight path if have one') 199 | parser.add_argument('--workers', type=int, default=2, help='number of workers for dataloader') 200 | parser.add_argument('--save_interval', type=int, default=100, help='number of iterations to save model') 201 | 202 | args = parser.parse_args() 203 | print(args) 204 | 205 | train(args) 206 | --------------------------------------------------------------------------------