├── .github └── workflows │ └── publish.yml ├── .gitignore ├── LICENSE ├── README.md ├── __init__.py ├── empty_text_embed.pt ├── examples ├── marigold_LCM_example_01.json └── marigold_example_01.json ├── gmflow ├── __init__.py ├── backbone.py ├── geometry.py ├── gmflow.py ├── gmflow_things-e9887eda.pth ├── matching.py ├── position.py ├── transformer.py ├── trident_conv.py └── utils.py ├── marigold ├── model │ ├── __init__.py │ ├── marigold_pipeline.py │ ├── rgb_encoder.py │ └── stacked_depth_AE.py └── util │ ├── batchsize.py │ ├── ensemble.py │ ├── flow_estimation.py │ ├── image_util.py │ └── seed_all.py ├── nodes.py ├── nodes_v2.py ├── prestartup_script.py ├── pyproject.toml └── requirements.txt /.github/workflows/publish.yml: -------------------------------------------------------------------------------- 1 | name: Publish to Comfy registry 2 | on: 3 | workflow_dispatch: 4 | push: 5 | branches: 6 | - main 7 | paths: 8 | - "pyproject.toml" 9 | 10 | permissions: 11 | issues: write 12 | 13 | jobs: 14 | publish-node: 15 | name: Publish Custom Node to registry 16 | runs-on: ubuntu-latest 17 | if: ${{ github.repository_owner == 'kijai' }} 18 | steps: 19 | - name: Check out code 20 | uses: actions/checkout@v4 21 | - name: Publish Custom Node 22 | uses: Comfy-Org/publish-node-action@v1 23 | with: 24 | ## Add your own personal access token to your Github Repository secrets and reference it here. 25 | personal_access_token: ${{ secrets.REGISTRY_ACCESS_TOKEN }} 26 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | __pycache__ 2 | /venv 3 | /checkpoints 4 | .vscode 5 | *.ckpt 6 | *.safetensors 7 | types -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Marigold depth estimation in ComfyUI 2 | 3 | ![image](https://github.com/kijai/ComfyUI-Marigold/assets/40791699/266f6eb4-ec9c-4c25-bdb9-4c1da97bd9be) 4 | 5 | https://github.com/kijai/ComfyUI-Marigold/assets/40791699/0b39fece-592e-4302-b9eb-16fa979d4365 6 | 7 | This is a wrapper node for Marigold depth estimation: 8 | https://github.com/prs-eth/Marigold 9 | 10 | Join us at the [Banodoco Discord](https://discord.gg/xAkA6NTyA3) for discussion on the use and node development: 11 | https://discord.com/channels/1076117621407223829/1184863853096484865 12 | 13 | What I know of the parameters so far: 14 | 15 | `denoise_steps`: steps per depth map, increase for accuracy in exchange of processing time 16 | 17 | `n_repeat`: amount of iterations to be ensembled into single depth map, increase for accuracy in exchange of processing time 18 | 19 | `n_repeat_batch_size`: how many of the n_repeats are processed as a batch, if you have the VRAM this can match the n_repeats for faster processing 20 | 21 | `invert`: marigold by default produces depth map where black is front, for controlnets etc. we want the opposite 22 | 23 | regularizer_strength, reduction_method, max_iter, tol (tolerance) are settings for the ensembling process, don't fully know how to use them yet. 24 | 25 | It can pretty memory hungry, and slow, fp16 halves the memory use. Marigold is meant to be run around 768p resolution so resizing is recommended, at higher res your mileage may wary. 26 | I added a remap node to see the full range better, and OpenEXR node to save the full range, works wonders compared to default png when used in VFX/3D modeling software. 27 | 28 | ## Installing: 29 | Recommended way: 30 | 31 | Use the ComfyUI manager (search for "marigold") 32 | 33 | Manual install: 34 | 35 | Clone this repo to `ComfyUI/custom_nodes` 36 | Install requirements: `pip install -r requirements.txt` 37 | 38 | Get the model: 39 | 40 | Currently using the same diffusers pipeline as in the original implementation, so in addition to the custom node, you need the model in diffusers format. 41 | 42 | If the model is not found, it should autodownload with hugginface_hub. 43 | Alternatively get it manually from: https://huggingface.co/Bingxin/Marigold (or do `git clone https://huggingface.co/Bingxin/Marigold/`) in either of these folders: 44 | 45 | `ComfyUI\custom_nodes\ComfyUI-Marigold\checkpoints` or `ComfyUI\models\diffusers` 46 | -------------------------------------------------------------------------------- /__init__.py: -------------------------------------------------------------------------------- 1 | from .nodes import MarigoldDepthEstimation, MarigoldDepthEstimationVideo, ColorizeDepthmap, SaveImageOpenEXR, RemapDepth 2 | from .nodes_v2 import MarigoldModelLoader, MarigoldDepthEstimation_v2, MarigoldDepthEstimation_v2_video 3 | 4 | NODE_CLASS_MAPPINGS = { 5 | "MarigoldModelLoader": MarigoldModelLoader, 6 | "MarigoldDepthEstimation_v2": MarigoldDepthEstimation_v2, 7 | "MarigoldDepthEstimation_v2_video": MarigoldDepthEstimation_v2_video, 8 | "MarigoldDepthEstimation": MarigoldDepthEstimation, 9 | "MarigoldDepthEstimationVideo": MarigoldDepthEstimationVideo, 10 | "ColorizeDepthmap": ColorizeDepthmap, 11 | "SaveImageOpenEXR": SaveImageOpenEXR, 12 | "RemapDepth": RemapDepth 13 | } 14 | NODE_DISPLAY_NAME_MAPPINGS = { 15 | "MarigoldModelLoader": "MarigoldModelLoader", 16 | "MarigoldDepthEstimation_v2": "MarigoldDepthEstimation_v2", 17 | "MarigoldDepthEstimation_v2_video": "MarigoldDepthEstimation_v2_video", 18 | "MarigoldDepthEstimation": "MarigoldDepthEstimation", 19 | "MarigoldDepthEstimationVideo": "MarigoldDepthEstimationVideo", 20 | "ColorizeDepthmap": "Colorize Depthmap", 21 | "SaveImageOpenEXR": "SaveImageOpenEXR", 22 | "RemapDepth": "Remap Depth" 23 | } 24 | __all__ = ["NODE_CLASS_MAPPINGS", "NODE_DISPLAY_NAME_MAPPINGS"] -------------------------------------------------------------------------------- /empty_text_embed.pt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kijai/ComfyUI-Marigold/2adfec75c430b0751a98a82453dc2dd8077bca85/empty_text_embed.pt -------------------------------------------------------------------------------- /examples/marigold_LCM_example_01.json: -------------------------------------------------------------------------------- 1 | { 2 | "last_node_id": 15, 3 | "last_link_id": 15, 4 | "nodes": [ 5 | { 6 | "id": 2, 7 | "type": "ImageResize+", 8 | "pos": [ 9 | 427, 10 | 98 11 | ], 12 | "size": { 13 | "0": 315, 14 | "1": 218 15 | }, 16 | "flags": {}, 17 | "order": 5, 18 | "mode": 0, 19 | "inputs": [ 20 | { 21 | "name": "image", 22 | "type": "IMAGE", 23 | "link": 2, 24 | "slot_index": 0 25 | } 26 | ], 27 | "outputs": [ 28 | { 29 | "name": "IMAGE", 30 | "type": "IMAGE", 31 | "links": [ 32 | 1 33 | ], 34 | "shape": 3, 35 | "slot_index": 0 36 | }, 37 | { 38 | "name": "width", 39 | "type": "INT", 40 | "links": null, 41 | "shape": 3 42 | }, 43 | { 44 | "name": "height", 45 | "type": "INT", 46 | "links": null, 47 | "shape": 3 48 | } 49 | ], 50 | "properties": { 51 | "Node name for S&R": "ImageResize+" 52 | }, 53 | "widgets_values": [ 54 | 768, 55 | 768, 56 | "nearest", 57 | true, 58 | "always", 59 | 32 60 | ] 61 | }, 62 | { 63 | "id": 3, 64 | "type": "LoadImage", 65 | "pos": [ 66 | 102, 67 | 99 68 | ], 69 | "size": [ 70 | 297, 71 | 430 72 | ], 73 | "flags": {}, 74 | "order": 0, 75 | "mode": 0, 76 | "outputs": [ 77 | { 78 | "name": "IMAGE", 79 | "type": "IMAGE", 80 | "links": [ 81 | 2 82 | ], 83 | "shape": 3 84 | }, 85 | { 86 | "name": "MASK", 87 | "type": "MASK", 88 | "links": null, 89 | "shape": 3 90 | } 91 | ], 92 | "properties": { 93 | "Node name for S&R": "LoadImage" 94 | }, 95 | "widgets_values": [ 96 | "marigold_example_0.jpg", 97 | "image" 98 | ] 99 | }, 100 | { 101 | "id": 9, 102 | "type": "ImageInvert", 103 | "pos": [ 104 | 1186, 105 | 184 106 | ], 107 | "size": { 108 | "0": 210, 109 | "1": 26 110 | }, 111 | "flags": {}, 112 | "order": 9, 113 | "mode": 0, 114 | "inputs": [ 115 | { 116 | "name": "image", 117 | "type": "IMAGE", 118 | "link": 15 119 | } 120 | ], 121 | "outputs": [ 122 | { 123 | "name": "IMAGE", 124 | "type": "IMAGE", 125 | "links": [ 126 | 13 127 | ], 128 | "shape": 3, 129 | "slot_index": 0 130 | } 131 | ], 132 | "properties": { 133 | "Node name for S&R": "ImageInvert" 134 | } 135 | }, 136 | { 137 | "id": 5, 138 | "type": "ColorizeDepthmap", 139 | "pos": [ 140 | 1170, 141 | 266 142 | ], 143 | "size": { 144 | "0": 315, 145 | "1": 58 146 | }, 147 | "flags": {}, 148 | "order": 10, 149 | "mode": 0, 150 | "inputs": [ 151 | { 152 | "name": "image", 153 | "type": "IMAGE", 154 | "link": 13 155 | } 156 | ], 157 | "outputs": [ 158 | { 159 | "name": "image", 160 | "type": "IMAGE", 161 | "links": [ 162 | 14 163 | ], 164 | "shape": 3, 165 | "slot_index": 0 166 | } 167 | ], 168 | "properties": { 169 | "Node name for S&R": "ColorizeDepthmap" 170 | }, 171 | "widgets_values": [ 172 | "Spectral" 173 | ] 174 | }, 175 | { 176 | "id": 8, 177 | "type": "PreviewImage", 178 | "pos": [ 179 | 1547, 180 | 26 181 | ], 182 | "size": [ 183 | 381.5950622558594, 184 | 526.610237121582 185 | ], 186 | "flags": {}, 187 | "order": 8, 188 | "mode": 0, 189 | "inputs": [ 190 | { 191 | "name": "images", 192 | "type": "IMAGE", 193 | "link": 7, 194 | "slot_index": 0 195 | } 196 | ], 197 | "properties": { 198 | "Node name for S&R": "PreviewImage" 199 | } 200 | }, 201 | { 202 | "id": 7, 203 | "type": "PreviewImage", 204 | "pos": [ 205 | 1181, 206 | 377 207 | ], 208 | "size": [ 209 | 320.5950622558594, 210 | 468.61023712158203 211 | ], 212 | "flags": {}, 213 | "order": 11, 214 | "mode": 0, 215 | "inputs": [ 216 | { 217 | "name": "images", 218 | "type": "IMAGE", 219 | "link": 14, 220 | "slot_index": 0 221 | } 222 | ], 223 | "properties": { 224 | "Node name for S&R": "PreviewImage" 225 | } 226 | }, 227 | { 228 | "id": 6, 229 | "type": "RemapDepth", 230 | "pos": [ 231 | 1183, 232 | 23 233 | ], 234 | "size": { 235 | "0": 315, 236 | "1": 106 237 | }, 238 | "flags": {}, 239 | "order": 7, 240 | "mode": 0, 241 | "inputs": [ 242 | { 243 | "name": "image", 244 | "type": "IMAGE", 245 | "link": 8, 246 | "slot_index": 0 247 | } 248 | ], 249 | "outputs": [ 250 | { 251 | "name": "IMAGE", 252 | "type": "IMAGE", 253 | "links": [ 254 | 7, 255 | 15 256 | ], 257 | "shape": 3, 258 | "slot_index": 0 259 | } 260 | ], 261 | "properties": { 262 | "Node name for S&R": "RemapDepth" 263 | }, 264 | "widgets_values": [ 265 | 0, 266 | 1, 267 | true 268 | ] 269 | }, 270 | { 271 | "id": 12, 272 | "type": "Note", 273 | "pos": [ 274 | 426, 275 | -18 276 | ], 277 | "size": { 278 | "0": 305.4951171875, 279 | "1": 64.41022491455078 280 | }, 281 | "flags": {}, 282 | "order": 1, 283 | "mode": 0, 284 | "title": "Note: Image Size", 285 | "properties": { 286 | "text": "" 287 | }, 288 | "widgets_values": [ 289 | "Marigold works best close to 768p" 290 | ], 291 | "color": "#432", 292 | "bgcolor": "#653" 293 | }, 294 | { 295 | "id": 13, 296 | "type": "Note", 297 | "pos": [ 298 | 766, 299 | -186 300 | ], 301 | "size": [ 302 | 354.9950408935547, 303 | 178.50989379882816 304 | ], 305 | "flags": {}, 306 | "order": 2, 307 | "mode": 0, 308 | "title": "Note: Marigold", 309 | "properties": { 310 | "text": "" 311 | }, 312 | "widgets_values": [ 313 | "- denoise_steps: diffusion step count, more can increase quality, less is faster\n- n_repeat: how many times the prediction is done\n- regulazer_strenth/method, max_iter, tol:\nThese are settings for the ensembler, generally do not touch\n- n_repeat_batch_size: batches the n_repeats for speed, INCREASES MEMORY USE\n-use_fp16: can lower quality a bit, disabling DOUBLES MEMORY USE\n- scheduler: different schedulers have bit different outputs, experimental\n" 314 | ], 315 | "color": "#432", 316 | "bgcolor": "#653" 317 | }, 318 | { 319 | "id": 11, 320 | "type": "Note", 321 | "pos": [ 322 | 1182, 323 | -87 324 | ], 325 | "size": [ 326 | 305.49512596130376, 327 | 64.41022338867188 328 | ], 329 | "flags": {}, 330 | "order": 3, 331 | "mode": 0, 332 | "title": "Note: RemapDepth", 333 | "properties": { 334 | "text": "" 335 | }, 336 | "widgets_values": [ 337 | "You can use this to adjust the depth map range" 338 | ], 339 | "color": "#432", 340 | "bgcolor": "#653" 341 | }, 342 | { 343 | "id": 14, 344 | "type": "Note", 345 | "pos": [ 346 | 773, 347 | 541 348 | ], 349 | "size": [ 350 | 343.2861170959475, 351 | 74.30443054199225 352 | ], 353 | "flags": {}, 354 | "order": 4, 355 | "mode": 0, 356 | "title": "Note: Marigold", 357 | "properties": { 358 | "text": "" 359 | }, 360 | "widgets_values": [ 361 | "Model:\nModels are autodownloaded from Hugginface to ComfyUI/models/diffusers -folder\n" 362 | ], 363 | "color": "#432", 364 | "bgcolor": "#653" 365 | }, 366 | { 367 | "id": 1, 368 | "type": "MarigoldDepthEstimation", 369 | "pos": [ 370 | 783, 371 | 84 372 | ], 373 | "size": [ 374 | 356, 375 | 394 376 | ], 377 | "flags": {}, 378 | "order": 6, 379 | "mode": 0, 380 | "inputs": [ 381 | { 382 | "name": "image", 383 | "type": "IMAGE", 384 | "link": 1, 385 | "slot_index": 0 386 | } 387 | ], 388 | "outputs": [ 389 | { 390 | "name": "ensembled_image", 391 | "type": "IMAGE", 392 | "links": [ 393 | 8 394 | ], 395 | "shape": 3, 396 | "slot_index": 0 397 | } 398 | ], 399 | "properties": { 400 | "Node name for S&R": "MarigoldDepthEstimation" 401 | }, 402 | "widgets_values": [ 403 | 904467591362851, 404 | "fixed", 405 | 1, 406 | 4, 407 | 0.02, 408 | "median", 409 | 5, 410 | 0.001, 411 | true, 412 | true, 413 | 1, 414 | true, 415 | "LCMScheduler", 416 | true, 417 | "marigold-lcm-v1-0" 418 | ] 419 | } 420 | ], 421 | "links": [ 422 | [ 423 | 1, 424 | 2, 425 | 0, 426 | 1, 427 | 0, 428 | "IMAGE" 429 | ], 430 | [ 431 | 2, 432 | 3, 433 | 0, 434 | 2, 435 | 0, 436 | "IMAGE" 437 | ], 438 | [ 439 | 7, 440 | 6, 441 | 0, 442 | 8, 443 | 0, 444 | "IMAGE" 445 | ], 446 | [ 447 | 8, 448 | 1, 449 | 0, 450 | 6, 451 | 0, 452 | "IMAGE" 453 | ], 454 | [ 455 | 13, 456 | 9, 457 | 0, 458 | 5, 459 | 0, 460 | "IMAGE" 461 | ], 462 | [ 463 | 14, 464 | 5, 465 | 0, 466 | 7, 467 | 0, 468 | "IMAGE" 469 | ], 470 | [ 471 | 15, 472 | 6, 473 | 0, 474 | 9, 475 | 0, 476 | "IMAGE" 477 | ] 478 | ], 479 | "groups": [], 480 | "config": {}, 481 | "extra": {}, 482 | "version": 0.4 483 | } -------------------------------------------------------------------------------- /examples/marigold_example_01.json: -------------------------------------------------------------------------------- 1 | { 2 | "last_node_id": 15, 3 | "last_link_id": 15, 4 | "nodes": [ 5 | { 6 | "id": 2, 7 | "type": "ImageResize+", 8 | "pos": [ 9 | 427, 10 | 98 11 | ], 12 | "size": { 13 | "0": 315, 14 | "1": 218 15 | }, 16 | "flags": {}, 17 | "order": 5, 18 | "mode": 0, 19 | "inputs": [ 20 | { 21 | "name": "image", 22 | "type": "IMAGE", 23 | "link": 2, 24 | "slot_index": 0 25 | } 26 | ], 27 | "outputs": [ 28 | { 29 | "name": "IMAGE", 30 | "type": "IMAGE", 31 | "links": [ 32 | 1 33 | ], 34 | "shape": 3, 35 | "slot_index": 0 36 | }, 37 | { 38 | "name": "width", 39 | "type": "INT", 40 | "links": null, 41 | "shape": 3 42 | }, 43 | { 44 | "name": "height", 45 | "type": "INT", 46 | "links": null, 47 | "shape": 3 48 | } 49 | ], 50 | "properties": { 51 | "Node name for S&R": "ImageResize+" 52 | }, 53 | "widgets_values": [ 54 | 768, 55 | 768, 56 | "nearest", 57 | true, 58 | "always", 59 | 32 60 | ] 61 | }, 62 | { 63 | "id": 3, 64 | "type": "LoadImage", 65 | "pos": [ 66 | 102, 67 | 99 68 | ], 69 | "size": [ 70 | 297, 71 | 430 72 | ], 73 | "flags": {}, 74 | "order": 0, 75 | "mode": 0, 76 | "outputs": [ 77 | { 78 | "name": "IMAGE", 79 | "type": "IMAGE", 80 | "links": [ 81 | 2 82 | ], 83 | "shape": 3 84 | }, 85 | { 86 | "name": "MASK", 87 | "type": "MASK", 88 | "links": null, 89 | "shape": 3 90 | } 91 | ], 92 | "properties": { 93 | "Node name for S&R": "LoadImage" 94 | }, 95 | "widgets_values": [ 96 | "marigold_example_0.jpg", 97 | "image" 98 | ] 99 | }, 100 | { 101 | "id": 9, 102 | "type": "ImageInvert", 103 | "pos": [ 104 | 1186, 105 | 184 106 | ], 107 | "size": { 108 | "0": 210, 109 | "1": 26 110 | }, 111 | "flags": {}, 112 | "order": 9, 113 | "mode": 0, 114 | "inputs": [ 115 | { 116 | "name": "image", 117 | "type": "IMAGE", 118 | "link": 15 119 | } 120 | ], 121 | "outputs": [ 122 | { 123 | "name": "IMAGE", 124 | "type": "IMAGE", 125 | "links": [ 126 | 13 127 | ], 128 | "shape": 3, 129 | "slot_index": 0 130 | } 131 | ], 132 | "properties": { 133 | "Node name for S&R": "ImageInvert" 134 | } 135 | }, 136 | { 137 | "id": 5, 138 | "type": "ColorizeDepthmap", 139 | "pos": [ 140 | 1170, 141 | 266 142 | ], 143 | "size": { 144 | "0": 315, 145 | "1": 58 146 | }, 147 | "flags": {}, 148 | "order": 10, 149 | "mode": 0, 150 | "inputs": [ 151 | { 152 | "name": "image", 153 | "type": "IMAGE", 154 | "link": 13 155 | } 156 | ], 157 | "outputs": [ 158 | { 159 | "name": "image", 160 | "type": "IMAGE", 161 | "links": [ 162 | 14 163 | ], 164 | "shape": 3, 165 | "slot_index": 0 166 | } 167 | ], 168 | "properties": { 169 | "Node name for S&R": "ColorizeDepthmap" 170 | }, 171 | "widgets_values": [ 172 | "Spectral" 173 | ] 174 | }, 175 | { 176 | "id": 8, 177 | "type": "PreviewImage", 178 | "pos": [ 179 | 1547, 180 | 26 181 | ], 182 | "size": [ 183 | 381.5950622558594, 184 | 526.610237121582 185 | ], 186 | "flags": {}, 187 | "order": 8, 188 | "mode": 0, 189 | "inputs": [ 190 | { 191 | "name": "images", 192 | "type": "IMAGE", 193 | "link": 7, 194 | "slot_index": 0 195 | } 196 | ], 197 | "properties": { 198 | "Node name for S&R": "PreviewImage" 199 | } 200 | }, 201 | { 202 | "id": 7, 203 | "type": "PreviewImage", 204 | "pos": [ 205 | 1181, 206 | 377 207 | ], 208 | "size": [ 209 | 320.5950622558594, 210 | 468.61023712158203 211 | ], 212 | "flags": {}, 213 | "order": 11, 214 | "mode": 0, 215 | "inputs": [ 216 | { 217 | "name": "images", 218 | "type": "IMAGE", 219 | "link": 14, 220 | "slot_index": 0 221 | } 222 | ], 223 | "properties": { 224 | "Node name for S&R": "PreviewImage" 225 | } 226 | }, 227 | { 228 | "id": 6, 229 | "type": "RemapDepth", 230 | "pos": [ 231 | 1183, 232 | 23 233 | ], 234 | "size": { 235 | "0": 315, 236 | "1": 106 237 | }, 238 | "flags": {}, 239 | "order": 7, 240 | "mode": 0, 241 | "inputs": [ 242 | { 243 | "name": "image", 244 | "type": "IMAGE", 245 | "link": 8, 246 | "slot_index": 0 247 | } 248 | ], 249 | "outputs": [ 250 | { 251 | "name": "IMAGE", 252 | "type": "IMAGE", 253 | "links": [ 254 | 7, 255 | 15 256 | ], 257 | "shape": 3, 258 | "slot_index": 0 259 | } 260 | ], 261 | "properties": { 262 | "Node name for S&R": "RemapDepth" 263 | }, 264 | "widgets_values": [ 265 | 0, 266 | 1, 267 | true 268 | ] 269 | }, 270 | { 271 | "id": 12, 272 | "type": "Note", 273 | "pos": [ 274 | 426, 275 | -18 276 | ], 277 | "size": { 278 | "0": 305.4951171875, 279 | "1": 64.41022491455078 280 | }, 281 | "flags": {}, 282 | "order": 1, 283 | "mode": 0, 284 | "title": "Note: Image Size", 285 | "properties": { 286 | "text": "" 287 | }, 288 | "widgets_values": [ 289 | "Marigold works best close to 768p" 290 | ], 291 | "color": "#432", 292 | "bgcolor": "#653" 293 | }, 294 | { 295 | "id": 1, 296 | "type": "MarigoldDepthEstimation", 297 | "pos": [ 298 | 775, 299 | 89 300 | ], 301 | "size": [ 302 | 356, 303 | 394 304 | ], 305 | "flags": {}, 306 | "order": 6, 307 | "mode": 0, 308 | "inputs": [ 309 | { 310 | "name": "image", 311 | "type": "IMAGE", 312 | "link": 1, 313 | "slot_index": 0 314 | } 315 | ], 316 | "outputs": [ 317 | { 318 | "name": "ensembled_image", 319 | "type": "IMAGE", 320 | "links": [ 321 | 8 322 | ], 323 | "shape": 3, 324 | "slot_index": 0 325 | } 326 | ], 327 | "properties": { 328 | "Node name for S&R": "MarigoldDepthEstimation" 329 | }, 330 | "widgets_values": [ 331 | 904467591362851, 332 | "fixed", 333 | 10, 334 | 10, 335 | 0.02, 336 | "median", 337 | 5, 338 | 0.001, 339 | true, 340 | true, 341 | 1, 342 | true, 343 | "DDIMScheduler", 344 | true, 345 | "Marigold" 346 | ] 347 | }, 348 | { 349 | "id": 13, 350 | "type": "Note", 351 | "pos": [ 352 | 766, 353 | -186 354 | ], 355 | "size": [ 356 | 354.9950408935547, 357 | 178.50989379882816 358 | ], 359 | "flags": {}, 360 | "order": 2, 361 | "mode": 0, 362 | "title": "Note: Marigold", 363 | "properties": { 364 | "text": "" 365 | }, 366 | "widgets_values": [ 367 | "- denoise_steps: diffusion step count, more can increase quality, less is faster\n- n_repeat: how many times the prediction is done\n- regulazer_strenth/method, max_iter, tol:\nThese are settings for the ensembler, generally do not touch\n- n_repeat_batch_size: batches the n_repeats for speed, INCREASES MEMORY USE\n-use_fp16: can lower quality a bit, disabling DOUBLES MEMORY USE\n- scheduler: different schedulers have bit different outputs, experimental\n" 368 | ], 369 | "color": "#432", 370 | "bgcolor": "#653" 371 | }, 372 | { 373 | "id": 14, 374 | "type": "Note", 375 | "pos": [ 376 | 773, 377 | 541 378 | ], 379 | "size": [ 380 | 353.2261158336289, 381 | 105.75985843879096 382 | ], 383 | "flags": {}, 384 | "order": 3, 385 | "mode": 0, 386 | "title": "Note: Marigold", 387 | "properties": { 388 | "text": "" 389 | }, 390 | "widgets_values": [ 391 | "Model:\nModels are autodownloaded from Hugginface to ComfyUI/models/diffusers -folder\nTo use LCM model use just a single denoise_step and n_repeat 4" 392 | ], 393 | "color": "#432", 394 | "bgcolor": "#653" 395 | }, 396 | { 397 | "id": 11, 398 | "type": "Note", 399 | "pos": [ 400 | 1182, 401 | -87 402 | ], 403 | "size": [ 404 | 305.49512596130376, 405 | 64.41022338867188 406 | ], 407 | "flags": {}, 408 | "order": 4, 409 | "mode": 0, 410 | "title": "Note: RemapDepth", 411 | "properties": { 412 | "text": "" 413 | }, 414 | "widgets_values": [ 415 | "You can use this to adjust the depth map range" 416 | ], 417 | "color": "#432", 418 | "bgcolor": "#653" 419 | } 420 | ], 421 | "links": [ 422 | [ 423 | 1, 424 | 2, 425 | 0, 426 | 1, 427 | 0, 428 | "IMAGE" 429 | ], 430 | [ 431 | 2, 432 | 3, 433 | 0, 434 | 2, 435 | 0, 436 | "IMAGE" 437 | ], 438 | [ 439 | 7, 440 | 6, 441 | 0, 442 | 8, 443 | 0, 444 | "IMAGE" 445 | ], 446 | [ 447 | 8, 448 | 1, 449 | 0, 450 | 6, 451 | 0, 452 | "IMAGE" 453 | ], 454 | [ 455 | 13, 456 | 9, 457 | 0, 458 | 5, 459 | 0, 460 | "IMAGE" 461 | ], 462 | [ 463 | 14, 464 | 5, 465 | 0, 466 | 7, 467 | 0, 468 | "IMAGE" 469 | ], 470 | [ 471 | 15, 472 | 6, 473 | 0, 474 | 9, 475 | 0, 476 | "IMAGE" 477 | ] 478 | ], 479 | "groups": [], 480 | "config": {}, 481 | "extra": {}, 482 | "version": 0.4 483 | } -------------------------------------------------------------------------------- /gmflow/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kijai/ComfyUI-Marigold/2adfec75c430b0751a98a82453dc2dd8077bca85/gmflow/__init__.py -------------------------------------------------------------------------------- /gmflow/backbone.py: -------------------------------------------------------------------------------- 1 | import torch.nn as nn 2 | 3 | from .trident_conv import MultiScaleTridentConv 4 | 5 | 6 | class ResidualBlock(nn.Module): 7 | def __init__(self, in_planes, planes, norm_layer=nn.InstanceNorm2d, stride=1, dilation=1, 8 | ): 9 | super(ResidualBlock, self).__init__() 10 | 11 | self.conv1 = nn.Conv2d(in_planes, planes, kernel_size=3, 12 | dilation=dilation, padding=dilation, stride=stride, bias=False) 13 | self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, 14 | dilation=dilation, padding=dilation, bias=False) 15 | self.relu = nn.ReLU(inplace=True) 16 | 17 | self.norm1 = norm_layer(planes) 18 | self.norm2 = norm_layer(planes) 19 | if not stride == 1 or in_planes != planes: 20 | self.norm3 = norm_layer(planes) 21 | 22 | if stride == 1 and in_planes == planes: 23 | self.downsample = None 24 | else: 25 | self.downsample = nn.Sequential( 26 | nn.Conv2d(in_planes, planes, kernel_size=1, stride=stride), self.norm3) 27 | 28 | def forward(self, x): 29 | y = x 30 | y = self.relu(self.norm1(self.conv1(y))) 31 | y = self.relu(self.norm2(self.conv2(y))) 32 | 33 | if self.downsample is not None: 34 | x = self.downsample(x) 35 | 36 | return self.relu(x + y) 37 | 38 | 39 | class CNNEncoder(nn.Module): 40 | def __init__(self, output_dim=128, 41 | norm_layer=nn.InstanceNorm2d, 42 | num_output_scales=1, 43 | **kwargs, 44 | ): 45 | super(CNNEncoder, self).__init__() 46 | self.num_branch = num_output_scales 47 | 48 | feature_dims = [64, 96, 128] 49 | 50 | self.conv1 = nn.Conv2d(3, feature_dims[0], kernel_size=7, stride=2, padding=3, bias=False) # 1/2 51 | self.norm1 = norm_layer(feature_dims[0]) 52 | self.relu1 = nn.ReLU(inplace=True) 53 | 54 | self.in_planes = feature_dims[0] 55 | self.layer1 = self._make_layer(feature_dims[0], stride=1, norm_layer=norm_layer) # 1/2 56 | self.layer2 = self._make_layer(feature_dims[1], stride=2, norm_layer=norm_layer) # 1/4 57 | 58 | # highest resolution 1/4 or 1/8 59 | stride = 2 if num_output_scales == 1 else 1 60 | self.layer3 = self._make_layer(feature_dims[2], stride=stride, 61 | norm_layer=norm_layer, 62 | ) # 1/4 or 1/8 63 | 64 | self.conv2 = nn.Conv2d(feature_dims[2], output_dim, 1, 1, 0) 65 | 66 | if self.num_branch > 1: 67 | if self.num_branch == 4: 68 | strides = (1, 2, 4, 8) 69 | elif self.num_branch == 3: 70 | strides = (1, 2, 4) 71 | elif self.num_branch == 2: 72 | strides = (1, 2) 73 | else: 74 | raise ValueError 75 | 76 | self.trident_conv = MultiScaleTridentConv(output_dim, output_dim, 77 | kernel_size=3, 78 | strides=strides, 79 | paddings=1, 80 | num_branch=self.num_branch, 81 | ) 82 | 83 | for m in self.modules(): 84 | if isinstance(m, nn.Conv2d): 85 | nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu') 86 | elif isinstance(m, (nn.BatchNorm2d, nn.InstanceNorm2d, nn.GroupNorm)): 87 | if m.weight is not None: 88 | nn.init.constant_(m.weight, 1) 89 | if m.bias is not None: 90 | nn.init.constant_(m.bias, 0) 91 | 92 | def _make_layer(self, dim, stride=1, dilation=1, norm_layer=nn.InstanceNorm2d): 93 | layer1 = ResidualBlock(self.in_planes, dim, norm_layer=norm_layer, stride=stride, dilation=dilation) 94 | layer2 = ResidualBlock(dim, dim, norm_layer=norm_layer, stride=1, dilation=dilation) 95 | 96 | layers = (layer1, layer2) 97 | 98 | self.in_planes = dim 99 | return nn.Sequential(*layers) 100 | 101 | def forward(self, x): 102 | x = self.conv1(x) 103 | x = self.norm1(x) 104 | x = self.relu1(x) 105 | 106 | x = self.layer1(x) # 1/2 107 | x = self.layer2(x) # 1/4 108 | x = self.layer3(x) # 1/8 or 1/4 109 | 110 | x = self.conv2(x) 111 | 112 | if self.num_branch > 1: 113 | out = self.trident_conv([x] * self.num_branch) # high to low res 114 | else: 115 | out = [x] 116 | 117 | return out 118 | -------------------------------------------------------------------------------- /gmflow/geometry.py: -------------------------------------------------------------------------------- 1 | import torch 2 | import torch.nn.functional as F 3 | 4 | 5 | def coords_grid(b, h, w, homogeneous=False, device=None): 6 | y, x = torch.meshgrid(torch.arange(h), torch.arange(w)) # [H, W] 7 | 8 | stacks = [x, y] 9 | 10 | if homogeneous: 11 | ones = torch.ones_like(x) # [H, W] 12 | stacks.append(ones) 13 | 14 | grid = torch.stack(stacks, dim=0).float() # [2, H, W] or [3, H, W] 15 | 16 | grid = grid[None].repeat(b, 1, 1, 1) # [B, 2, H, W] or [B, 3, H, W] 17 | 18 | if device is not None: 19 | grid = grid.to(device) 20 | 21 | return grid 22 | 23 | 24 | def generate_window_grid(h_min, h_max, w_min, w_max, len_h, len_w, device=None): 25 | assert device is not None 26 | 27 | x, y = torch.meshgrid([torch.linspace(w_min, w_max, len_w, device=device), 28 | torch.linspace(h_min, h_max, len_h, device=device)], 29 | ) 30 | grid = torch.stack((x, y), -1).transpose(0, 1).float() # [H, W, 2] 31 | 32 | return grid 33 | 34 | 35 | def normalize_coords(coords, h, w): 36 | # coords: [B, H, W, 2] 37 | c = torch.Tensor([(w - 1) / 2., (h - 1) / 2.]).float().to(coords.device) 38 | return (coords - c) / c # [-1, 1] 39 | 40 | 41 | def bilinear_sample(img, sample_coords, mode='bilinear', padding_mode='zeros', return_mask=False): 42 | # img: [B, C, H, W] 43 | # sample_coords: [B, 2, H, W] in image scale 44 | if sample_coords.size(1) != 2: # [B, H, W, 2] 45 | sample_coords = sample_coords.permute(0, 3, 1, 2) 46 | 47 | b, _, h, w = sample_coords.shape 48 | 49 | # Normalize to [-1, 1] 50 | x_grid = 2 * sample_coords[:, 0] / (w - 1) - 1 51 | y_grid = 2 * sample_coords[:, 1] / (h - 1) - 1 52 | 53 | grid = torch.stack([x_grid, y_grid], dim=-1) # [B, H, W, 2] 54 | 55 | img = F.grid_sample(img, grid, mode=mode, padding_mode=padding_mode, align_corners=True) 56 | 57 | if return_mask: 58 | mask = (x_grid >= -1) & (y_grid >= -1) & (x_grid <= 1) & (y_grid <= 1) # [B, H, W] 59 | 60 | return img, mask 61 | 62 | return img 63 | 64 | 65 | def flow_warp(feature, flow, mask=False, padding_mode='zeros'): 66 | b, c, h, w = feature.size() 67 | assert flow.size(1) == 2 68 | 69 | grid = coords_grid(b, h, w).to(flow.device) + flow # [B, 2, H, W] 70 | 71 | return bilinear_sample(feature, grid, padding_mode=padding_mode, 72 | return_mask=mask) 73 | 74 | 75 | def forward_backward_consistency_check(fwd_flow, bwd_flow, 76 | alpha=0.01, 77 | beta=0.5 78 | ): 79 | # fwd_flow, bwd_flow: [B, 2, H, W] 80 | # alpha and beta values are following UnFlow (https://arxiv.org/abs/1711.07837) 81 | assert fwd_flow.dim() == 4 and bwd_flow.dim() == 4 82 | assert fwd_flow.size(1) == 2 and bwd_flow.size(1) == 2 83 | flow_mag = torch.norm(fwd_flow, dim=1) + torch.norm(bwd_flow, dim=1) # [B, H, W] 84 | 85 | warped_bwd_flow = flow_warp(bwd_flow, fwd_flow) # [B, 2, H, W] 86 | warped_fwd_flow = flow_warp(fwd_flow, bwd_flow) # [B, 2, H, W] 87 | 88 | diff_fwd = torch.norm(fwd_flow + warped_bwd_flow, dim=1) # [B, H, W] 89 | diff_bwd = torch.norm(bwd_flow + warped_fwd_flow, dim=1) 90 | 91 | threshold = alpha * flow_mag + beta 92 | 93 | fwd_occ = (diff_fwd > threshold).float() # [B, H, W] 94 | bwd_occ = (diff_bwd > threshold).float() 95 | 96 | return fwd_occ, bwd_occ 97 | -------------------------------------------------------------------------------- /gmflow/gmflow.py: -------------------------------------------------------------------------------- 1 | import torch 2 | import torch.nn as nn 3 | import torch.nn.functional as F 4 | 5 | from .backbone import CNNEncoder 6 | from .transformer import FeatureTransformer, FeatureFlowAttention 7 | from .matching import global_correlation_softmax, local_correlation_softmax 8 | from .geometry import flow_warp 9 | from .utils import normalize_img, feature_add_position 10 | 11 | 12 | class GMFlow(nn.Module): 13 | def __init__(self, 14 | num_scales=1, 15 | upsample_factor=8, 16 | feature_channels=128, 17 | attention_type='swin', 18 | num_transformer_layers=6, 19 | ffn_dim_expansion=4, 20 | num_head=1, 21 | **kwargs, 22 | ): 23 | super(GMFlow, self).__init__() 24 | 25 | self.num_scales = num_scales 26 | self.feature_channels = feature_channels 27 | self.upsample_factor = upsample_factor 28 | self.attention_type = attention_type 29 | self.num_transformer_layers = num_transformer_layers 30 | 31 | # CNN backbone 32 | self.backbone = CNNEncoder(output_dim=feature_channels, num_output_scales=num_scales) 33 | 34 | # Transformer 35 | self.transformer = FeatureTransformer(num_layers=num_transformer_layers, 36 | d_model=feature_channels, 37 | nhead=num_head, 38 | attention_type=attention_type, 39 | ffn_dim_expansion=ffn_dim_expansion, 40 | ) 41 | 42 | # flow propagation with self-attn 43 | self.feature_flow_attn = FeatureFlowAttention(in_channels=feature_channels) 44 | 45 | # convex upsampling: concat feature0 and flow as input 46 | self.upsampler = nn.Sequential(nn.Conv2d(2 + feature_channels, 256, 3, 1, 1), 47 | nn.ReLU(inplace=True), 48 | nn.Conv2d(256, upsample_factor ** 2 * 9, 1, 1, 0)) 49 | 50 | def extract_feature(self, img0, img1): 51 | concat = torch.cat((img0, img1), dim=0) # [2B, C, H, W] 52 | features = self.backbone(concat) # list of [2B, C, H, W], resolution from high to low 53 | 54 | # reverse: resolution from low to high 55 | features = features[::-1] 56 | 57 | feature0, feature1 = [], [] 58 | 59 | for i in range(len(features)): 60 | feature = features[i] 61 | chunks = torch.chunk(feature, 2, 0) # tuple 62 | feature0.append(chunks[0]) 63 | feature1.append(chunks[1]) 64 | 65 | return feature0, feature1 66 | 67 | def upsample_flow(self, flow, feature, bilinear=False, upsample_factor=8, 68 | ): 69 | if bilinear: 70 | up_flow = F.interpolate(flow, scale_factor=upsample_factor, 71 | mode='bilinear', align_corners=True) * upsample_factor 72 | 73 | else: 74 | # convex upsampling 75 | concat = torch.cat((flow, feature), dim=1) 76 | 77 | mask = self.upsampler(concat) 78 | b, flow_channel, h, w = flow.shape 79 | mask = mask.view(b, 1, 9, self.upsample_factor, self.upsample_factor, h, w) # [B, 1, 9, K, K, H, W] 80 | mask = torch.softmax(mask, dim=2) 81 | 82 | up_flow = F.unfold(self.upsample_factor * flow, [3, 3], padding=1) 83 | up_flow = up_flow.view(b, flow_channel, 9, 1, 1, h, w) # [B, 2, 9, 1, 1, H, W] 84 | 85 | up_flow = torch.sum(mask * up_flow, dim=2) # [B, 2, K, K, H, W] 86 | up_flow = up_flow.permute(0, 1, 4, 2, 5, 3) # [B, 2, K, H, K, W] 87 | up_flow = up_flow.reshape(b, flow_channel, self.upsample_factor * h, 88 | self.upsample_factor * w) # [B, 2, K*H, K*W] 89 | 90 | return up_flow 91 | 92 | def forward(self, img0, img1, 93 | attn_splits_list=None, 94 | corr_radius_list=None, 95 | prop_radius_list=None, 96 | pred_bidir_flow=False, 97 | **kwargs, 98 | ): 99 | 100 | results_dict = {} 101 | flow_preds = [] 102 | 103 | img0, img1 = normalize_img(img0, img1) # [B, 3, H, W] 104 | 105 | # resolution low to high 106 | feature0_list, feature1_list = self.extract_feature(img0, img1) # list of features 107 | 108 | flow = None 109 | 110 | assert len(attn_splits_list) == len(corr_radius_list) == len(prop_radius_list) == self.num_scales 111 | 112 | for scale_idx in range(self.num_scales): 113 | feature0, feature1 = feature0_list[scale_idx], feature1_list[scale_idx] 114 | 115 | if pred_bidir_flow and scale_idx > 0: 116 | # predicting bidirectional flow with refinement 117 | feature0, feature1 = torch.cat((feature0, feature1), dim=0), torch.cat((feature1, feature0), dim=0) 118 | 119 | upsample_factor = self.upsample_factor * (2 ** (self.num_scales - 1 - scale_idx)) 120 | 121 | if scale_idx > 0: 122 | flow = F.interpolate(flow, scale_factor=2, mode='bilinear', align_corners=True) * 2 123 | 124 | if flow is not None: 125 | flow = flow.detach() 126 | feature1 = flow_warp(feature1, flow) # [B, C, H, W] 127 | 128 | attn_splits = attn_splits_list[scale_idx] 129 | corr_radius = corr_radius_list[scale_idx] 130 | prop_radius = prop_radius_list[scale_idx] 131 | 132 | # add position to features 133 | feature0, feature1 = feature_add_position(feature0, feature1, attn_splits, self.feature_channels) 134 | 135 | # Transformer 136 | feature0, feature1 = self.transformer(feature0, feature1, attn_num_splits=attn_splits) 137 | 138 | # correlation and softmax 139 | if corr_radius == -1: # global matching 140 | flow_pred = global_correlation_softmax(feature0, feature1, pred_bidir_flow)[0] 141 | else: # local matching 142 | flow_pred = local_correlation_softmax(feature0, feature1, corr_radius)[0] 143 | 144 | # flow or residual flow 145 | flow = flow + flow_pred if flow is not None else flow_pred 146 | 147 | # upsample to the original resolution for supervison 148 | if self.training: # only need to upsample intermediate flow predictions at training time 149 | flow_bilinear = self.upsample_flow(flow, None, bilinear=True, upsample_factor=upsample_factor) 150 | flow_preds.append(flow_bilinear) 151 | 152 | # flow propagation with self-attn 153 | if pred_bidir_flow and scale_idx == 0: 154 | feature0 = torch.cat((feature0, feature1), dim=0) # [2*B, C, H, W] for propagation 155 | flow = self.feature_flow_attn(feature0, flow.detach(), 156 | local_window_attn=prop_radius > 0, 157 | local_window_radius=prop_radius) 158 | 159 | # bilinear upsampling at training time except the last one 160 | if self.training and scale_idx < self.num_scales - 1: 161 | flow_up = self.upsample_flow(flow, feature0, bilinear=True, upsample_factor=upsample_factor) 162 | flow_preds.append(flow_up) 163 | 164 | if scale_idx == self.num_scales - 1: 165 | flow_up = self.upsample_flow(flow, feature0) 166 | flow_preds.append(flow_up) 167 | 168 | results_dict.update({'flow_preds': flow_preds}) 169 | 170 | return results_dict 171 | -------------------------------------------------------------------------------- /gmflow/gmflow_things-e9887eda.pth: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kijai/ComfyUI-Marigold/2adfec75c430b0751a98a82453dc2dd8077bca85/gmflow/gmflow_things-e9887eda.pth -------------------------------------------------------------------------------- /gmflow/matching.py: -------------------------------------------------------------------------------- 1 | import torch 2 | import torch.nn.functional as F 3 | 4 | from .geometry import coords_grid, generate_window_grid, normalize_coords 5 | 6 | 7 | def global_correlation_softmax(feature0, feature1, 8 | pred_bidir_flow=False, 9 | ): 10 | # global correlation 11 | b, c, h, w = feature0.shape 12 | feature0 = feature0.view(b, c, -1).permute(0, 2, 1) # [B, H*W, C] 13 | feature1 = feature1.view(b, c, -1) # [B, C, H*W] 14 | 15 | correlation = torch.matmul(feature0, feature1).view(b, h, w, h, w) / (c ** 0.5) # [B, H, W, H, W] 16 | 17 | # flow from softmax 18 | init_grid = coords_grid(b, h, w).to(correlation.device) # [B, 2, H, W] 19 | grid = init_grid.view(b, 2, -1).permute(0, 2, 1) # [B, H*W, 2] 20 | 21 | correlation = correlation.view(b, h * w, h * w) # [B, H*W, H*W] 22 | 23 | if pred_bidir_flow: 24 | correlation = torch.cat((correlation, correlation.permute(0, 2, 1)), dim=0) # [2*B, H*W, H*W] 25 | init_grid = init_grid.repeat(2, 1, 1, 1) # [2*B, 2, H, W] 26 | grid = grid.repeat(2, 1, 1) # [2*B, H*W, 2] 27 | b = b * 2 28 | 29 | prob = F.softmax(correlation, dim=-1) # [B, H*W, H*W] 30 | 31 | correspondence = torch.matmul(prob, grid).view(b, h, w, 2).permute(0, 3, 1, 2) # [B, 2, H, W] 32 | 33 | # when predicting bidirectional flow, flow is the concatenation of forward flow and backward flow 34 | flow = correspondence - init_grid 35 | 36 | return flow, prob 37 | 38 | 39 | def local_correlation_softmax(feature0, feature1, local_radius, 40 | padding_mode='zeros', 41 | ): 42 | b, c, h, w = feature0.size() 43 | coords_init = coords_grid(b, h, w).to(feature0.device) # [B, 2, H, W] 44 | coords = coords_init.view(b, 2, -1).permute(0, 2, 1) # [B, H*W, 2] 45 | 46 | local_h = 2 * local_radius + 1 47 | local_w = 2 * local_radius + 1 48 | 49 | window_grid = generate_window_grid(-local_radius, local_radius, 50 | -local_radius, local_radius, 51 | local_h, local_w, device=feature0.device) # [2R+1, 2R+1, 2] 52 | window_grid = window_grid.reshape(-1, 2).repeat(b, 1, 1, 1) # [B, 1, (2R+1)^2, 2] 53 | sample_coords = coords.unsqueeze(-2) + window_grid # [B, H*W, (2R+1)^2, 2] 54 | 55 | sample_coords_softmax = sample_coords 56 | 57 | # exclude coords that are out of image space 58 | valid_x = (sample_coords[:, :, :, 0] >= 0) & (sample_coords[:, :, :, 0] < w) # [B, H*W, (2R+1)^2] 59 | valid_y = (sample_coords[:, :, :, 1] >= 0) & (sample_coords[:, :, :, 1] < h) # [B, H*W, (2R+1)^2] 60 | 61 | valid = valid_x & valid_y # [B, H*W, (2R+1)^2], used to mask out invalid values when softmax 62 | 63 | # normalize coordinates to [-1, 1] 64 | sample_coords_norm = normalize_coords(sample_coords, h, w) # [-1, 1] 65 | window_feature = F.grid_sample(feature1, sample_coords_norm, 66 | padding_mode=padding_mode, align_corners=True 67 | ).permute(0, 2, 1, 3) # [B, H*W, C, (2R+1)^2] 68 | feature0_view = feature0.permute(0, 2, 3, 1).view(b, h * w, 1, c) # [B, H*W, 1, C] 69 | 70 | corr = torch.matmul(feature0_view, window_feature).view(b, h * w, -1) / (c ** 0.5) # [B, H*W, (2R+1)^2] 71 | 72 | # mask invalid locations 73 | corr[~valid] = -1e9 74 | 75 | prob = F.softmax(corr, -1) # [B, H*W, (2R+1)^2] 76 | 77 | correspondence = torch.matmul(prob.unsqueeze(-2), sample_coords_softmax).squeeze(-2).view( 78 | b, h, w, 2).permute(0, 3, 1, 2) # [B, 2, H, W] 79 | 80 | flow = correspondence - coords_init 81 | match_prob = prob 82 | 83 | return flow, match_prob 84 | -------------------------------------------------------------------------------- /gmflow/position.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved 2 | # https://github.com/facebookresearch/detr/blob/main/models/position_encoding.py 3 | 4 | import torch 5 | import torch.nn as nn 6 | import math 7 | 8 | 9 | class PositionEmbeddingSine(nn.Module): 10 | """ 11 | This is a more standard version of the position embedding, very similar to the one 12 | used by the Attention is all you need paper, generalized to work on images. 13 | """ 14 | 15 | def __init__(self, num_pos_feats=64, temperature=10000, normalize=True, scale=None): 16 | super().__init__() 17 | self.num_pos_feats = num_pos_feats 18 | self.temperature = temperature 19 | self.normalize = normalize 20 | if scale is not None and normalize is False: 21 | raise ValueError("normalize should be True if scale is passed") 22 | if scale is None: 23 | scale = 2 * math.pi 24 | self.scale = scale 25 | 26 | def forward(self, x): 27 | # x = tensor_list.tensors # [B, C, H, W] 28 | # mask = tensor_list.mask # [B, H, W], input with padding, valid as 0 29 | b, c, h, w = x.size() 30 | mask = torch.ones((b, h, w), device=x.device) # [B, H, W] 31 | y_embed = mask.cumsum(1, dtype=torch.float32) 32 | x_embed = mask.cumsum(2, dtype=torch.float32) 33 | if self.normalize: 34 | eps = 1e-6 35 | y_embed = y_embed / (y_embed[:, -1:, :] + eps) * self.scale 36 | x_embed = x_embed / (x_embed[:, :, -1:] + eps) * self.scale 37 | 38 | dim_t = torch.arange(self.num_pos_feats, dtype=torch.float32, device=x.device) 39 | dim_t = self.temperature ** (2 * (dim_t // 2) / self.num_pos_feats) 40 | 41 | pos_x = x_embed[:, :, :, None] / dim_t 42 | pos_y = y_embed[:, :, :, None] / dim_t 43 | pos_x = torch.stack((pos_x[:, :, :, 0::2].sin(), pos_x[:, :, :, 1::2].cos()), dim=4).flatten(3) 44 | pos_y = torch.stack((pos_y[:, :, :, 0::2].sin(), pos_y[:, :, :, 1::2].cos()), dim=4).flatten(3) 45 | pos = torch.cat((pos_y, pos_x), dim=3).permute(0, 3, 1, 2) 46 | return pos 47 | -------------------------------------------------------------------------------- /gmflow/transformer.py: -------------------------------------------------------------------------------- 1 | import torch 2 | import torch.nn as nn 3 | import torch.nn.functional as F 4 | 5 | from .utils import split_feature, merge_splits 6 | 7 | 8 | def single_head_full_attention(q, k, v): 9 | # q, k, v: [B, L, C] 10 | assert q.dim() == k.dim() == v.dim() == 3 11 | 12 | scores = torch.matmul(q, k.permute(0, 2, 1)) / (q.size(2) ** .5) # [B, L, L] 13 | attn = torch.softmax(scores, dim=2) # [B, L, L] 14 | out = torch.matmul(attn, v) # [B, L, C] 15 | 16 | return out 17 | 18 | 19 | def generate_shift_window_attn_mask(input_resolution, window_size_h, window_size_w, 20 | shift_size_h, shift_size_w, device=torch.device('cuda')): 21 | # Ref: https://github.com/microsoft/Swin-Transformer/blob/main/models/swin_transformer.py 22 | # calculate attention mask for SW-MSA 23 | h, w = input_resolution 24 | img_mask = torch.zeros((1, h, w, 1)).to(device) # 1 H W 1 25 | h_slices = (slice(0, -window_size_h), 26 | slice(-window_size_h, -shift_size_h), 27 | slice(-shift_size_h, None)) 28 | w_slices = (slice(0, -window_size_w), 29 | slice(-window_size_w, -shift_size_w), 30 | slice(-shift_size_w, None)) 31 | cnt = 0 32 | for h in h_slices: 33 | for w in w_slices: 34 | img_mask[:, h, w, :] = cnt 35 | cnt += 1 36 | 37 | mask_windows = split_feature(img_mask, num_splits=input_resolution[-1] // window_size_w, channel_last=True) 38 | 39 | mask_windows = mask_windows.view(-1, window_size_h * window_size_w) 40 | attn_mask = mask_windows.unsqueeze(1) - mask_windows.unsqueeze(2) 41 | attn_mask = attn_mask.masked_fill(attn_mask != 0, float(-100.0)).masked_fill(attn_mask == 0, float(0.0)) 42 | 43 | return attn_mask 44 | 45 | 46 | def single_head_split_window_attention(q, k, v, 47 | num_splits=1, 48 | with_shift=False, 49 | h=None, 50 | w=None, 51 | attn_mask=None, 52 | ): 53 | # Ref: https://github.com/microsoft/Swin-Transformer/blob/main/models/swin_transformer.py 54 | # q, k, v: [B, L, C] 55 | assert q.dim() == k.dim() == v.dim() == 3 56 | 57 | assert h is not None and w is not None 58 | assert q.size(1) == h * w 59 | 60 | b, _, c = q.size() 61 | 62 | b_new = b * num_splits * num_splits 63 | 64 | window_size_h = h // num_splits 65 | window_size_w = w // num_splits 66 | 67 | q = q.view(b, h, w, c) # [B, H, W, C] 68 | k = k.view(b, h, w, c) 69 | v = v.view(b, h, w, c) 70 | 71 | scale_factor = c ** 0.5 72 | 73 | if with_shift: 74 | assert attn_mask is not None # compute once 75 | shift_size_h = window_size_h // 2 76 | shift_size_w = window_size_w // 2 77 | 78 | q = torch.roll(q, shifts=(-shift_size_h, -shift_size_w), dims=(1, 2)) 79 | k = torch.roll(k, shifts=(-shift_size_h, -shift_size_w), dims=(1, 2)) 80 | v = torch.roll(v, shifts=(-shift_size_h, -shift_size_w), dims=(1, 2)) 81 | 82 | q = split_feature(q, num_splits=num_splits, channel_last=True) # [B*K*K, H/K, W/K, C] 83 | k = split_feature(k, num_splits=num_splits, channel_last=True) 84 | v = split_feature(v, num_splits=num_splits, channel_last=True) 85 | 86 | scores = torch.matmul(q.view(b_new, -1, c), k.view(b_new, -1, c).permute(0, 2, 1) 87 | ) / scale_factor # [B*K*K, H/K*W/K, H/K*W/K] 88 | 89 | if with_shift: 90 | scores += attn_mask.repeat(b, 1, 1) 91 | 92 | attn = torch.softmax(scores, dim=-1) 93 | 94 | out = torch.matmul(attn, v.view(b_new, -1, c)) # [B*K*K, H/K*W/K, C] 95 | 96 | out = merge_splits(out.view(b_new, h // num_splits, w // num_splits, c), 97 | num_splits=num_splits, channel_last=True) # [B, H, W, C] 98 | 99 | # shift back 100 | if with_shift: 101 | out = torch.roll(out, shifts=(shift_size_h, shift_size_w), dims=(1, 2)) 102 | 103 | out = out.view(b, -1, c) 104 | 105 | return out 106 | 107 | 108 | class TransformerLayer(nn.Module): 109 | def __init__(self, 110 | d_model=256, 111 | nhead=1, 112 | attention_type='swin', 113 | no_ffn=False, 114 | ffn_dim_expansion=4, 115 | with_shift=False, 116 | **kwargs, 117 | ): 118 | super(TransformerLayer, self).__init__() 119 | 120 | self.dim = d_model 121 | self.nhead = nhead 122 | self.attention_type = attention_type 123 | self.no_ffn = no_ffn 124 | 125 | self.with_shift = with_shift 126 | 127 | # multi-head attention 128 | self.q_proj = nn.Linear(d_model, d_model, bias=False) 129 | self.k_proj = nn.Linear(d_model, d_model, bias=False) 130 | self.v_proj = nn.Linear(d_model, d_model, bias=False) 131 | 132 | self.merge = nn.Linear(d_model, d_model, bias=False) 133 | 134 | self.norm1 = nn.LayerNorm(d_model) 135 | 136 | # no ffn after self-attn, with ffn after cross-attn 137 | if not self.no_ffn: 138 | in_channels = d_model * 2 139 | self.mlp = nn.Sequential( 140 | nn.Linear(in_channels, in_channels * ffn_dim_expansion, bias=False), 141 | nn.GELU(), 142 | nn.Linear(in_channels * ffn_dim_expansion, d_model, bias=False), 143 | ) 144 | 145 | self.norm2 = nn.LayerNorm(d_model) 146 | 147 | def forward(self, source, target, 148 | height=None, 149 | width=None, 150 | shifted_window_attn_mask=None, 151 | attn_num_splits=None, 152 | **kwargs, 153 | ): 154 | # source, target: [B, L, C] 155 | query, key, value = source, target, target 156 | 157 | # single-head attention 158 | query = self.q_proj(query) # [B, L, C] 159 | key = self.k_proj(key) # [B, L, C] 160 | value = self.v_proj(value) # [B, L, C] 161 | 162 | if self.attention_type == 'swin' and attn_num_splits > 1: 163 | if self.nhead > 1: 164 | # we observe that multihead attention slows down the speed and increases the memory consumption 165 | # without bringing obvious performance gains and thus the implementation is removed 166 | raise NotImplementedError 167 | else: 168 | message = single_head_split_window_attention(query, key, value, 169 | num_splits=attn_num_splits, 170 | with_shift=self.with_shift, 171 | h=height, 172 | w=width, 173 | attn_mask=shifted_window_attn_mask, 174 | ) 175 | else: 176 | message = single_head_full_attention(query, key, value) # [B, L, C] 177 | 178 | message = self.merge(message) # [B, L, C] 179 | message = self.norm1(message) 180 | 181 | if not self.no_ffn: 182 | message = self.mlp(torch.cat([source, message], dim=-1)) 183 | message = self.norm2(message) 184 | 185 | return source + message 186 | 187 | 188 | class TransformerBlock(nn.Module): 189 | """self attention + cross attention + FFN""" 190 | 191 | def __init__(self, 192 | d_model=256, 193 | nhead=1, 194 | attention_type='swin', 195 | ffn_dim_expansion=4, 196 | with_shift=False, 197 | **kwargs, 198 | ): 199 | super(TransformerBlock, self).__init__() 200 | 201 | self.self_attn = TransformerLayer(d_model=d_model, 202 | nhead=nhead, 203 | attention_type=attention_type, 204 | no_ffn=True, 205 | ffn_dim_expansion=ffn_dim_expansion, 206 | with_shift=with_shift, 207 | ) 208 | 209 | self.cross_attn_ffn = TransformerLayer(d_model=d_model, 210 | nhead=nhead, 211 | attention_type=attention_type, 212 | ffn_dim_expansion=ffn_dim_expansion, 213 | with_shift=with_shift, 214 | ) 215 | 216 | def forward(self, source, target, 217 | height=None, 218 | width=None, 219 | shifted_window_attn_mask=None, 220 | attn_num_splits=None, 221 | **kwargs, 222 | ): 223 | # source, target: [B, L, C] 224 | 225 | # self attention 226 | source = self.self_attn(source, source, 227 | height=height, 228 | width=width, 229 | shifted_window_attn_mask=shifted_window_attn_mask, 230 | attn_num_splits=attn_num_splits, 231 | ) 232 | 233 | # cross attention and ffn 234 | source = self.cross_attn_ffn(source, target, 235 | height=height, 236 | width=width, 237 | shifted_window_attn_mask=shifted_window_attn_mask, 238 | attn_num_splits=attn_num_splits, 239 | ) 240 | 241 | return source 242 | 243 | 244 | class FeatureTransformer(nn.Module): 245 | def __init__(self, 246 | num_layers=6, 247 | d_model=128, 248 | nhead=1, 249 | attention_type='swin', 250 | ffn_dim_expansion=4, 251 | **kwargs, 252 | ): 253 | super(FeatureTransformer, self).__init__() 254 | 255 | self.attention_type = attention_type 256 | 257 | self.d_model = d_model 258 | self.nhead = nhead 259 | 260 | self.layers = nn.ModuleList([ 261 | TransformerBlock(d_model=d_model, 262 | nhead=nhead, 263 | attention_type=attention_type, 264 | ffn_dim_expansion=ffn_dim_expansion, 265 | with_shift=True if attention_type == 'swin' and i % 2 == 1 else False, 266 | ) 267 | for i in range(num_layers)]) 268 | 269 | for p in self.parameters(): 270 | if p.dim() > 1: 271 | nn.init.xavier_uniform_(p) 272 | 273 | def forward(self, feature0, feature1, 274 | attn_num_splits=None, 275 | **kwargs, 276 | ): 277 | 278 | b, c, h, w = feature0.shape 279 | assert self.d_model == c 280 | 281 | feature0 = feature0.flatten(-2).permute(0, 2, 1) # [B, H*W, C] 282 | feature1 = feature1.flatten(-2).permute(0, 2, 1) # [B, H*W, C] 283 | 284 | if self.attention_type == 'swin' and attn_num_splits > 1: 285 | # global and refine use different number of splits 286 | window_size_h = h // attn_num_splits 287 | window_size_w = w // attn_num_splits 288 | 289 | # compute attn mask once 290 | shifted_window_attn_mask = generate_shift_window_attn_mask( 291 | input_resolution=(h, w), 292 | window_size_h=window_size_h, 293 | window_size_w=window_size_w, 294 | shift_size_h=window_size_h // 2, 295 | shift_size_w=window_size_w // 2, 296 | device=feature0.device, 297 | ) # [K*K, H/K*W/K, H/K*W/K] 298 | else: 299 | shifted_window_attn_mask = None 300 | 301 | # concat feature0 and feature1 in batch dimension to compute in parallel 302 | concat0 = torch.cat((feature0, feature1), dim=0) # [2B, H*W, C] 303 | concat1 = torch.cat((feature1, feature0), dim=0) # [2B, H*W, C] 304 | 305 | for layer in self.layers: 306 | concat0 = layer(concat0, concat1, 307 | height=h, 308 | width=w, 309 | shifted_window_attn_mask=shifted_window_attn_mask, 310 | attn_num_splits=attn_num_splits, 311 | ) 312 | 313 | # update feature1 314 | concat1 = torch.cat(concat0.chunk(chunks=2, dim=0)[::-1], dim=0) 315 | 316 | feature0, feature1 = concat0.chunk(chunks=2, dim=0) # [B, H*W, C] 317 | 318 | # reshape back 319 | feature0 = feature0.view(b, h, w, c).permute(0, 3, 1, 2).contiguous() # [B, C, H, W] 320 | feature1 = feature1.view(b, h, w, c).permute(0, 3, 1, 2).contiguous() # [B, C, H, W] 321 | 322 | return feature0, feature1 323 | 324 | 325 | class FeatureFlowAttention(nn.Module): 326 | """ 327 | flow propagation with self-attention on feature 328 | query: feature0, key: feature0, value: flow 329 | """ 330 | 331 | def __init__(self, in_channels, 332 | **kwargs, 333 | ): 334 | super(FeatureFlowAttention, self).__init__() 335 | 336 | self.q_proj = nn.Linear(in_channels, in_channels) 337 | self.k_proj = nn.Linear(in_channels, in_channels) 338 | 339 | for p in self.parameters(): 340 | if p.dim() > 1: 341 | nn.init.xavier_uniform_(p) 342 | 343 | def forward(self, feature0, flow, 344 | local_window_attn=False, 345 | local_window_radius=1, 346 | **kwargs, 347 | ): 348 | # q, k: feature [B, C, H, W], v: flow [B, 2, H, W] 349 | if local_window_attn: 350 | return self.forward_local_window_attn(feature0, flow, 351 | local_window_radius=local_window_radius) 352 | 353 | b, c, h, w = feature0.size() 354 | 355 | query = feature0.view(b, c, h * w).permute(0, 2, 1) # [B, H*W, C] 356 | 357 | # a note: the ``correct'' implementation should be: 358 | # ``query = self.q_proj(query), key = self.k_proj(query)'' 359 | # this problem is observed while cleaning up the code 360 | # however, this doesn't affect the performance since the projection is a linear operation, 361 | # thus the two projection matrices for key can be merged 362 | # so I just leave it as is in order to not re-train all models :) 363 | query = self.q_proj(query) # [B, H*W, C] 364 | key = self.k_proj(query) # [B, H*W, C] 365 | 366 | value = flow.view(b, flow.size(1), h * w).permute(0, 2, 1) # [B, H*W, 2] 367 | 368 | scores = torch.matmul(query, key.permute(0, 2, 1)) / (c ** 0.5) # [B, H*W, H*W] 369 | prob = torch.softmax(scores, dim=-1) 370 | 371 | out = torch.matmul(prob, value) # [B, H*W, 2] 372 | out = out.view(b, h, w, value.size(-1)).permute(0, 3, 1, 2) # [B, 2, H, W] 373 | 374 | return out 375 | 376 | def forward_local_window_attn(self, feature0, flow, 377 | local_window_radius=1, 378 | ): 379 | assert flow.size(1) == 2 380 | assert local_window_radius > 0 381 | 382 | b, c, h, w = feature0.size() 383 | 384 | feature0_reshape = self.q_proj(feature0.view(b, c, -1).permute(0, 2, 1) 385 | ).reshape(b * h * w, 1, c) # [B*H*W, 1, C] 386 | 387 | kernel_size = 2 * local_window_radius + 1 388 | 389 | feature0_proj = self.k_proj(feature0.view(b, c, -1).permute(0, 2, 1)).permute(0, 2, 1).reshape(b, c, h, w) 390 | 391 | feature0_window = F.unfold(feature0_proj, kernel_size=kernel_size, 392 | padding=local_window_radius) # [B, C*(2R+1)^2), H*W] 393 | 394 | feature0_window = feature0_window.view(b, c, kernel_size ** 2, h, w).permute( 395 | 0, 3, 4, 1, 2).reshape(b * h * w, c, kernel_size ** 2) # [B*H*W, C, (2R+1)^2] 396 | 397 | flow_window = F.unfold(flow, kernel_size=kernel_size, 398 | padding=local_window_radius) # [B, 2*(2R+1)^2), H*W] 399 | 400 | flow_window = flow_window.view(b, 2, kernel_size ** 2, h, w).permute( 401 | 0, 3, 4, 2, 1).reshape(b * h * w, kernel_size ** 2, 2) # [B*H*W, (2R+1)^2, 2] 402 | 403 | scores = torch.matmul(feature0_reshape, feature0_window) / (c ** 0.5) # [B*H*W, 1, (2R+1)^2] 404 | 405 | prob = torch.softmax(scores, dim=-1) 406 | 407 | out = torch.matmul(prob, flow_window).view(b, h, w, 2).permute(0, 3, 1, 2).contiguous() # [B, 2, H, W] 408 | 409 | return out 410 | -------------------------------------------------------------------------------- /gmflow/trident_conv.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. 2 | # https://github.com/facebookresearch/detectron2/blob/main/projects/TridentNet/tridentnet/trident_conv.py 3 | 4 | import torch 5 | from torch import nn 6 | from torch.nn import functional as F 7 | from torch.nn.modules.utils import _pair 8 | 9 | 10 | class MultiScaleTridentConv(nn.Module): 11 | def __init__( 12 | self, 13 | in_channels, 14 | out_channels, 15 | kernel_size, 16 | stride=1, 17 | strides=1, 18 | paddings=0, 19 | dilations=1, 20 | dilation=1, 21 | groups=1, 22 | num_branch=1, 23 | test_branch_idx=-1, 24 | bias=False, 25 | norm=None, 26 | activation=None, 27 | ): 28 | super(MultiScaleTridentConv, self).__init__() 29 | self.in_channels = in_channels 30 | self.out_channels = out_channels 31 | self.kernel_size = _pair(kernel_size) 32 | self.num_branch = num_branch 33 | self.stride = _pair(stride) 34 | self.groups = groups 35 | self.with_bias = bias 36 | self.dilation = dilation 37 | if isinstance(paddings, int): 38 | paddings = [paddings] * self.num_branch 39 | if isinstance(dilations, int): 40 | dilations = [dilations] * self.num_branch 41 | if isinstance(strides, int): 42 | strides = [strides] * self.num_branch 43 | self.paddings = [_pair(padding) for padding in paddings] 44 | self.dilations = [_pair(dilation) for dilation in dilations] 45 | self.strides = [_pair(stride) for stride in strides] 46 | self.test_branch_idx = test_branch_idx 47 | self.norm = norm 48 | self.activation = activation 49 | 50 | assert len({self.num_branch, len(self.paddings), len(self.strides)}) == 1 51 | 52 | self.weight = nn.Parameter( 53 | torch.Tensor(out_channels, in_channels // groups, *self.kernel_size) 54 | ) 55 | if bias: 56 | self.bias = nn.Parameter(torch.Tensor(out_channels)) 57 | else: 58 | self.bias = None 59 | 60 | nn.init.kaiming_uniform_(self.weight, nonlinearity="relu") 61 | if self.bias is not None: 62 | nn.init.constant_(self.bias, 0) 63 | 64 | def forward(self, inputs): 65 | num_branch = self.num_branch if self.training or self.test_branch_idx == -1 else 1 66 | assert len(inputs) == num_branch 67 | 68 | if self.training or self.test_branch_idx == -1: 69 | outputs = [ 70 | F.conv2d(input, self.weight, self.bias, stride, padding, self.dilation, self.groups) 71 | for input, stride, padding in zip(inputs, self.strides, self.paddings) 72 | ] 73 | else: 74 | outputs = [ 75 | F.conv2d( 76 | inputs[0], 77 | self.weight, 78 | self.bias, 79 | self.strides[self.test_branch_idx] if self.test_branch_idx == -1 else self.strides[-1], 80 | self.paddings[self.test_branch_idx] if self.test_branch_idx == -1 else self.paddings[-1], 81 | self.dilation, 82 | self.groups, 83 | ) 84 | ] 85 | 86 | if self.norm is not None: 87 | outputs = [self.norm(x) for x in outputs] 88 | if self.activation is not None: 89 | outputs = [self.activation(x) for x in outputs] 90 | return outputs 91 | -------------------------------------------------------------------------------- /gmflow/utils.py: -------------------------------------------------------------------------------- 1 | import torch 2 | from .position import PositionEmbeddingSine 3 | 4 | 5 | class InputPadder: 6 | """ Pads images such that dimensions are divisible by 8 """ 7 | 8 | def __init__(self, dims, mode='sintel', padding_factor=8): 9 | self.ht, self.wd = dims[-2:] 10 | pad_ht = (((self.ht // padding_factor) + 1) * padding_factor - self.ht) % padding_factor 11 | pad_wd = (((self.wd // padding_factor) + 1) * padding_factor - self.wd) % padding_factor 12 | if mode == 'sintel': 13 | self._pad = [pad_wd // 2, pad_wd - pad_wd // 2, pad_ht // 2, pad_ht - pad_ht // 2] 14 | else: 15 | self._pad = [pad_wd // 2, pad_wd - pad_wd // 2, 0, pad_ht] 16 | 17 | def pad(self, *inputs): 18 | return [F.pad(x, self._pad, mode='replicate') for x in inputs] 19 | 20 | def unpad(self, x): 21 | ht, wd = x.shape[-2:] 22 | c = [self._pad[2], ht - self._pad[3], self._pad[0], wd - self._pad[1]] 23 | return x[..., c[0]:c[1], c[2]:c[3]] 24 | 25 | def split_feature(feature, 26 | num_splits=2, 27 | channel_last=False, 28 | ): 29 | if channel_last: # [B, H, W, C] 30 | b, h, w, c = feature.size() 31 | assert h % num_splits == 0 and w % num_splits == 0 32 | 33 | b_new = b * num_splits * num_splits 34 | h_new = h // num_splits 35 | w_new = w // num_splits 36 | 37 | feature = feature.view(b, num_splits, h // num_splits, num_splits, w // num_splits, c 38 | ).permute(0, 1, 3, 2, 4, 5).reshape(b_new, h_new, w_new, c) # [B*K*K, H/K, W/K, C] 39 | else: # [B, C, H, W] 40 | b, c, h, w = feature.size() 41 | assert h % num_splits == 0 and w % num_splits == 0 42 | 43 | b_new = b * num_splits * num_splits 44 | h_new = h // num_splits 45 | w_new = w // num_splits 46 | 47 | feature = feature.view(b, c, num_splits, h // num_splits, num_splits, w // num_splits 48 | ).permute(0, 2, 4, 1, 3, 5).reshape(b_new, c, h_new, w_new) # [B*K*K, C, H/K, W/K] 49 | 50 | return feature 51 | 52 | 53 | def merge_splits(splits, 54 | num_splits=2, 55 | channel_last=False, 56 | ): 57 | if channel_last: # [B*K*K, H/K, W/K, C] 58 | b, h, w, c = splits.size() 59 | new_b = b // num_splits // num_splits 60 | 61 | splits = splits.view(new_b, num_splits, num_splits, h, w, c) 62 | merge = splits.permute(0, 1, 3, 2, 4, 5).contiguous().view( 63 | new_b, num_splits * h, num_splits * w, c) # [B, H, W, C] 64 | else: # [B*K*K, C, H/K, W/K] 65 | b, c, h, w = splits.size() 66 | new_b = b // num_splits // num_splits 67 | 68 | splits = splits.view(new_b, num_splits, num_splits, c, h, w) 69 | merge = splits.permute(0, 3, 1, 4, 2, 5).contiguous().view( 70 | new_b, c, num_splits * h, num_splits * w) # [B, C, H, W] 71 | 72 | return merge 73 | 74 | 75 | def normalize_img(img0, img1): 76 | # loaded images are in [0, 255] 77 | # normalize by ImageNet mean and std 78 | mean = torch.tensor([0.485, 0.456, 0.406]).view(1, 3, 1, 1).to(img1.device) 79 | std = torch.tensor([0.229, 0.224, 0.225]).view(1, 3, 1, 1).to(img1.device) 80 | img0 = (img0 / 255. - mean) / std 81 | img1 = (img1 / 255. - mean) / std 82 | 83 | return img0, img1 84 | 85 | 86 | def feature_add_position(feature0, feature1, attn_splits, feature_channels): 87 | pos_enc = PositionEmbeddingSine(num_pos_feats=feature_channels // 2) 88 | 89 | if attn_splits > 1: # add position in splited window 90 | feature0_splits = split_feature(feature0, num_splits=attn_splits) 91 | feature1_splits = split_feature(feature1, num_splits=attn_splits) 92 | 93 | position = pos_enc(feature0_splits) 94 | 95 | feature0_splits = feature0_splits + position 96 | feature1_splits = feature1_splits + position 97 | 98 | feature0 = merge_splits(feature0_splits, num_splits=attn_splits) 99 | feature1 = merge_splits(feature1_splits, num_splits=attn_splits) 100 | else: 101 | position = pos_enc(feature0) 102 | 103 | feature0 = feature0 + position 104 | feature1 = feature1 + position 105 | 106 | return feature0, feature1 107 | -------------------------------------------------------------------------------- /marigold/model/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kijai/ComfyUI-Marigold/2adfec75c430b0751a98a82453dc2dd8077bca85/marigold/model/__init__.py -------------------------------------------------------------------------------- /marigold/model/marigold_pipeline.py: -------------------------------------------------------------------------------- 1 | # Author: Bingxin Ke 2 | # Last modified: 2023-12-11 3 | 4 | import logging 5 | from typing import Dict 6 | 7 | import numpy as np 8 | import torch 9 | from diffusers import ( 10 | DDIMScheduler, 11 | DDPMScheduler, 12 | PNDMScheduler, 13 | DEISMultistepScheduler, 14 | SchedulerMixin, 15 | UNet2DConditionModel, 16 | LCMScheduler 17 | ) 18 | from torch import nn 19 | from torch.nn import Conv2d 20 | from torch.nn.parameter import Parameter 21 | from tqdm.auto import tqdm 22 | from transformers import CLIPTextModel, CLIPTokenizer 23 | 24 | from .rgb_encoder import RGBEncoder 25 | from .stacked_depth_AE import StackedDepthAE 26 | 27 | 28 | class MarigoldPipeline(nn.Module): 29 | """ 30 | Marigold monocular depth estimator. 31 | """ 32 | 33 | def __init__( 34 | self, 35 | unet_pretrained_path: Dict, # {path: xxx, subfolder: xxx} 36 | rgb_encoder_pretrained_path: Dict, 37 | depht_ae_pretrained_path: Dict, 38 | noise_scheduler_pretrained_path: Dict, 39 | tokenizer_pretrained_path: Dict, 40 | text_encoder_pretrained_path: Dict, 41 | empty_text_embed=None, 42 | trainable_unet=False, 43 | rgb_latent_scale_factor=0.18215, 44 | depth_latent_scale_factor=0.18215, 45 | noise_scheduler_type=None, 46 | enable_gradient_checkpointing=False, 47 | enable_xformers=True, 48 | ) -> None: 49 | super().__init__() 50 | 51 | self.rgb_latent_scale_factor = rgb_latent_scale_factor 52 | self.depth_latent_scale_factor = depth_latent_scale_factor 53 | self.device = "cpu" 54 | 55 | # ******* Initialize modules ******* 56 | # Trainable modules 57 | self.trainable_module_dic: Dict[str, nn.Module] = {} 58 | self.trainable_unet = trainable_unet 59 | 60 | # Denoising UNet 61 | self.unet: UNet2DConditionModel = UNet2DConditionModel.from_pretrained( 62 | unet_pretrained_path["path"], subfolder=unet_pretrained_path["subfolder"] 63 | ) 64 | logging.info(f"pretrained UNet loaded from: {unet_pretrained_path}") 65 | if 8 != self.unet.config["in_channels"]: 66 | self._replace_unet_conv_in() 67 | logging.warning("Unet conv_in layer is replaced") 68 | if enable_xformers: 69 | self.unet.enable_xformers_memory_efficient_attention() 70 | else: 71 | self.unet.disable_xformers_memory_efficient_attention() 72 | 73 | # Image encoder 74 | self.rgb_encoder = RGBEncoder( 75 | pretrained_path=rgb_encoder_pretrained_path["path"], 76 | subfolder=rgb_encoder_pretrained_path["subfolder"], 77 | ) 78 | logging.info( 79 | f"pretrained RGBEncoder loaded from: {rgb_encoder_pretrained_path}" 80 | ) 81 | self.rgb_encoder.requires_grad_(False) 82 | 83 | # Depth encoder-decoder 84 | self.depth_ae = StackedDepthAE( 85 | pretrained_path=depht_ae_pretrained_path["path"], 86 | subfolder=depht_ae_pretrained_path["subfolder"], 87 | ) 88 | logging.info( 89 | f"pretrained Depth Autoencoder loaded from: {rgb_encoder_pretrained_path}" 90 | ) 91 | 92 | # Trainability 93 | # unet 94 | if self.trainable_unet: 95 | self.unet.requires_grad_(True) 96 | self.trainable_module_dic["unet"] = self.unet 97 | logging.debug(f"UNet is set to trainable") 98 | else: 99 | self.unet.requires_grad_(False) 100 | logging.debug(f"UNet is set to frozen") 101 | 102 | # Gradient checkpointing 103 | if enable_gradient_checkpointing: 104 | self.unet.enable_gradient_checkpointing() 105 | self.depth_ae.vae.enable_gradient_checkpointing() 106 | 107 | # Noise scheduler 108 | if "DDPMScheduler" == noise_scheduler_type: 109 | self.noise_scheduler: SchedulerMixin = DDPMScheduler.from_pretrained( 110 | noise_scheduler_pretrained_path["path"], 111 | subfolder=noise_scheduler_pretrained_path["subfolder"], 112 | ) 113 | elif "DDIMScheduler" == noise_scheduler_type: 114 | self.noise_scheduler: SchedulerMixin = DDIMScheduler.from_pretrained( 115 | noise_scheduler_pretrained_path["path"], 116 | subfolder=noise_scheduler_pretrained_path["subfolder"], 117 | ) 118 | elif "PNDMScheduler" == noise_scheduler_type: 119 | self.noise_scheduler: SchedulerMixin = PNDMScheduler.from_pretrained( 120 | noise_scheduler_pretrained_path["path"], 121 | subfolder=noise_scheduler_pretrained_path["subfolder"], 122 | ) 123 | elif "DEISMultistepScheduler" == noise_scheduler_type: 124 | self.noise_scheduler: SchedulerMixin = DEISMultistepScheduler.from_pretrained( 125 | noise_scheduler_pretrained_path["path"], 126 | subfolder=noise_scheduler_pretrained_path["subfolder"], 127 | ) 128 | elif "LCMScheduler" == noise_scheduler_type: 129 | self.noise_scheduler: SchedulerMixin = LCMScheduler.from_pretrained( 130 | noise_scheduler_pretrained_path["path"], 131 | subfolder=noise_scheduler_pretrained_path["subfolder"], 132 | ) 133 | else: 134 | raise NotImplementedError 135 | 136 | # Text embed for empty prompt (always in CPU) 137 | if empty_text_embed is None: 138 | tokenizer: CLIPTokenizer = CLIPTokenizer.from_pretrained( 139 | tokenizer_pretrained_path["path"], 140 | subfolder=tokenizer_pretrained_path["subfolder"], 141 | ) 142 | text_encoder: CLIPTextModel = CLIPTextModel.from_pretrained( 143 | text_encoder_pretrained_path["path"], 144 | subfolder=text_encoder_pretrained_path["subfolder"], 145 | ) 146 | with torch.no_grad(): 147 | self.empty_text_embed = self._encode_text( 148 | "", tokenizer, text_encoder 149 | ).detach()#.to(dtype=precision) # [1, 2, 1024] 150 | else: 151 | self.empty_text_embed = empty_text_embed 152 | 153 | def from_pretrained(pretrained_path, **kwargs): 154 | return __class__( 155 | unet_pretrained_path={"path": pretrained_path, "subfolder": "unet"}, 156 | rgb_encoder_pretrained_path={"path": pretrained_path, "subfolder": "vae"}, 157 | depht_ae_pretrained_path={"path": pretrained_path, "subfolder": "vae"}, 158 | noise_scheduler_pretrained_path={ 159 | "path": pretrained_path, 160 | "subfolder": "scheduler", 161 | }, 162 | tokenizer_pretrained_path={ 163 | "path": pretrained_path, 164 | "subfolder": "tokenizer", 165 | }, 166 | text_encoder_pretrained_path={ 167 | "path": pretrained_path, 168 | "subfolder": "text_encoder", 169 | }, 170 | **kwargs, 171 | ) 172 | 173 | def _replace_unet_conv_in(self): 174 | # Replace the first layer to accept 8 in_channels. Only applied when loading pretrained SD U-Net 175 | _weight = self.unet.conv_in.weight.clone() # [320, 4, 3, 3] 176 | _bias = self.unet.conv_in.bias.clone() # [320] 177 | _weight = _weight.repeat((1, 2, 1, 1)) # Keep selected channel(s) 178 | # half the activation magnitude 179 | _weight *= 0.5 180 | _bias *= 0.5 181 | # new conv_in channel 182 | _n_convin_out_channel = self.unet.conv_in.out_channels 183 | _new_conv_in = Conv2d( 184 | 8, _n_convin_out_channel, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1) 185 | ) 186 | _new_conv_in.weight = Parameter(_weight) 187 | _new_conv_in.bias = Parameter(_bias) 188 | self.unet.conv_in = _new_conv_in 189 | # replace config 190 | self.unet.config["in_channels"] = 8 191 | return 192 | 193 | def to(self, device): 194 | self.rgb_encoder.to(device) 195 | self.depth_ae.to(device) 196 | self.unet.to(device) 197 | self.empty_text_embed = self.empty_text_embed.to(device) 198 | self.device = device 199 | return self 200 | 201 | def forward( 202 | self, 203 | rgb_in, 204 | num_inference_steps: int = 50, 205 | num_output_inter_results: int = 0, 206 | show_pbar=False, 207 | init_depth_latent=None, 208 | return_depth_latent=False, 209 | noise_ratio: float = 0.2, 210 | ): 211 | device = rgb_in.device 212 | precision = self.unet.dtype 213 | # Set timesteps 214 | self.noise_scheduler.set_timesteps(num_inference_steps, device=device) 215 | timesteps = self.noise_scheduler.timesteps # [T] 216 | 217 | # Encode image 218 | rgb_latent = self.encode_rgb(rgb_in) 219 | 220 | # Initial depth map (noise) 221 | if init_depth_latent is not None: 222 | 223 | depth_latent = self.encode_rgb(init_depth_latent) 224 | depth_latent_noise = torch.randn(rgb_latent.shape, device=device, dtype=precision) 225 | depth_latent = depth_latent* (1- noise_ratio) + depth_latent_noise * noise_ratio 226 | 227 | depth_latent = torch.clip(depth_latent, -1.0, 1.0) 228 | assert depth_latent.min() >= -1.0 and depth_latent.max() <= 1.0 229 | 230 | else: 231 | depth_latent = torch.randn(rgb_latent.shape, device=device, dtype=precision) # [B, 4, h, w] 232 | 233 | # Expand text embeding for batch 234 | batch_empty_text_embed = self.empty_text_embed.repeat( 235 | (rgb_latent.shape[0], 1, 1) 236 | ).to(device=device, dtype=precision) # [B, 2, 1024] 237 | 238 | # Export intermediate denoising steps 239 | if num_output_inter_results > 0: 240 | depth_latent_ls = [] 241 | inter_steps = [] 242 | _idx = ( 243 | -1 244 | * ( 245 | np.arange(0, num_output_inter_results) 246 | * num_inference_steps 247 | / num_output_inter_results 248 | ) 249 | .round() 250 | .astype(int) 251 | - 1 252 | ) 253 | steps_to_output = timesteps[_idx] 254 | 255 | # Denoising loop 256 | if show_pbar: 257 | iterable = tqdm(enumerate(timesteps), total=len(timesteps), leave=False, desc="denoising") 258 | else: 259 | iterable = enumerate(timesteps) 260 | for i, t in iterable: 261 | unet_input = torch.cat( 262 | [rgb_latent, depth_latent], dim=1 263 | ) # this order is important 264 | unet_input = unet_input.to(dtype=precision) 265 | # predict the noise residual 266 | noise_pred = self.unet( 267 | unet_input, t, encoder_hidden_states=batch_empty_text_embed 268 | ).sample # [B, 4, h, w] 269 | # compute the previous noisy sample x_t -> x_t-1 270 | depth_latent = self.noise_scheduler.step( 271 | noise_pred, t, depth_latent 272 | ).prev_sample.to(dtype=precision) 273 | 274 | 275 | if num_output_inter_results > 0 and t in steps_to_output: 276 | depth_latent_ls.append(depth_latent.detach().clone()) 277 | #depth_latent_ls = depth_latent_ls.to(dtype=precision) 278 | inter_steps.append(t - 1) 279 | 280 | # Decode depth latent 281 | if num_output_inter_results > 0: 282 | assert 0 in inter_steps 283 | depth = [self.decode_depth(lat) for lat in depth_latent_ls] 284 | if return_depth_latent: 285 | return depth, inter_steps, depth_latent_ls 286 | else: 287 | return depth, inter_steps 288 | else: 289 | depth = self.decode_depth(depth_latent) 290 | if return_depth_latent: 291 | return depth, depth_latent 292 | else: 293 | return depth 294 | 295 | def encode_rgb(self, rgb_in): 296 | rgb_latent = self.rgb_encoder(rgb_in) # [B, 4, h, w] 297 | rgb_latent = rgb_latent * self.rgb_latent_scale_factor 298 | return rgb_latent 299 | 300 | def encode_depth(self, depth_in): 301 | depth_latent = self.depth_ae.encode(depth_in) 302 | depth_latent = depth_latent * self.depth_latent_scale_factor 303 | return depth_latent 304 | 305 | def decode_depth(self, depth_latent): 306 | #depth_latent = depth_latent.to(dtype=torch.float16) 307 | depth_latent = depth_latent / self.depth_latent_scale_factor 308 | depth = self.depth_ae.decode(depth_latent) # [B, 1, H, W] 309 | return depth 310 | 311 | @staticmethod 312 | def _encode_text(prompt, tokenizer, text_encoder): 313 | text_inputs = tokenizer( 314 | prompt, 315 | padding="do_not_pad", 316 | max_length=tokenizer.model_max_length, 317 | truncation=True, 318 | return_tensors="pt", 319 | ) 320 | text_input_ids = text_inputs.input_ids.to(text_encoder.device) 321 | text_embed = text_encoder(text_input_ids)[0] 322 | return text_embed 323 | -------------------------------------------------------------------------------- /marigold/model/rgb_encoder.py: -------------------------------------------------------------------------------- 1 | # Author: Bingxin Ke 2 | # Last modified: 2023-12-05 3 | 4 | import torch 5 | import torch.nn as nn 6 | import logging 7 | from diffusers import AutoencoderKL 8 | 9 | 10 | class RGBEncoder(nn.Module): 11 | """ 12 | The encoder of pretrained Stable Diffusion VAE 13 | """ 14 | 15 | def __init__(self, pretrained_path, subfolder=None) -> None: 16 | super().__init__() 17 | 18 | vae: AutoencoderKL = AutoencoderKL.from_pretrained(pretrained_path, subfolder=subfolder) 19 | logging.info(f"pretrained AutoencoderKL loaded from: {pretrained_path}") 20 | 21 | self.rgb_encoder = nn.Sequential( 22 | vae.encoder, 23 | vae.quant_conv, 24 | ) 25 | 26 | def to(self, *args, **kwargs): 27 | self.rgb_encoder.to(*args, **kwargs) 28 | 29 | def forward(self, rgb_in): 30 | return self.encode(rgb_in) 31 | 32 | def encode(self, rgb_in): 33 | moments = self.rgb_encoder(rgb_in) # [B, 8, H/8, W/8] 34 | mean, logvar = torch.chunk(moments, 2, dim=1) 35 | rgb_latent = mean 36 | return rgb_latent -------------------------------------------------------------------------------- /marigold/model/stacked_depth_AE.py: -------------------------------------------------------------------------------- 1 | # Author: Bingxin Ke 2 | # Last modified: 2023-12-05 3 | 4 | import torch 5 | import torch.nn as nn 6 | import logging 7 | from diffusers import AutoencoderKL 8 | 9 | 10 | class StackedDepthAE(nn.Module): 11 | """ 12 | Tailored pretrained image VAE for depth map. 13 | Encode: Depth images are repeated into 3 channels. 14 | Decode: The average of 3 chennels are taken as output. 15 | """ 16 | 17 | def __init__(self, pretrained_path, subfolder=None) -> None: 18 | super().__init__() 19 | 20 | self.vae: AutoencoderKL = AutoencoderKL.from_pretrained(pretrained_path, subfolder=subfolder) 21 | logging.info(f"pretrained AutoencoderKL loaded from: {pretrained_path}") 22 | 23 | def forward(self, depth_in): 24 | depth_latent = self.encode(depth_in) 25 | depth_out = self.decode(depth_latent) 26 | return depth_out 27 | 28 | def to(self, *args, **kwargs): 29 | self.vae.to(*args, **kwargs) 30 | 31 | @staticmethod 32 | def _stack_depth_images(depth_in): 33 | if 4 == len(depth_in.shape): 34 | stacked = depth_in.repeat(1, 3, 1, 1) 35 | elif 3 == len(depth_in.shape): 36 | stacked = depth_in.unsqueeze(1) 37 | stacked = depth_in.repeat(1, 3, 1, 1) 38 | return stacked 39 | 40 | def encode(self, depth_in): 41 | stacked = self._stack_depth_images(depth_in) 42 | h = self.vae.encoder(stacked) 43 | moments = self.vae.quant_conv(h) 44 | mean, logvar = torch.chunk(moments, 2, dim=1) 45 | depth_latent = mean 46 | return depth_latent 47 | 48 | def decode(self, depth_latent): 49 | z = self.vae.post_quant_conv(depth_latent) 50 | stacked = self.vae.decoder(z) 51 | depth_mean = stacked.mean(dim=1, keepdim=True) 52 | return depth_mean -------------------------------------------------------------------------------- /marigold/util/batchsize.py: -------------------------------------------------------------------------------- 1 | # Author: Bingxin Ke 2 | # Last modified: 2023-12-11 3 | 4 | import torch 5 | import math 6 | 7 | 8 | # Search table for suggested max. inference batch size 9 | bs_search_table = [ 10 | # tested on A100-PCIE-80GB 11 | {"res": 768, "total_vram": 79, "bs": 35}, 12 | {"res": 1024, "total_vram": 79, "bs": 20}, 13 | # tested on A100-PCIE-40GB 14 | {"res": 768, "total_vram": 39, "bs": 15}, 15 | {"res": 1024, "total_vram": 39, "bs": 8}, 16 | # tested on RTX3090, RTX4090 17 | {"res": 512, "total_vram": 23, "bs": 20}, 18 | {"res": 768, "total_vram": 23, "bs": 7}, 19 | {"res": 1024, "total_vram": 23, "bs": 3}, 20 | # tested on GTX1080Ti 21 | {"res": 512, "total_vram": 10, "bs": 5}, 22 | {"res": 768, "total_vram": 10, "bs": 2}, 23 | ] 24 | 25 | 26 | 27 | def find_batch_size(n_repeat, input_res): 28 | total_vram = torch.cuda.mem_get_info()[1] / 1024.0**3 29 | 30 | for settings in sorted(bs_search_table, key=lambda k: (k['res'], -k['total_vram'])): 31 | if input_res <= settings['res'] and total_vram >= settings['total_vram']: 32 | bs = settings['bs'] 33 | if bs > n_repeat: 34 | bs = n_repeat 35 | elif bs > math.ceil(n_repeat / 2) and bs < n_repeat: 36 | bs = math.ceil(n_repeat / 2) 37 | return bs 38 | return 1 -------------------------------------------------------------------------------- /marigold/util/ensemble.py: -------------------------------------------------------------------------------- 1 | # Test align depth images 2 | # Author: Bingxin Ke 3 | # Last modified: 2023-12-11 4 | 5 | import numpy as np 6 | import torch 7 | 8 | from scipy.optimize import minimize 9 | 10 | def inter_distances(tensors): 11 | """ 12 | To calculate the distance between each two depth maps. 13 | """ 14 | distances = [] 15 | for i, j in torch.combinations(torch.arange(tensors.shape[0])): 16 | arr1 = tensors[i:i+1] 17 | arr2 = tensors[j:j+1] 18 | distances.append(arr1 - arr2) 19 | dist = torch.concatenate(distances, dim=0) 20 | return dist 21 | 22 | 23 | def ensemble_depths(input_images, regularizer_strength=0.02, max_iter=2, tol=1e-3, reduction='median', max_res=None, disp=False, device='cuda'): 24 | """ 25 | To ensemble multiple affine-invariant depth images (up to scale and shift), 26 | by aligning estimating the scale and shift 27 | """ 28 | device = input_images.device 29 | original_input = input_images.clone() 30 | n_img = input_images.shape[0] 31 | ori_shape = input_images.shape 32 | 33 | if max_res is not None: 34 | scale_factor = torch.min(max_res / torch.tensor(ori_shape[-2:])) 35 | if scale_factor < 1: 36 | downscaler = torch.nn.Upsample(scale_factor=scale_factor, mode='nearest') 37 | input_images = downscaler(torch.from_numpy(input_images)).numpy() 38 | 39 | # init guess 40 | _min = np.min(input_images.reshape((n_img, -1)).cpu().numpy(), axis=1) 41 | _max = np.max(input_images.reshape((n_img, -1)).cpu().numpy(), axis=1) 42 | s_init = 1.0 / (_max - _min).reshape((-1, 1, 1)) 43 | t_init = (-1 * s_init.flatten() * _min.flatten()).reshape((-1, 1, 1)) 44 | x = np.concatenate([s_init, t_init]).reshape(-1) 45 | 46 | input_images = input_images.to(device) 47 | 48 | # objective function 49 | def closure(x): 50 | x = x.astype(np.float32) 51 | l = len(x) 52 | s = x[:int(l/2)] 53 | t = x[int(l/2):] 54 | s = torch.from_numpy(s).to(device) 55 | t = torch.from_numpy(t).to(device) 56 | 57 | transformed_arrays = input_images * s.view((-1, 1, 1)) + t.view((-1, 1, 1)) 58 | dists = inter_distances(transformed_arrays) 59 | sqrt_dist = torch.sqrt(torch.mean(dists**2)) 60 | 61 | if 'mean' == reduction: 62 | pred = torch.mean(transformed_arrays, dim=0) 63 | elif 'median' == reduction: 64 | pred = torch.median(transformed_arrays, dim=0).values 65 | else: 66 | raise ValueError 67 | 68 | near_err = torch.sqrt((0 - torch.min(pred))**2) 69 | far_err = torch.sqrt((1 - torch.max(pred))**2) 70 | 71 | err = sqrt_dist + (near_err + far_err) * regularizer_strength 72 | err = err.detach().cpu().numpy() 73 | return err 74 | 75 | res = minimize(closure, x, method='BFGS', tol=tol, options={'maxiter': max_iter, 'disp': disp}) 76 | x = res.x 77 | l = len(x) 78 | s = x[:int(l/2)] 79 | t = x[int(l/2):] 80 | 81 | # Prediction 82 | try: 83 | s = torch.from_numpy(s).to(device) 84 | t = torch.from_numpy(t).to(device) 85 | except: 86 | s = torch.from_numpy(s.astype(np.float32)).to(device) 87 | t = torch.from_numpy(t.astype(np.float32)).to(device) 88 | 89 | transformed_arrays = original_input * s.view(-1, 1, 1) + t.view(-1, 1, 1) 90 | if 'mean' == reduction: 91 | aligned_images = torch.mean(transformed_arrays, dim=0) 92 | std = torch.std(transformed_arrays, dim=0) 93 | uncertainty = std 94 | elif 'median' == reduction: 95 | aligned_images = torch.median(transformed_arrays, dim=0).values 96 | # MAD (median absolute deviation) as uncertainty indicator 97 | abs_dev = torch.abs(transformed_arrays - aligned_images) 98 | mad = torch.median(abs_dev, dim=0).values 99 | uncertainty = mad 100 | else: 101 | raise ValueError 102 | 103 | # Scale and shift to [0, 1] 104 | _min = torch.min(aligned_images) 105 | _max = torch.max(aligned_images) 106 | aligned_images = (aligned_images - _min) / (_max - _min) 107 | uncertainty /= (_max - _min) 108 | return aligned_images, uncertainty 109 | -------------------------------------------------------------------------------- /marigold/util/flow_estimation.py: -------------------------------------------------------------------------------- 1 | import torch 2 | from ...gmflow.gmflow import GMFlow 3 | import numpy as np 4 | import os 5 | from ...gmflow.utils import InputPadder 6 | import torch.nn.functional as F 7 | import cv2 8 | 9 | class FlowEstimator: 10 | def __init__(self, model_path, device): 11 | self.model = self.load_model(model_path, device) 12 | self.device = device 13 | 14 | def load_model(self, model_path, device): 15 | loc = 'cuda:{}'.format(0) 16 | checkpoint = torch.load(model_path, map_location=device) 17 | weights = checkpoint['model'] if 'model' in checkpoint else checkpoint 18 | model = GMFlow().to(device) 19 | model_without_ddp = model 20 | model_without_ddp.load_state_dict(weights) 21 | model_without_ddp.eval() 22 | 23 | return model_without_ddp 24 | 25 | def estimate_flow(self, img0, img1): 26 | # Obtain original image size 27 | og_size = (img0.shape[1], img0.shape[2]) 28 | 29 | # Run the model to get flow predictions 30 | results_dict = self.model(img0, img1, [2], [-1], [-1]) 31 | flow_preds = results_dict['flow_preds'] 32 | 33 | # Resize the flow prediction to the original image size 34 | flow_pred = F.interpolate(flow_preds[0], size=og_size, mode='bilinear', align_corners=True) 35 | 36 | return flow_pred 37 | 38 | def warp_with_flow(flow, curImg): 39 | 40 | curImg = curImg.unsqueeze(0).unsqueeze(0) 41 | device = curImg.device 42 | dtype = curImg.dtype 43 | N, C, H, W = flow.shape 44 | flow = -flow 45 | 46 | # Convert to numpy, add the grid, then convert back to torch tensor 47 | flow_np = flow.cpu().numpy() 48 | flow_np[:, 0, :, :] += np.arange(W) # Add x-coordinates to the flow's x component 49 | flow_np[:, 1, :, :] += np.arange(H)[:, np.newaxis] # Add y-coordinates to the flow's y component 50 | flow = torch.from_numpy(flow_np).to(flow.device) 51 | 52 | # Now permute and normalize the flow to get a grid in the range [-1, 1] 53 | flow = flow.permute(0, 2, 3, 1).to(dtype).to(device) 54 | flow[:, :, :, 0] = (flow[:, :, :, 0] / (W - 1) * 2) - 1 55 | flow[:, :, :, 1] = (flow[:, :, :, 1] / (H - 1) * 2) - 1 56 | 57 | # Warp the image by the flow 58 | nextImg = F.grid_sample(curImg, flow, mode='bilinear', padding_mode='zeros', align_corners=True) 59 | 60 | # Remove batch and channel dimensions before returning 61 | nextImg = nextImg.squeeze(0).squeeze(0) 62 | 63 | return nextImg 64 | -------------------------------------------------------------------------------- /marigold/util/image_util.py: -------------------------------------------------------------------------------- 1 | 2 | import matplotlib 3 | import numpy as np 4 | import torch 5 | from PIL import Image 6 | 7 | def colorize_depth_maps(depth_map, min_depth, max_depth, cmap='Spectral', valid_mask=None): 8 | """ 9 | Colorize depth maps. 10 | """ 11 | assert len(depth_map.shape) >= 2, "Invalid dimension" 12 | 13 | if isinstance(depth_map, torch.Tensor): 14 | depth = depth_map.detach().clone().squeeze().numpy() 15 | elif isinstance(depth_map, np.ndarray): 16 | depth = depth_map.copy().squeeze() 17 | # reshape to [ (B,) H, W ] 18 | if depth.ndim < 3: 19 | depth = depth[np.newaxis, :, :] 20 | 21 | # colorize 22 | cm = matplotlib.colormaps[cmap] 23 | depth = ((depth - min_depth) / (max_depth - min_depth)).clip(0, 1) 24 | img_colored_np = cm(depth, bytes=False)[:,:,:,0:3] # value from 0 to 1 25 | img_colored_np = np.rollaxis(img_colored_np, 3, 1) 26 | 27 | if valid_mask is not None: 28 | if isinstance(depth_map, torch.Tensor): 29 | valid_mask = valid_mask.detach().numpy() 30 | valid_mask = valid_mask.squeeze() # [H, W] or [B, H, W] 31 | if valid_mask.ndim < 3: 32 | valid_mask = valid_mask[np.newaxis, np.newaxis, :, :] 33 | else: 34 | valid_mask = valid_mask[:, np.newaxis, :, :] 35 | valid_mask = np.repeat(valid_mask, 3, axis=1) 36 | img_colored_np[~valid_mask] = 0 37 | 38 | if isinstance(depth_map, torch.Tensor): 39 | img_colored = torch.from_numpy(img_colored_np).float() 40 | elif isinstance(depth_map, np.ndarray): 41 | img_colored = img_colored_np 42 | 43 | return img_colored 44 | 45 | 46 | def chw2hwc(chw): 47 | assert 3 == len(chw.shape) 48 | if isinstance(chw, torch.Tensor): 49 | hwc = torch.permute(chw, (1, 2, 0)) 50 | elif isinstance(chw, np.ndarray): 51 | hwc = np.moveaxis(chw, 0, -1) 52 | return hwc 53 | 54 | 55 | def resize_max_res(img: Image.Image, max_edge_resolution): 56 | original_width, original_height = img.size 57 | downscale_factor = min(max_edge_resolution / original_width, max_edge_resolution / original_height) 58 | 59 | new_width = int(original_width * downscale_factor) 60 | new_height = int(original_height * downscale_factor) 61 | 62 | resized_img = img.resize((new_width, new_height)) 63 | return resized_img 64 | 65 | 66 | -------------------------------------------------------------------------------- /marigold/util/seed_all.py: -------------------------------------------------------------------------------- 1 | 2 | import numpy as np 3 | import random 4 | import torch 5 | 6 | 7 | def seed_all(seed: int = 0): 8 | """ 9 | Set random seeds of all components. 10 | """ 11 | random.seed(seed) 12 | np.random.seed(seed) 13 | torch.manual_seed(seed) 14 | torch.cuda.manual_seed_all(seed) -------------------------------------------------------------------------------- /nodes.py: -------------------------------------------------------------------------------- 1 | import os 2 | import torch 3 | import numpy as np 4 | 5 | from PIL import Image 6 | import torchvision.transforms as transforms 7 | 8 | from .marigold.model.marigold_pipeline import MarigoldPipeline 9 | from .marigold.util.ensemble import ensemble_depths 10 | from .marigold.util.image_util import chw2hwc, colorize_depth_maps 11 | 12 | 13 | import comfy.utils 14 | import model_management 15 | import folder_paths 16 | 17 | def colorizedepth(depth_map, colorize_method): 18 | depth_map = depth_map.cpu().numpy() 19 | percentile = 0.03 20 | min_depth_pct = np.percentile(depth_map, percentile) 21 | max_depth_pct = np.percentile(depth_map, 100 - percentile) 22 | 23 | depth_colored = colorize_depth_maps( 24 | depth_map, min_depth_pct, max_depth_pct, cmap=colorize_method 25 | ).squeeze() # [3, H, W], value in (0, 1) 26 | depth_colored = (depth_colored * 255).astype(np.uint8) 27 | depth_colored_hwc = chw2hwc(depth_colored) 28 | return depth_colored_hwc 29 | 30 | def convert_dtype(dtype_str): 31 | if dtype_str == 'fp32': 32 | return torch.float32 33 | elif dtype_str == 'fp16': 34 | return torch.float16 35 | elif dtype_str == 'bf16': 36 | return torch.bfloat16 37 | elif dtype_str == 'fp8': 38 | return torch.float8_e4m3fn 39 | 40 | else: 41 | raise NotImplementedError 42 | 43 | script_directory = os.path.dirname(os.path.abspath(__file__)) 44 | empty_text_embed = torch.load(os.path.join(script_directory, "empty_text_embed.pt"), map_location="cpu") 45 | 46 | class MarigoldDepthEstimation: 47 | @classmethod 48 | def INPUT_TYPES(s): 49 | return {"required": { 50 | "image": ("IMAGE", ), 51 | "seed": ("INT", {"default": 123,"min": 0, "max": 0xffffffffffffffff, "step": 1}), 52 | "denoise_steps": ("INT", {"default": 10, "min": 1, "max": 4096, "step": 1}), 53 | "n_repeat": ("INT", {"default": 10, "min": 1, "max": 4096, "step": 1}), 54 | "regularizer_strength": ("FLOAT", {"default": 0.02, "min": 0.001, "max": 4096, "step": 0.001}), 55 | "reduction_method": ( 56 | [ 57 | 'median', 58 | 'mean', 59 | ], { 60 | "default": 'median' 61 | }), 62 | "max_iter": ("INT", {"default": 5, "min": 1, "max": 4096, "step": 1}), 63 | "tol": ("FLOAT", {"default": 1e-3, "min": 1e-6, "max": 1e-1, "step": 1e-6}), 64 | 65 | "invert": ("BOOLEAN", {"default": True}), 66 | "keep_model_loaded": ("BOOLEAN", {"default": True}), 67 | "n_repeat_batch_size": ("INT", {"default": 2, "min": 1, "max": 4096, "step": 1}), 68 | "use_fp16": ("BOOLEAN", {"default": True}), 69 | "scheduler": ( 70 | [ 71 | 'DDIMScheduler', 72 | 'DDPMScheduler', 73 | 'PNDMScheduler', 74 | 'DEISMultistepScheduler', 75 | 'LCMScheduler', 76 | ], { 77 | "default": 'DDIMScheduler' 78 | }), 79 | "normalize": ("BOOLEAN", {"default": True}), 80 | }, 81 | "optional": { 82 | "model": ( 83 | [ 84 | 'Marigold', 85 | 'marigold-lcm-v1-0', 86 | ], { 87 | "default": 'Marigold' 88 | }), 89 | } 90 | 91 | } 92 | 93 | RETURN_TYPES = ("IMAGE",) 94 | RETURN_NAMES =("ensembled_image",) 95 | FUNCTION = "process" 96 | CATEGORY = "Marigold" 97 | DESCRIPTION = """ 98 | Diffusion-based monocular depth estimation: 99 | https://github.com/prs-eth/Marigold 100 | 101 | - denoise_steps: steps per depth map, increase for accuracy in exchange of processing time 102 | - n_repeat: amount of iterations to be ensembled into single depth map 103 | - n_repeat_batch_size: how many of the n_repeats are processed as a batch, 104 | if you have the VRAM this can match the n_repeats for faster processing 105 | - model: Marigold or it's LCM version marigold-lcm-v1-0 106 | For the LCM model use around 4 steps and the LCMScheduler 107 | - scheduler: Different schedulers give bit different results 108 | - invert: marigold by default produces depth map where black is front, 109 | for controlnets etc. we want the opposite. 110 | - regularizer_strength, reduction_method, max_iter, tol (tolerance) are settings 111 | for the ensembling process, generally do not touch. 112 | - use_fp16: if true, use fp16, if false use fp32 113 | fp16 uses much less VRAM, but in some cases can lead to loss of quality. 114 | """ 115 | 116 | def process(self, image, seed, denoise_steps, n_repeat, regularizer_strength, reduction_method, max_iter, tol,invert, keep_model_loaded, n_repeat_batch_size, use_fp16, scheduler, normalize, model="Marigold"): 117 | batch_size = image.shape[0] 118 | precision = torch.float16 if use_fp16 else torch.float32 119 | device = model_management.get_torch_device() 120 | torch.manual_seed(seed) 121 | 122 | image = image.permute(0, 3, 1, 2).to(device).to(dtype=precision) 123 | if normalize: 124 | image = image * 2.0 - 1.0 125 | 126 | diffusers_model_path = os.path.join(folder_paths.models_dir,'diffusers') 127 | #load the diffusers model 128 | if model == "Marigold": 129 | folders_to_check = [ 130 | os.path.join(script_directory,"checkpoints","Marigold_v1_merged",), 131 | os.path.join(script_directory,"checkpoints","Marigold",), 132 | os.path.join(diffusers_model_path,"Marigold_v1_merged"), 133 | os.path.join(diffusers_model_path,"Marigold") 134 | ] 135 | elif model == "marigold-lcm-v1-0": 136 | folders_to_check = [ 137 | os.path.join(diffusers_model_path,"marigold-lcm-v1-0"), 138 | os.path.join(diffusers_model_path,"checkpoints","marigold-lcm-v1-0") 139 | ] 140 | self.custom_config = { 141 | "model": model, 142 | "use_fp16": use_fp16, 143 | "scheduler": scheduler, 144 | } 145 | if not hasattr(self, 'marigold_pipeline') or self.marigold_pipeline is None or self.current_config != self.custom_config: 146 | self.current_config = self.custom_config 147 | # Load the model only if it hasn't been loaded before 148 | checkpoint_path = None 149 | for folder in folders_to_check: 150 | if os.path.exists(folder): 151 | checkpoint_path = folder 152 | break 153 | to_ignore = ["*.bin", "*fp16*"] 154 | 155 | if checkpoint_path is None: 156 | if model == "Marigold": 157 | try: 158 | from huggingface_hub import snapshot_download 159 | checkpoint_path = os.path.join(diffusers_model_path, "Marigold") 160 | snapshot_download(repo_id="Bingxin/Marigold", ignore_patterns=to_ignore, local_dir=checkpoint_path, local_dir_use_symlinks=False) 161 | except: 162 | raise FileNotFoundError(f"No checkpoint directory found at {checkpoint_path}") 163 | if model == "marigold-lcm-v1-0": 164 | try: 165 | from huggingface_hub import snapshot_download 166 | checkpoint_path = os.path.join(diffusers_model_path, "marigold-lcm-v1-0") 167 | snapshot_download(repo_id="prs-eth/marigold-lcm-v1-0", ignore_patterns=to_ignore, local_dir=checkpoint_path, local_dir_use_symlinks=False) 168 | except: 169 | raise FileNotFoundError(f"No checkpoint directory found at {checkpoint_path}") 170 | 171 | self.marigold_pipeline = MarigoldPipeline.from_pretrained(checkpoint_path, enable_xformers=False, empty_text_embed=empty_text_embed, noise_scheduler_type=scheduler) 172 | self.marigold_pipeline = self.marigold_pipeline.to(device).half() if use_fp16 else self.marigold_pipeline.to(device) 173 | self.marigold_pipeline.unet.eval() # Set the model to evaluation mode 174 | pbar = comfy.utils.ProgressBar(batch_size * n_repeat) 175 | 176 | out = [] 177 | 178 | with torch.no_grad(): 179 | for i in range(batch_size): 180 | # Duplicate the current image n_repeat times 181 | duplicated_batch = image[i].unsqueeze(0).repeat(n_repeat, 1, 1, 1) 182 | 183 | # Process the duplicated batch in sub-batches 184 | depth_maps = [] 185 | for j in range(0, n_repeat, n_repeat_batch_size): 186 | # Get the current sub-batch 187 | sub_batch = duplicated_batch[j:j + n_repeat_batch_size] 188 | 189 | # Process the sub-batch 190 | depth_maps_sub_batch = self.marigold_pipeline(sub_batch, num_inference_steps=denoise_steps, show_pbar=False) 191 | 192 | # Process each depth map in the sub-batch if necessary 193 | for depth_map in depth_maps_sub_batch: 194 | depth_map = torch.clip(depth_map, -1.0, 1.0) 195 | depth_map = (depth_map + 1.0) / 2.0 196 | depth_maps.append(depth_map) 197 | pbar.update(1) 198 | 199 | depth_predictions = torch.cat(depth_maps, dim=0).squeeze() 200 | del duplicated_batch, depth_maps_sub_batch 201 | torch.cuda.empty_cache() # clear vram cache for ensembling 202 | 203 | # Test-time ensembling 204 | if n_repeat > 1: 205 | depth_map, pred_uncert = ensemble_depths( 206 | depth_predictions, 207 | regularizer_strength=regularizer_strength, 208 | max_iter=max_iter, 209 | tol=tol, 210 | reduction=reduction_method, 211 | max_res=None, 212 | device=device, 213 | ) 214 | print(depth_map.shape) 215 | depth_map = depth_map.unsqueeze(2).repeat(1, 1, 3) 216 | print(depth_map.shape) 217 | else: 218 | depth_map = depth_map.permute(1, 2, 0) 219 | depth_map = depth_map.repeat(1, 1, 3) 220 | print(depth_map.shape) 221 | 222 | out.append(depth_map) 223 | del depth_map, depth_predictions 224 | 225 | if invert: 226 | outstack = 1.0 - torch.stack(out, dim=0).cpu().to(torch.float32) 227 | else: 228 | outstack = torch.stack(out, dim=0).cpu().to(torch.float32) 229 | 230 | if not keep_model_loaded: 231 | self.marigold_pipeline = None 232 | model_management.soft_empty_cache() 233 | return (outstack,) 234 | 235 | class MarigoldDepthEstimationVideo: 236 | @classmethod 237 | def INPUT_TYPES(s): 238 | return {"required": { 239 | "image": ("IMAGE", ), 240 | "seed": ("INT", {"default": 123,"min": 0, "max": 0xffffffffffffffff, "step": 1}), 241 | "first_frame_denoise_steps": ("INT", {"default": 4, "min": 1, "max": 4096, "step": 1}), 242 | "first_frame_n_repeat": ("INT", {"default": 1, "min": 1, "max": 4096, "step": 1}), 243 | "n_repeat_batch_size": ("INT", {"default": 1, "min": 1, "max": 4096, "step": 1}), 244 | "invert": ("BOOLEAN", {"default": True}), 245 | "keep_model_loaded": ("BOOLEAN", {"default": True}), 246 | "scheduler": ( 247 | [ 248 | 'DDIMScheduler', 249 | 'DDPMScheduler', 250 | 'PNDMScheduler', 251 | 'DEISMultistepScheduler', 252 | 'LCMScheduler', 253 | ], { 254 | "default": 'DEISMultistepScheduler' 255 | }), 256 | "normalize": ("BOOLEAN", {"default": True}), 257 | "denoise_steps": ("INT", {"default": 4, "min": 1, "max": 4096, "step": 1}), 258 | "flow_warping": ("BOOLEAN", {"default": True}), 259 | "flow_depth_mix": ("FLOAT", {"default": 0.3, "min": 0.0, "max": 1.0, "step": 0.05}), 260 | "noise_ratio": ("FLOAT", {"default": 0.5, "min": 0.0, "max": 1.0, "step": 0.01}), 261 | "dtype": ( 262 | [ 263 | 'fp16', 264 | 'bf16', 265 | 'fp32', 266 | ], { 267 | "default": 'fp16' 268 | }), 269 | }, 270 | "optional": { 271 | "model": ( 272 | [ 273 | 'Marigold', 274 | 'marigold-lcm-v1-0', 275 | ], { 276 | "default": 'Marigold' 277 | }), 278 | } 279 | 280 | } 281 | 282 | RETURN_TYPES = ("IMAGE",) 283 | RETURN_NAMES =("ensembled_image",) 284 | FUNCTION = "process" 285 | CATEGORY = "Marigold" 286 | DESCRIPTION = """ 287 | Diffusion-based monocular depth estimation: 288 | https://github.com/prs-eth/Marigold 289 | 290 | This node is experimental version that includes optical flow 291 | for video consistency between frames. 292 | 293 | - denoise_steps: steps per depth map, increase for accuracy in exchange of processing time 294 | - n_repeat: amount of iterations to be ensembled into single depth map 295 | - n_repeat_batch_size: how many of the n_repeats are processed as a batch, 296 | if you have the VRAM this can match the n_repeats for faster processing 297 | - model: Marigold or it's LCM version marigold-lcm-v1-0 298 | For the LCM model use around 4 steps and the LCMScheduler 299 | - scheduler: Different schedulers give bit different results 300 | - invert: marigold by default produces depth map where black is front, 301 | for controlnets etc. we want the opposite. 302 | - regularizer_strength, reduction_method, max_iter, tol (tolerance) are settings 303 | for the ensembling process, generally do not touch. 304 | """ 305 | 306 | def process(self, image, seed, first_frame_denoise_steps, denoise_steps, first_frame_n_repeat, keep_model_loaded, invert, 307 | n_repeat_batch_size, dtype, scheduler, normalize, flow_warping, flow_depth_mix, noise_ratio, model="Marigold"): 308 | batch_size = image.shape[0] 309 | 310 | precision = convert_dtype(dtype) 311 | 312 | device = model_management.get_torch_device() 313 | torch.manual_seed(seed) 314 | 315 | image = image.permute(0, 3, 1, 2).to(device).to(dtype=precision) 316 | if normalize: 317 | image = image * 2.0 - 1.0 318 | 319 | if flow_warping: 320 | from .marigold.util.flow_estimation import FlowEstimator 321 | flow_estimator = FlowEstimator(os.path.join(script_directory, "gmflow", "gmflow_things-e9887eda.pth"), device) 322 | diffusers_model_path = os.path.join(folder_paths.models_dir,'diffusers') 323 | if model == "Marigold": 324 | folders_to_check = [ 325 | os.path.join(script_directory,"checkpoints","Marigold_v1_merged",), 326 | os.path.join(script_directory,"checkpoints","Marigold",), 327 | os.path.join(diffusers_model_path,"Marigold_v1_merged"), 328 | os.path.join(diffusers_model_path,"Marigold") 329 | ] 330 | elif model == "marigold-lcm-v1-0": 331 | folders_to_check = [ 332 | os.path.join(diffusers_model_path,"marigold-lcm-v1-0"), 333 | os.path.join(diffusers_model_path,"checkpoints","marigold-lcm-v1-0") 334 | ] 335 | self.custom_config = { 336 | "model": model, 337 | "dtype": dtype, 338 | "scheduler": scheduler, 339 | } 340 | if not hasattr(self, 'marigold_pipeline') or self.marigold_pipeline is None or self.current_config != self.custom_config: 341 | self.current_config = self.custom_config 342 | # Load the model only if it hasn't been loaded before 343 | checkpoint_path = None 344 | for folder in folders_to_check: 345 | potential_path = os.path.join(script_directory, folder) 346 | if os.path.exists(potential_path): 347 | checkpoint_path = potential_path 348 | break 349 | to_ignore = ["*.bin", "*fp16*"] 350 | if checkpoint_path is None: 351 | if model == "Marigold": 352 | try: 353 | from huggingface_hub import snapshot_download 354 | checkpoint_path = os.path.join(diffusers_model_path, "Marigold") 355 | snapshot_download(repo_id="Bingxin/Marigold", ignore_patterns=to_ignore, local_dir=checkpoint_path, local_dir_use_symlinks=False) 356 | except: 357 | raise FileNotFoundError(f"No checkpoint directory found at {checkpoint_path}") 358 | if model == "marigold-lcm-v1-0": 359 | try: 360 | from huggingface_hub import snapshot_download 361 | checkpoint_path = os.path.join(diffusers_model_path, "marigold-lcm-v1-0") 362 | snapshot_download(repo_id="prs-eth/marigold-lcm-v1-0", ignore_patterns=to_ignore, local_dir=checkpoint_path, local_dir_use_symlinks=False) 363 | except: 364 | raise FileNotFoundError(f"No checkpoint directory found at {checkpoint_path}") 365 | 366 | self.marigold_pipeline = MarigoldPipeline.from_pretrained(checkpoint_path, enable_xformers=False, empty_text_embed=empty_text_embed, noise_scheduler_type=scheduler) 367 | self.marigold_pipeline = self.marigold_pipeline.to(precision).to(device) 368 | self.marigold_pipeline.unet.eval() 369 | pbar = comfy.utils.ProgressBar(batch_size) 370 | 371 | out = [] 372 | for i in range(batch_size): 373 | if flow_warping: 374 | current_image = image[i] 375 | prev_image = image[i-1] 376 | flow = flow_estimator.estimate_flow(prev_image.to(torch.float32), current_image.to(torch.float32)) 377 | if i == 0 or not flow_warping: 378 | # Duplicate the current image n_repeat times 379 | duplicated_batch = image[i].unsqueeze(0).repeat(first_frame_n_repeat, 1, 1, 1) 380 | # Process the duplicated batch in sub-batches 381 | depth_maps = [] 382 | for j in range(0, first_frame_n_repeat, n_repeat_batch_size): 383 | # Get the current sub-batch 384 | sub_batch = duplicated_batch[j:j + n_repeat_batch_size] 385 | 386 | # Process the sub-batch 387 | depth_maps_sub_batch = self.marigold_pipeline(sub_batch, num_inference_steps=first_frame_denoise_steps, show_pbar=False) 388 | 389 | # Process each depth map in the sub-batch if necessary 390 | for depth_map in depth_maps_sub_batch: 391 | depth_map = torch.clip(depth_map, -1.0, 1.0) 392 | depth_map = (depth_map + 1.0) / 2.0 393 | depth_maps.append(depth_map) 394 | 395 | depth_predictions = torch.cat(depth_maps, dim=0).squeeze() 396 | 397 | del duplicated_batch, depth_maps_sub_batch 398 | comfy.model_management.soft_empty_cache() 399 | 400 | # Test-time ensembling 401 | if first_frame_n_repeat > 1: 402 | depth_map, pred_uncert = ensemble_depths( 403 | depth_predictions, 404 | regularizer_strength=0.02, 405 | max_iter=5, 406 | tol=1e-3, 407 | reduction="median", 408 | max_res=None, 409 | device=device, 410 | ) 411 | prev_depth_map = torch.clip(depth_map, 0.0, 1.0) 412 | depth_map = depth_map.unsqueeze(2).repeat(1, 1, 3) 413 | out.append(depth_map) 414 | pbar.update(1) 415 | else: 416 | prev_depth_map = torch.clip(depth_map[0], 0.0, 1.0) 417 | depth_map = depth_map[0].unsqueeze(2).repeat(1, 1, 3) 418 | out.append(depth_map) 419 | pbar.update(1) 420 | 421 | else: 422 | #idea and original implementation from https://github.com/pablodawson/Marigold-Video 423 | warped_depth_map = FlowEstimator.warp_with_flow(flow, prev_depth_map).to(precision).to(device) 424 | warped_depth_map = (warped_depth_map + 1.0) / 2.0 425 | assert warped_depth_map.min() >= -1.0 and warped_depth_map.max() <= 1.0 426 | depth_predictions = self.marigold_pipeline(current_image.unsqueeze(0), init_depth_latent=warped_depth_map.unsqueeze(0).repeat(3, 1, 1).unsqueeze(0), 427 | noise_ratio=noise_ratio, num_inference_steps=denoise_steps, show_pbar=False) 428 | 429 | warped_depth_map = warped_depth_map / warped_depth_map.max() 430 | depth_out = flow_depth_mix * depth_predictions + (1 - flow_depth_mix) * warped_depth_map 431 | depth_out = torch.clip(depth_out, 0.0, 1.0) 432 | 433 | prev_depth_map = depth_out.squeeze() 434 | depth_out = depth_out.squeeze().unsqueeze(2).repeat(1, 1, 3) 435 | 436 | out.append(depth_out) 437 | pbar.update(1) 438 | 439 | del depth_predictions, warped_depth_map 440 | if invert: 441 | outstack = 1.0 - torch.stack(out, dim=0).cpu().to(torch.float32) 442 | else: 443 | outstack = torch.stack(out, dim=0).cpu().to(torch.float32) 444 | if not keep_model_loaded: 445 | self.marigold_pipeline = None 446 | model_management.soft_empty_cache() 447 | return (outstack,) 448 | 449 | class ColorizeDepthmap: 450 | @classmethod 451 | def INPUT_TYPES(s): 452 | return {"required": { 453 | "image": ("IMAGE", ), 454 | "colorize_method": ( 455 | [ 456 | 'Spectral', 457 | 'terrain', 458 | 'viridis', 459 | 'plasma', 460 | 'inferno', 461 | 'magma', 462 | 'cividis', 463 | 'twilight', 464 | 'rainbow', 465 | 'gist_rainbow', 466 | 'gist_ncar', 467 | 'gist_earth', 468 | 'turbo', 469 | 'jet', 470 | 'afmhot', 471 | 'copper', 472 | 'seismic', 473 | 'hsv', 474 | 'brg', 475 | 476 | ], { 477 | "default": 'Spectral' 478 | }), 479 | }, 480 | 481 | } 482 | 483 | RETURN_TYPES = ("IMAGE",) 484 | RETURN_NAMES =("image",) 485 | FUNCTION = "color" 486 | 487 | CATEGORY = "Marigold" 488 | 489 | def color(self, image, colorize_method): 490 | colored_images = [] 491 | for i in range(image.shape[0]): # Iterate over the batch dimension 492 | depth_map = image[i].squeeze().permute(2, 0, 1) 493 | depth_map = depth_map[0] 494 | depth_map = colorizedepth(depth_map, colorize_method) 495 | depth_map = torch.from_numpy(depth_map) / 255 496 | depth_map = depth_map.unsqueeze(0) 497 | colored_images.append(depth_map) 498 | 499 | # Stack the list of tensors along a new dimension 500 | colored_images = torch.cat(colored_images, dim=0) 501 | return (colored_images,) 502 | 503 | import folder_paths 504 | 505 | class SaveImageOpenEXR: 506 | def __init__(self): 507 | try: 508 | import OpenEXR 509 | import Imath 510 | self.OpenEXR = OpenEXR 511 | self.Imath = Imath 512 | self.use_openexr = True 513 | except ImportError: 514 | print("No OpenEXR module found, trying OpenCV...") 515 | self.use_openexr = False 516 | try: 517 | os.environ["OPENCV_IO_ENABLE_OPENEXR"] = "1" 518 | import cv2 519 | self.cv2 = cv2 520 | except ImportError: 521 | raise ImportError("No OpenEXR or OpenCV module found, can't save EXR") 522 | 523 | self.output_dir = folder_paths.get_output_directory() 524 | self.type = "output" 525 | self.prefix_append = "" 526 | @classmethod 527 | def INPUT_TYPES(s): 528 | return {"required": { 529 | "images": ("IMAGE", ), 530 | "filename_prefix": ("STRING", {"default": "ComfyUI_EXR"}) 531 | }, 532 | 533 | } 534 | 535 | RETURN_TYPES = ("STRING",) 536 | RETURN_NAMES =("file_url",) 537 | FUNCTION = "saveexr" 538 | OUTPUT_NODE = True 539 | CATEGORY = "Marigold" 540 | 541 | def saveexr(self, images, filename_prefix): 542 | import re 543 | filename_prefix += self.prefix_append 544 | full_output_folder, filename, counter, subfolder, filename_prefix = folder_paths.get_save_image_path(filename_prefix, self.output_dir, images[0].shape[1], images[0].shape[0]) 545 | results = list() 546 | def file_counter(): 547 | max_counter = 0 548 | # Loop through the existing files 549 | for existing_file in os.listdir(full_output_folder): 550 | # Check if the file matches the expected format 551 | match = re.fullmatch(f"{filename}_(\d+)_?\.[a-zA-Z0-9]+", existing_file) 552 | if match: 553 | # Extract the numeric portion of the filename 554 | file_counter = int(match.group(1)) 555 | # Update the maximum counter value if necessary 556 | if file_counter > max_counter: 557 | max_counter = file_counter 558 | return max_counter 559 | 560 | for image in images: 561 | # Ensure the tensor is on the CPU and convert it to a numpy array 562 | image_np = image.cpu().numpy() 563 | image_np = image_np.astype(np.float32) 564 | 565 | if self.use_openexr: 566 | # Assuming the image is in the format of floating point 32 bit (change PIXEL_TYPE if not) 567 | PIXEL_TYPE = self.Imath.PixelType(self.Imath.PixelType.FLOAT) 568 | height, width, channels = image_np.shape 569 | 570 | # Prepare the EXR header 571 | header = self.OpenEXR.Header(width, height) 572 | half_chan = self.Imath.Channel(PIXEL_TYPE) 573 | header['channels'] = dict([(c, half_chan) for c in "RGB"]) 574 | 575 | # Split the channels for OpenEXR 576 | R = image_np[:, :, 0].tostring() 577 | G = image_np[:, :, 1].tostring() 578 | B = image_np[:, :, 2].tostring() 579 | 580 | # Increment the counter by 1 to get the next available value 581 | counter = file_counter() + 1 582 | file = f"{filename}_{counter:05}.exr" 583 | 584 | # Write the EXR file 585 | exr_file = self.OpenEXR.OutputFile(os.path.join(full_output_folder, file), header) 586 | exr_file.writePixels({'R': R, 'G': G, 'B': B}) 587 | exr_file.close() 588 | else: 589 | counter = file_counter() + 1 590 | file = f"{filename}_{counter:05}.exr" 591 | exr_file = os.path.join(full_output_folder, file) 592 | self.cv2.imwrite(exr_file, image_np) 593 | 594 | return (f"/view?filename={file}&subfolder=&type=output",) 595 | 596 | class RemapDepth: 597 | @classmethod 598 | def INPUT_TYPES(s): 599 | return {"required": { 600 | "image": ("IMAGE",), 601 | "min": ("FLOAT", {"default": 0.0,"min": -10.0, "max": 1.0, "step": 0.01}), 602 | "max": ("FLOAT", {"default": 1.0,"min": 0.0, "max": 10.0, "step": 0.01}), 603 | "clamp": ("BOOLEAN", {"default": True}), 604 | }, 605 | } 606 | 607 | RETURN_TYPES = ("IMAGE",) 608 | FUNCTION = "remap" 609 | 610 | CATEGORY = "Marigold" 611 | 612 | def remap(self, image, min, max, clamp): 613 | if image.dtype == torch.float16: 614 | image = image.to(torch.float32) 615 | image = min + image * (max - min) 616 | if clamp: 617 | image = torch.clamp(image, min=0.0, max=1.0) 618 | return (image, ) 619 | 620 | NODE_CLASS_MAPPINGS = { 621 | "MarigoldDepthEstimation": MarigoldDepthEstimation, 622 | "MarigoldDepthEstimationVideo": MarigoldDepthEstimationVideo, 623 | "ColorizeDepthmap": ColorizeDepthmap, 624 | "SaveImageOpenEXR": SaveImageOpenEXR, 625 | "RemapDepth": RemapDepth 626 | } 627 | NODE_DISPLAY_NAME_MAPPINGS = { 628 | "MarigoldDepthEstimation": "MarigoldDepthEstimation", 629 | "MarigoldDepthEstimationVideo": "MarigoldDepthEstimationVideo", 630 | "ColorizeDepthmap": "ColorizeDepthmap", 631 | "SaveImageOpenEXR": "SaveImageOpenEXR", 632 | "RemapDepth": "RemapDepth" 633 | } -------------------------------------------------------------------------------- /nodes_v2.py: -------------------------------------------------------------------------------- 1 | import os 2 | import torch 3 | import torchvision.transforms as transforms 4 | 5 | from diffusers.schedulers import ( 6 | DDIMScheduler, 7 | LCMScheduler 8 | ) 9 | 10 | import comfy.utils 11 | import model_management 12 | import folder_paths 13 | 14 | class MarigoldModelLoader: 15 | @classmethod 16 | def INPUT_TYPES(s): 17 | return {"required": { 18 | "model": ( 19 | [ 20 | 'prs-eth/marigold-v1-0', 21 | 'prs-eth/marigold-depth-lcm-v1-0', 22 | 'prs-eth/marigold-depth-v1-1', 23 | 'prs-eth/marigold-normals-v0-1', 24 | 'prs-eth/marigold-normals-lcm-v0-1', 25 | 'prs-eth/marigold-normals-v1-1', 26 | 'GonzaloMG/marigold-e2e-ft-depth', 27 | 'GonzaloMG/marigold-e2e-ft-normals', 28 | 'prs-eth/marigold-iid-lighting-v1-1', 29 | 'prs-eth/marigold-iid-appearance-v1-1' 30 | ], 31 | { 32 | "default": 'marigold-lcm-v1-0' 33 | }), 34 | }, 35 | } 36 | 37 | RETURN_TYPES = ("MARIGOLDMODEL",) 38 | RETURN_NAMES =("marigold_model",) 39 | FUNCTION = "load" 40 | CATEGORY = "Marigold" 41 | DESCRIPTION = """ 42 | Diffusion-based monocular depth estimation: 43 | https://github.com/prs-eth/Marigold 44 | 45 | Uses Diffusers 0.28.0 Marigold pipelines. 46 | Models are automatically downloaded to 47 | ComfyUI/models/diffusers -folder 48 | """ 49 | 50 | def load(self, model): 51 | try: 52 | 53 | from diffusers import MarigoldDepthPipeline, MarigoldNormalsPipeline, MarigoldIntrinsicsPipeline 54 | except: 55 | raise Exception("diffusers>=0.28 is required for v2 nodes") 56 | 57 | device = model_management.get_torch_device() 58 | diffusers_model_path = os.path.join(folder_paths.models_dir,'diffusers') 59 | checkpoint_path = os.path.join(diffusers_model_path, model.split("/")[-1]) 60 | if "GonzaloMG" in model: 61 | allow_patterns=None 62 | variant=None 63 | else: 64 | allow_patterns=["*.json", "*.txt","*fp16*"] 65 | variant="fp16" 66 | 67 | if not os.path.exists(checkpoint_path): 68 | print(f"Selected model: {checkpoint_path} not found, downloading...") 69 | from huggingface_hub import snapshot_download 70 | snapshot_download(repo_id=model, 71 | allow_patterns=allow_patterns, 72 | ignore_patterns=["*.bin"], 73 | local_dir=checkpoint_path, 74 | local_dir_use_symlinks=False 75 | ) 76 | if "normals" in model: 77 | modeltype = "normals" 78 | self.marigold_pipeline = MarigoldNormalsPipeline.from_pretrained( 79 | checkpoint_path, 80 | variant=variant, 81 | torch_dtype=torch.float16).to(device) 82 | elif "iid" in model: 83 | modeltype = "intrinsics" 84 | self.marigold_pipeline = MarigoldIntrinsicsPipeline.from_pretrained( 85 | checkpoint_path, 86 | variant=variant, 87 | torch_dtype=torch.float16).to(device) 88 | else: 89 | modeltype = "depth" 90 | self.marigold_pipeline = MarigoldDepthPipeline.from_pretrained( 91 | checkpoint_path, 92 | variant=variant, 93 | torch_dtype=torch.float16).to(device) 94 | 95 | marigold_model = { 96 | "pipeline": self.marigold_pipeline, 97 | "modeltype": modeltype 98 | } 99 | return (marigold_model,) 100 | 101 | class MarigoldDepthEstimation_v2: 102 | @classmethod 103 | def INPUT_TYPES(s): 104 | return {"required": { 105 | "marigold_model": ("MARIGOLDMODEL",), 106 | "image": ("IMAGE", ), 107 | "seed": ("INT", {"default": 123,"min": 0, "max": 0xffffffffffffffff, "step": 1}), 108 | "denoise_steps": ("INT", {"default": 4, "min": 1, "max": 4096, "step": 1}), 109 | "ensemble_size": ("INT", {"default": 3, "min": 1, "max": 4096, "step": 1}), 110 | "processing_resolution": ("INT", {"default": 768, "min": 64, "max": 4096, "step": 8}), 111 | "scheduler": ( 112 | ["DDIMScheduler", "LCMScheduler",], 113 | { 114 | "default": 'LCMScheduler' 115 | }), 116 | "use_taesd_vae": ("BOOLEAN", {"default": False}), 117 | }, 118 | "optional": { 119 | "keep_model_loaded": ("BOOLEAN", {"default": False}), 120 | } 121 | } 122 | 123 | RETURN_TYPES = ("IMAGE",) 124 | RETURN_NAMES =("image",) 125 | FUNCTION = "process" 126 | CATEGORY = "Marigold" 127 | DESCRIPTION = """ 128 | Diffusion-based monocular depth estimation: 129 | https://github.com/prs-eth/Marigold 130 | 131 | Uses Diffusers 0.28.0 Marigold pipelines. 132 | """ 133 | 134 | def process(self, marigold_model, image, seed, denoise_steps, processing_resolution, ensemble_size, scheduler, use_taesd_vae, keep_model_loaded=False): 135 | try: 136 | from diffusers import AutoencoderTiny 137 | except: 138 | raise Exception("diffusers==0.28 is required for v2 nodes") 139 | batch_size = image.shape[0] 140 | device = model_management.get_torch_device() 141 | offload_device = model_management.unet_offload_device() 142 | intermediate_device = model_management.intermediate_device() 143 | torch.manual_seed(seed) 144 | 145 | image = image.permute(0, 3, 1, 2).to(device) 146 | 147 | pipeline = marigold_model['pipeline'] 148 | pred_type = marigold_model['modeltype'] 149 | 150 | if use_taesd_vae: 151 | pipeline.vae = AutoencoderTiny.from_pretrained("madebyollin/taesd", torch_dtype=torch.float16).to(device) 152 | 153 | pbar = comfy.utils.ProgressBar(batch_size) 154 | 155 | scheduler_kwargs = { 156 | DDIMScheduler: { 157 | "num_inference_steps": denoise_steps, 158 | "ensemble_size": ensemble_size, 159 | }, 160 | LCMScheduler: { 161 | "num_inference_steps": denoise_steps, 162 | "ensemble_size": ensemble_size, 163 | }, 164 | } 165 | if scheduler == 'DDIMScheduler': 166 | pipe_kwargs = scheduler_kwargs[DDIMScheduler] 167 | elif scheduler == 'LCMScheduler': 168 | pipe_kwargs = scheduler_kwargs[LCMScheduler] 169 | 170 | generator = torch.Generator(device).manual_seed(seed) 171 | 172 | processed_out_list = [] 173 | 174 | pipeline.to(device) 175 | 176 | for i in range(batch_size): 177 | processed = pipeline( 178 | image[i], 179 | output_type = "pt", 180 | generator = generator, 181 | processing_resolution = processing_resolution, 182 | **pipe_kwargs 183 | ) 184 | #print("processed", processed[0].shape) 185 | 186 | pbar.update(1) 187 | if pred_type == "normals": 188 | normals = pipeline.image_processor.visualize_normals(processed.prediction) 189 | normals_tensor = transforms.ToTensor()(normals[0]) 190 | processed_out_list.append(normals_tensor) 191 | else: 192 | processed_out_list.append(processed[0]) 193 | if not keep_model_loaded: 194 | pipeline.to(offload_device) 195 | model_management.soft_empty_cache() 196 | 197 | if pred_type == "normals": 198 | processed_out = torch.stack(processed_out_list, dim=0) 199 | processed_out = processed_out.permute(0, 2, 3, 1) 200 | elif pred_type == "intrinsics": 201 | processed_out = torch.cat(processed_out_list, dim=0) 202 | processed_out = processed_out.permute(0, 2, 3, 1) 203 | else: 204 | processed_out = torch.cat(processed_out_list, dim=0) 205 | processed_out = processed_out.permute(0, 2, 3, 1).repeat(1, 1, 1, 3) 206 | processed_out = 1.0 - processed_out 207 | 208 | return (processed_out.to(intermediate_device).float(),) 209 | 210 | class MarigoldDepthEstimation_v2_video: 211 | @classmethod 212 | def INPUT_TYPES(s): 213 | return {"required": { 214 | "marigold_model": ("MARIGOLDMODEL",), 215 | "images": ("IMAGE", ), 216 | "seed": ("INT", {"default": 123,"min": 0, "max": 0xffffffffffffffff, "step": 1}), 217 | "denoise_steps": ("INT", {"default": 4, "min": 1, "max": 4096, "step": 1}), 218 | "processing_resolution": ("INT", {"default": 768, "min": 64, "max": 4096, "step": 8}), 219 | "scheduler": ( 220 | ["DDIMScheduler", "LCMScheduler",], 221 | { 222 | "default": 'LCMScheduler' 223 | }), 224 | 225 | "blend_factor": ("FLOAT", {"default": 0.1,"min": 0.0, "max": 1.0, "step": 0.01}), 226 | "use_taesd_vae": ("BOOLEAN", {"default": True}), 227 | }, 228 | "optional": { 229 | "keep_model_loaded": ("BOOLEAN", {"default": False}), 230 | } 231 | } 232 | 233 | RETURN_TYPES = ("IMAGE",) 234 | RETURN_NAMES =("image",) 235 | FUNCTION = "process" 236 | CATEGORY = "Marigold" 237 | DESCRIPTION = """ 238 | Diffusion-based monocular depth estimation: 239 | https://github.com/prs-eth/Marigold 240 | 241 | Uses Diffusers 0.28.0 Marigold pipelines. 242 | This node uses the previous frame as init latent to 243 | smooth out the video. 244 | """ 245 | 246 | def process(self, marigold_model, images, seed, denoise_steps, processing_resolution, blend_factor, scheduler, use_taesd_vae, keep_model_loaded=False): 247 | try: 248 | from diffusers import AutoencoderTiny 249 | except: 250 | raise Exception("diffusers==0.28 is required for v2 nodes") 251 | device = model_management.get_torch_device() 252 | offload_device = model_management.unet_offload_device() 253 | intermediate_device = model_management.intermediate_device() 254 | 255 | pipeline = marigold_model['pipeline'] 256 | pred_type = marigold_model['modeltype'] 257 | 258 | if use_taesd_vae: 259 | pipeline.vae = AutoencoderTiny.from_pretrained("madebyollin/taesd", torch_dtype=torch.float16).to(device) 260 | 261 | scheduler_kwargs = { 262 | DDIMScheduler: { 263 | "num_inference_steps": denoise_steps, 264 | "ensemble_size": 1, 265 | }, 266 | LCMScheduler: { 267 | "num_inference_steps": denoise_steps, 268 | "ensemble_size": 1, 269 | }, 270 | } 271 | if scheduler == 'DDIMScheduler': 272 | pipe_kwargs = scheduler_kwargs[DDIMScheduler] 273 | elif scheduler == 'LCMScheduler': 274 | pipe_kwargs = scheduler_kwargs[LCMScheduler] 275 | 276 | 277 | B, H, W, C = images.shape 278 | size = [W, H] 279 | images = images.permute(0, 3, 1, 2).to(device) 280 | 281 | last_frame_latent = None 282 | torch.manual_seed(seed) 283 | latent_common = torch.randn((1, 4, processing_resolution * size[1] // (8 * max(size)), processing_resolution * size[0] // (8 * max(size)))).to(device=device, dtype=torch.float16) 284 | pbar = comfy.utils.ProgressBar(B) 285 | 286 | pipeline.to(device) 287 | 288 | processed_out = [] 289 | for img in images: 290 | latents = latent_common 291 | if last_frame_latent is not None: 292 | latents = (1 - blend_factor) * latents + blend_factor * last_frame_latent 293 | 294 | processed = pipeline( 295 | img, 296 | processing_resolution = processing_resolution, 297 | match_input_resolution=False, 298 | latents=latents, 299 | output_latent=True, 300 | output_type = "pt", 301 | **pipe_kwargs 302 | ) 303 | last_frame_latent = processed.latent 304 | pbar.update(1) 305 | if pred_type == "normals": 306 | normals = pipeline.image_processor.visualize_normals(processed.prediction) 307 | normals_tensor = transforms.ToTensor()(normals[0]) 308 | processed_out.append(normals_tensor) 309 | else: 310 | processed_out.append(processed[0]) 311 | 312 | if not keep_model_loaded: 313 | pipeline.to(offload_device) 314 | model_management.soft_empty_cache() 315 | 316 | if pred_type == "normals": 317 | processed_out = torch.stack(processed_out, dim=0) 318 | processed_out = processed_out.permute(0, 2, 3, 1) 319 | else: 320 | processed_out = torch.cat(processed_out, dim=0) 321 | processed_out = processed_out.permute(0, 2, 3, 1).repeat(1, 1, 1, 3) 322 | processed_out = 1.0 - processed_out 323 | 324 | return (processed_out.to(intermediate_device).float(),) 325 | 326 | NODE_CLASS_MAPPINGS = { 327 | "MarigoldModelLoader": MarigoldModelLoader, 328 | "MarigoldDepthEstimation_v2": MarigoldDepthEstimation_v2, 329 | "MarigoldDepthEstimation_v2_video": MarigoldDepthEstimation_v2_video, 330 | } 331 | NODE_DISPLAY_NAME_MAPPINGS = { 332 | "MarigoldModelLoader": MarigoldModelLoader, 333 | "MarigoldDepthEstimation_v2": "MarigoldDepthEstimation_v2", 334 | "MarigoldDepthEstimation_v2_video": "MarigoldDepthEstimation_v2_video", 335 | } -------------------------------------------------------------------------------- /prestartup_script.py: -------------------------------------------------------------------------------- 1 | import os 2 | os.environ["OPENCV_IO_ENABLE_OPENEXR"] = "1" -------------------------------------------------------------------------------- /pyproject.toml: -------------------------------------------------------------------------------- 1 | [project] 2 | name = "comfyui-marigold" 3 | description = "This is a wrapper node for Marigold depth estimation: [https://github.com/prs-eth/Marigold](https://github.com/kijai/ComfyUI-Marigold). Currently using the same diffusers pipeline as in the original implementation, so in addition to the custom node, you need the model in diffusers format.\nNOTE: See details in repo to install." 4 | version = "1.0.1" 5 | license = { file = "LICENSE" } 6 | dependencies = ["accelerate>=0.22.0", "diffusers>=0.33.0", "matplotlib", "scipy", "torch>=2.0.1", "transformers>=4.32.1", "huggingface-hub"] 7 | 8 | [project.urls] 9 | Repository = "https://github.com/kijai/ComfyUI-Marigold" 10 | # Used by Comfy Registry https://comfyregistry.org 11 | 12 | [tool.comfy] 13 | PublisherId = "kijai" 14 | DisplayName = "ComfyUI-Marigold" 15 | Icon = "" 16 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | accelerate>=0.22.0 2 | diffusers>=0.33.0 3 | matplotlib 4 | scipy 5 | torch>=2.0.1 6 | transformers>=4.32.1 7 | huggingface-hub --------------------------------------------------------------------------------