├── LICENSE ├── README.md ├── UniDiffuser.ipynb ├── assets ├── ArialBoldMT.ttf ├── demos_v0.png ├── space.jpg └── unidiffuser.png ├── configs ├── sample_unidiffuser_v0.py └── sample_unidiffuser_v1.py ├── dpm_solver_pp.py ├── libs ├── __init__.py ├── autoencoder.py ├── caption_decoder.py ├── clip.py ├── timm.py ├── uvit_multi_post_ln.py └── uvit_multi_post_ln_v1.py ├── sample_multi_v0.py ├── sample_multi_v1.py └── utils.py /LICENSE: -------------------------------------------------------------------------------- 1 | GNU AFFERO GENERAL PUBLIC LICENSE 2 | Version 3, 19 November 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU Affero General Public License is a free, copyleft license for 11 | software and other kinds of works, specifically designed to ensure 12 | cooperation with the community in the case of network server software. 13 | 14 | The licenses for most software and other practical works are designed 15 | to take away your freedom to share and change the works. By contrast, 16 | our General Public Licenses are intended to guarantee your freedom to 17 | share and change all versions of a program--to make sure it remains free 18 | software for all its users. 19 | 20 | When we speak of free software, we are referring to freedom, not 21 | price. Our General Public Licenses are designed to make sure that you 22 | have the freedom to distribute copies of free software (and charge for 23 | them if you wish), that you receive source code or can get it if you 24 | want it, that you can change the software or use pieces of it in new 25 | free programs, and that you know you can do these things. 26 | 27 | Developers that use our General Public Licenses protect your rights 28 | with two steps: (1) assert copyright on the software, and (2) offer 29 | you this License which gives you legal permission to copy, distribute 30 | and/or modify the software. 31 | 32 | A secondary benefit of defending all users' freedom is that 33 | improvements made in alternate versions of the program, if they 34 | receive widespread use, become available for other developers to 35 | incorporate. Many developers of free software are heartened and 36 | encouraged by the resulting cooperation. However, in the case of 37 | software used on network servers, this result may fail to come about. 38 | The GNU General Public License permits making a modified version and 39 | letting the public access it on a server without ever releasing its 40 | source code to the public. 41 | 42 | The GNU Affero General Public License is designed specifically to 43 | ensure that, in such cases, the modified source code becomes available 44 | to the community. It requires the operator of a network server to 45 | provide the source code of the modified version running there to the 46 | users of that server. Therefore, public use of a modified version, on 47 | a publicly accessible server, gives the public access to the source 48 | code of the modified version. 49 | 50 | An older license, called the Affero General Public License and 51 | published by Affero, was designed to accomplish similar goals. This is 52 | a different license, not a version of the Affero GPL, but Affero has 53 | released a new version of the Affero GPL which permits relicensing under 54 | this license. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | TERMS AND CONDITIONS 60 | 61 | 0. Definitions. 62 | 63 | "This License" refers to version 3 of the GNU Affero General Public License. 64 | 65 | "Copyright" also means copyright-like laws that apply to other kinds of 66 | works, such as semiconductor masks. 67 | 68 | "The Program" refers to any copyrightable work licensed under this 69 | License. Each licensee is addressed as "you". "Licensees" and 70 | "recipients" may be individuals or organizations. 71 | 72 | To "modify" a work means to copy from or adapt all or part of the work 73 | in a fashion requiring copyright permission, other than the making of an 74 | exact copy. The resulting work is called a "modified version" of the 75 | earlier work or a work "based on" the earlier work. 76 | 77 | A "covered work" means either the unmodified Program or a work based 78 | on the Program. 79 | 80 | To "propagate" a work means to do anything with it that, without 81 | permission, would make you directly or secondarily liable for 82 | infringement under applicable copyright law, except executing it on a 83 | computer or modifying a private copy. Propagation includes copying, 84 | distribution (with or without modification), making available to the 85 | public, and in some countries other activities as well. 86 | 87 | To "convey" a work means any kind of propagation that enables other 88 | parties to make or receive copies. Mere interaction with a user through 89 | a computer network, with no transfer of a copy, is not conveying. 90 | 91 | An interactive user interface displays "Appropriate Legal Notices" 92 | to the extent that it includes a convenient and prominently visible 93 | feature that (1) displays an appropriate copyright notice, and (2) 94 | tells the user that there is no warranty for the work (except to the 95 | extent that warranties are provided), that licensees may convey the 96 | work under this License, and how to view a copy of this License. If 97 | the interface presents a list of user commands or options, such as a 98 | menu, a prominent item in the list meets this criterion. 99 | 100 | 1. Source Code. 101 | 102 | The "source code" for a work means the preferred form of the work 103 | for making modifications to it. "Object code" means any non-source 104 | form of a work. 105 | 106 | A "Standard Interface" means an interface that either is an official 107 | standard defined by a recognized standards body, or, in the case of 108 | interfaces specified for a particular programming language, one that 109 | is widely used among developers working in that language. 110 | 111 | The "System Libraries" of an executable work include anything, other 112 | than the work as a whole, that (a) is included in the normal form of 113 | packaging a Major Component, but which is not part of that Major 114 | Component, and (b) serves only to enable use of the work with that 115 | Major Component, or to implement a Standard Interface for which an 116 | implementation is available to the public in source code form. A 117 | "Major Component", in this context, means a major essential component 118 | (kernel, window system, and so on) of the specific operating system 119 | (if any) on which the executable work runs, or a compiler used to 120 | produce the work, or an object code interpreter used to run it. 121 | 122 | The "Corresponding Source" for a work in object code form means all 123 | the source code needed to generate, install, and (for an executable 124 | work) run the object code and to modify the work, including scripts to 125 | control those activities. However, it does not include the work's 126 | System Libraries, or general-purpose tools or generally available free 127 | programs which are used unmodified in performing those activities but 128 | which are not part of the work. For example, Corresponding Source 129 | includes interface definition files associated with source files for 130 | the work, and the source code for shared libraries and dynamically 131 | linked subprograms that the work is specifically designed to require, 132 | such as by intimate data communication or control flow between those 133 | subprograms and other parts of the work. 134 | 135 | The Corresponding Source need not include anything that users 136 | can regenerate automatically from other parts of the Corresponding 137 | Source. 138 | 139 | The Corresponding Source for a work in source code form is that 140 | same work. 141 | 142 | 2. Basic Permissions. 143 | 144 | All rights granted under this License are granted for the term of 145 | copyright on the Program, and are irrevocable provided the stated 146 | conditions are met. This License explicitly affirms your unlimited 147 | permission to run the unmodified Program. The output from running a 148 | covered work is covered by this License only if the output, given its 149 | content, constitutes a covered work. This License acknowledges your 150 | rights of fair use or other equivalent, as provided by copyright law. 151 | 152 | You may make, run and propagate covered works that you do not 153 | convey, without conditions so long as your license otherwise remains 154 | in force. You may convey covered works to others for the sole purpose 155 | of having them make modifications exclusively for you, or provide you 156 | with facilities for running those works, provided that you comply with 157 | the terms of this License in conveying all material for which you do 158 | not control copyright. Those thus making or running the covered works 159 | for you must do so exclusively on your behalf, under your direction 160 | and control, on terms that prohibit them from making any copies of 161 | your copyrighted material outside their relationship with you. 162 | 163 | Conveying under any other circumstances is permitted solely under 164 | the conditions stated below. Sublicensing is not allowed; section 10 165 | makes it unnecessary. 166 | 167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 168 | 169 | No covered work shall be deemed part of an effective technological 170 | measure under any applicable law fulfilling obligations under article 171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 172 | similar laws prohibiting or restricting circumvention of such 173 | measures. 174 | 175 | When you convey a covered work, you waive any legal power to forbid 176 | circumvention of technological measures to the extent such circumvention 177 | is effected by exercising rights under this License with respect to 178 | the covered work, and you disclaim any intention to limit operation or 179 | modification of the work as a means of enforcing, against the work's 180 | users, your or third parties' legal rights to forbid circumvention of 181 | technological measures. 182 | 183 | 4. Conveying Verbatim Copies. 184 | 185 | You may convey verbatim copies of the Program's source code as you 186 | receive it, in any medium, provided that you conspicuously and 187 | appropriately publish on each copy an appropriate copyright notice; 188 | keep intact all notices stating that this License and any 189 | non-permissive terms added in accord with section 7 apply to the code; 190 | keep intact all notices of the absence of any warranty; and give all 191 | recipients a copy of this License along with the Program. 192 | 193 | You may charge any price or no price for each copy that you convey, 194 | and you may offer support or warranty protection for a fee. 195 | 196 | 5. Conveying Modified Source Versions. 197 | 198 | You may convey a work based on the Program, or the modifications to 199 | produce it from the Program, in the form of source code under the 200 | terms of section 4, provided that you also meet all of these conditions: 201 | 202 | a) The work must carry prominent notices stating that you modified 203 | it, and giving a relevant date. 204 | 205 | b) The work must carry prominent notices stating that it is 206 | released under this License and any conditions added under section 207 | 7. This requirement modifies the requirement in section 4 to 208 | "keep intact all notices". 209 | 210 | c) You must license the entire work, as a whole, under this 211 | License to anyone who comes into possession of a copy. This 212 | License will therefore apply, along with any applicable section 7 213 | additional terms, to the whole of the work, and all its parts, 214 | regardless of how they are packaged. This License gives no 215 | permission to license the work in any other way, but it does not 216 | invalidate such permission if you have separately received it. 217 | 218 | d) If the work has interactive user interfaces, each must display 219 | Appropriate Legal Notices; however, if the Program has interactive 220 | interfaces that do not display Appropriate Legal Notices, your 221 | work need not make them do so. 222 | 223 | A compilation of a covered work with other separate and independent 224 | works, which are not by their nature extensions of the covered work, 225 | and which are not combined with it such as to form a larger program, 226 | in or on a volume of a storage or distribution medium, is called an 227 | "aggregate" if the compilation and its resulting copyright are not 228 | used to limit the access or legal rights of the compilation's users 229 | beyond what the individual works permit. Inclusion of a covered work 230 | in an aggregate does not cause this License to apply to the other 231 | parts of the aggregate. 232 | 233 | 6. Conveying Non-Source Forms. 234 | 235 | You may convey a covered work in object code form under the terms 236 | of sections 4 and 5, provided that you also convey the 237 | machine-readable Corresponding Source under the terms of this License, 238 | in one of these ways: 239 | 240 | a) Convey the object code in, or embodied in, a physical product 241 | (including a physical distribution medium), accompanied by the 242 | Corresponding Source fixed on a durable physical medium 243 | customarily used for software interchange. 244 | 245 | b) Convey the object code in, or embodied in, a physical product 246 | (including a physical distribution medium), accompanied by a 247 | written offer, valid for at least three years and valid for as 248 | long as you offer spare parts or customer support for that product 249 | model, to give anyone who possesses the object code either (1) a 250 | copy of the Corresponding Source for all the software in the 251 | product that is covered by this License, on a durable physical 252 | medium customarily used for software interchange, for a price no 253 | more than your reasonable cost of physically performing this 254 | conveying of source, or (2) access to copy the 255 | Corresponding Source from a network server at no charge. 256 | 257 | c) Convey individual copies of the object code with a copy of the 258 | written offer to provide the Corresponding Source. This 259 | alternative is allowed only occasionally and noncommercially, and 260 | only if you received the object code with such an offer, in accord 261 | with subsection 6b. 262 | 263 | d) Convey the object code by offering access from a designated 264 | place (gratis or for a charge), and offer equivalent access to the 265 | Corresponding Source in the same way through the same place at no 266 | further charge. You need not require recipients to copy the 267 | Corresponding Source along with the object code. If the place to 268 | copy the object code is a network server, the Corresponding Source 269 | may be on a different server (operated by you or a third party) 270 | that supports equivalent copying facilities, provided you maintain 271 | clear directions next to the object code saying where to find the 272 | Corresponding Source. Regardless of what server hosts the 273 | Corresponding Source, you remain obligated to ensure that it is 274 | available for as long as needed to satisfy these requirements. 275 | 276 | e) Convey the object code using peer-to-peer transmission, provided 277 | you inform other peers where the object code and Corresponding 278 | Source of the work are being offered to the general public at no 279 | charge under subsection 6d. 280 | 281 | A separable portion of the object code, whose source code is excluded 282 | from the Corresponding Source as a System Library, need not be 283 | included in conveying the object code work. 284 | 285 | A "User Product" is either (1) a "consumer product", which means any 286 | tangible personal property which is normally used for personal, family, 287 | or household purposes, or (2) anything designed or sold for incorporation 288 | into a dwelling. In determining whether a product is a consumer product, 289 | doubtful cases shall be resolved in favor of coverage. For a particular 290 | product received by a particular user, "normally used" refers to a 291 | typical or common use of that class of product, regardless of the status 292 | of the particular user or of the way in which the particular user 293 | actually uses, or expects or is expected to use, the product. A product 294 | is a consumer product regardless of whether the product has substantial 295 | commercial, industrial or non-consumer uses, unless such uses represent 296 | the only significant mode of use of the product. 297 | 298 | "Installation Information" for a User Product means any methods, 299 | procedures, authorization keys, or other information required to install 300 | and execute modified versions of a covered work in that User Product from 301 | a modified version of its Corresponding Source. The information must 302 | suffice to ensure that the continued functioning of the modified object 303 | code is in no case prevented or interfered with solely because 304 | modification has been made. 305 | 306 | If you convey an object code work under this section in, or with, or 307 | specifically for use in, a User Product, and the conveying occurs as 308 | part of a transaction in which the right of possession and use of the 309 | User Product is transferred to the recipient in perpetuity or for a 310 | fixed term (regardless of how the transaction is characterized), the 311 | Corresponding Source conveyed under this section must be accompanied 312 | by the Installation Information. But this requirement does not apply 313 | if neither you nor any third party retains the ability to install 314 | modified object code on the User Product (for example, the work has 315 | been installed in ROM). 316 | 317 | The requirement to provide Installation Information does not include a 318 | requirement to continue to provide support service, warranty, or updates 319 | for a work that has been modified or installed by the recipient, or for 320 | the User Product in which it has been modified or installed. Access to a 321 | network may be denied when the modification itself materially and 322 | adversely affects the operation of the network or violates the rules and 323 | protocols for communication across the network. 324 | 325 | Corresponding Source conveyed, and Installation Information provided, 326 | in accord with this section must be in a format that is publicly 327 | documented (and with an implementation available to the public in 328 | source code form), and must require no special password or key for 329 | unpacking, reading or copying. 330 | 331 | 7. Additional Terms. 332 | 333 | "Additional permissions" are terms that supplement the terms of this 334 | License by making exceptions from one or more of its conditions. 335 | Additional permissions that are applicable to the entire Program shall 336 | be treated as though they were included in this License, to the extent 337 | that they are valid under applicable law. If additional permissions 338 | apply only to part of the Program, that part may be used separately 339 | under those permissions, but the entire Program remains governed by 340 | this License without regard to the additional permissions. 341 | 342 | When you convey a copy of a covered work, you may at your option 343 | remove any additional permissions from that copy, or from any part of 344 | it. (Additional permissions may be written to require their own 345 | removal in certain cases when you modify the work.) You may place 346 | additional permissions on material, added by you to a covered work, 347 | for which you have or can give appropriate copyright permission. 348 | 349 | Notwithstanding any other provision of this License, for material you 350 | add to a covered work, you may (if authorized by the copyright holders of 351 | that material) supplement the terms of this License with terms: 352 | 353 | a) Disclaiming warranty or limiting liability differently from the 354 | terms of sections 15 and 16 of this License; or 355 | 356 | b) Requiring preservation of specified reasonable legal notices or 357 | author attributions in that material or in the Appropriate Legal 358 | Notices displayed by works containing it; or 359 | 360 | c) Prohibiting misrepresentation of the origin of that material, or 361 | requiring that modified versions of such material be marked in 362 | reasonable ways as different from the original version; or 363 | 364 | d) Limiting the use for publicity purposes of names of licensors or 365 | authors of the material; or 366 | 367 | e) Declining to grant rights under trademark law for use of some 368 | trade names, trademarks, or service marks; or 369 | 370 | f) Requiring indemnification of licensors and authors of that 371 | material by anyone who conveys the material (or modified versions of 372 | it) with contractual assumptions of liability to the recipient, for 373 | any liability that these contractual assumptions directly impose on 374 | those licensors and authors. 375 | 376 | All other non-permissive additional terms are considered "further 377 | restrictions" within the meaning of section 10. If the Program as you 378 | received it, or any part of it, contains a notice stating that it is 379 | governed by this License along with a term that is a further 380 | restriction, you may remove that term. If a license document contains 381 | a further restriction but permits relicensing or conveying under this 382 | License, you may add to a covered work material governed by the terms 383 | of that license document, provided that the further restriction does 384 | not survive such relicensing or conveying. 385 | 386 | If you add terms to a covered work in accord with this section, you 387 | must place, in the relevant source files, a statement of the 388 | additional terms that apply to those files, or a notice indicating 389 | where to find the applicable terms. 390 | 391 | Additional terms, permissive or non-permissive, may be stated in the 392 | form of a separately written license, or stated as exceptions; 393 | the above requirements apply either way. 394 | 395 | 8. Termination. 396 | 397 | You may not propagate or modify a covered work except as expressly 398 | provided under this License. Any attempt otherwise to propagate or 399 | modify it is void, and will automatically terminate your rights under 400 | this License (including any patent licenses granted under the third 401 | paragraph of section 11). 402 | 403 | However, if you cease all violation of this License, then your 404 | license from a particular copyright holder is reinstated (a) 405 | provisionally, unless and until the copyright holder explicitly and 406 | finally terminates your license, and (b) permanently, if the copyright 407 | holder fails to notify you of the violation by some reasonable means 408 | prior to 60 days after the cessation. 409 | 410 | Moreover, your license from a particular copyright holder is 411 | reinstated permanently if the copyright holder notifies you of the 412 | violation by some reasonable means, this is the first time you have 413 | received notice of violation of this License (for any work) from that 414 | copyright holder, and you cure the violation prior to 30 days after 415 | your receipt of the notice. 416 | 417 | Termination of your rights under this section does not terminate the 418 | licenses of parties who have received copies or rights from you under 419 | this License. If your rights have been terminated and not permanently 420 | reinstated, you do not qualify to receive new licenses for the same 421 | material under section 10. 422 | 423 | 9. Acceptance Not Required for Having Copies. 424 | 425 | You are not required to accept this License in order to receive or 426 | run a copy of the Program. Ancillary propagation of a covered work 427 | occurring solely as a consequence of using peer-to-peer transmission 428 | to receive a copy likewise does not require acceptance. However, 429 | nothing other than this License grants you permission to propagate or 430 | modify any covered work. These actions infringe copyright if you do 431 | not accept this License. Therefore, by modifying or propagating a 432 | covered work, you indicate your acceptance of this License to do so. 433 | 434 | 10. Automatic Licensing of Downstream Recipients. 435 | 436 | Each time you convey a covered work, the recipient automatically 437 | receives a license from the original licensors, to run, modify and 438 | propagate that work, subject to this License. You are not responsible 439 | for enforcing compliance by third parties with this License. 440 | 441 | An "entity transaction" is a transaction transferring control of an 442 | organization, or substantially all assets of one, or subdividing an 443 | organization, or merging organizations. If propagation of a covered 444 | work results from an entity transaction, each party to that 445 | transaction who receives a copy of the work also receives whatever 446 | licenses to the work the party's predecessor in interest had or could 447 | give under the previous paragraph, plus a right to possession of the 448 | Corresponding Source of the work from the predecessor in interest, if 449 | the predecessor has it or can get it with reasonable efforts. 450 | 451 | You may not impose any further restrictions on the exercise of the 452 | rights granted or affirmed under this License. For example, you may 453 | not impose a license fee, royalty, or other charge for exercise of 454 | rights granted under this License, and you may not initiate litigation 455 | (including a cross-claim or counterclaim in a lawsuit) alleging that 456 | any patent claim is infringed by making, using, selling, offering for 457 | sale, or importing the Program or any portion of it. 458 | 459 | 11. Patents. 460 | 461 | A "contributor" is a copyright holder who authorizes use under this 462 | License of the Program or a work on which the Program is based. The 463 | work thus licensed is called the contributor's "contributor version". 464 | 465 | A contributor's "essential patent claims" are all patent claims 466 | owned or controlled by the contributor, whether already acquired or 467 | hereafter acquired, that would be infringed by some manner, permitted 468 | by this License, of making, using, or selling its contributor version, 469 | but do not include claims that would be infringed only as a 470 | consequence of further modification of the contributor version. For 471 | purposes of this definition, "control" includes the right to grant 472 | patent sublicenses in a manner consistent with the requirements of 473 | this License. 474 | 475 | Each contributor grants you a non-exclusive, worldwide, royalty-free 476 | patent license under the contributor's essential patent claims, to 477 | make, use, sell, offer for sale, import and otherwise run, modify and 478 | propagate the contents of its contributor version. 479 | 480 | In the following three paragraphs, a "patent license" is any express 481 | agreement or commitment, however denominated, not to enforce a patent 482 | (such as an express permission to practice a patent or covenant not to 483 | sue for patent infringement). To "grant" such a patent license to a 484 | party means to make such an agreement or commitment not to enforce a 485 | patent against the party. 486 | 487 | If you convey a covered work, knowingly relying on a patent license, 488 | and the Corresponding Source of the work is not available for anyone 489 | to copy, free of charge and under the terms of this License, through a 490 | publicly available network server or other readily accessible means, 491 | then you must either (1) cause the Corresponding Source to be so 492 | available, or (2) arrange to deprive yourself of the benefit of the 493 | patent license for this particular work, or (3) arrange, in a manner 494 | consistent with the requirements of this License, to extend the patent 495 | license to downstream recipients. "Knowingly relying" means you have 496 | actual knowledge that, but for the patent license, your conveying the 497 | covered work in a country, or your recipient's use of the covered work 498 | in a country, would infringe one or more identifiable patents in that 499 | country that you have reason to believe are valid. 500 | 501 | If, pursuant to or in connection with a single transaction or 502 | arrangement, you convey, or propagate by procuring conveyance of, a 503 | covered work, and grant a patent license to some of the parties 504 | receiving the covered work authorizing them to use, propagate, modify 505 | or convey a specific copy of the covered work, then the patent license 506 | you grant is automatically extended to all recipients of the covered 507 | work and works based on it. 508 | 509 | A patent license is "discriminatory" if it does not include within 510 | the scope of its coverage, prohibits the exercise of, or is 511 | conditioned on the non-exercise of one or more of the rights that are 512 | specifically granted under this License. You may not convey a covered 513 | work if you are a party to an arrangement with a third party that is 514 | in the business of distributing software, under which you make payment 515 | to the third party based on the extent of your activity of conveying 516 | the work, and under which the third party grants, to any of the 517 | parties who would receive the covered work from you, a discriminatory 518 | patent license (a) in connection with copies of the covered work 519 | conveyed by you (or copies made from those copies), or (b) primarily 520 | for and in connection with specific products or compilations that 521 | contain the covered work, unless you entered into that arrangement, 522 | or that patent license was granted, prior to 28 March 2007. 523 | 524 | Nothing in this License shall be construed as excluding or limiting 525 | any implied license or other defenses to infringement that may 526 | otherwise be available to you under applicable patent law. 527 | 528 | 12. No Surrender of Others' Freedom. 529 | 530 | If conditions are imposed on you (whether by court order, agreement or 531 | otherwise) that contradict the conditions of this License, they do not 532 | excuse you from the conditions of this License. If you cannot convey a 533 | covered work so as to satisfy simultaneously your obligations under this 534 | License and any other pertinent obligations, then as a consequence you may 535 | not convey it at all. For example, if you agree to terms that obligate you 536 | to collect a royalty for further conveying from those to whom you convey 537 | the Program, the only way you could satisfy both those terms and this 538 | License would be to refrain entirely from conveying the Program. 539 | 540 | 13. Remote Network Interaction; Use with the GNU General Public License. 541 | 542 | Notwithstanding any other provision of this License, if you modify the 543 | Program, your modified version must prominently offer all users 544 | interacting with it remotely through a computer network (if your version 545 | supports such interaction) an opportunity to receive the Corresponding 546 | Source of your version by providing access to the Corresponding Source 547 | from a network server at no charge, through some standard or customary 548 | means of facilitating copying of software. This Corresponding Source 549 | shall include the Corresponding Source for any work covered by version 3 550 | of the GNU General Public License that is incorporated pursuant to the 551 | following paragraph. 552 | 553 | Notwithstanding any other provision of this License, you have 554 | permission to link or combine any covered work with a work licensed 555 | under version 3 of the GNU General Public License into a single 556 | combined work, and to convey the resulting work. The terms of this 557 | License will continue to apply to the part which is the covered work, 558 | but the work with which it is combined will remain governed by version 559 | 3 of the GNU General Public License. 560 | 561 | 14. Revised Versions of this License. 562 | 563 | The Free Software Foundation may publish revised and/or new versions of 564 | the GNU Affero General Public License from time to time. Such new versions 565 | will be similar in spirit to the present version, but may differ in detail to 566 | address new problems or concerns. 567 | 568 | Each version is given a distinguishing version number. If the 569 | Program specifies that a certain numbered version of the GNU Affero General 570 | Public License "or any later version" applies to it, you have the 571 | option of following the terms and conditions either of that numbered 572 | version or of any later version published by the Free Software 573 | Foundation. If the Program does not specify a version number of the 574 | GNU Affero General Public License, you may choose any version ever published 575 | by the Free Software Foundation. 576 | 577 | If the Program specifies that a proxy can decide which future 578 | versions of the GNU Affero General Public License can be used, that proxy's 579 | public statement of acceptance of a version permanently authorizes you 580 | to choose that version for the Program. 581 | 582 | Later license versions may give you additional or different 583 | permissions. However, no additional obligations are imposed on any 584 | author or copyright holder as a result of your choosing to follow a 585 | later version. 586 | 587 | 15. Disclaimer of Warranty. 588 | 589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 597 | 598 | 16. Limitation of Liability. 599 | 600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 608 | SUCH DAMAGES. 609 | 610 | 17. Interpretation of Sections 15 and 16. 611 | 612 | If the disclaimer of warranty and limitation of liability provided 613 | above cannot be given local legal effect according to their terms, 614 | reviewing courts shall apply local law that most closely approximates 615 | an absolute waiver of all civil liability in connection with the 616 | Program, unless a warranty or assumption of liability accompanies a 617 | copy of the Program in return for a fee. 618 | 619 | END OF TERMS AND CONDITIONS 620 | 621 | How to Apply These Terms to Your New Programs 622 | 623 | If you develop a new program, and you want it to be of the greatest 624 | possible use to the public, the best way to achieve this is to make it 625 | free software which everyone can redistribute and change under these terms. 626 | 627 | To do so, attach the following notices to the program. It is safest 628 | to attach them to the start of each source file to most effectively 629 | state the exclusion of warranty; and each file should have at least 630 | the "copyright" line and a pointer to where the full notice is found. 631 | 632 | 633 | Copyright (C) 634 | 635 | This program is free software: you can redistribute it and/or modify 636 | it under the terms of the GNU Affero General Public License as published 637 | by the Free Software Foundation, either version 3 of the License, or 638 | (at your option) any later version. 639 | 640 | This program is distributed in the hope that it will be useful, 641 | but WITHOUT ANY WARRANTY; without even the implied warranty of 642 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 643 | GNU Affero General Public License for more details. 644 | 645 | You should have received a copy of the GNU Affero General Public License 646 | along with this program. If not, see . 647 | 648 | Also add information on how to contact you by electronic and paper mail. 649 | 650 | If your software can interact with users remotely through a computer 651 | network, you should also make sure that it provides a way for users to 652 | get its source. For example, if your program is a web application, its 653 | interface could display a "Source" link that leads users to an archive 654 | of the code. There are many ways you could offer source, and different 655 | solutions will be better for different programs; see section 13 for the 656 | specific requirements. 657 | 658 | You should also get your employer (if you work as a programmer) or school, 659 | if any, to sign a "copyright disclaimer" for the program, if necessary. 660 | For more information on this, and how to apply and follow the GNU AGPL, see 661 | . 662 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ## UniDiffuser 2 | 3 | Code and models for the paper ["One Transformer Fits All Distributions in Multi-Modal Diffusion"](https://arxiv.org/abs/2303.06555) 4 | 5 | [![Hugging Face Spaces](https://img.shields.io/badge/%F0%9F%A4%97%20Hugging%20Face-Spaces-blue)](https://huggingface.co/spaces/thu-ml/unidiffuser) 6 | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/thu-ml/unidiffuser/blob/main/UniDiffuser.ipynb) 7 | [![Replicate](https://replicate.com/cjwbw/unidiffuser/badge)](https://replicate.com/cjwbw/unidiffuser) 8 | [![Diffusers](https://img.shields.io/badge/%F0%9F%A7%A8-diffusers-red)](https://huggingface.co/docs/diffusers/main/en/api/pipelines/unidiffuser) 9 | drawing 10 | 11 | UniDiffuser is a unified diffusion framework to fit all distributions relevant to a set of multi-modal data in one model. 12 | Its key insight is -- learning diffusion models for marginal, conditional, and joint distributions can be unified as predicting the noise in the perturbed data, where the perturbation levels (i.e. timesteps) can be different for different modalities. 13 | Inspired by the unified view, UniDiffuser learns all distributions simultaneously with a minimal modification to the original diffusion model -- perturbs data in all modalities instead of a single modality, inputs individual timesteps in different modalities, and predicts the noise of all modalities instead of a single modality. 14 | UniDiffuser is parameterized by a transformer for diffusion models to handle input types of different modalities. 15 | Implemented on large-scale paired image-text data, UniDiffuser is able to perform image, text, text-to-image, image-to-text, and image-text pair generation by setting proper timesteps without additional overhead. 16 | In particular, UniDiffuser is able to produce perceptually realistic samples in all tasks and its quantitative results (e.g., the FID and CLIP score) are not only superior to existing general-purpose models but also comparable to the bespoken models (e.g., Stable Diffusion and DALL-E 2) in representative tasks (e.g., text-to-image generation). 17 | 18 | drawing 19 | 20 | -------------------- 21 | 22 | ## Dependency 23 | 24 | ```sh 25 | conda create -n unidiffuser python=3.9 26 | conda activate unidiffuser 27 | pip install torch torchvision --extra-index-url https://download.pytorch.org/whl/cu116 # install torch-1.13.1 28 | pip install accelerate==0.12.0 absl-py ml_collections einops ftfy==6.1.1 transformers==4.23.1 29 | pip install -e git+https://github.com/openai/CLIP.git@main#egg=clip 30 | 31 | # xformers is optional, but it would greatly speed up the attention computation. 32 | pip install -U xformers 33 | pip install -U --pre triton 34 | ``` 35 | 36 | * We highly suggest install [xformers](https://github.com/facebookresearch/xformers), which would greatly speed up the attention computation for *both training and inference*. 37 | 38 | 39 | 40 | ## Pretrained Models 41 | 42 | UniDiffuser employs a variation of transformer, called [U-ViT](https://github.com/baofff/U-ViT), which parameterizes the joint noise prediction network. Other components perform as encoders and decoders of different modalities, including a pretrained image autoencoder from [Stable Diffusion](https://github.com/CompVis/stable-diffusion), a pretrained [image ViT-B/32 CLIP encoder](https://github.com/openai/CLIP), a pretrained [text ViT-L CLIP encoder](https://huggingface.co/openai/clip-vit-large-patch14), and a [GPT-2](https://github.com/openai/gpt-2) text decoder finetuned by ourselves. 43 | 44 | 45 | We provide two versions of UniDiffuser, which contain U-ViT of 1B parameters and can run on a GPU with at least 10 GB memory. They can be downloaded from Hugging Face: 46 | - [UniDiffuser-v0](https://huggingface.co/thu-ml/unidiffuser-v0): This version is trained on [LAION-5B](https://laion.ai/) at 512x512 resolution, which contains noisy webdata of text-image pairs. 47 | - [UniDiffuser-v1](https://huggingface.co/thu-ml/unidiffuser-v1): This version is resumed from UniDiffuser-v0, and is further trained with a set of less noisy internal text-image pairs. It uses a flag as its input to distinguish webdata and internal data during training. 48 | 49 | Both links contain three files: 50 | - `autoencoder_kl.pth` is the weight of the image autoencoder converted from [Stable Diffusion](https://github.com/CompVis/stable-diffusion). 51 | - `caption_decoder.pth` is the weight of the finetuned GPT-2 text decoder. 52 | - `uvit_v0.pth or uvit_v1.pth` is the weight of U-ViT for UniDiffuser-v0 or UniDiffuser-v1. 53 | 54 | Note that UniDiffuser-v0 and UniDiffuser-v1 share the same `autoencoder_kl.pth` and `caption_decoder.pth`. You only need to download them once. 55 | As for other components, they will be automatically downloaded. 56 | 57 | 58 | After downloading, create a new folder named `models` and put all pretrained models into this folder as follows: 59 | 60 | ``` 61 | ├── models 62 | │   └── autoencoder_kl.pth 63 | │   └── caption_decoder.pth 64 | │ └── uvit_v0.pth or uvit_v1.pth 65 | ``` 66 | 67 | ## Inference 68 | 69 | We suggest to use UniDiffuser-v1 for a better performance. Results are put into `out` directory by default. 70 | 71 | * **text-to-image generation** 72 | ```shell 73 | python sample_multi_v1.py --mode=t2i --prompt="an elephant under the sea" 74 | ``` 75 | * **image-to-text generation** 76 | ```shell 77 | python sample_multi_v1.py --mode=i2t --img=assets/space.jpg 78 | ``` 79 | 80 | * **joint generation** 81 | ```shell 82 | python sample_multi_v1.py --mode=joint 83 | ``` 84 | 85 | * **image generation** 86 | ```shell 87 | python sample_multi_v1.py --mode=i 88 | ``` 89 | 90 | * **text generation** 91 | ```shell 92 | python sample_multi_v1.py --mode=t 93 | ``` 94 | 95 | * **image variation** 96 | ```shell 97 | python sample_multi_v1.py --mode=i2t2i --img=assets/space.jpg 98 | ``` 99 | 100 | * **text variation** 101 | ```shell 102 | python sample_multi_v1.py --mode=t2i2t --prompt="an elephant under the sea" 103 | ``` 104 | 105 | We provide all supported arguments below 106 | ``` 107 | all supported arguments: 108 | --mode type of generation, one of t2i / i2t / joint / i / t / i2t2i/ t2i2t 109 | t2i: text to image 110 | i2t: image to text 111 | joint: joint generation of text and image 112 | i: only generate image 113 | t: only generate text 114 | i2t2i: image variation, first image to text, then text to image 115 | t2i2t: text variation, first text to image, the image to text 116 | --prompt the prompt for text-to-image generation and text variation 117 | --img the image path for image-to-text generation and image variation 118 | --n_samples the number of samples to generate, default is 1 119 | --nrow number of images displayed in each row of the grid, default is 4 120 | --output_path dir to write results to, default is out 121 | --config.seed random seed, default is 1234 122 | --config.sample.sample_steps number of dpm_solver sampling steps, default is 50 123 | --config.sample.scale the classfier-free guidance for conditional generation, default is 7 124 | --config.sample.t2i_cfg_mode used for text-to-image generation, one of true_uncond / empty_token, default is true_uncond 125 | true_uncond: use the unconditional model of UniDiffuser to perform classifier-free guidance 126 | empty_token: use the empty string to perform classifier-free guidance 127 | --config.data_type one of 0 / 1, used for UniDiffuser-v1, default is 1 128 | 0: corresponds to WebDataset during training 129 | 1: corresponds to internal data during training 130 | ``` 131 | 132 | 133 | 134 | The inference command of UniDiffuser-v0 is basically the same as UniDiffuser-v1, only need to change 135 | `sample_multi_v1.py` to `sample_multi_v0.py`. For example: 136 | ```shell 137 | python sample_multi_v0.py --mode=t2i --prompt="an elephant under the sea" 138 | ``` 139 | 140 | ## Integration with 🧨 diffusers 141 | 142 | UniDiffuser is also available in 🧨 diffusers. It is available in six different modes. 143 | Here is how one can use the `UniDiffuserPipeline` to generate images from text: 144 | 145 | ```python 146 | import torch 147 | from diffusers import UniDiffuserPipeline 148 | 149 | device = "cuda" 150 | model_id_or_path = "thu-ml/unidiffuser-v1" 151 | pipe = UniDiffuserPipeline.from_pretrained(model_id_or_path, torch_dtype=torch.float16) 152 | pipe.to(device) 153 | 154 | # Text-to-image generation 155 | prompt = "an elephant under the sea" 156 | 157 | sample = pipe(prompt=prompt, num_inference_steps=20, guidance_scale=8.0) 158 | t2i_image = sample.images[0] 159 | t2i_image.save("unidiffuser_text2img_sample_image.png") 160 | ``` 161 | 162 | To learn more details, check out the official [UniDiffuser documentation](https://huggingface.co/docs/diffusers/main/en/api/pipelines/unidiffuser). 163 | 164 | 165 | ## References 166 | If you find the code useful for your research, please consider citing 167 | ```bib 168 | @article{bao2022one, 169 | title={One Transformer Fits All Distributions in Multi-Modal Diffusion at Scale}, 170 | author={Bao, Fan and Nie, Shen and Xue, Kaiwen and Li, Chongxuan and Pu, Shi and Wang, Yaole and Yue, Gang and Cao, Yue and Su, Hang and Zhu, Jun}, 171 | year={2023} 172 | } 173 | 174 | @inproceedings{bao2022all, 175 | title={All are Worth Words: A ViT Backbone for Diffusion Models}, 176 | author={Bao, Fan and Nie, Shen and Xue, Kaiwen and Cao, Yue and Li, Chongxuan and Su, Hang and Zhu, Jun}, 177 | booktitle = {CVPR}, 178 | year={2023} 179 | } 180 | ``` 181 | 182 | This implementation is heavily based on the [U-ViT](https://github.com/baofff/U-ViT) code. 183 | -------------------------------------------------------------------------------- /UniDiffuser.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "nbformat": 4, 3 | "nbformat_minor": 0, 4 | "metadata": { 5 | "colab": { 6 | "provenance": [], 7 | "authorship_tag": "ABX9TyNNUL2WHcN0SX5H8gm9pLZ2", 8 | "include_colab_link": true 9 | }, 10 | "kernelspec": { 11 | "name": "python3", 12 | "display_name": "Python 3" 13 | }, 14 | "language_info": { 15 | "name": "python" 16 | }, 17 | "accelerator": "GPU", 18 | "gpuClass": "standard" 19 | }, 20 | "cells": [ 21 | { 22 | "cell_type": "markdown", 23 | "metadata": { 24 | "id": "view-in-github", 25 | "colab_type": "text" 26 | }, 27 | "source": [ 28 | "\"Open" 29 | ] 30 | }, 31 | { 32 | "cell_type": "markdown", 33 | "source": [ 34 | "# [One Transformer Fits All Distributions in Multi-Modal Diffusion at Scale](https://arxiv.org/abs/2303.06555)\n", 35 | "\n", 36 | "This is a demo for sampling from [UniDiffuser](https://arxiv.org/abs/2303.06555) . UniDiffuser is a unified diffusion framework to fit all distributions relevant to a set of multi-modal data in one model. Implemented on large-scale paired image-text data, UniDiffuser is able to perform image, text, text-to-image, image-to-text, and image-text pair generation.\n", 37 | "\n", 38 | "[Paper](https://arxiv.org/abs/2303.06555) | [GitHub](https://github.com/thu-ml/unidiffuser)" 39 | ], 40 | "metadata": { 41 | "id": "-vRJ-KSH5334" 42 | } 43 | }, 44 | { 45 | "cell_type": "markdown", 46 | "source": [ 47 | "# Dependency and Pretrained Models" 48 | ], 49 | "metadata": { 50 | "id": "vEEqy9bRPYKY" 51 | } 52 | }, 53 | { 54 | "cell_type": "markdown", 55 | "source": [ 56 | "Download repository and install dependence" 57 | ], 58 | "metadata": { 59 | "id": "rgAzXSsIA_wS" 60 | } 61 | }, 62 | { 63 | "cell_type": "code", 64 | "source": [ 65 | "!git clone https://github.com/thu-ml/unidiffuser.git\n", 66 | "!git clone https://github.com/openai/CLIP.git\n", 67 | "\n", 68 | "!pip install -e ./CLIP\n", 69 | "!pip install accelerate==0.12.0 absl-py ml_collections einops ftfy==6.1.1 transformers==4.23.1\n", 70 | "\n", 71 | "!pip install -U xformers\n", 72 | "!pip install -U --pre triton\n", 73 | "\n", 74 | "import sys\n", 75 | "sys.path.append(\".\")\n", 76 | "sys.path.append('/content/CLIP')" 77 | ], 78 | "metadata": { 79 | "id": "_txRP2VTAy3P" 80 | }, 81 | "execution_count": null, 82 | "outputs": [] 83 | }, 84 | { 85 | "cell_type": "markdown", 86 | "source": [ 87 | "Download pretrained models from HuggingFace" 88 | ], 89 | "metadata": { 90 | "id": "YV-uS9KaJ8sw" 91 | } 92 | }, 93 | { 94 | "cell_type": "code", 95 | "source": [ 96 | "import os\n", 97 | "os.chdir('/content/unidiffuser')\n", 98 | "\n", 99 | "!mkdir models\n", 100 | "%cd models\n", 101 | "!wget -c https://huggingface.co/thu-ml/unidiffuser-v1/resolve/main/autoencoder_kl.pth \n", 102 | "!wget -c https://huggingface.co/thu-ml/unidiffuser-v1/resolve/main/caption_decoder.pth\n", 103 | "!wget -c https://huggingface.co/thu-ml/unidiffuser-v1/resolve/main/uvit_v1.pth\n", 104 | "%cd ..\n" 105 | ], 106 | "metadata": { 107 | "id": "p7TqlfbVKFjC" 108 | }, 109 | "execution_count": null, 110 | "outputs": [] 111 | }, 112 | { 113 | "cell_type": "markdown", 114 | "source": [ 115 | "Let's also check what type of GPU we've got." 116 | ], 117 | "metadata": { 118 | "id": "zVXoPmHicHLZ" 119 | } 120 | }, 121 | { 122 | "cell_type": "code", 123 | "source": [ 124 | "!nvidia-smi" 125 | ], 126 | "metadata": { 127 | "id": "fH4JqaIxVe1R" 128 | }, 129 | "execution_count": null, 130 | "outputs": [] 131 | }, 132 | { 133 | "cell_type": "markdown", 134 | "source": [ 135 | "Import what we need" 136 | ], 137 | "metadata": { 138 | "id": "hUTfjc225L1o" 139 | } 140 | }, 141 | { 142 | "cell_type": "code", 143 | "source": [ 144 | "import ml_collections\n", 145 | "import torch\n", 146 | "import random\n", 147 | "import utils\n", 148 | "from dpm_solver_pp import NoiseScheduleVP, DPM_Solver\n", 149 | "from absl import logging\n", 150 | "import einops\n", 151 | "import libs.autoencoder\n", 152 | "import libs.clip\n", 153 | "from torchvision.utils import save_image, make_grid\n", 154 | "import torchvision.transforms as standard_transforms\n", 155 | "import numpy as np\n", 156 | "import clip\n", 157 | "from PIL import Image" 158 | ], 159 | "metadata": { 160 | "id": "wE_YD_A_5OAq" 161 | }, 162 | "execution_count": null, 163 | "outputs": [] 164 | }, 165 | { 166 | "cell_type": "markdown", 167 | "source": [ 168 | "Load models" 169 | ], 170 | "metadata": { 171 | "id": "yms6SlIC3qnK" 172 | } 173 | }, 174 | { 175 | "cell_type": "code", 176 | "source": [ 177 | "from libs.uvit_multi_post_ln_v1 import UViT\n", 178 | "\n", 179 | "device = 'cuda' if torch.cuda.is_available() else 'cpu'\n", 180 | "nnet = UViT(\n", 181 | " img_size=64,\n", 182 | " in_chans=4,\n", 183 | " patch_size=2,\n", 184 | " embed_dim=1536,\n", 185 | " depth=30,\n", 186 | " num_heads=24,\n", 187 | " text_dim=64,\n", 188 | " num_text_tokens=77,\n", 189 | " clip_img_dim=512,\n", 190 | " use_checkpoint=True\n", 191 | ")\n", 192 | "nnet.to(device)\n", 193 | "nnet.load_state_dict(torch.load('models/uvit_v1.pth', map_location='cpu'))\n", 194 | "nnet.eval()\n", 195 | "\n", 196 | "\n", 197 | "from libs.caption_decoder import CaptionDecoder\n", 198 | "caption_decoder = CaptionDecoder(device=device, pretrained_path=\"models/caption_decoder.pth\", hidden_dim=64)\n", 199 | "\n", 200 | "clip_text_model = libs.clip.FrozenCLIPEmbedder(device=device)\n", 201 | "clip_text_model.eval()\n", 202 | "clip_text_model.to(device)\n", 203 | "\n", 204 | "autoencoder = libs.autoencoder.get_model(pretrained_path='models/autoencoder_kl.pth')\n", 205 | "autoencoder.to(device)\n", 206 | "\n", 207 | "clip_img_model, clip_img_model_preprocess = clip.load(\"ViT-B/32\", device=device, jit=False)\n", 208 | "\n", 209 | "@torch.cuda.amp.autocast()\n", 210 | "def encode(_batch):\n", 211 | " return autoencoder.encode(_batch)\n", 212 | "\n", 213 | "@torch.cuda.amp.autocast()\n", 214 | "def decode(_batch):\n", 215 | " return autoencoder.decode(_batch)\n" 216 | ], 217 | "metadata": { 218 | "id": "JGDO6IUI3qR2" 219 | }, 220 | "execution_count": null, 221 | "outputs": [] 222 | }, 223 | { 224 | "cell_type": "markdown", 225 | "source": [ 226 | "# Prepare" 227 | ], 228 | "metadata": { 229 | "id": "lr5JaWajQD3O" 230 | } 231 | }, 232 | { 233 | "cell_type": "markdown", 234 | "source": [ 235 | "Define required function" 236 | ], 237 | "metadata": { 238 | "id": "Jia6mVVDGjYA" 239 | } 240 | }, 241 | { 242 | "cell_type": "code", 243 | "source": [ 244 | "def stable_diffusion_beta_schedule(linear_start=0.00085, linear_end=0.0120, n_timestep=1000):\n", 245 | " _betas = (\n", 246 | " torch.linspace(linear_start ** 0.5, linear_end ** 0.5, n_timestep, dtype=torch.float64) ** 2\n", 247 | " )\n", 248 | " return _betas.numpy()\n", 249 | "_betas = stable_diffusion_beta_schedule()\n", 250 | "N = len(_betas)\n", 251 | "\n", 252 | "def split(x):\n", 253 | " C, H, W = 4, 64, 64\n", 254 | " z_dim = C * H * W\n", 255 | " z, clip_img = x.split([z_dim, 512], dim=1)\n", 256 | " z = einops.rearrange(z, 'B (C H W) -> B C H W', C=C, H=H, W=W)\n", 257 | " clip_img = einops.rearrange(clip_img, 'B (L D) -> B L D', L=1, D=512)\n", 258 | " return z, clip_img\n", 259 | "\n", 260 | "def combine(z, clip_img):\n", 261 | " z = einops.rearrange(z, 'B C H W -> B (C H W)')\n", 262 | " clip_img = einops.rearrange(clip_img, 'B L D -> B (L D)')\n", 263 | " return torch.concat([z, clip_img], dim=-1)\n", 264 | "\n", 265 | "def combine_joint(z, clip_img, text):\n", 266 | " z = einops.rearrange(z, 'B C H W -> B (C H W)')\n", 267 | " clip_img = einops.rearrange(clip_img, 'B L D -> B (L D)')\n", 268 | " text = einops.rearrange(text, 'B L D -> B (L D)')\n", 269 | " return torch.concat([z, clip_img, text], dim=-1)\n", 270 | "\n", 271 | "def split_joint(x):\n", 272 | " C, H, W = 4, 64, 64\n", 273 | " z_dim = C * H * W\n", 274 | " z, clip_img, text = x.split([z_dim, 512, 77 * 64], dim=1)\n", 275 | " z = einops.rearrange(z, 'B (C H W) -> B C H W', C=C, H=H, W=W)\n", 276 | " clip_img = einops.rearrange(clip_img, 'B (L D) -> B L D', L=1, D=512)\n", 277 | " text = einops.rearrange(text, 'B (L D) -> B L D', L=77, D=64)\n", 278 | " return z, clip_img, text\n", 279 | "\n", 280 | "def unpreprocess(v): # to B C H W and [0, 1]\n", 281 | " v = 0.5 * (v + 1.)\n", 282 | " v.clamp_(0., 1.)\n", 283 | " return v\n", 284 | "\n", 285 | "\n", 286 | "def set_seed(seed: int):\n", 287 | " random.seed(seed)\n", 288 | " np.random.seed(seed)\n", 289 | " torch.manual_seed(seed)\n", 290 | " torch.cuda.manual_seed_all(seed)\n", 291 | "\n", 292 | "def watermarking(save_path):\n", 293 | " img_pre = Image.open(save_path)\n", 294 | " img_pos = utils.add_water(img_pre)\n", 295 | " img_pos.save(save_path)" 296 | ], 297 | "metadata": { 298 | "id": "w9Ui064gGnlM" 299 | }, 300 | "execution_count": null, 301 | "outputs": [] 302 | }, 303 | { 304 | "cell_type": "markdown", 305 | "source": [ 306 | "# Sample from UniDiffuser" 307 | ], 308 | "metadata": { 309 | "id": "dDUqUaMMQL-0" 310 | } 311 | }, 312 | { 313 | "cell_type": "markdown", 314 | "source": [ 315 | "Define hyperparameters" 316 | ], 317 | "metadata": { 318 | "id": "2Z1x1Wbu-AtC" 319 | } 320 | }, 321 | { 322 | "cell_type": "code", 323 | "source": [ 324 | "mode = \"t2i\" #@param {type:\"string\"}\n", 325 | "\"\"\"\n", 326 | "t2i: text-to-image generation\n", 327 | "i2t: image-to-text generation\n", 328 | "joint: joint generation\n", 329 | "i: image generation\n", 330 | "t: text generation\n", 331 | "t2i2t: text variation\n", 332 | "i2t2i: image variation\n", 333 | "\"\"\"\n", 334 | "assert mode in ['t2i', 'i2t', 'joint', 't', 'i', 't2i2t', 'i2t2i']\n", 335 | "prompt = \"an elephant under the sea\" #@param {type:\"string\"}\n", 336 | "img = 'assets/space.jpg' #@param {type:\"string\"}\n", 337 | "seed = 1234 #@param {type:\"number\"}\n", 338 | "steps = 50 #@param {type:\"slider\", min:0, max:100, step:1}\n", 339 | "cfg_scale = 8 #@param {type:\"slider\", min:0, max:10, step:0.1}\n", 340 | "n_samples = 4 #@param {type:\"number\"}\n", 341 | "nrow = 2 #@param {type:\"number\"}\n", 342 | "data_type = 1\n", 343 | "output_path = 'out'\n", 344 | "\n", 345 | "if mode == 't2i' or mode == 't2i2t':\n", 346 | " prompts = [ prompt ] * n_samples\n", 347 | " contexts = clip_text_model.encode(prompts)\n", 348 | " contexts_low_dim = caption_decoder.encode_prefix(contexts)\n", 349 | "elif mode == 'i2t' or mode == 'i2t2i':\n", 350 | " from PIL import Image\n", 351 | " img_contexts = []\n", 352 | " clip_imgs = []\n", 353 | "\n", 354 | " def get_img_feature(image):\n", 355 | " image = np.array(image).astype(np.uint8)\n", 356 | " image = utils.center_crop(512, 512, image)\n", 357 | " clip_img_feature = clip_img_model.encode_image(clip_img_model_preprocess(Image.fromarray(image)).unsqueeze(0).to(device))\n", 358 | "\n", 359 | " image = (image / 127.5 - 1.0).astype(np.float32)\n", 360 | " image = einops.rearrange(image, 'h w c -> 1 c h w')\n", 361 | " image = torch.tensor(image, device=device)\n", 362 | " moments = autoencoder.encode_moments(image)\n", 363 | "\n", 364 | " return clip_img_feature, moments\n", 365 | "\n", 366 | " image = Image.open(img).convert('RGB')\n", 367 | " clip_img, img_context = get_img_feature(image)\n", 368 | "\n", 369 | " img_contexts.append(img_context)\n", 370 | " clip_imgs.append(clip_img)\n", 371 | " img_contexts = img_contexts * n_samples\n", 372 | " clip_imgs = clip_imgs * n_samples\n", 373 | "\n", 374 | " img_contexts = torch.concat(img_contexts, dim=0)\n", 375 | " z_img = autoencoder.sample(img_contexts)\n", 376 | " clip_imgs = torch.stack(clip_imgs, dim=0)\n", 377 | "\n" 378 | ], 379 | "metadata": { 380 | "id": "ZptJaHbG65zW" 381 | }, 382 | "execution_count": null, 383 | "outputs": [] 384 | }, 385 | { 386 | "cell_type": "markdown", 387 | "source": [ 388 | "Define the required functions" 389 | ], 390 | "metadata": { 391 | "id": "r6optBAy9U12" 392 | } 393 | }, 394 | { 395 | "cell_type": "code", 396 | "source": [ 397 | "def t2i_nnet(x, timesteps, text): # text is the low dimension version of the text clip embedding\n", 398 | " \"\"\"\n", 399 | " 1. calculate the conditional model output\n", 400 | " 2. calculate unconditional model output\n", 401 | " config.sample.t2i_cfg_mode == 'empty_token': using the original cfg with the empty string\n", 402 | " config.sample.t2i_cfg_mode == 'true_uncond: using the unconditional model learned by our method\n", 403 | " 3. return linear combination of conditional output and unconditional output\n", 404 | " \"\"\"\n", 405 | " z, clip_img = split(x)\n", 406 | "\n", 407 | " t_text = torch.zeros(timesteps.size(0), dtype=torch.int, device=device)\n", 408 | "\n", 409 | " z_out, clip_img_out, text_out = nnet(z, clip_img, text=text, t_img=timesteps, t_text=t_text,\n", 410 | " data_type=torch.zeros_like(t_text, device=device, dtype=torch.int) + data_type)\n", 411 | " x_out = combine(z_out, clip_img_out)\n", 412 | "\n", 413 | " if cfg_scale == 0.:\n", 414 | " return x_out\n", 415 | "\n", 416 | " text_N = torch.randn_like(text) # 3 other possible choices\n", 417 | " z_out_uncond, clip_img_out_uncond, text_out_uncond = nnet(z, clip_img, text=text_N, t_img=timesteps, t_text=torch.ones_like(timesteps) * N,\n", 418 | " data_type=torch.zeros_like(t_text, device=device, dtype=torch.int) + data_type)\n", 419 | " x_out_uncond = combine(z_out_uncond, clip_img_out_uncond)\n", 420 | " \n", 421 | "\n", 422 | " return x_out + cfg_scale * (x_out - x_out_uncond)\n", 423 | "\n", 424 | "def i_nnet(x, timesteps):\n", 425 | " z, clip_img = split(x)\n", 426 | " text = torch.randn(x.size(0), 77, 64, device=device)\n", 427 | " t_text = torch.ones_like(timesteps) * N\n", 428 | " z_out, clip_img_out, text_out = nnet(z, clip_img, text=text, t_img=timesteps, t_text=t_text,\n", 429 | " data_type=torch.zeros_like(t_text, device=device, dtype=torch.int) + data_type)\n", 430 | " x_out = combine(z_out, clip_img_out)\n", 431 | " return x_out\n", 432 | "\n", 433 | "def t_nnet(x, timesteps):\n", 434 | " z = torch.randn(x.size(0), *[4, 64, 64], device=device)\n", 435 | " clip_img = torch.randn(x.size(0), 1, 512, device=device)\n", 436 | " z_out, clip_img_out, text_out = nnet(z, clip_img, text=x, t_img=torch.ones_like(timesteps) * N, t_text=timesteps,\n", 437 | " data_type=torch.zeros_like(timesteps, device=device, dtype=torch.int) + data_type)\n", 438 | " return text_out\n", 439 | "\n", 440 | "def i2t_nnet(x, timesteps, z, clip_img):\n", 441 | " \"\"\"\n", 442 | " 1. calculate the conditional model output\n", 443 | " 2. calculate unconditional model output\n", 444 | " 3. return linear combination of conditional output and unconditional output\n", 445 | " \"\"\"\n", 446 | " t_img = torch.zeros(timesteps.size(0), dtype=torch.int, device=device)\n", 447 | "\n", 448 | " z_out, clip_img_out, text_out = nnet(z, clip_img, text=x, t_img=t_img, t_text=timesteps,\n", 449 | " data_type=torch.zeros_like(t_img, device=device, dtype=torch.int) + data_type)\n", 450 | "\n", 451 | " if cfg_scale == 0.:\n", 452 | " return text_out\n", 453 | "\n", 454 | " z_N = torch.randn_like(z) # 3 other possible choices\n", 455 | " clip_img_N = torch.randn_like(clip_img)\n", 456 | " z_out_uncond, clip_img_out_uncond, text_out_uncond = nnet(z_N, clip_img_N, text=x, t_img=torch.ones_like(timesteps) * N, t_text=timesteps,\n", 457 | " data_type=torch.zeros_like(timesteps, device=device, dtype=torch.int) + data_type)\n", 458 | "\n", 459 | " return text_out + cfg_scale * (text_out - text_out_uncond)\n", 460 | "\n", 461 | "def joint_nnet(x, timesteps):\n", 462 | " z, clip_img, text = split_joint(x)\n", 463 | " z_out, clip_img_out, text_out = nnet(z, clip_img, text=text, t_img=timesteps, t_text=timesteps,\n", 464 | " data_type=torch.zeros_like(timesteps, device=device, dtype=torch.int) + data_type)\n", 465 | " x_out = combine_joint(z_out, clip_img_out, text_out)\n", 466 | "\n", 467 | " if cfg_scale == 0.:\n", 468 | " return x_out\n", 469 | "\n", 470 | " z_noise = torch.randn(x.size(0), *(4, 64, 64), device=device)\n", 471 | " clip_img_noise = torch.randn(x.size(0), 1, 512, device=device)\n", 472 | " text_noise = torch.randn(x.size(0), 77, 64, device=device)\n", 473 | "\n", 474 | " _, _, text_out_uncond = nnet(z_noise, clip_img_noise, text=text, t_img=torch.ones_like(timesteps) * N, t_text=timesteps,\n", 475 | " data_type=torch.zeros_like(timesteps, device=device, dtype=torch.int) + data_type)\n", 476 | " z_out_uncond, clip_img_out_uncond, _ = nnet(z, clip_img, text=text_noise, t_img=timesteps, t_text=torch.ones_like(timesteps) * N,\n", 477 | " data_type=torch.zeros_like(timesteps, device=device, dtype=torch.int) + data_type)\n", 478 | "\n", 479 | " x_out_uncond = combine_joint(z_out_uncond, clip_img_out_uncond, text_out_uncond)\n", 480 | "\n", 481 | " return x_out + cfg_scale * (x_out - x_out_uncond)\n", 482 | "\n", 483 | "\n", 484 | "def sample_fn(mode, **kwargs):\n", 485 | "\n", 486 | " _z_init = torch.randn(n_samples, *(4, 64, 64), device=device)\n", 487 | " _clip_img_init = torch.randn(n_samples, 1, 512, device=device)\n", 488 | " _text_init = torch.randn(n_samples, 77, 64, device=device)\n", 489 | " if mode == 'joint':\n", 490 | " _x_init = combine_joint(_z_init, _clip_img_init, _text_init)\n", 491 | " elif mode in ['t2i', 'i']:\n", 492 | " _x_init = combine(_z_init, _clip_img_init)\n", 493 | " elif mode in ['i2t', 't']:\n", 494 | " _x_init = _text_init\n", 495 | " noise_schedule = NoiseScheduleVP(schedule='discrete', betas=torch.tensor(_betas, device=device).float())\n", 496 | "\n", 497 | " def model_fn(x, t_continuous):\n", 498 | " t = t_continuous * N\n", 499 | " if mode == 'joint':\n", 500 | " return joint_nnet(x, t)\n", 501 | " elif mode == 't2i':\n", 502 | " return t2i_nnet(x, t, **kwargs)\n", 503 | " elif mode == 'i2t':\n", 504 | " return i2t_nnet(x, t, **kwargs)\n", 505 | " elif mode == 'i':\n", 506 | " return i_nnet(x, t)\n", 507 | " elif mode == 't':\n", 508 | " return t_nnet(x, t)\n", 509 | "\n", 510 | " dpm_solver = DPM_Solver(model_fn, noise_schedule, predict_x0=True, thresholding=False)\n", 511 | " with torch.no_grad():\n", 512 | " with torch.autocast(device_type=device):\n", 513 | " x = dpm_solver.sample(_x_init, steps=steps, eps=1. / N, T=1.)\n", 514 | "\n", 515 | " os.makedirs(output_path, exist_ok=True)\n", 516 | " if mode == 'joint':\n", 517 | " _z, _clip_img, _text = split_joint(x)\n", 518 | " return _z, _clip_img, _text\n", 519 | " elif mode in ['t2i', 'i']:\n", 520 | " _z, _clip_img = split(x)\n", 521 | " return _z, _clip_img\n", 522 | " elif mode in ['i2t', 't']:\n", 523 | " return x\n" 524 | ], 525 | "metadata": { 526 | "id": "PQFyP5Vu9Ub5" 527 | }, 528 | "execution_count": null, 529 | "outputs": [] 530 | }, 531 | { 532 | "cell_type": "markdown", 533 | "source": [ 534 | "Sample" 535 | ], 536 | "metadata": { 537 | "id": "SV0uxXQ6CEoZ" 538 | } 539 | }, 540 | { 541 | "cell_type": "code", 542 | "source": [ 543 | "set_seed(seed)\n", 544 | "def show(path):\n", 545 | " samples = Image.open(path)\n", 546 | " display(samples)\n", 547 | "\n", 548 | "if mode in ['joint']:\n", 549 | " _z, _clip_img, _text = sample_fn(mode)\n", 550 | " samples = unpreprocess(decode(_z))\n", 551 | " prompts = caption_decoder.generate_captions(_text)\n", 552 | " os.makedirs(os.path.join(output_path, mode), exist_ok=True)\n", 553 | " print(prompts)\n", 554 | " with open(os.path.join(output_path, mode, 'prompts.txt'), 'w') as f:\n", 555 | " print('\\n'.join(prompts), file=f)\n", 556 | " for idx, sample in enumerate(samples):\n", 557 | " save_path = os.path.join(output_path, mode, f'{idx}.png')\n", 558 | " save_image(sample, save_path)\n", 559 | " watermarking(save_path)\n", 560 | " # save a grid of generated images\n", 561 | " samples_pos = []\n", 562 | " for idx, sample in enumerate(samples):\n", 563 | " sample_pil = standard_transforms.ToPILImage()(sample)\n", 564 | " sample_pil = utils.add_water(sample_pil)\n", 565 | " sample = standard_transforms.ToTensor()(sample_pil)\n", 566 | " samples_pos.append(sample)\n", 567 | " samples = make_grid(samples_pos, nrow)\n", 568 | " save_path = os.path.join(output_path, mode, f'grid.png')\n", 569 | " save_image(samples, save_path)\n", 570 | " show(save_path)\n", 571 | "\n", 572 | "elif mode in ['t2i', 'i', 'i2t2i']:\n", 573 | " if mode == 't2i':\n", 574 | " _z, _clip_img = sample_fn(mode, text=contexts_low_dim) # conditioned on the text embedding\n", 575 | " elif mode == 'i':\n", 576 | " _z, _clip_img = sample_fn(mode)\n", 577 | " elif mode == 'i2t2i':\n", 578 | " _text = sample_fn('i2t', z=z_img, clip_img=clip_imgs) # conditioned on the image embedding\n", 579 | " _z, _clip_img = sample_fn('t2i', text=_text)\n", 580 | " samples = unpreprocess(decode(_z))\n", 581 | " os.makedirs(os.path.join(output_path, mode), exist_ok=True)\n", 582 | " for idx, sample in enumerate(samples):\n", 583 | " save_path = os.path.join(output_path, mode, f'{idx}.png')\n", 584 | " save_image(sample, save_path)\n", 585 | " watermarking(save_path)\n", 586 | " # save a grid of generated images\n", 587 | " samples_pos = []\n", 588 | " for idx, sample in enumerate(samples):\n", 589 | " sample_pil = standard_transforms.ToPILImage()(sample)\n", 590 | " sample_pil = utils.add_water(sample_pil)\n", 591 | " sample = standard_transforms.ToTensor()(sample_pil)\n", 592 | " samples_pos.append(sample)\n", 593 | " samples = make_grid(samples_pos, nrow)\n", 594 | " save_path = os.path.join(output_path, mode, f'grid.png')\n", 595 | " save_image(samples, save_path)\n", 596 | " show(save_path)\n", 597 | "\n", 598 | "\n", 599 | "elif mode in ['i2t', 't', 't2i2t']:\n", 600 | " if mode == 'i2t':\n", 601 | " _text = sample_fn(mode, z=z_img, clip_img=clip_imgs) # conditioned on the image embedding\n", 602 | " elif mode == 't':\n", 603 | " _text = sample_fn(mode)\n", 604 | " elif mode == 't2i2t':\n", 605 | " _z, _clip_img = sample_fn('t2i', text=contexts_low_dim)\n", 606 | " _text = sample_fn('i2t', z=_z, clip_img=_clip_img)\n", 607 | " samples = caption_decoder.generate_captions(_text)\n", 608 | " print(samples)\n", 609 | " logging.info(samples)\n", 610 | " os.makedirs(os.path.join(output_path, mode), exist_ok=True)\n", 611 | " with open(os.path.join(output_path, mode, f'{mode}.txt'), 'w') as f:\n", 612 | " print('\\n'.join(samples), file=f)" 613 | ], 614 | "metadata": { 615 | "id": "ip4LuG_rCGqD" 616 | }, 617 | "execution_count": null, 618 | "outputs": [] 619 | } 620 | ] 621 | } -------------------------------------------------------------------------------- /assets/ArialBoldMT.ttf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/thu-ml/unidiffuser/845e14f7939fb28a7f8d879ff18b7c9e09c7434b/assets/ArialBoldMT.ttf -------------------------------------------------------------------------------- /assets/demos_v0.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/thu-ml/unidiffuser/845e14f7939fb28a7f8d879ff18b7c9e09c7434b/assets/demos_v0.png -------------------------------------------------------------------------------- /assets/space.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/thu-ml/unidiffuser/845e14f7939fb28a7f8d879ff18b7c9e09c7434b/assets/space.jpg -------------------------------------------------------------------------------- /assets/unidiffuser.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/thu-ml/unidiffuser/845e14f7939fb28a7f8d879ff18b7c9e09c7434b/assets/unidiffuser.png -------------------------------------------------------------------------------- /configs/sample_unidiffuser_v0.py: -------------------------------------------------------------------------------- 1 | import ml_collections 2 | 3 | 4 | def d(**kwargs): 5 | """Helper of creating a config dict.""" 6 | return ml_collections.ConfigDict(initial_dictionary=kwargs) 7 | 8 | 9 | def get_config(): 10 | config = ml_collections.ConfigDict() 11 | 12 | config.seed = 1234 13 | config.pred = 'noise_pred' 14 | config.z_shape = (4, 64, 64) 15 | config.clip_img_dim = 512 16 | config.clip_text_dim = 768 17 | config.text_dim = 64 # reduce dimension 18 | 19 | config.autoencoder = d( 20 | pretrained_path='models/autoencoder_kl.pth', 21 | ) 22 | 23 | config.caption_decoder = d( 24 | pretrained_path="models/caption_decoder.pth", 25 | hidden_dim=config.get_ref('text_dim') 26 | ) 27 | 28 | config.nnet = d( 29 | name='uvit_multi_post_ln', 30 | img_size=64, 31 | in_chans=4, 32 | patch_size=2, 33 | embed_dim=1536, 34 | depth=30, 35 | num_heads=24, 36 | mlp_ratio=4, 37 | qkv_bias=False, 38 | pos_drop_rate=0., 39 | drop_rate=0., 40 | attn_drop_rate=0., 41 | mlp_time_embed=False, 42 | text_dim=config.get_ref('text_dim'), 43 | num_text_tokens=77, 44 | clip_img_dim=config.get_ref('clip_img_dim'), 45 | use_checkpoint=True 46 | ) 47 | 48 | config.sample = d( 49 | sample_steps=50, 50 | scale=7., 51 | t2i_cfg_mode='true_uncond' 52 | ) 53 | 54 | return config 55 | -------------------------------------------------------------------------------- /configs/sample_unidiffuser_v1.py: -------------------------------------------------------------------------------- 1 | import ml_collections 2 | 3 | 4 | def d(**kwargs): 5 | """Helper of creating a config dict.""" 6 | return ml_collections.ConfigDict(initial_dictionary=kwargs) 7 | 8 | 9 | def get_config(): 10 | config = ml_collections.ConfigDict() 11 | 12 | config.seed = 1234 13 | config.pred = 'noise_pred' 14 | config.z_shape = (4, 64, 64) 15 | config.clip_img_dim = 512 16 | config.clip_text_dim = 768 17 | config.text_dim = 64 # reduce dimension 18 | config.data_type = 1 19 | 20 | config.autoencoder = d( 21 | pretrained_path='models/autoencoder_kl.pth', 22 | ) 23 | 24 | config.caption_decoder = d( 25 | pretrained_path="models/caption_decoder.pth", 26 | hidden_dim=config.get_ref('text_dim') 27 | ) 28 | 29 | config.nnet = d( 30 | name='uvit_multi_post_ln_v1', 31 | img_size=64, 32 | in_chans=4, 33 | patch_size=2, 34 | embed_dim=1536, 35 | depth=30, 36 | num_heads=24, 37 | mlp_ratio=4, 38 | qkv_bias=False, 39 | pos_drop_rate=0., 40 | drop_rate=0., 41 | attn_drop_rate=0., 42 | mlp_time_embed=False, 43 | text_dim=config.get_ref('text_dim'), 44 | num_text_tokens=77, 45 | clip_img_dim=config.get_ref('clip_img_dim'), 46 | use_checkpoint=True 47 | ) 48 | 49 | config.sample = d( 50 | sample_steps=50, 51 | scale=7., 52 | t2i_cfg_mode='true_uncond' 53 | ) 54 | 55 | return config 56 | -------------------------------------------------------------------------------- /libs/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/thu-ml/unidiffuser/845e14f7939fb28a7f8d879ff18b7c9e09c7434b/libs/__init__.py -------------------------------------------------------------------------------- /libs/autoencoder.py: -------------------------------------------------------------------------------- 1 | import torch 2 | import torch.nn as nn 3 | import numpy as np 4 | from einops import rearrange 5 | 6 | 7 | class LinearAttention(nn.Module): 8 | def __init__(self, dim, heads=4, dim_head=32): 9 | super().__init__() 10 | self.heads = heads 11 | hidden_dim = dim_head * heads 12 | self.to_qkv = nn.Conv2d(dim, hidden_dim * 3, 1, bias = False) 13 | self.to_out = nn.Conv2d(hidden_dim, dim, 1) 14 | 15 | def forward(self, x): 16 | b, c, h, w = x.shape 17 | qkv = self.to_qkv(x) 18 | q, k, v = rearrange(qkv, 'b (qkv heads c) h w -> qkv b heads c (h w)', heads = self.heads, qkv=3) 19 | k = k.softmax(dim=-1) 20 | context = torch.einsum('bhdn,bhen->bhde', k, v) 21 | out = torch.einsum('bhde,bhdn->bhen', context, q) 22 | out = rearrange(out, 'b heads c (h w) -> b (heads c) h w', heads=self.heads, h=h, w=w) 23 | return self.to_out(out) 24 | 25 | 26 | def nonlinearity(x): 27 | # swish 28 | return x*torch.sigmoid(x) 29 | 30 | 31 | def Normalize(in_channels, num_groups=32): 32 | return torch.nn.GroupNorm(num_groups=num_groups, num_channels=in_channels, eps=1e-6, affine=True) 33 | 34 | 35 | class Upsample(nn.Module): 36 | def __init__(self, in_channels, with_conv): 37 | super().__init__() 38 | self.with_conv = with_conv 39 | if self.with_conv: 40 | self.conv = torch.nn.Conv2d(in_channels, 41 | in_channels, 42 | kernel_size=3, 43 | stride=1, 44 | padding=1) 45 | 46 | def forward(self, x): 47 | x = torch.nn.functional.interpolate(x, scale_factor=2.0, mode="nearest") 48 | if self.with_conv: 49 | x = self.conv(x) 50 | return x 51 | 52 | 53 | class Downsample(nn.Module): 54 | def __init__(self, in_channels, with_conv): 55 | super().__init__() 56 | self.with_conv = with_conv 57 | if self.with_conv: 58 | # no asymmetric padding in torch conv, must do it ourselves 59 | self.conv = torch.nn.Conv2d(in_channels, 60 | in_channels, 61 | kernel_size=3, 62 | stride=2, 63 | padding=0) 64 | 65 | def forward(self, x): 66 | if self.with_conv: 67 | pad = (0,1,0,1) 68 | x = torch.nn.functional.pad(x, pad, mode="constant", value=0) 69 | x = self.conv(x) 70 | else: 71 | x = torch.nn.functional.avg_pool2d(x, kernel_size=2, stride=2) 72 | return x 73 | 74 | 75 | class ResnetBlock(nn.Module): 76 | def __init__(self, *, in_channels, out_channels=None, conv_shortcut=False, 77 | dropout, temb_channels=512): 78 | super().__init__() 79 | self.in_channels = in_channels 80 | out_channels = in_channels if out_channels is None else out_channels 81 | self.out_channels = out_channels 82 | self.use_conv_shortcut = conv_shortcut 83 | 84 | self.norm1 = Normalize(in_channels) 85 | self.conv1 = torch.nn.Conv2d(in_channels, 86 | out_channels, 87 | kernel_size=3, 88 | stride=1, 89 | padding=1) 90 | if temb_channels > 0: 91 | self.temb_proj = torch.nn.Linear(temb_channels, 92 | out_channels) 93 | self.norm2 = Normalize(out_channels) 94 | self.dropout = torch.nn.Dropout(dropout) 95 | self.conv2 = torch.nn.Conv2d(out_channels, 96 | out_channels, 97 | kernel_size=3, 98 | stride=1, 99 | padding=1) 100 | if self.in_channels != self.out_channels: 101 | if self.use_conv_shortcut: 102 | self.conv_shortcut = torch.nn.Conv2d(in_channels, 103 | out_channels, 104 | kernel_size=3, 105 | stride=1, 106 | padding=1) 107 | else: 108 | self.nin_shortcut = torch.nn.Conv2d(in_channels, 109 | out_channels, 110 | kernel_size=1, 111 | stride=1, 112 | padding=0) 113 | 114 | def forward(self, x, temb): 115 | h = x 116 | h = self.norm1(h) 117 | h = nonlinearity(h) 118 | h = self.conv1(h) 119 | 120 | if temb is not None: 121 | h = h + self.temb_proj(nonlinearity(temb))[:,:,None,None] 122 | 123 | h = self.norm2(h) 124 | h = nonlinearity(h) 125 | h = self.dropout(h) 126 | h = self.conv2(h) 127 | 128 | if self.in_channels != self.out_channels: 129 | if self.use_conv_shortcut: 130 | x = self.conv_shortcut(x) 131 | else: 132 | x = self.nin_shortcut(x) 133 | 134 | return x+h 135 | 136 | 137 | class LinAttnBlock(LinearAttention): 138 | """to match AttnBlock usage""" 139 | def __init__(self, in_channels): 140 | super().__init__(dim=in_channels, heads=1, dim_head=in_channels) 141 | 142 | 143 | class AttnBlock(nn.Module): 144 | def __init__(self, in_channels): 145 | super().__init__() 146 | self.in_channels = in_channels 147 | 148 | self.norm = Normalize(in_channels) 149 | self.q = torch.nn.Conv2d(in_channels, 150 | in_channels, 151 | kernel_size=1, 152 | stride=1, 153 | padding=0) 154 | self.k = torch.nn.Conv2d(in_channels, 155 | in_channels, 156 | kernel_size=1, 157 | stride=1, 158 | padding=0) 159 | self.v = torch.nn.Conv2d(in_channels, 160 | in_channels, 161 | kernel_size=1, 162 | stride=1, 163 | padding=0) 164 | self.proj_out = torch.nn.Conv2d(in_channels, 165 | in_channels, 166 | kernel_size=1, 167 | stride=1, 168 | padding=0) 169 | 170 | 171 | def forward(self, x): 172 | h_ = x 173 | h_ = self.norm(h_) 174 | q = self.q(h_) 175 | k = self.k(h_) 176 | v = self.v(h_) 177 | 178 | # compute attention 179 | b,c,h,w = q.shape 180 | q = q.reshape(b,c,h*w) 181 | q = q.permute(0,2,1) # b,hw,c 182 | k = k.reshape(b,c,h*w) # b,c,hw 183 | w_ = torch.bmm(q,k) # b,hw,hw w[b,i,j]=sum_c q[b,i,c]k[b,c,j] 184 | w_ = w_ * (int(c)**(-0.5)) 185 | w_ = torch.nn.functional.softmax(w_, dim=2) 186 | 187 | # attend to values 188 | v = v.reshape(b,c,h*w) 189 | w_ = w_.permute(0,2,1) # b,hw,hw (first hw of k, second of q) 190 | h_ = torch.bmm(v,w_) # b, c,hw (hw of q) h_[b,c,j] = sum_i v[b,c,i] w_[b,i,j] 191 | h_ = h_.reshape(b,c,h,w) 192 | 193 | h_ = self.proj_out(h_) 194 | 195 | return x+h_ 196 | 197 | 198 | def make_attn(in_channels, attn_type="vanilla"): 199 | assert attn_type in ["vanilla", "linear", "none"], f'attn_type {attn_type} unknown' 200 | print(f"making attention of type '{attn_type}' with {in_channels} in_channels") 201 | if attn_type == "vanilla": 202 | return AttnBlock(in_channels) 203 | elif attn_type == "none": 204 | return nn.Identity(in_channels) 205 | else: 206 | return LinAttnBlock(in_channels) 207 | 208 | 209 | class Encoder(nn.Module): 210 | def __init__(self, *, ch, out_ch, ch_mult=(1,2,4,8), num_res_blocks, 211 | attn_resolutions, dropout=0.0, resamp_with_conv=True, in_channels, 212 | resolution, z_channels, double_z=True, use_linear_attn=False, attn_type="vanilla", 213 | **ignore_kwargs): 214 | super().__init__() 215 | if use_linear_attn: attn_type = "linear" 216 | self.ch = ch 217 | self.temb_ch = 0 218 | self.num_resolutions = len(ch_mult) 219 | self.num_res_blocks = num_res_blocks 220 | self.resolution = resolution 221 | self.in_channels = in_channels 222 | 223 | # downsampling 224 | self.conv_in = torch.nn.Conv2d(in_channels, 225 | self.ch, 226 | kernel_size=3, 227 | stride=1, 228 | padding=1) 229 | 230 | curr_res = resolution 231 | in_ch_mult = (1,)+tuple(ch_mult) 232 | self.in_ch_mult = in_ch_mult 233 | self.down = nn.ModuleList() 234 | for i_level in range(self.num_resolutions): 235 | block = nn.ModuleList() 236 | attn = nn.ModuleList() 237 | block_in = ch*in_ch_mult[i_level] 238 | block_out = ch*ch_mult[i_level] 239 | for i_block in range(self.num_res_blocks): 240 | block.append(ResnetBlock(in_channels=block_in, 241 | out_channels=block_out, 242 | temb_channels=self.temb_ch, 243 | dropout=dropout)) 244 | block_in = block_out 245 | if curr_res in attn_resolutions: 246 | attn.append(make_attn(block_in, attn_type=attn_type)) 247 | down = nn.Module() 248 | down.block = block 249 | down.attn = attn 250 | if i_level != self.num_resolutions-1: 251 | down.downsample = Downsample(block_in, resamp_with_conv) 252 | curr_res = curr_res // 2 253 | self.down.append(down) 254 | 255 | # middle 256 | self.mid = nn.Module() 257 | self.mid.block_1 = ResnetBlock(in_channels=block_in, 258 | out_channels=block_in, 259 | temb_channels=self.temb_ch, 260 | dropout=dropout) 261 | self.mid.attn_1 = make_attn(block_in, attn_type=attn_type) 262 | self.mid.block_2 = ResnetBlock(in_channels=block_in, 263 | out_channels=block_in, 264 | temb_channels=self.temb_ch, 265 | dropout=dropout) 266 | 267 | # end 268 | self.norm_out = Normalize(block_in) 269 | self.conv_out = torch.nn.Conv2d(block_in, 270 | 2*z_channels if double_z else z_channels, 271 | kernel_size=3, 272 | stride=1, 273 | padding=1) 274 | 275 | def forward(self, x): 276 | # timestep embedding 277 | temb = None 278 | 279 | # downsampling 280 | hs = [self.conv_in(x)] 281 | for i_level in range(self.num_resolutions): 282 | for i_block in range(self.num_res_blocks): 283 | h = self.down[i_level].block[i_block](hs[-1], temb) 284 | if len(self.down[i_level].attn) > 0: 285 | h = self.down[i_level].attn[i_block](h) 286 | hs.append(h) 287 | if i_level != self.num_resolutions-1: 288 | hs.append(self.down[i_level].downsample(hs[-1])) 289 | 290 | # middle 291 | h = hs[-1] 292 | h = self.mid.block_1(h, temb) 293 | h = self.mid.attn_1(h) 294 | h = self.mid.block_2(h, temb) 295 | 296 | # end 297 | h = self.norm_out(h) 298 | h = nonlinearity(h) 299 | h = self.conv_out(h) 300 | return h 301 | 302 | 303 | class Decoder(nn.Module): 304 | def __init__(self, *, ch, out_ch, ch_mult=(1,2,4,8), num_res_blocks, 305 | attn_resolutions, dropout=0.0, resamp_with_conv=True, in_channels, 306 | resolution, z_channels, give_pre_end=False, tanh_out=False, use_linear_attn=False, 307 | attn_type="vanilla", **ignorekwargs): 308 | super().__init__() 309 | if use_linear_attn: attn_type = "linear" 310 | self.ch = ch 311 | self.temb_ch = 0 312 | self.num_resolutions = len(ch_mult) 313 | self.num_res_blocks = num_res_blocks 314 | self.resolution = resolution 315 | self.in_channels = in_channels 316 | self.give_pre_end = give_pre_end 317 | self.tanh_out = tanh_out 318 | 319 | # compute in_ch_mult, block_in and curr_res at lowest res 320 | in_ch_mult = (1,)+tuple(ch_mult) 321 | block_in = ch*ch_mult[self.num_resolutions-1] 322 | curr_res = resolution // 2**(self.num_resolutions-1) 323 | self.z_shape = (1,z_channels,curr_res,curr_res) 324 | print("Working with z of shape {} = {} dimensions.".format( 325 | self.z_shape, np.prod(self.z_shape))) 326 | 327 | # z to block_in 328 | self.conv_in = torch.nn.Conv2d(z_channels, 329 | block_in, 330 | kernel_size=3, 331 | stride=1, 332 | padding=1) 333 | 334 | # middle 335 | self.mid = nn.Module() 336 | self.mid.block_1 = ResnetBlock(in_channels=block_in, 337 | out_channels=block_in, 338 | temb_channels=self.temb_ch, 339 | dropout=dropout) 340 | self.mid.attn_1 = make_attn(block_in, attn_type=attn_type) 341 | self.mid.block_2 = ResnetBlock(in_channels=block_in, 342 | out_channels=block_in, 343 | temb_channels=self.temb_ch, 344 | dropout=dropout) 345 | 346 | # upsampling 347 | self.up = nn.ModuleList() 348 | for i_level in reversed(range(self.num_resolutions)): 349 | block = nn.ModuleList() 350 | attn = nn.ModuleList() 351 | block_out = ch*ch_mult[i_level] 352 | for i_block in range(self.num_res_blocks+1): 353 | block.append(ResnetBlock(in_channels=block_in, 354 | out_channels=block_out, 355 | temb_channels=self.temb_ch, 356 | dropout=dropout)) 357 | block_in = block_out 358 | if curr_res in attn_resolutions: 359 | attn.append(make_attn(block_in, attn_type=attn_type)) 360 | up = nn.Module() 361 | up.block = block 362 | up.attn = attn 363 | if i_level != 0: 364 | up.upsample = Upsample(block_in, resamp_with_conv) 365 | curr_res = curr_res * 2 366 | self.up.insert(0, up) # prepend to get consistent order 367 | 368 | # end 369 | self.norm_out = Normalize(block_in) 370 | self.conv_out = torch.nn.Conv2d(block_in, 371 | out_ch, 372 | kernel_size=3, 373 | stride=1, 374 | padding=1) 375 | 376 | def forward(self, z): 377 | #assert z.shape[1:] == self.z_shape[1:] 378 | self.last_z_shape = z.shape 379 | 380 | # timestep embedding 381 | temb = None 382 | 383 | # z to block_in 384 | h = self.conv_in(z) 385 | 386 | # middle 387 | h = self.mid.block_1(h, temb) 388 | h = self.mid.attn_1(h) 389 | h = self.mid.block_2(h, temb) 390 | 391 | # upsampling 392 | for i_level in reversed(range(self.num_resolutions)): 393 | for i_block in range(self.num_res_blocks+1): 394 | h = self.up[i_level].block[i_block](h, temb) 395 | if len(self.up[i_level].attn) > 0: 396 | h = self.up[i_level].attn[i_block](h) 397 | if i_level != 0: 398 | h = self.up[i_level].upsample(h) 399 | 400 | # end 401 | if self.give_pre_end: 402 | return h 403 | 404 | h = self.norm_out(h) 405 | h = nonlinearity(h) 406 | h = self.conv_out(h) 407 | if self.tanh_out: 408 | h = torch.tanh(h) 409 | return h 410 | 411 | 412 | class FrozenAutoencoderKL(nn.Module): 413 | def __init__(self, ddconfig, embed_dim, pretrained_path, scale_factor=0.18215): 414 | super().__init__() 415 | print(f'Create autoencoder with scale_factor={scale_factor}') 416 | self.encoder = Encoder(**ddconfig) 417 | self.decoder = Decoder(**ddconfig) 418 | assert ddconfig["double_z"] 419 | self.quant_conv = torch.nn.Conv2d(2 * ddconfig["z_channels"], 2 * embed_dim, 1) 420 | self.post_quant_conv = torch.nn.Conv2d(embed_dim, ddconfig["z_channels"], 1) 421 | self.embed_dim = embed_dim 422 | self.scale_factor = scale_factor 423 | m, u = self.load_state_dict(torch.load(pretrained_path, map_location='cpu')) 424 | assert len(m) == 0 and len(u) == 0 425 | self.eval() 426 | self.requires_grad_(False) 427 | 428 | def encode_moments(self, x): 429 | h = self.encoder(x) 430 | moments = self.quant_conv(h) 431 | return moments 432 | 433 | def sample(self, moments): 434 | mean, logvar = torch.chunk(moments, 2, dim=1) 435 | logvar = torch.clamp(logvar, -30.0, 20.0) 436 | std = torch.exp(0.5 * logvar) 437 | z = mean + std * torch.randn_like(mean) 438 | z = self.scale_factor * z 439 | return z 440 | 441 | def encode(self, x): 442 | moments = self.encode_moments(x) 443 | z = self.sample(moments) 444 | return z 445 | 446 | def decode(self, z): 447 | z = (1. / self.scale_factor) * z 448 | z = self.post_quant_conv(z) 449 | dec = self.decoder(z) 450 | return dec 451 | 452 | def forward(self, inputs, fn): 453 | if fn == 'encode_moments': 454 | return self.encode_moments(inputs) 455 | elif fn == 'encode': 456 | return self.encode(inputs) 457 | elif fn == 'decode': 458 | return self.decode(inputs) 459 | else: 460 | raise NotImplementedError 461 | 462 | 463 | def get_model(pretrained_path, scale_factor=0.18215): 464 | ddconfig = dict( 465 | double_z=True, 466 | z_channels=4, 467 | resolution=256, 468 | in_channels=3, 469 | out_ch=3, 470 | ch=128, 471 | ch_mult=[1, 2, 4, 4], 472 | num_res_blocks=2, 473 | attn_resolutions=[], 474 | dropout=0.0 475 | ) 476 | return FrozenAutoencoderKL(ddconfig, 4, pretrained_path, scale_factor) 477 | 478 | 479 | def main(): 480 | import torchvision.transforms as transforms 481 | from torchvision.utils import save_image 482 | import os 483 | from PIL import Image 484 | 485 | model = get_model('assets/stable-diffusion/autoencoder_kl.pth') 486 | device = torch.device("cuda") if torch.cuda.is_available() else torch.device("cpu") 487 | model = model.to(device) 488 | 489 | scale_factor = 0.18215 490 | T = transforms.Compose([transforms.Resize(256), transforms.CenterCrop(256), transforms.ToTensor()]) 491 | path = 'imgs' 492 | fnames = os.listdir(path) 493 | for fname in fnames: 494 | p = os.path.join(path, fname) 495 | img = Image.open(p) 496 | img = T(img) 497 | img = img * 2. - 1 498 | img = img[None, ...] 499 | img = img.to(device) 500 | 501 | # with torch.cuda.amp.autocast(): 502 | # moments = model.encode_moments(img) 503 | # mean, logvar = torch.chunk(moments, 2, dim=1) 504 | # logvar = torch.clamp(logvar, -30.0, 20.0) 505 | # std = torch.exp(0.5 * logvar) 506 | # zs = [(mean + std * torch.randn_like(mean)) * scale_factor for _ in range(4)] 507 | # recons = [model.decode(z) for z in zs] 508 | 509 | with torch.cuda.amp.autocast(): 510 | print('test encode & decode') 511 | recons = [model.decode(model.encode(img)) for _ in range(4)] 512 | 513 | out = torch.cat([img, *recons], dim=0) 514 | out = (out + 1) * 0.5 515 | save_image(out, f'recons_{fname}') 516 | 517 | 518 | if __name__ == "__main__": 519 | main() 520 | -------------------------------------------------------------------------------- /libs/caption_decoder.py: -------------------------------------------------------------------------------- 1 | import os 2 | import numpy as np 3 | import torch 4 | from torch import nn 5 | from torch.nn import functional as nnf 6 | 7 | from transformers import GPT2Tokenizer, GPT2LMHeadModel 8 | from transformers import default_data_collator 9 | from transformers import EarlyStoppingCallback 10 | 11 | data_collator = default_data_collator 12 | es = EarlyStoppingCallback(early_stopping_patience=5) 13 | import json 14 | import argparse 15 | from typing import Union, Optional 16 | from collections import OrderedDict 17 | 18 | 19 | # %% model initial 20 | class ClipCaptionModel(nn.Module): 21 | """ 22 | """ 23 | 24 | def get_dummy_token(self, batch_size: int, device: torch.device) -> torch.Tensor: 25 | return torch.zeros(batch_size, self.prefix_length, dtype=torch.int64, device=device) 26 | 27 | def forward(self, tokens: torch.Tensor, prefix: torch.Tensor, mask: Optional[torch.Tensor] = None, 28 | labels: Optional[torch.Tensor] = None): 29 | """ 30 | : param tokens: (Tensor) [N x max_seq_len] eg. [4 X 33] 31 | : param prefix: (Tensor) [N x prefix_length x 768] eg. [4 x 77 x 768] 32 | : param mask: (Tensor) [N x (prefix_length + max_seq_len) x 768] eg. [4 x 110 x768] 33 | 34 | : attribute embedding_text: (Tensor) [N x max_seq_len x 768] eg. [4 x 33 x 768] 35 | : attribute embedding_cat: (Tensor) [N x (prefix_length + max_seq_len) x 768] eg. [4 x 110 x 768] 36 | """ 37 | embedding_text = self.gpt.transformer.wte(tokens) 38 | hidden = self.encode_prefix(prefix) 39 | prefix = self.decode_prefix(hidden) 40 | embedding_cat = torch.cat((prefix, embedding_text), dim=1) 41 | 42 | if labels is not None: 43 | dummy_token = self.get_dummy_token(tokens.shape[0], tokens.device) 44 | labels = torch.cat((dummy_token, tokens), dim=1) 45 | out = self.gpt(inputs_embeds=embedding_cat, labels=labels, attention_mask=mask) 46 | if self.hidden_dim is not None: 47 | return out, hidden 48 | else: 49 | return out 50 | 51 | def encode_decode_prefix(self, prefix): 52 | return self.decode_prefix(self.encode_prefix(prefix)) 53 | 54 | def __init__(self, prefix_length: int, hidden_dim=None): 55 | super(ClipCaptionModel, self).__init__() 56 | self.prefix_length = prefix_length 57 | eos = '<|EOS|>' 58 | special_tokens_dict = {'eos_token': eos} 59 | base_tokenizer = GPT2Tokenizer.from_pretrained('gpt2') 60 | base_tokenizer.add_special_tokens(special_tokens_dict) 61 | self.gpt = GPT2LMHeadModel.from_pretrained('gpt2', eos_token_id=base_tokenizer.eos_token_id) 62 | self.gpt.resize_token_embeddings(len(base_tokenizer)) 63 | 64 | self.hidden_dim = hidden_dim 65 | self.encode_prefix = nn.Linear(768, hidden_dim) if hidden_dim is not None else nn.Identity() 66 | self.decode_prefix = nn.Linear(hidden_dim, 768) if hidden_dim is not None else nn.Identity() 67 | 68 | 69 | 70 | 71 | def load_model(config_path: str, epoch_or_latest: Union[str, int] = '_latest'): 72 | with open(config_path) as f: 73 | config = json.load(f) 74 | parser = argparse.ArgumentParser() 75 | parser.set_defaults(**config) 76 | args = parser.parse_args() 77 | if type(epoch_or_latest) is int: 78 | epoch_or_latest = f"-{epoch_or_latest:03d}" 79 | model_path = os.path.join(args.out_dir, f"{args.prefix}{epoch_or_latest}.pt") 80 | model = ClipCaptionModel(args.prefix_length) 81 | if os.path.isfile(model_path): 82 | print(f"loading model from {model_path}") 83 | model.load_state_dict(torch.load(model_path, map_location=torch.device('cpu'))) 84 | else: 85 | print(f"{model_path} is not exist") 86 | return model, parser 87 | 88 | 89 | def generate_beam( 90 | model, 91 | tokenizer, 92 | beam_size: int = 5, 93 | prompt=None, 94 | embed=None, 95 | entry_length=67, 96 | temperature=1.0, 97 | stop_token: str = '<|EOS|>', 98 | ): 99 | model.eval() 100 | stop_token_index = tokenizer.encode(stop_token)[0] 101 | tokens = None 102 | scores = None 103 | device = next(model.parameters()).device 104 | seq_lengths = torch.ones(beam_size, device=device) 105 | is_stopped = torch.zeros(beam_size, device=device, dtype=torch.bool) 106 | with torch.no_grad(): 107 | if embed is not None: 108 | generated = embed 109 | else: 110 | if tokens is None: 111 | tokens = torch.tensor(tokenizer.encode(prompt)) 112 | tokens = tokens.unsqueeze(0).to(device) 113 | generated = model.gpt.transformer.wte(tokens) 114 | # pbar = tqdm(range(entry_length)) 115 | # pbar.set_description("generating text ...") 116 | for i in range(entry_length): 117 | # print(generated.shape) 118 | outputs = model.gpt(inputs_embeds=generated) 119 | logits = outputs.logits 120 | logits = logits[:, -1, :] / (temperature if temperature > 0 else 1.0) 121 | logits = logits.softmax(-1).log() 122 | if scores is None: 123 | scores, next_tokens = logits.topk(beam_size, -1) 124 | generated = generated.expand(beam_size, *generated.shape[1:]) 125 | next_tokens, scores = next_tokens.permute(1, 0), scores.squeeze(0) 126 | if tokens is None: 127 | tokens = next_tokens 128 | else: 129 | tokens = tokens.expand(beam_size, *tokens.shape[1:]) 130 | tokens = torch.cat((tokens, next_tokens), dim=1) 131 | else: 132 | logits[is_stopped] = -float(np.inf) 133 | logits[is_stopped, 0] = 0 134 | scores_sum = scores[:, None] + logits 135 | seq_lengths[~is_stopped] += 1 136 | scores_sum_average = scores_sum / seq_lengths[:, None] 137 | scores_sum_average, next_tokens = scores_sum_average.view(-1).topk( 138 | beam_size, -1 139 | ) 140 | next_tokens_source = next_tokens // scores_sum.shape[1] 141 | seq_lengths = seq_lengths[next_tokens_source] 142 | next_tokens = next_tokens % scores_sum.shape[1] 143 | next_tokens = next_tokens.unsqueeze(1) 144 | tokens = tokens[next_tokens_source] 145 | tokens = torch.cat((tokens, next_tokens), dim=1) 146 | generated = generated[next_tokens_source] 147 | scores = scores_sum_average * seq_lengths 148 | is_stopped = is_stopped[next_tokens_source] 149 | next_token_embed = model.gpt.transformer.wte(next_tokens.squeeze()).view( 150 | generated.shape[0], 1, -1 151 | ) 152 | generated = torch.cat((generated, next_token_embed), dim=1) 153 | is_stopped = is_stopped + next_tokens.eq(stop_token_index).squeeze() 154 | if is_stopped.all(): 155 | break 156 | scores = scores / seq_lengths 157 | output_list = tokens.cpu().numpy() 158 | output_texts = [ 159 | tokenizer.decode(output[: int(length)], skip_special_tokens=True) 160 | for output, length in zip(output_list, seq_lengths) 161 | ] 162 | order = scores.argsort(descending=True) 163 | output_texts = [output_texts[i] for i in order] 164 | model.train() 165 | return output_texts 166 | 167 | 168 | def generate2( 169 | model, 170 | tokenizer, 171 | tokens=None, 172 | prompt=None, 173 | embed=None, 174 | entry_count=1, 175 | entry_length=67, # maximum number of words 176 | top_p=0.8, 177 | temperature=1.0, 178 | stop_token: str = '<|EOS|>', 179 | ): 180 | model.eval() 181 | generated_num = 0 182 | generated_list = [] 183 | stop_token_index = tokenizer.encode(stop_token)[0] 184 | filter_value = -float("Inf") 185 | device = next(model.parameters()).device 186 | 187 | with torch.no_grad(): 188 | 189 | for entry_idx in range(entry_count): 190 | if embed is not None: 191 | generated = embed 192 | else: 193 | if tokens is None: 194 | tokens = torch.tensor(tokenizer.encode(prompt)) 195 | tokens = tokens.unsqueeze(0).to(device) 196 | 197 | generated = model.gpt.transformer.wte(tokens) 198 | 199 | for i in range(entry_length): 200 | 201 | outputs = model.gpt(inputs_embeds=generated) 202 | logits = outputs.logits 203 | logits = logits[:, -1, :] / (temperature if temperature > 0 else 1.0) 204 | sorted_logits, sorted_indices = torch.sort(logits, descending=True) 205 | cumulative_probs = torch.cumsum( 206 | nnf.softmax(sorted_logits, dim=-1), dim=-1 207 | ) 208 | sorted_indices_to_remove = cumulative_probs > top_p 209 | sorted_indices_to_remove[..., 1:] = sorted_indices_to_remove[ 210 | ..., :-1 211 | ].clone() 212 | sorted_indices_to_remove[..., 0] = 0 213 | 214 | indices_to_remove = sorted_indices[sorted_indices_to_remove] 215 | logits[:, indices_to_remove] = filter_value 216 | next_token = torch.argmax(logits, -1).unsqueeze(0) 217 | next_token_embed = model.gpt.transformer.wte(next_token) 218 | if tokens is None: 219 | tokens = next_token 220 | else: 221 | tokens = torch.cat((tokens, next_token), dim=1) 222 | generated = torch.cat((generated, next_token_embed), dim=1) 223 | if stop_token_index == next_token.item(): 224 | break 225 | 226 | output_list = list(tokens.squeeze().cpu().numpy()) 227 | output_text = tokenizer.decode(output_list) 228 | generated_list.append(output_text) 229 | 230 | return generated_list[0] 231 | 232 | 233 | class CaptionDecoder(object): 234 | def __init__(self, device, pretrained_path, hidden_dim=-1): 235 | if hidden_dim < 0: 236 | hidden_dim = None 237 | # tokenizer initialize 238 | eos = '<|EOS|>' 239 | special_tokens_dict = {'eos_token': eos} 240 | self.tokenizer = GPT2Tokenizer.from_pretrained('gpt2') 241 | self.tokenizer.add_special_tokens(special_tokens_dict) 242 | 243 | # model initialize 244 | feature_length = 77 245 | # modelFile = "assets/caption_decoder/coco_v2_latest.pt" 246 | self.caption_model = ClipCaptionModel(feature_length, hidden_dim=hidden_dim) 247 | # print("Load Model...") 248 | ckpt = torch.load(pretrained_path, map_location='cpu') 249 | state_dict = OrderedDict() 250 | for k, v in ckpt.items(): 251 | new_k = k[7:] 252 | state_dict[new_k] = v 253 | mk, uk = self.caption_model.load_state_dict(state_dict, strict=False) 254 | assert len(mk) == 0 255 | assert all([name.startswith('clip') for name in uk]) 256 | self.caption_model.eval() 257 | self.caption_model.to(device) 258 | self.caption_model.requires_grad_(False) 259 | self.device = device 260 | 261 | def encode_prefix(self, features): 262 | return self.caption_model.encode_prefix(features) 263 | 264 | def generate_captions(self, features): # the low dimension representation of clip feature 265 | """ 266 | generate captions given features 267 | : param features : (tensor([B x L x D])) 268 | : return generated_text: (list([L])) 269 | """ 270 | 271 | # generate config 272 | use_beam_search = True 273 | 274 | features = torch.split(features, 1, dim=0) 275 | generated_captions = [] 276 | with torch.no_grad(): 277 | for feature in features: 278 | feature = self.caption_model.decode_prefix(feature.to(self.device)) # back to the clip feature 279 | if use_beam_search: 280 | generated_captions.append(generate_beam(self.caption_model, self.tokenizer, embed=feature)[0]) 281 | else: 282 | generated_captions.append(generate2(self.caption_model, self.tokenizer, embed=feature)) 283 | return generated_captions 284 | -------------------------------------------------------------------------------- /libs/clip.py: -------------------------------------------------------------------------------- 1 | import torch.nn as nn 2 | from transformers import CLIPTokenizer, CLIPTextModel 3 | 4 | 5 | class AbstractEncoder(nn.Module): 6 | def __init__(self): 7 | super().__init__() 8 | 9 | def encode(self, *args, **kwargs): 10 | raise NotImplementedError 11 | 12 | 13 | class FrozenCLIPEmbedder(AbstractEncoder): 14 | """Uses the CLIP transformer encoder for text (from Hugging Face)""" 15 | def __init__(self, version="openai/clip-vit-large-patch14", device="cuda", max_length=77): 16 | super().__init__() 17 | self.tokenizer = CLIPTokenizer.from_pretrained(version) 18 | self.transformer = CLIPTextModel.from_pretrained(version) 19 | self.device = device 20 | self.max_length = max_length 21 | self.freeze() 22 | 23 | def freeze(self): 24 | self.transformer = self.transformer.eval() 25 | for param in self.parameters(): 26 | param.requires_grad = False 27 | 28 | def forward(self, text): 29 | batch_encoding = self.tokenizer(text, truncation=True, max_length=self.max_length, return_length=True, 30 | return_overflowing_tokens=False, padding="max_length", return_tensors="pt") 31 | tokens = batch_encoding["input_ids"].to(self.device) 32 | outputs = self.transformer(input_ids=tokens) 33 | 34 | z = outputs.last_hidden_state 35 | return z 36 | 37 | def encode(self, text): 38 | return self(text) 39 | -------------------------------------------------------------------------------- /libs/timm.py: -------------------------------------------------------------------------------- 1 | # code from timm 0.3.2 2 | import torch 3 | import torch.nn as nn 4 | import math 5 | import warnings 6 | 7 | 8 | def _no_grad_trunc_normal_(tensor, mean, std, a, b): 9 | # Cut & paste from PyTorch official master until it's in a few official releases - RW 10 | # Method based on https://people.sc.fsu.edu/~jburkardt/presentations/truncated_normal.pdf 11 | def norm_cdf(x): 12 | # Computes standard normal cumulative distribution function 13 | return (1. + math.erf(x / math.sqrt(2.))) / 2. 14 | 15 | if (mean < a - 2 * std) or (mean > b + 2 * std): 16 | warnings.warn("mean is more than 2 std from [a, b] in nn.init.trunc_normal_. " 17 | "The distribution of values may be incorrect.", 18 | stacklevel=2) 19 | 20 | with torch.no_grad(): 21 | # Values are generated by using a truncated uniform distribution and 22 | # then using the inverse CDF for the normal distribution. 23 | # Get upper and lower cdf values 24 | l = norm_cdf((a - mean) / std) 25 | u = norm_cdf((b - mean) / std) 26 | 27 | # Uniformly fill tensor with values from [l, u], then translate to 28 | # [2l-1, 2u-1]. 29 | tensor.uniform_(2 * l - 1, 2 * u - 1) 30 | 31 | # Use inverse cdf transform for normal distribution to get truncated 32 | # standard normal 33 | tensor.erfinv_() 34 | 35 | # Transform to proper mean, std 36 | tensor.mul_(std * math.sqrt(2.)) 37 | tensor.add_(mean) 38 | 39 | # Clamp to ensure it's in the proper range 40 | tensor.clamp_(min=a, max=b) 41 | return tensor 42 | 43 | 44 | def trunc_normal_(tensor, mean=0., std=1., a=-2., b=2.): 45 | # type: (Tensor, float, float, float, float) -> Tensor 46 | r"""Fills the input Tensor with values drawn from a truncated 47 | normal distribution. The values are effectively drawn from the 48 | normal distribution :math:`\mathcal{N}(\text{mean}, \text{std}^2)` 49 | with values outside :math:`[a, b]` redrawn until they are within 50 | the bounds. The method used for generating the random values works 51 | best when :math:`a \leq \text{mean} \leq b`. 52 | Args: 53 | tensor: an n-dimensional `torch.Tensor` 54 | mean: the mean of the normal distribution 55 | std: the standard deviation of the normal distribution 56 | a: the minimum cutoff value 57 | b: the maximum cutoff value 58 | Examples: 59 | >>> w = torch.empty(3, 5) 60 | >>> nn.init.trunc_normal_(w) 61 | """ 62 | return _no_grad_trunc_normal_(tensor, mean, std, a, b) 63 | 64 | 65 | def drop_path(x, drop_prob: float = 0., training: bool = False): 66 | """Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks). 67 | 68 | This is the same as the DropConnect impl I created for EfficientNet, etc networks, however, 69 | the original name is misleading as 'Drop Connect' is a different form of dropout in a separate paper... 70 | See discussion: https://github.com/tensorflow/tpu/issues/494#issuecomment-532968956 ... I've opted for 71 | changing the layer and argument names to 'drop path' rather than mix DropConnect as a layer name and use 72 | 'survival rate' as the argument. 73 | 74 | """ 75 | if drop_prob == 0. or not training: 76 | return x 77 | keep_prob = 1 - drop_prob 78 | shape = (x.shape[0],) + (1,) * (x.ndim - 1) # work with diff dim tensors, not just 2D ConvNets 79 | random_tensor = keep_prob + torch.rand(shape, dtype=x.dtype, device=x.device) 80 | random_tensor.floor_() # binarize 81 | output = x.div(keep_prob) * random_tensor 82 | return output 83 | 84 | 85 | class DropPath(nn.Module): 86 | """Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks). 87 | """ 88 | def __init__(self, drop_prob=None): 89 | super(DropPath, self).__init__() 90 | self.drop_prob = drop_prob 91 | 92 | def forward(self, x): 93 | return drop_path(x, self.drop_prob, self.training) 94 | 95 | 96 | class Mlp(nn.Module): 97 | def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, drop=0.): 98 | super().__init__() 99 | out_features = out_features or in_features 100 | hidden_features = hidden_features or in_features 101 | self.fc1 = nn.Linear(in_features, hidden_features) 102 | self.act = act_layer() 103 | self.fc2 = nn.Linear(hidden_features, out_features) 104 | self.drop = nn.Dropout(drop) 105 | 106 | def forward(self, x): 107 | x = self.fc1(x) 108 | x = self.act(x) 109 | x = self.drop(x) 110 | x = self.fc2(x) 111 | x = self.drop(x) 112 | return x 113 | -------------------------------------------------------------------------------- /libs/uvit_multi_post_ln.py: -------------------------------------------------------------------------------- 1 | import torch 2 | import torch.nn as nn 3 | import math 4 | from .timm import trunc_normal_, DropPath, Mlp 5 | import einops 6 | import torch.utils.checkpoint 7 | import torch.nn.functional as F 8 | 9 | if hasattr(torch.nn.functional, 'scaled_dot_product_attention'): 10 | ATTENTION_MODE = 'flash' 11 | else: 12 | try: 13 | import xformers 14 | import xformers.ops 15 | ATTENTION_MODE = 'xformers' 16 | except: 17 | ATTENTION_MODE = 'math' 18 | print(f'attention mode is {ATTENTION_MODE}') 19 | 20 | 21 | def timestep_embedding(timesteps, dim, max_period=10000): 22 | """ 23 | Create sinusoidal timestep embeddings. 24 | 25 | :param timesteps: a 1-D Tensor of N indices, one per batch element. 26 | These may be fractional. 27 | :param dim: the dimension of the output. 28 | :param max_period: controls the minimum frequency of the embeddings. 29 | :return: an [N x dim] Tensor of positional embeddings. 30 | """ 31 | half = dim // 2 32 | freqs = torch.exp( 33 | -math.log(max_period) * torch.arange(start=0, end=half, dtype=torch.float32) / half 34 | ).to(device=timesteps.device) 35 | args = timesteps[:, None].float() * freqs[None] 36 | embedding = torch.cat([torch.cos(args), torch.sin(args)], dim=-1) 37 | if dim % 2: 38 | embedding = torch.cat([embedding, torch.zeros_like(embedding[:, :1])], dim=-1) 39 | return embedding 40 | 41 | 42 | def patchify(imgs, patch_size): 43 | x = einops.rearrange(imgs, 'B C (h p1) (w p2) -> B (h w) (p1 p2 C)', p1=patch_size, p2=patch_size) 44 | return x 45 | 46 | 47 | def unpatchify(x, in_chans): 48 | patch_size = int((x.shape[2] // in_chans) ** 0.5) 49 | h = w = int(x.shape[1] ** .5) 50 | assert h * w == x.shape[1] and patch_size ** 2 * in_chans == x.shape[2] 51 | x = einops.rearrange(x, 'B (h w) (p1 p2 C) -> B C (h p1) (w p2)', h=h, p1=patch_size, p2=patch_size) 52 | return x 53 | 54 | 55 | def interpolate_pos_emb(pos_emb, old_shape, new_shape): 56 | pos_emb = einops.rearrange(pos_emb, 'B (H W) C -> B C H W', H=old_shape[0], W=old_shape[1]) 57 | pos_emb = F.interpolate(pos_emb, new_shape, mode='bilinear') 58 | pos_emb = einops.rearrange(pos_emb, 'B C H W -> B (H W) C') 59 | return pos_emb 60 | 61 | 62 | class Attention(nn.Module): 63 | def __init__(self, dim, num_heads=8, qkv_bias=False, qk_scale=None, attn_drop=0., proj_drop=0.): 64 | super().__init__() 65 | self.num_heads = num_heads 66 | head_dim = dim // num_heads 67 | self.scale = qk_scale or head_dim ** -0.5 68 | 69 | self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias) 70 | self.attn_drop = nn.Dropout(attn_drop) 71 | self.proj = nn.Linear(dim, dim) 72 | self.proj_drop = nn.Dropout(proj_drop) 73 | 74 | def forward(self, x): 75 | B, L, C = x.shape 76 | 77 | qkv = self.qkv(x) 78 | if ATTENTION_MODE == 'flash': 79 | qkv = einops.rearrange(qkv, 'B L (K H D) -> K B H L D', K=3, H=self.num_heads).float() 80 | q, k, v = qkv[0], qkv[1], qkv[2] # B H L D 81 | x = torch.nn.functional.scaled_dot_product_attention(q, k, v) 82 | x = einops.rearrange(x, 'B H L D -> B L (H D)') 83 | elif ATTENTION_MODE == 'xformers': 84 | qkv = einops.rearrange(qkv, 'B L (K H D) -> K B L H D', K=3, H=self.num_heads) 85 | q, k, v = qkv[0], qkv[1], qkv[2] # B L H D 86 | x = xformers.ops.memory_efficient_attention(q, k, v) 87 | x = einops.rearrange(x, 'B L H D -> B L (H D)', H=self.num_heads) 88 | elif ATTENTION_MODE == 'math': 89 | with torch.amp.autocast(device_type='cuda', enabled=False): 90 | qkv = einops.rearrange(qkv, 'B L (K H D) -> K B H L D', K=3, H=self.num_heads).float() 91 | q, k, v = qkv[0], qkv[1], qkv[2] # B H L D 92 | attn = (q @ k.transpose(-2, -1)) * self.scale 93 | attn = attn.softmax(dim=-1) 94 | attn = self.attn_drop(attn) 95 | x = (attn @ v).transpose(1, 2).reshape(B, L, C) 96 | else: 97 | raise NotImplemented 98 | 99 | x = self.proj(x) 100 | x = self.proj_drop(x) 101 | return x 102 | 103 | 104 | class Block(nn.Module): 105 | 106 | def __init__(self, dim, num_heads, mlp_ratio=4., qkv_bias=False, qk_scale=None, drop=0., attn_drop=0., 107 | drop_path=0., act_layer=nn.GELU, norm_layer=nn.LayerNorm, skip=False, use_checkpoint=False): 108 | super().__init__() 109 | self.norm1 = norm_layer(dim) if skip else None 110 | self.norm2 = norm_layer(dim) 111 | 112 | self.attn = Attention( 113 | dim, num_heads=num_heads, qkv_bias=qkv_bias, qk_scale=qk_scale, attn_drop=attn_drop, proj_drop=drop) 114 | self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity() 115 | self.norm3 = norm_layer(dim) 116 | mlp_hidden_dim = int(dim * mlp_ratio) 117 | self.mlp = Mlp(in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, drop=drop) 118 | self.skip_linear = nn.Linear(2 * dim, dim) if skip else None 119 | self.use_checkpoint = use_checkpoint 120 | 121 | def forward(self, x, skip=None): 122 | if self.use_checkpoint: 123 | return torch.utils.checkpoint.checkpoint(self._forward, x, skip) 124 | else: 125 | return self._forward(x, skip) 126 | 127 | def _forward(self, x, skip=None): 128 | if self.skip_linear is not None: 129 | x = self.skip_linear(torch.cat([x, skip], dim=-1)) 130 | x = self.norm1(x) 131 | x = x + self.drop_path(self.attn(x)) 132 | x = self.norm2(x) 133 | 134 | x = x + self.drop_path(self.mlp(x)) 135 | x = self.norm3(x) 136 | 137 | return x 138 | 139 | 140 | class PatchEmbed(nn.Module): 141 | """ Image to Patch Embedding 142 | """ 143 | def __init__(self, patch_size, in_chans=3, embed_dim=768): 144 | super().__init__() 145 | self.patch_size = patch_size 146 | self.proj = nn.Conv2d(in_chans, embed_dim, kernel_size=patch_size, stride=patch_size) 147 | 148 | def forward(self, x): 149 | B, C, H, W = x.shape 150 | assert H % self.patch_size == 0 and W % self.patch_size == 0 151 | x = self.proj(x).flatten(2).transpose(1, 2) 152 | return x 153 | 154 | 155 | class UViT(nn.Module): 156 | def __init__(self, img_size, in_chans, patch_size, embed_dim=768, depth=12, 157 | num_heads=12, mlp_ratio=4., qkv_bias=False, qk_scale=None, pos_drop_rate=0., drop_rate=0., attn_drop_rate=0., 158 | norm_layer=nn.LayerNorm, mlp_time_embed=False, use_checkpoint=False, 159 | text_dim=None, num_text_tokens=None, clip_img_dim=None): 160 | super().__init__() 161 | self.in_chans = in_chans 162 | self.patch_size = patch_size 163 | self.num_features = self.embed_dim = embed_dim # num_features for consistency with other models 164 | 165 | self.patch_embed = PatchEmbed(patch_size=patch_size, in_chans=in_chans, embed_dim=embed_dim) 166 | self.img_size = (img_size, img_size) if isinstance(img_size, int) else img_size # the default img size 167 | assert self.img_size[0] % patch_size == 0 and self.img_size[1] % patch_size == 0 168 | self.num_patches = (self.img_size[0] // patch_size) * (self.img_size[1] // patch_size) 169 | 170 | self.time_img_embed = nn.Sequential( 171 | nn.Linear(embed_dim, 4 * embed_dim), 172 | nn.SiLU(), 173 | nn.Linear(4 * embed_dim, embed_dim), 174 | ) if mlp_time_embed else nn.Identity() 175 | 176 | self.time_text_embed = nn.Sequential( 177 | nn.Linear(embed_dim, 4 * embed_dim), 178 | nn.SiLU(), 179 | nn.Linear(4 * embed_dim, embed_dim), 180 | ) if mlp_time_embed else nn.Identity() 181 | 182 | self.text_embed = nn.Linear(text_dim, embed_dim) 183 | self.text_out = nn.Linear(embed_dim, text_dim) 184 | 185 | self.clip_img_embed = nn.Linear(clip_img_dim, embed_dim) 186 | self.clip_img_out = nn.Linear(embed_dim, clip_img_dim) 187 | 188 | self.num_text_tokens = num_text_tokens 189 | self.num_tokens = 1 + 1 + num_text_tokens + 1 + self.num_patches 190 | 191 | self.pos_embed = nn.Parameter(torch.zeros(1, self.num_tokens, embed_dim)) 192 | self.pos_drop = nn.Dropout(p=pos_drop_rate) 193 | 194 | self.in_blocks = nn.ModuleList([ 195 | Block( 196 | dim=embed_dim, num_heads=num_heads, mlp_ratio=mlp_ratio, qkv_bias=qkv_bias, qk_scale=qk_scale, 197 | drop=drop_rate, attn_drop=attn_drop_rate, norm_layer=norm_layer, use_checkpoint=use_checkpoint) 198 | for _ in range(depth // 2)]) 199 | 200 | self.mid_block = Block( 201 | dim=embed_dim, num_heads=num_heads, mlp_ratio=mlp_ratio, qkv_bias=qkv_bias, qk_scale=qk_scale, 202 | drop=drop_rate, attn_drop=attn_drop_rate, norm_layer=norm_layer, use_checkpoint=use_checkpoint) 203 | 204 | self.out_blocks = nn.ModuleList([ 205 | Block( 206 | dim=embed_dim, num_heads=num_heads, mlp_ratio=mlp_ratio, qkv_bias=qkv_bias, qk_scale=qk_scale, 207 | drop=drop_rate, attn_drop=attn_drop_rate, norm_layer=norm_layer, skip=True, use_checkpoint=use_checkpoint) 208 | for _ in range(depth // 2)]) 209 | 210 | self.norm = norm_layer(embed_dim) 211 | self.patch_dim = patch_size ** 2 * in_chans 212 | self.decoder_pred = nn.Linear(embed_dim, self.patch_dim, bias=True) 213 | 214 | trunc_normal_(self.pos_embed, std=.02) 215 | self.apply(self._init_weights) 216 | 217 | def _init_weights(self, m): 218 | if isinstance(m, nn.Linear): 219 | trunc_normal_(m.weight, std=.02) 220 | if isinstance(m, nn.Linear) and m.bias is not None: 221 | nn.init.constant_(m.bias, 0) 222 | elif isinstance(m, nn.LayerNorm): 223 | nn.init.constant_(m.bias, 0) 224 | nn.init.constant_(m.weight, 1.0) 225 | 226 | @torch.jit.ignore 227 | def no_weight_decay(self): 228 | return {'pos_embed'} 229 | 230 | def forward(self, img, clip_img, text, t_img, t_text): 231 | _, _, H, W = img.shape 232 | 233 | img = self.patch_embed(img) 234 | 235 | t_img_token = self.time_img_embed(timestep_embedding(t_img, self.embed_dim)) 236 | t_img_token = t_img_token.unsqueeze(dim=1) 237 | t_text_token = self.time_text_embed(timestep_embedding(t_text, self.embed_dim)) 238 | t_text_token = t_text_token.unsqueeze(dim=1) 239 | 240 | text = self.text_embed(text) 241 | clip_img = self.clip_img_embed(clip_img) 242 | x = torch.cat((t_img_token, t_text_token, text, clip_img, img), dim=1) 243 | 244 | num_text_tokens, num_img_tokens = text.size(1), img.size(1) 245 | 246 | if H == self.img_size[0] and W == self.img_size[1]: 247 | pos_embed = self.pos_embed 248 | else: # interpolate the positional embedding when the input image is not of the default shape 249 | pos_embed_others, pos_embed_patches = torch.split(self.pos_embed, [1 + 1 + num_text_tokens + 1, self.num_patches], dim=1) 250 | pos_embed_patches = interpolate_pos_emb(pos_embed_patches, (self.img_size[0] // self.patch_size, self.img_size[1] // self.patch_size), 251 | (H // self.patch_size, W // self.patch_size)) 252 | pos_embed = torch.cat((pos_embed_others, pos_embed_patches), dim=1) 253 | 254 | x = x + pos_embed 255 | x = self.pos_drop(x) 256 | 257 | skips = [] 258 | for blk in self.in_blocks: 259 | x = blk(x) 260 | skips.append(x) 261 | 262 | x = self.mid_block(x) 263 | 264 | for blk in self.out_blocks: 265 | x = blk(x, skips.pop()) 266 | 267 | x = self.norm(x) 268 | 269 | t_img_token_out, t_text_token_out, text_out, clip_img_out, img_out = x.split((1, 1, num_text_tokens, 1, num_img_tokens), dim=1) 270 | 271 | img_out = self.decoder_pred(img_out) 272 | img_out = unpatchify(img_out, self.in_chans) 273 | 274 | clip_img_out = self.clip_img_out(clip_img_out) 275 | 276 | text_out = self.text_out(text_out) 277 | return img_out, clip_img_out, text_out 278 | -------------------------------------------------------------------------------- /libs/uvit_multi_post_ln_v1.py: -------------------------------------------------------------------------------- 1 | import torch 2 | import torch.nn as nn 3 | import math 4 | from .timm import trunc_normal_, DropPath, Mlp 5 | import einops 6 | import torch.utils.checkpoint 7 | import torch.nn.functional as F 8 | 9 | if hasattr(torch.nn.functional, 'scaled_dot_product_attention'): 10 | ATTENTION_MODE = 'flash' 11 | else: 12 | try: 13 | import xformers 14 | import xformers.ops 15 | ATTENTION_MODE = 'xformers' 16 | except: 17 | ATTENTION_MODE = 'math' 18 | print(f'attention mode is {ATTENTION_MODE}') 19 | 20 | 21 | def timestep_embedding(timesteps, dim, max_period=10000): 22 | """ 23 | Create sinusoidal timestep embeddings. 24 | 25 | :param timesteps: a 1-D Tensor of N indices, one per batch element. 26 | These may be fractional. 27 | :param dim: the dimension of the output. 28 | :param max_period: controls the minimum frequency of the embeddings. 29 | :return: an [N x dim] Tensor of positional embeddings. 30 | """ 31 | half = dim // 2 32 | freqs = torch.exp( 33 | -math.log(max_period) * torch.arange(start=0, end=half, dtype=torch.float32) / half 34 | ).to(device=timesteps.device) 35 | args = timesteps[:, None].float() * freqs[None] 36 | embedding = torch.cat([torch.cos(args), torch.sin(args)], dim=-1) 37 | if dim % 2: 38 | embedding = torch.cat([embedding, torch.zeros_like(embedding[:, :1])], dim=-1) 39 | return embedding 40 | 41 | 42 | def patchify(imgs, patch_size): 43 | x = einops.rearrange(imgs, 'B C (h p1) (w p2) -> B (h w) (p1 p2 C)', p1=patch_size, p2=patch_size) 44 | return x 45 | 46 | 47 | def unpatchify(x, in_chans): 48 | patch_size = int((x.shape[2] // in_chans) ** 0.5) 49 | h = w = int(x.shape[1] ** .5) 50 | assert h * w == x.shape[1] and patch_size ** 2 * in_chans == x.shape[2] 51 | x = einops.rearrange(x, 'B (h w) (p1 p2 C) -> B C (h p1) (w p2)', h=h, p1=patch_size, p2=patch_size) 52 | return x 53 | 54 | 55 | def interpolate_pos_emb(pos_emb, old_shape, new_shape): 56 | pos_emb = einops.rearrange(pos_emb, 'B (H W) C -> B C H W', H=old_shape[0], W=old_shape[1]) 57 | pos_emb = F.interpolate(pos_emb, new_shape, mode='bilinear') 58 | pos_emb = einops.rearrange(pos_emb, 'B C H W -> B (H W) C') 59 | return pos_emb 60 | 61 | 62 | class Attention(nn.Module): 63 | def __init__(self, dim, num_heads=8, qkv_bias=False, qk_scale=None, attn_drop=0., proj_drop=0.): 64 | super().__init__() 65 | self.num_heads = num_heads 66 | head_dim = dim // num_heads 67 | self.scale = qk_scale or head_dim ** -0.5 68 | 69 | self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias) 70 | self.attn_drop = nn.Dropout(attn_drop) 71 | self.proj = nn.Linear(dim, dim) 72 | self.proj_drop = nn.Dropout(proj_drop) 73 | 74 | def forward(self, x): 75 | B, L, C = x.shape 76 | 77 | qkv = self.qkv(x) 78 | if ATTENTION_MODE == 'flash': 79 | qkv = einops.rearrange(qkv, 'B L (K H D) -> K B H L D', K=3, H=self.num_heads).float() 80 | q, k, v = qkv[0], qkv[1], qkv[2] # B H L D 81 | x = torch.nn.functional.scaled_dot_product_attention(q, k, v) 82 | x = einops.rearrange(x, 'B H L D -> B L (H D)') 83 | elif ATTENTION_MODE == 'xformers': 84 | qkv = einops.rearrange(qkv, 'B L (K H D) -> K B L H D', K=3, H=self.num_heads) 85 | q, k, v = qkv[0], qkv[1], qkv[2] # B L H D 86 | x = xformers.ops.memory_efficient_attention(q, k, v) 87 | x = einops.rearrange(x, 'B L H D -> B L (H D)', H=self.num_heads) 88 | elif ATTENTION_MODE == 'math': 89 | with torch.amp.autocast(device_type='cuda', enabled=False): 90 | qkv = einops.rearrange(qkv, 'B L (K H D) -> K B H L D', K=3, H=self.num_heads).float() 91 | q, k, v = qkv[0], qkv[1], qkv[2] # B H L D 92 | attn = (q @ k.transpose(-2, -1)) * self.scale 93 | attn = attn.softmax(dim=-1) 94 | attn = self.attn_drop(attn) 95 | x = (attn @ v).transpose(1, 2).reshape(B, L, C) 96 | else: 97 | raise NotImplemented 98 | 99 | x = self.proj(x) 100 | x = self.proj_drop(x) 101 | return x 102 | 103 | 104 | class Block(nn.Module): 105 | 106 | def __init__(self, dim, num_heads, mlp_ratio=4., qkv_bias=False, qk_scale=None, drop=0., attn_drop=0., 107 | drop_path=0., act_layer=nn.GELU, norm_layer=nn.LayerNorm, skip=False, use_checkpoint=False): 108 | super().__init__() 109 | self.norm1 = norm_layer(dim) if skip else None 110 | self.norm2 = norm_layer(dim) 111 | 112 | self.attn = Attention( 113 | dim, num_heads=num_heads, qkv_bias=qkv_bias, qk_scale=qk_scale, attn_drop=attn_drop, proj_drop=drop) 114 | self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity() 115 | self.norm3 = norm_layer(dim) 116 | mlp_hidden_dim = int(dim * mlp_ratio) 117 | self.mlp = Mlp(in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, drop=drop) 118 | self.skip_linear = nn.Linear(2 * dim, dim) if skip else None 119 | self.use_checkpoint = use_checkpoint 120 | 121 | def forward(self, x, skip=None): 122 | if self.use_checkpoint: 123 | return torch.utils.checkpoint.checkpoint(self._forward, x, skip) 124 | else: 125 | return self._forward(x, skip) 126 | 127 | def _forward(self, x, skip=None): 128 | if self.skip_linear is not None: 129 | x = self.skip_linear(torch.cat([x, skip], dim=-1)) 130 | x = self.norm1(x) 131 | x = x + self.drop_path(self.attn(x)) 132 | x = self.norm2(x) 133 | 134 | x = x + self.drop_path(self.mlp(x)) 135 | x = self.norm3(x) 136 | 137 | return x 138 | 139 | 140 | class PatchEmbed(nn.Module): 141 | """ Image to Patch Embedding 142 | """ 143 | def __init__(self, patch_size, in_chans=3, embed_dim=768): 144 | super().__init__() 145 | self.patch_size = patch_size 146 | self.proj = nn.Conv2d(in_chans, embed_dim, kernel_size=patch_size, stride=patch_size) 147 | 148 | def forward(self, x): 149 | B, C, H, W = x.shape 150 | assert H % self.patch_size == 0 and W % self.patch_size == 0 151 | x = self.proj(x).flatten(2).transpose(1, 2) 152 | return x 153 | 154 | 155 | class UViT(nn.Module): 156 | def __init__(self, img_size, in_chans, patch_size, embed_dim=768, depth=12, 157 | num_heads=12, mlp_ratio=4., qkv_bias=False, qk_scale=None, pos_drop_rate=0., drop_rate=0., attn_drop_rate=0., 158 | norm_layer=nn.LayerNorm, mlp_time_embed=False, use_checkpoint=False, 159 | text_dim=None, num_text_tokens=None, clip_img_dim=None): 160 | super().__init__() 161 | self.in_chans = in_chans 162 | self.patch_size = patch_size 163 | self.num_features = self.embed_dim = embed_dim # num_features for consistency with other models 164 | 165 | self.patch_embed = PatchEmbed(patch_size=patch_size, in_chans=in_chans, embed_dim=embed_dim) 166 | self.img_size = (img_size, img_size) if isinstance(img_size, int) else img_size # the default img size 167 | assert self.img_size[0] % patch_size == 0 and self.img_size[1] % patch_size == 0 168 | self.num_patches = (self.img_size[0] // patch_size) * (self.img_size[1] // patch_size) 169 | 170 | self.time_img_embed = nn.Sequential( 171 | nn.Linear(embed_dim, 4 * embed_dim), 172 | nn.SiLU(), 173 | nn.Linear(4 * embed_dim, embed_dim), 174 | ) if mlp_time_embed else nn.Identity() 175 | 176 | self.time_text_embed = nn.Sequential( 177 | nn.Linear(embed_dim, 4 * embed_dim), 178 | nn.SiLU(), 179 | nn.Linear(4 * embed_dim, embed_dim), 180 | ) if mlp_time_embed else nn.Identity() 181 | 182 | self.text_embed = nn.Linear(text_dim, embed_dim) 183 | self.text_out = nn.Linear(embed_dim, text_dim) 184 | 185 | self.clip_img_embed = nn.Linear(clip_img_dim, embed_dim) 186 | self.clip_img_out = nn.Linear(embed_dim, clip_img_dim) 187 | 188 | self.num_text_tokens = num_text_tokens 189 | self.num_tokens = 1 + 1 + num_text_tokens + 1 + self.num_patches 190 | 191 | self.pos_embed = nn.Parameter(torch.zeros(1, self.num_tokens, embed_dim)) 192 | self.pos_drop = nn.Dropout(p=pos_drop_rate) 193 | 194 | self.in_blocks = nn.ModuleList([ 195 | Block( 196 | dim=embed_dim, num_heads=num_heads, mlp_ratio=mlp_ratio, qkv_bias=qkv_bias, qk_scale=qk_scale, 197 | drop=drop_rate, attn_drop=attn_drop_rate, norm_layer=norm_layer, use_checkpoint=use_checkpoint) 198 | for _ in range(depth // 2)]) 199 | 200 | self.mid_block = Block( 201 | dim=embed_dim, num_heads=num_heads, mlp_ratio=mlp_ratio, qkv_bias=qkv_bias, qk_scale=qk_scale, 202 | drop=drop_rate, attn_drop=attn_drop_rate, norm_layer=norm_layer, use_checkpoint=use_checkpoint) 203 | 204 | self.out_blocks = nn.ModuleList([ 205 | Block( 206 | dim=embed_dim, num_heads=num_heads, mlp_ratio=mlp_ratio, qkv_bias=qkv_bias, qk_scale=qk_scale, 207 | drop=drop_rate, attn_drop=attn_drop_rate, norm_layer=norm_layer, skip=True, use_checkpoint=use_checkpoint) 208 | for _ in range(depth // 2)]) 209 | 210 | self.norm = norm_layer(embed_dim) 211 | self.patch_dim = patch_size ** 2 * in_chans 212 | self.decoder_pred = nn.Linear(embed_dim, self.patch_dim, bias=True) 213 | 214 | trunc_normal_(self.pos_embed, std=.02) 215 | self.apply(self._init_weights) 216 | 217 | self.token_embedding = nn.Embedding(2, embed_dim) 218 | self.pos_embed_token = nn.Parameter(torch.zeros(1, 1, embed_dim)) 219 | 220 | def _init_weights(self, m): 221 | if isinstance(m, nn.Linear): 222 | trunc_normal_(m.weight, std=.02) 223 | if isinstance(m, nn.Linear) and m.bias is not None: 224 | nn.init.constant_(m.bias, 0) 225 | elif isinstance(m, nn.LayerNorm): 226 | nn.init.constant_(m.bias, 0) 227 | nn.init.constant_(m.weight, 1.0) 228 | 229 | @torch.jit.ignore 230 | def no_weight_decay(self): 231 | return {'pos_embed'} 232 | 233 | def forward(self, img, clip_img, text, t_img, t_text, data_type): 234 | _, _, H, W = img.shape 235 | 236 | img = self.patch_embed(img) 237 | 238 | t_img_token = self.time_img_embed(timestep_embedding(t_img, self.embed_dim)) 239 | t_img_token = t_img_token.unsqueeze(dim=1) 240 | t_text_token = self.time_text_embed(timestep_embedding(t_text, self.embed_dim)) 241 | t_text_token = t_text_token.unsqueeze(dim=1) 242 | 243 | text = self.text_embed(text) 244 | clip_img = self.clip_img_embed(clip_img) 245 | 246 | token_embed = self.token_embedding(data_type).unsqueeze(dim=1) 247 | 248 | x = torch.cat((t_img_token, t_text_token, token_embed, text, clip_img, img), dim=1) 249 | 250 | num_text_tokens, num_img_tokens = text.size(1), img.size(1) 251 | 252 | pos_embed = torch.cat( 253 | [self.pos_embed[:, :1 + 1, :], self.pos_embed_token, self.pos_embed[:, 1 + 1:, :]], dim=1) 254 | if H == self.img_size[0] and W == self.img_size[1]: 255 | pass 256 | else: # interpolate the positional embedding when the input image is not of the default shape 257 | pos_embed_others, pos_embed_patches = torch.split(pos_embed, [1 + 1 + 1 + num_text_tokens + 1, self.num_patches], dim=1) 258 | pos_embed_patches = interpolate_pos_emb(pos_embed_patches, (self.img_size[0] // self.patch_size, self.img_size[1] // self.patch_size), 259 | (H // self.patch_size, W // self.patch_size)) 260 | pos_embed = torch.cat((pos_embed_others, pos_embed_patches), dim=1) 261 | 262 | x = x + pos_embed 263 | x = self.pos_drop(x) 264 | 265 | skips = [] 266 | for blk in self.in_blocks: 267 | x = blk(x) 268 | skips.append(x) 269 | 270 | x = self.mid_block(x) 271 | 272 | for blk in self.out_blocks: 273 | x = blk(x, skips.pop()) 274 | 275 | x = self.norm(x) 276 | 277 | t_img_token_out, t_text_token_out, token_embed_out, text_out, clip_img_out, img_out = x.split((1, 1, 1, num_text_tokens, 1, num_img_tokens), dim=1) 278 | 279 | img_out = self.decoder_pred(img_out) 280 | img_out = unpatchify(img_out, self.in_chans) 281 | 282 | clip_img_out = self.clip_img_out(clip_img_out) 283 | 284 | text_out = self.text_out(text_out) 285 | return img_out, clip_img_out, text_out 286 | -------------------------------------------------------------------------------- /sample_multi_v0.py: -------------------------------------------------------------------------------- 1 | import ml_collections 2 | import torch 3 | import random 4 | import utils 5 | from dpm_solver_pp import NoiseScheduleVP, DPM_Solver 6 | from absl import logging 7 | import einops 8 | import libs.autoencoder 9 | import libs.clip 10 | from torchvision.utils import save_image, make_grid 11 | import torchvision.transforms as standard_transforms 12 | import numpy as np 13 | import clip 14 | from PIL import Image 15 | import time 16 | 17 | 18 | def stable_diffusion_beta_schedule(linear_start=0.00085, linear_end=0.0120, n_timestep=1000): 19 | _betas = ( 20 | torch.linspace(linear_start ** 0.5, linear_end ** 0.5, n_timestep, dtype=torch.float64) ** 2 21 | ) 22 | return _betas.numpy() 23 | 24 | 25 | def prepare_contexts(config, clip_text_model, clip_img_model, clip_img_model_preprocess, autoencoder): 26 | resolution = config.z_shape[-1] * 8 27 | device = 'cuda' if torch.cuda.is_available() else 'cpu' 28 | 29 | contexts = torch.randn(config.n_samples, 77, config.clip_text_dim).to(device) 30 | img_contexts = torch.randn(config.n_samples, 2 * config.z_shape[0], config.z_shape[1], config.z_shape[2]) 31 | clip_imgs = torch.randn(config.n_samples, 1, config.clip_img_dim) 32 | 33 | if config.mode in ['t2i', 't2i2t']: 34 | prompts = [ config.prompt ] * config.n_samples 35 | contexts = clip_text_model.encode(prompts) 36 | 37 | elif config.mode in ['i2t', 'i2t2i']: 38 | from PIL import Image 39 | img_contexts = [] 40 | clip_imgs = [] 41 | 42 | def get_img_feature(image): 43 | image = np.array(image).astype(np.uint8) 44 | image = utils.center_crop(resolution, resolution, image) 45 | clip_img_feature = clip_img_model.encode_image(clip_img_model_preprocess(Image.fromarray(image)).unsqueeze(0).to(device)) 46 | 47 | image = (image / 127.5 - 1.0).astype(np.float32) 48 | image = einops.rearrange(image, 'h w c -> 1 c h w') 49 | image = torch.tensor(image, device=device) 50 | moments = autoencoder.encode_moments(image) 51 | 52 | return clip_img_feature, moments 53 | 54 | image = Image.open(config.img).convert('RGB') 55 | clip_img, img_context = get_img_feature(image) 56 | 57 | img_contexts.append(img_context) 58 | clip_imgs.append(clip_img) 59 | img_contexts = img_contexts * config.n_samples 60 | clip_imgs = clip_imgs * config.n_samples 61 | 62 | img_contexts = torch.concat(img_contexts, dim=0) 63 | clip_imgs = torch.stack(clip_imgs, dim=0) 64 | 65 | return contexts, img_contexts, clip_imgs 66 | 67 | 68 | def unpreprocess(v): # to B C H W and [0, 1] 69 | v = 0.5 * (v + 1.) 70 | v.clamp_(0., 1.) 71 | return v 72 | 73 | 74 | def set_seed(seed: int): 75 | random.seed(seed) 76 | np.random.seed(seed) 77 | torch.manual_seed(seed) 78 | torch.cuda.manual_seed_all(seed) 79 | 80 | 81 | def evaluate(config): 82 | if config.get('benchmark', False): 83 | torch.backends.cudnn.benchmark = True 84 | torch.backends.cudnn.deterministic = False 85 | 86 | device = 'cuda' if torch.cuda.is_available() else 'cpu' 87 | set_seed(config.seed) 88 | 89 | config = ml_collections.FrozenConfigDict(config) 90 | utils.set_logger(log_level='info') 91 | 92 | _betas = stable_diffusion_beta_schedule() 93 | N = len(_betas) 94 | 95 | nnet = utils.get_nnet(**config.nnet) 96 | logging.info(f'load nnet from {config.nnet_path}') 97 | nnet.load_state_dict(torch.load(config.nnet_path, map_location='cpu')) 98 | nnet.to(device) 99 | nnet.eval() 100 | 101 | use_caption_decoder = config.text_dim < config.clip_text_dim or config.mode != 't2i' 102 | if use_caption_decoder: 103 | from libs.caption_decoder import CaptionDecoder 104 | caption_decoder = CaptionDecoder(device=device, **config.caption_decoder) 105 | else: 106 | caption_decoder = None 107 | 108 | clip_text_model = libs.clip.FrozenCLIPEmbedder(device=device) 109 | clip_text_model.eval() 110 | clip_text_model.to(device) 111 | 112 | autoencoder = libs.autoencoder.get_model(**config.autoencoder) 113 | autoencoder.to(device) 114 | 115 | clip_img_model, clip_img_model_preprocess = clip.load("ViT-B/32", device=device, jit=False) 116 | 117 | empty_context = clip_text_model.encode([''])[0] 118 | 119 | def split(x): 120 | C, H, W = config.z_shape 121 | z_dim = C * H * W 122 | z, clip_img = x.split([z_dim, config.clip_img_dim], dim=1) 123 | z = einops.rearrange(z, 'B (C H W) -> B C H W', C=C, H=H, W=W) 124 | clip_img = einops.rearrange(clip_img, 'B (L D) -> B L D', L=1, D=config.clip_img_dim) 125 | return z, clip_img 126 | 127 | 128 | def combine(z, clip_img): 129 | z = einops.rearrange(z, 'B C H W -> B (C H W)') 130 | clip_img = einops.rearrange(clip_img, 'B L D -> B (L D)') 131 | return torch.concat([z, clip_img], dim=-1) 132 | 133 | 134 | def t2i_nnet(x, timesteps, text): # text is the low dimension version of the text clip embedding 135 | """ 136 | 1. calculate the conditional model output 137 | 2. calculate unconditional model output 138 | config.sample.t2i_cfg_mode == 'empty_token': using the original cfg with the empty string 139 | config.sample.t2i_cfg_mode == 'true_uncond: using the unconditional model learned by our method 140 | 3. return linear combination of conditional output and unconditional output 141 | """ 142 | z, clip_img = split(x) 143 | 144 | t_text = torch.zeros(timesteps.size(0), dtype=torch.int, device=device) 145 | 146 | z_out, clip_img_out, text_out = nnet(z, clip_img, text=text, t_img=timesteps, t_text=t_text) 147 | x_out = combine(z_out, clip_img_out) 148 | 149 | if config.sample.scale == 0.: 150 | return x_out 151 | 152 | if config.sample.t2i_cfg_mode == 'empty_token': 153 | _empty_context = einops.repeat(empty_context, 'L D -> B L D', B=x.size(0)) 154 | if use_caption_decoder: 155 | _empty_context = caption_decoder.encode_prefix(_empty_context) 156 | z_out_uncond, clip_img_out_uncond, text_out_uncond = nnet(z, clip_img, text=_empty_context, t_img=timesteps, t_text=t_text) 157 | x_out_uncond = combine(z_out_uncond, clip_img_out_uncond) 158 | elif config.sample.t2i_cfg_mode == 'true_uncond': 159 | text_N = torch.randn_like(text) # 3 other possible choices 160 | z_out_uncond, clip_img_out_uncond, text_out_uncond = nnet(z, clip_img, text=text_N, t_img=timesteps, t_text=torch.ones_like(timesteps) * N) 161 | x_out_uncond = combine(z_out_uncond, clip_img_out_uncond) 162 | else: 163 | raise NotImplementedError 164 | 165 | return x_out + config.sample.scale * (x_out - x_out_uncond) 166 | 167 | 168 | def i_nnet(x, timesteps): 169 | z, clip_img = split(x) 170 | text = torch.randn(x.size(0), 77, config.text_dim, device=device) 171 | t_text = torch.ones_like(timesteps) * N 172 | z_out, clip_img_out, text_out = nnet(z, clip_img, text=text, t_img=timesteps, t_text=t_text) 173 | x_out = combine(z_out, clip_img_out) 174 | return x_out 175 | 176 | def t_nnet(x, timesteps): 177 | z = torch.randn(x.size(0), *config.z_shape, device=device) 178 | clip_img = torch.randn(x.size(0), 1, config.clip_img_dim, device=device) 179 | z_out, clip_img_out, text_out = nnet(z, clip_img, text=x, t_img=torch.ones_like(timesteps) * N, t_text=timesteps) 180 | return text_out 181 | 182 | def i2t_nnet(x, timesteps, z, clip_img): 183 | """ 184 | 1. calculate the conditional model output 185 | 2. calculate unconditional model output 186 | 3. return linear combination of conditional output and unconditional output 187 | """ 188 | t_img = torch.zeros(timesteps.size(0), dtype=torch.int, device=device) 189 | 190 | z_out, clip_img_out, text_out = nnet(z, clip_img, text=x, t_img=t_img, t_text=timesteps) 191 | 192 | if config.sample.scale == 0.: 193 | return text_out 194 | 195 | z_N = torch.randn_like(z) # 3 other possible choices 196 | clip_img_N = torch.randn_like(clip_img) 197 | z_out_uncond, clip_img_out_uncond, text_out_uncond = nnet(z_N, clip_img_N, text=x, t_img=torch.ones_like(timesteps) * N, t_text=timesteps) 198 | 199 | return text_out + config.sample.scale * (text_out - text_out_uncond) 200 | 201 | def split_joint(x): 202 | C, H, W = config.z_shape 203 | z_dim = C * H * W 204 | z, clip_img, text = x.split([z_dim, config.clip_img_dim, 77 * config.text_dim], dim=1) 205 | z = einops.rearrange(z, 'B (C H W) -> B C H W', C=C, H=H, W=W) 206 | clip_img = einops.rearrange(clip_img, 'B (L D) -> B L D', L=1, D=config.clip_img_dim) 207 | text = einops.rearrange(text, 'B (L D) -> B L D', L=77, D=config.text_dim) 208 | return z, clip_img, text 209 | 210 | def combine_joint(z, clip_img, text): 211 | z = einops.rearrange(z, 'B C H W -> B (C H W)') 212 | clip_img = einops.rearrange(clip_img, 'B L D -> B (L D)') 213 | text = einops.rearrange(text, 'B L D -> B (L D)') 214 | return torch.concat([z, clip_img, text], dim=-1) 215 | 216 | def joint_nnet(x, timesteps): 217 | z, clip_img, text = split_joint(x) 218 | z_out, clip_img_out, text_out = nnet(z, clip_img, text=text, t_img=timesteps, t_text=timesteps) 219 | x_out = combine_joint(z_out, clip_img_out, text_out) 220 | 221 | if config.sample.scale == 0.: 222 | return x_out 223 | 224 | z_noise = torch.randn(x.size(0), *config.z_shape, device=device) 225 | clip_img_noise = torch.randn(x.size(0), 1, config.clip_img_dim, device=device) 226 | text_noise = torch.randn(x.size(0), 77, config.text_dim, device=device) 227 | 228 | _, _, text_out_uncond = nnet(z_noise, clip_img_noise, text=text, t_img=torch.ones_like(timesteps) * N, t_text=timesteps) 229 | z_out_uncond, clip_img_out_uncond, _ = nnet(z, clip_img, text=text_noise, t_img=timesteps, t_text=torch.ones_like(timesteps) * N) 230 | 231 | x_out_uncond = combine_joint(z_out_uncond, clip_img_out_uncond, text_out_uncond) 232 | 233 | return x_out + config.sample.scale * (x_out - x_out_uncond) 234 | 235 | @torch.cuda.amp.autocast() 236 | def encode(_batch): 237 | return autoencoder.encode(_batch) 238 | 239 | @torch.cuda.amp.autocast() 240 | def decode(_batch): 241 | return autoencoder.decode(_batch) 242 | 243 | 244 | logging.info(config.sample) 245 | logging.info(f'N={N}') 246 | 247 | contexts, img_contexts, clip_imgs = prepare_contexts(config, clip_text_model, clip_img_model, clip_img_model_preprocess, autoencoder) 248 | 249 | contexts = contexts # the clip embedding of conditioned texts 250 | contexts_low_dim = contexts if not use_caption_decoder else caption_decoder.encode_prefix(contexts) # the low dimensional version of the contexts, which is the input to the nnet 251 | 252 | img_contexts = img_contexts # img_contexts is the autoencoder moment 253 | z_img = autoencoder.sample(img_contexts) 254 | clip_imgs = clip_imgs # the clip embedding of conditioned image 255 | 256 | if config.mode in ['t2i', 't2i2t']: 257 | _n_samples = contexts_low_dim.size(0) 258 | elif config.mode in ['i2t', 'i2t2i']: 259 | _n_samples = img_contexts.size(0) 260 | else: 261 | _n_samples = config.n_samples 262 | 263 | 264 | def sample_fn(mode, **kwargs): 265 | 266 | _z_init = torch.randn(_n_samples, *config.z_shape, device=device) 267 | _clip_img_init = torch.randn(_n_samples, 1, config.clip_img_dim, device=device) 268 | _text_init = torch.randn(_n_samples, 77, config.text_dim, device=device) 269 | if mode == 'joint': 270 | _x_init = combine_joint(_z_init, _clip_img_init, _text_init) 271 | elif mode in ['t2i', 'i']: 272 | _x_init = combine(_z_init, _clip_img_init) 273 | elif mode in ['i2t', 't']: 274 | _x_init = _text_init 275 | noise_schedule = NoiseScheduleVP(schedule='discrete', betas=torch.tensor(_betas, device=device).float()) 276 | 277 | def model_fn(x, t_continuous): 278 | t = t_continuous * N 279 | if mode == 'joint': 280 | return joint_nnet(x, t) 281 | elif mode == 't2i': 282 | return t2i_nnet(x, t, **kwargs) 283 | elif mode == 'i2t': 284 | return i2t_nnet(x, t, **kwargs) 285 | elif mode == 'i': 286 | return i_nnet(x, t) 287 | elif mode == 't': 288 | return t_nnet(x, t) 289 | 290 | dpm_solver = DPM_Solver(model_fn, noise_schedule, predict_x0=True, thresholding=False) 291 | with torch.no_grad(): 292 | with torch.autocast(device_type=device): 293 | start_time = time.time() 294 | x = dpm_solver.sample(_x_init, steps=config.sample.sample_steps, eps=1. / N, T=1.) 295 | end_time = time.time() 296 | print(f'\ngenerate {_n_samples} samples with {config.sample.sample_steps} steps takes {end_time - start_time:.2f}s') 297 | 298 | os.makedirs(config.output_path, exist_ok=True) 299 | if mode == 'joint': 300 | _z, _clip_img, _text = split_joint(x) 301 | return _z, _clip_img, _text 302 | elif mode in ['t2i', 'i']: 303 | _z, _clip_img = split(x) 304 | return _z, _clip_img 305 | elif mode in ['i2t', 't']: 306 | return x 307 | 308 | def watermarking(save_path): 309 | img_pre = Image.open(save_path) 310 | img_pos = utils.add_water(img_pre) 311 | img_pos.save(save_path) 312 | 313 | if config.mode in ['joint']: 314 | _z, _clip_img, _text = sample_fn(config.mode) 315 | samples = unpreprocess(decode(_z)) 316 | prompts = caption_decoder.generate_captions(_text) 317 | os.makedirs(os.path.join(config.output_path, config.mode), exist_ok=True) 318 | with open(os.path.join(config.output_path, config.mode, 'prompts.txt'), 'w') as f: 319 | print('\n'.join(prompts), file=f) 320 | for idx, sample in enumerate(samples): 321 | save_path = os.path.join(config.output_path, config.mode, f'{idx}.png') 322 | save_image(sample, save_path) 323 | watermarking(save_path) 324 | 325 | elif config.mode in ['t2i', 'i', 'i2t2i']: 326 | if config.mode == 't2i': 327 | _z, _clip_img = sample_fn(config.mode, text=contexts_low_dim) # conditioned on the text embedding 328 | elif config.mode == 'i': 329 | _z, _clip_img = sample_fn(config.mode) 330 | elif config.mode == 'i2t2i': 331 | _text = sample_fn('i2t', z=z_img, clip_img=clip_imgs) # conditioned on the image embedding 332 | _z, _clip_img = sample_fn('t2i', text=_text) 333 | samples = unpreprocess(decode(_z)) 334 | os.makedirs(os.path.join(config.output_path, config.mode), exist_ok=True) 335 | for idx, sample in enumerate(samples): 336 | save_path = os.path.join(config.output_path, config.mode, f'{idx}.png') 337 | save_image(sample, save_path) 338 | watermarking(save_path) 339 | # save a grid of generated images 340 | samples_pos = [] 341 | for idx, sample in enumerate(samples): 342 | sample_pil = standard_transforms.ToPILImage()(sample) 343 | sample_pil = utils.add_water(sample_pil) 344 | sample = standard_transforms.ToTensor()(sample_pil) 345 | samples_pos.append(sample) 346 | samples = make_grid(samples_pos, config.nrow) 347 | save_path = os.path.join(config.output_path, config.mode, f'grid.png') 348 | save_image(samples, save_path) 349 | 350 | 351 | elif config.mode in ['i2t', 't', 't2i2t']: 352 | if config.mode == 'i2t': 353 | _text = sample_fn(config.mode, z=z_img, clip_img=clip_imgs) # conditioned on the image embedding 354 | elif config.mode == 't': 355 | _text = sample_fn(config.mode) 356 | elif config.mode == 't2i2t': 357 | _z, _clip_img = sample_fn('t2i', text=contexts_low_dim) 358 | _text = sample_fn('i2t', z=_z, clip_img=_clip_img) 359 | samples = caption_decoder.generate_captions(_text) 360 | logging.info(samples) 361 | os.makedirs(os.path.join(config.output_path, config.mode), exist_ok=True) 362 | with open(os.path.join(config.output_path, config.mode, f'{config.mode}.txt'), 'w') as f: 363 | print('\n'.join(samples), file=f) 364 | 365 | print(f'\nGPU memory usage: {torch.cuda.max_memory_reserved() / 1024 ** 3:.2f} GB') 366 | print(f'\nresults are saved in {os.path.join(config.output_path, config.mode)} :)') 367 | 368 | 369 | from absl import flags 370 | from absl import app 371 | from ml_collections import config_flags 372 | import os 373 | 374 | 375 | FLAGS = flags.FLAGS 376 | config_flags.DEFINE_config_file( 377 | "config", "configs/sample_unidiffuser_v0.py", "Configuration.", lock_config=False) 378 | flags.DEFINE_string("nnet_path", "models/uvit_v0.pth", "The nnet to evaluate.") 379 | flags.DEFINE_string("output_path", "out", "dir to write results to") 380 | flags.DEFINE_string("prompt", "an elephant under the sea", "the prompt for text-to-image generation and text variation") 381 | flags.DEFINE_string("img", "assets/space.jpg", "the image path for image-to-text generation and image variation") 382 | flags.DEFINE_integer("n_samples", 1, "the number of samples to generate") 383 | flags.DEFINE_integer("nrow", 4, "number of images displayed in each row of the grid") 384 | flags.DEFINE_string("mode", None, 385 | "type of generation, one of t2i / i2t / joint / i / t / i2t2i/ t2i2t\n" 386 | "t2i: text to image\n" 387 | "i2t: image to text\n" 388 | "joint: joint generation of text and image\n" 389 | "i: only generate image\n" 390 | "t: only generate text\n" 391 | "i2t2i: image variation, first image to text, then text to image\n" 392 | "t2i2t: text variation, first text to image, the image to text\n" 393 | ) 394 | 395 | 396 | def main(argv): 397 | config = FLAGS.config 398 | config.nnet_path = FLAGS.nnet_path 399 | config.output_path = FLAGS.output_path 400 | config.prompt = FLAGS.prompt 401 | config.nrow = min(FLAGS.nrow, FLAGS.n_samples) 402 | config.img = FLAGS.img 403 | config.n_samples = FLAGS.n_samples 404 | config.mode = FLAGS.mode 405 | evaluate(config) 406 | 407 | 408 | if __name__ == "__main__": 409 | app.run(main) 410 | -------------------------------------------------------------------------------- /sample_multi_v1.py: -------------------------------------------------------------------------------- 1 | import ml_collections 2 | import torch 3 | import random 4 | import utils 5 | from dpm_solver_pp import NoiseScheduleVP, DPM_Solver 6 | from absl import logging 7 | import einops 8 | import libs.autoencoder 9 | import libs.clip 10 | from torchvision.utils import save_image, make_grid 11 | import torchvision.transforms as standard_transforms 12 | import numpy as np 13 | import clip 14 | from PIL import Image 15 | import time 16 | 17 | 18 | def stable_diffusion_beta_schedule(linear_start=0.00085, linear_end=0.0120, n_timestep=1000): 19 | _betas = ( 20 | torch.linspace(linear_start ** 0.5, linear_end ** 0.5, n_timestep, dtype=torch.float64) ** 2 21 | ) 22 | return _betas.numpy() 23 | 24 | 25 | def prepare_contexts(config, clip_text_model, clip_img_model, clip_img_model_preprocess, autoencoder): 26 | resolution = config.z_shape[-1] * 8 27 | device = 'cuda' if torch.cuda.is_available() else 'cpu' 28 | 29 | contexts = torch.randn(config.n_samples, 77, config.clip_text_dim).to(device) 30 | img_contexts = torch.randn(config.n_samples, 2 * config.z_shape[0], config.z_shape[1], config.z_shape[2]) 31 | clip_imgs = torch.randn(config.n_samples, 1, config.clip_img_dim) 32 | 33 | if config.mode in ['t2i', 't2i2t']: 34 | prompts = [ config.prompt ] * config.n_samples 35 | contexts = clip_text_model.encode(prompts) 36 | 37 | elif config.mode in ['i2t', 'i2t2i']: 38 | from PIL import Image 39 | img_contexts = [] 40 | clip_imgs = [] 41 | 42 | def get_img_feature(image): 43 | image = np.array(image).astype(np.uint8) 44 | image = utils.center_crop(resolution, resolution, image) 45 | clip_img_feature = clip_img_model.encode_image(clip_img_model_preprocess(Image.fromarray(image)).unsqueeze(0).to(device)) 46 | 47 | image = (image / 127.5 - 1.0).astype(np.float32) 48 | image = einops.rearrange(image, 'h w c -> 1 c h w') 49 | image = torch.tensor(image, device=device) 50 | moments = autoencoder.encode_moments(image) 51 | 52 | return clip_img_feature, moments 53 | 54 | image = Image.open(config.img).convert('RGB') 55 | clip_img, img_context = get_img_feature(image) 56 | 57 | img_contexts.append(img_context) 58 | clip_imgs.append(clip_img) 59 | img_contexts = img_contexts * config.n_samples 60 | clip_imgs = clip_imgs * config.n_samples 61 | 62 | img_contexts = torch.concat(img_contexts, dim=0) 63 | clip_imgs = torch.stack(clip_imgs, dim=0) 64 | 65 | return contexts, img_contexts, clip_imgs 66 | 67 | 68 | def unpreprocess(v): # to B C H W and [0, 1] 69 | v = 0.5 * (v + 1.) 70 | v.clamp_(0., 1.) 71 | return v 72 | 73 | 74 | def set_seed(seed: int): 75 | random.seed(seed) 76 | np.random.seed(seed) 77 | torch.manual_seed(seed) 78 | torch.cuda.manual_seed_all(seed) 79 | 80 | 81 | def evaluate(config): 82 | if config.get('benchmark', False): 83 | torch.backends.cudnn.benchmark = True 84 | torch.backends.cudnn.deterministic = False 85 | 86 | device = 'cuda' if torch.cuda.is_available() else 'cpu' 87 | set_seed(config.seed) 88 | 89 | config = ml_collections.FrozenConfigDict(config) 90 | utils.set_logger(log_level='info') 91 | 92 | _betas = stable_diffusion_beta_schedule() 93 | N = len(_betas) 94 | 95 | nnet = utils.get_nnet(**config.nnet) 96 | logging.info(f'load nnet from {config.nnet_path}') 97 | nnet.load_state_dict(torch.load(config.nnet_path, map_location='cpu')) 98 | nnet.to(device) 99 | nnet.eval() 100 | 101 | use_caption_decoder = config.text_dim < config.clip_text_dim or config.mode != 't2i' 102 | if use_caption_decoder: 103 | from libs.caption_decoder import CaptionDecoder 104 | caption_decoder = CaptionDecoder(device=device, **config.caption_decoder) 105 | else: 106 | caption_decoder = None 107 | 108 | clip_text_model = libs.clip.FrozenCLIPEmbedder(device=device) 109 | clip_text_model.eval() 110 | clip_text_model.to(device) 111 | 112 | autoencoder = libs.autoencoder.get_model(**config.autoencoder) 113 | autoencoder.to(device) 114 | 115 | clip_img_model, clip_img_model_preprocess = clip.load("ViT-B/32", device=device, jit=False) 116 | 117 | empty_context = clip_text_model.encode([''])[0] 118 | 119 | def split(x): 120 | C, H, W = config.z_shape 121 | z_dim = C * H * W 122 | z, clip_img = x.split([z_dim, config.clip_img_dim], dim=1) 123 | z = einops.rearrange(z, 'B (C H W) -> B C H W', C=C, H=H, W=W) 124 | clip_img = einops.rearrange(clip_img, 'B (L D) -> B L D', L=1, D=config.clip_img_dim) 125 | return z, clip_img 126 | 127 | 128 | def combine(z, clip_img): 129 | z = einops.rearrange(z, 'B C H W -> B (C H W)') 130 | clip_img = einops.rearrange(clip_img, 'B L D -> B (L D)') 131 | return torch.concat([z, clip_img], dim=-1) 132 | 133 | 134 | def t2i_nnet(x, timesteps, text): # text is the low dimension version of the text clip embedding 135 | """ 136 | 1. calculate the conditional model output 137 | 2. calculate unconditional model output 138 | config.sample.t2i_cfg_mode == 'empty_token': using the original cfg with the empty string 139 | config.sample.t2i_cfg_mode == 'true_uncond: using the unconditional model learned by our method 140 | 3. return linear combination of conditional output and unconditional output 141 | """ 142 | z, clip_img = split(x) 143 | 144 | t_text = torch.zeros(timesteps.size(0), dtype=torch.int, device=device) 145 | 146 | z_out, clip_img_out, text_out = nnet(z, clip_img, text=text, t_img=timesteps, t_text=t_text, 147 | data_type=torch.zeros_like(t_text, device=device, dtype=torch.int) + config.data_type) 148 | x_out = combine(z_out, clip_img_out) 149 | 150 | if config.sample.scale == 0.: 151 | return x_out 152 | 153 | if config.sample.t2i_cfg_mode == 'empty_token': 154 | _empty_context = einops.repeat(empty_context, 'L D -> B L D', B=x.size(0)) 155 | if use_caption_decoder: 156 | _empty_context = caption_decoder.encode_prefix(_empty_context) 157 | z_out_uncond, clip_img_out_uncond, text_out_uncond = nnet(z, clip_img, text=_empty_context, t_img=timesteps, t_text=t_text, 158 | data_type=torch.zeros_like(t_text, device=device, dtype=torch.int) + config.data_type) 159 | x_out_uncond = combine(z_out_uncond, clip_img_out_uncond) 160 | elif config.sample.t2i_cfg_mode == 'true_uncond': 161 | text_N = torch.randn_like(text) # 3 other possible choices 162 | z_out_uncond, clip_img_out_uncond, text_out_uncond = nnet(z, clip_img, text=text_N, t_img=timesteps, t_text=torch.ones_like(timesteps) * N, 163 | data_type=torch.zeros_like(t_text, device=device, dtype=torch.int) + config.data_type) 164 | x_out_uncond = combine(z_out_uncond, clip_img_out_uncond) 165 | else: 166 | raise NotImplementedError 167 | 168 | return x_out + config.sample.scale * (x_out - x_out_uncond) 169 | 170 | 171 | def i_nnet(x, timesteps): 172 | z, clip_img = split(x) 173 | text = torch.randn(x.size(0), 77, config.text_dim, device=device) 174 | t_text = torch.ones_like(timesteps) * N 175 | z_out, clip_img_out, text_out = nnet(z, clip_img, text=text, t_img=timesteps, t_text=t_text, 176 | data_type=torch.zeros_like(t_text, device=device, dtype=torch.int) + config.data_type) 177 | x_out = combine(z_out, clip_img_out) 178 | return x_out 179 | 180 | def t_nnet(x, timesteps): 181 | z = torch.randn(x.size(0), *config.z_shape, device=device) 182 | clip_img = torch.randn(x.size(0), 1, config.clip_img_dim, device=device) 183 | z_out, clip_img_out, text_out = nnet(z, clip_img, text=x, t_img=torch.ones_like(timesteps) * N, t_text=timesteps, 184 | data_type=torch.zeros_like(timesteps, device=device, dtype=torch.int) + config.data_type) 185 | return text_out 186 | 187 | def i2t_nnet(x, timesteps, z, clip_img): 188 | """ 189 | 1. calculate the conditional model output 190 | 2. calculate unconditional model output 191 | 3. return linear combination of conditional output and unconditional output 192 | """ 193 | t_img = torch.zeros(timesteps.size(0), dtype=torch.int, device=device) 194 | 195 | z_out, clip_img_out, text_out = nnet(z, clip_img, text=x, t_img=t_img, t_text=timesteps, 196 | data_type=torch.zeros_like(t_img, device=device, dtype=torch.int) + config.data_type) 197 | 198 | if config.sample.scale == 0.: 199 | return text_out 200 | 201 | z_N = torch.randn_like(z) # 3 other possible choices 202 | clip_img_N = torch.randn_like(clip_img) 203 | z_out_uncond, clip_img_out_uncond, text_out_uncond = nnet(z_N, clip_img_N, text=x, t_img=torch.ones_like(timesteps) * N, t_text=timesteps, 204 | data_type=torch.zeros_like(timesteps, device=device, dtype=torch.int) + config.data_type) 205 | 206 | return text_out + config.sample.scale * (text_out - text_out_uncond) 207 | 208 | def split_joint(x): 209 | C, H, W = config.z_shape 210 | z_dim = C * H * W 211 | z, clip_img, text = x.split([z_dim, config.clip_img_dim, 77 * config.text_dim], dim=1) 212 | z = einops.rearrange(z, 'B (C H W) -> B C H W', C=C, H=H, W=W) 213 | clip_img = einops.rearrange(clip_img, 'B (L D) -> B L D', L=1, D=config.clip_img_dim) 214 | text = einops.rearrange(text, 'B (L D) -> B L D', L=77, D=config.text_dim) 215 | return z, clip_img, text 216 | 217 | def combine_joint(z, clip_img, text): 218 | z = einops.rearrange(z, 'B C H W -> B (C H W)') 219 | clip_img = einops.rearrange(clip_img, 'B L D -> B (L D)') 220 | text = einops.rearrange(text, 'B L D -> B (L D)') 221 | return torch.concat([z, clip_img, text], dim=-1) 222 | 223 | def joint_nnet(x, timesteps): 224 | z, clip_img, text = split_joint(x) 225 | z_out, clip_img_out, text_out = nnet(z, clip_img, text=text, t_img=timesteps, t_text=timesteps, 226 | data_type=torch.zeros_like(timesteps, device=device, dtype=torch.int) + config.data_type) 227 | x_out = combine_joint(z_out, clip_img_out, text_out) 228 | 229 | if config.sample.scale == 0.: 230 | return x_out 231 | 232 | z_noise = torch.randn(x.size(0), *config.z_shape, device=device) 233 | clip_img_noise = torch.randn(x.size(0), 1, config.clip_img_dim, device=device) 234 | text_noise = torch.randn(x.size(0), 77, config.text_dim, device=device) 235 | 236 | _, _, text_out_uncond = nnet(z_noise, clip_img_noise, text=text, t_img=torch.ones_like(timesteps) * N, t_text=timesteps, 237 | data_type=torch.zeros_like(timesteps, device=device, dtype=torch.int) + config.data_type) 238 | z_out_uncond, clip_img_out_uncond, _ = nnet(z, clip_img, text=text_noise, t_img=timesteps, t_text=torch.ones_like(timesteps) * N, 239 | data_type=torch.zeros_like(timesteps, device=device, dtype=torch.int) + config.data_type) 240 | 241 | x_out_uncond = combine_joint(z_out_uncond, clip_img_out_uncond, text_out_uncond) 242 | 243 | return x_out + config.sample.scale * (x_out - x_out_uncond) 244 | 245 | @torch.cuda.amp.autocast() 246 | def encode(_batch): 247 | return autoencoder.encode(_batch) 248 | 249 | @torch.cuda.amp.autocast() 250 | def decode(_batch): 251 | return autoencoder.decode(_batch) 252 | 253 | 254 | logging.info(config.sample) 255 | logging.info(f'N={N}') 256 | 257 | contexts, img_contexts, clip_imgs = prepare_contexts(config, clip_text_model, clip_img_model, clip_img_model_preprocess, autoencoder) 258 | 259 | contexts = contexts # the clip embedding of conditioned texts 260 | contexts_low_dim = contexts if not use_caption_decoder else caption_decoder.encode_prefix(contexts) # the low dimensional version of the contexts, which is the input to the nnet 261 | 262 | img_contexts = img_contexts # img_contexts is the autoencoder moment 263 | z_img = autoencoder.sample(img_contexts) 264 | clip_imgs = clip_imgs # the clip embedding of conditioned image 265 | 266 | if config.mode in ['t2i', 't2i2t']: 267 | _n_samples = contexts_low_dim.size(0) 268 | elif config.mode in ['i2t', 'i2t2i']: 269 | _n_samples = img_contexts.size(0) 270 | else: 271 | _n_samples = config.n_samples 272 | 273 | 274 | def sample_fn(mode, **kwargs): 275 | 276 | _z_init = torch.randn(_n_samples, *config.z_shape, device=device) 277 | _clip_img_init = torch.randn(_n_samples, 1, config.clip_img_dim, device=device) 278 | _text_init = torch.randn(_n_samples, 77, config.text_dim, device=device) 279 | if mode == 'joint': 280 | _x_init = combine_joint(_z_init, _clip_img_init, _text_init) 281 | elif mode in ['t2i', 'i']: 282 | _x_init = combine(_z_init, _clip_img_init) 283 | elif mode in ['i2t', 't']: 284 | _x_init = _text_init 285 | noise_schedule = NoiseScheduleVP(schedule='discrete', betas=torch.tensor(_betas, device=device).float()) 286 | 287 | def model_fn(x, t_continuous): 288 | t = t_continuous * N 289 | if mode == 'joint': 290 | return joint_nnet(x, t) 291 | elif mode == 't2i': 292 | return t2i_nnet(x, t, **kwargs) 293 | elif mode == 'i2t': 294 | return i2t_nnet(x, t, **kwargs) 295 | elif mode == 'i': 296 | return i_nnet(x, t) 297 | elif mode == 't': 298 | return t_nnet(x, t) 299 | 300 | dpm_solver = DPM_Solver(model_fn, noise_schedule, predict_x0=True, thresholding=False) 301 | with torch.no_grad(): 302 | with torch.autocast(device_type=device): 303 | start_time = time.time() 304 | x = dpm_solver.sample(_x_init, steps=config.sample.sample_steps, eps=1. / N, T=1.) 305 | end_time = time.time() 306 | print(f'\ngenerate {_n_samples} samples with {config.sample.sample_steps} steps takes {end_time - start_time:.2f}s') 307 | 308 | os.makedirs(config.output_path, exist_ok=True) 309 | if mode == 'joint': 310 | _z, _clip_img, _text = split_joint(x) 311 | return _z, _clip_img, _text 312 | elif mode in ['t2i', 'i']: 313 | _z, _clip_img = split(x) 314 | return _z, _clip_img 315 | elif mode in ['i2t', 't']: 316 | return x 317 | 318 | def watermarking(save_path): 319 | img_pre = Image.open(save_path) 320 | img_pos = utils.add_water(img_pre) 321 | img_pos.save(save_path) 322 | 323 | if config.mode in ['joint']: 324 | _z, _clip_img, _text = sample_fn(config.mode) 325 | samples = unpreprocess(decode(_z)) 326 | prompts = caption_decoder.generate_captions(_text) 327 | os.makedirs(os.path.join(config.output_path, config.mode), exist_ok=True) 328 | with open(os.path.join(config.output_path, config.mode, 'prompts.txt'), 'w') as f: 329 | print('\n'.join(prompts), file=f) 330 | for idx, sample in enumerate(samples): 331 | save_path = os.path.join(config.output_path, config.mode, f'{idx}.png') 332 | save_image(sample, save_path) 333 | watermarking(save_path) 334 | 335 | elif config.mode in ['t2i', 'i', 'i2t2i']: 336 | if config.mode == 't2i': 337 | _z, _clip_img = sample_fn(config.mode, text=contexts_low_dim) # conditioned on the text embedding 338 | elif config.mode == 'i': 339 | _z, _clip_img = sample_fn(config.mode) 340 | elif config.mode == 'i2t2i': 341 | _text = sample_fn('i2t', z=z_img, clip_img=clip_imgs) # conditioned on the image embedding 342 | _z, _clip_img = sample_fn('t2i', text=_text) 343 | samples = unpreprocess(decode(_z)) 344 | os.makedirs(os.path.join(config.output_path, config.mode), exist_ok=True) 345 | for idx, sample in enumerate(samples): 346 | save_path = os.path.join(config.output_path, config.mode, f'{idx}.png') 347 | save_image(sample, save_path) 348 | watermarking(save_path) 349 | # save a grid of generated images 350 | samples_pos = [] 351 | for idx, sample in enumerate(samples): 352 | sample_pil = standard_transforms.ToPILImage()(sample) 353 | sample_pil = utils.add_water(sample_pil) 354 | sample = standard_transforms.ToTensor()(sample_pil) 355 | samples_pos.append(sample) 356 | samples = make_grid(samples_pos, config.nrow) 357 | save_path = os.path.join(config.output_path, config.mode, f'grid.png') 358 | save_image(samples, save_path) 359 | 360 | 361 | elif config.mode in ['i2t', 't', 't2i2t']: 362 | if config.mode == 'i2t': 363 | _text = sample_fn(config.mode, z=z_img, clip_img=clip_imgs) # conditioned on the image embedding 364 | elif config.mode == 't': 365 | _text = sample_fn(config.mode) 366 | elif config.mode == 't2i2t': 367 | _z, _clip_img = sample_fn('t2i', text=contexts_low_dim) 368 | _text = sample_fn('i2t', z=_z, clip_img=_clip_img) 369 | samples = caption_decoder.generate_captions(_text) 370 | logging.info(samples) 371 | os.makedirs(os.path.join(config.output_path, config.mode), exist_ok=True) 372 | with open(os.path.join(config.output_path, config.mode, f'{config.mode}.txt'), 'w') as f: 373 | print('\n'.join(samples), file=f) 374 | 375 | print(f'\nGPU memory usage: {torch.cuda.max_memory_reserved() / 1024 ** 3:.2f} GB') 376 | print(f'\nresults are saved in {os.path.join(config.output_path, config.mode)} :)') 377 | 378 | 379 | from absl import flags 380 | from absl import app 381 | from ml_collections import config_flags 382 | import os 383 | 384 | 385 | FLAGS = flags.FLAGS 386 | config_flags.DEFINE_config_file( 387 | "config", "configs/sample_unidiffuser_v1.py", "Configuration.", lock_config=False) 388 | flags.DEFINE_string("nnet_path", "models/uvit_v1.pth", "The nnet to evaluate.") 389 | flags.DEFINE_string("output_path", "out", "dir to write results to") 390 | flags.DEFINE_string("prompt", "an elephant under the sea", "the prompt for text-to-image generation and text variation") 391 | flags.DEFINE_string("img", "assets/space.jpg", "the image path for image-to-text generation and image variation") 392 | flags.DEFINE_integer("n_samples", 1, "the number of samples to generate") 393 | flags.DEFINE_integer("nrow", 4, "number of images displayed in each row of the grid") 394 | flags.DEFINE_string("mode", None, 395 | "type of generation, one of t2i / i2t / joint / i / t / i2t2i/ t2i2t\n" 396 | "t2i: text to image\n" 397 | "i2t: image to text\n" 398 | "joint: joint generation of text and image\n" 399 | "i: only generate image\n" 400 | "t: only generate text\n" 401 | "i2t2i: image variation, first image to text, then text to image\n" 402 | "t2i2t: text variation, first text to image, the image to text\n" 403 | ) 404 | 405 | 406 | def main(argv): 407 | config = FLAGS.config 408 | config.nnet_path = FLAGS.nnet_path 409 | config.output_path = FLAGS.output_path 410 | config.prompt = FLAGS.prompt 411 | config.nrow = min(FLAGS.nrow, FLAGS.n_samples) 412 | config.img = FLAGS.img 413 | config.n_samples = FLAGS.n_samples 414 | config.mode = FLAGS.mode 415 | evaluate(config) 416 | 417 | 418 | if __name__ == "__main__": 419 | app.run(main) 420 | -------------------------------------------------------------------------------- /utils.py: -------------------------------------------------------------------------------- 1 | from absl import logging 2 | import numpy as np 3 | from PIL import Image, ImageDraw, ImageFont 4 | 5 | 6 | def center_crop(width, height, img): 7 | resample = {'box': Image.BOX, 'lanczos': Image.LANCZOS}['lanczos'] 8 | crop = np.min(img.shape[:2]) 9 | img = img[(img.shape[0] - crop) // 2: (img.shape[0] + crop) // 2, 10 | (img.shape[1] - crop) // 2: (img.shape[1] + crop) // 2] # center crop 11 | try: 12 | img = Image.fromarray(img, 'RGB') 13 | except: 14 | img = Image.fromarray(img) 15 | img = img.resize((width, height), resample) # resize the center crop from [crop, crop] to [width, height] 16 | 17 | return np.array(img).astype(np.uint8) 18 | 19 | 20 | def set_logger(log_level='info', fname=None): 21 | import logging as _logging 22 | handler = logging.get_absl_handler() 23 | formatter = _logging.Formatter('%(asctime)s - %(filename)s - %(message)s') 24 | handler.setFormatter(formatter) 25 | logging.set_verbosity(log_level) 26 | if fname is not None: 27 | handler = _logging.FileHandler(fname) 28 | handler.setFormatter(formatter) 29 | logging.get_absl_logger().addHandler(handler) 30 | 31 | 32 | def get_nnet(name, **kwargs): 33 | if name == 'uvit_multi_post_ln': 34 | from libs.uvit_multi_post_ln import UViT 35 | return UViT(**kwargs) 36 | elif name == 'uvit_multi_post_ln_v1': 37 | from libs.uvit_multi_post_ln_v1 import UViT 38 | return UViT(**kwargs) 39 | else: 40 | raise NotImplementedError(name) 41 | 42 | 43 | def drawRoundRec(draw, color, x, y, w, h, r): 44 | drawObject = draw 45 | 46 | '''Rounds''' 47 | drawObject.ellipse((x, y, x + r, y + r), fill=color) 48 | drawObject.ellipse((x + w - r, y, x + w, y + r), fill=color) 49 | drawObject.ellipse((x, y + h - r, x + r, y + h), fill=color) 50 | drawObject.ellipse((x + w - r, y + h - r, x + w, y + h), fill=color) 51 | 52 | '''rec.s''' 53 | drawObject.rectangle((x + r / 2, y, x + w - (r / 2), y + h), fill=color) 54 | drawObject.rectangle((x, y + r / 2, x + w, y + h - (r / 2)), fill=color) 55 | 56 | 57 | def add_water(img, text='UniDiffuser', pos=3): 58 | width, height = img.size 59 | scale = 4 60 | scale_size = 0.5 61 | img = img.resize((width * scale, height * scale), Image.LANCZOS) 62 | result = Image.new(img.mode, (width * scale, height * scale), color=(255, 255, 255)) 63 | result.paste(img, box=(0, 0)) 64 | 65 | delta_w = int(width * scale * 0.27 * scale_size) # text width 66 | delta_h = width * scale * 0.05 * scale_size # text height 67 | postions = np.array([[0, 0], [0, height * scale - delta_h], [width * scale - delta_w, 0], 68 | [width * scale - delta_w, height * scale - delta_h]]) 69 | postion = postions[pos] 70 | # 文本 71 | draw = ImageDraw.Draw(result) 72 | fillColor = (107, 92, 231) 73 | setFont = ImageFont.truetype("assets/ArialBoldMT.ttf", int(width * scale * 0.05 * scale_size)) 74 | delta = 20 * scale_size 75 | padding = 15 * scale_size 76 | drawRoundRec(draw, (223, 230, 233), postion[0] - delta - padding, postion[1] - delta - padding, 77 | w=delta_w + 2 * padding, h=delta_h + 2 * padding, r=50 * scale_size) 78 | draw.text((postion[0] - delta, postion[1] - delta), text, font=setFont, fill=fillColor) 79 | 80 | return result.resize((width, height), Image.LANCZOS) 81 | --------------------------------------------------------------------------------