81 Commits
Author SHA1 Message Date
Jukka Seppänen 99d49e912c Update README.md 2026-04-29 18:30:56 +03:00
kijai fe0d660f7c Fix for latest ComfyUI 2026-03-15 17:02:02 +02:00
kijai 0613a9239f version 1.0.3 2026-02-04 16:55:13 +02:00
kijai 4ebf22bc2c Some cleanup 2026-02-04 16:53:20 +02:00
Jukka Seppänen 6e972b1f60 Merge pull request #174 from ComfyNodePRs/update-publish-yaml
Update Github Action for Publishing to Comfy Registry
2026-02-04 16:49:40 +02:00
Jukka Seppänen 30aac9a766 Merge pull request #177 from hj-desperado/main
Add dtype selection in decoder, aligning with encoder
2026-02-04 16:48:18 +02:00
kijai 159995e440 Fix for newer ComfyUI version 2026-02-04 16:47:23 +02:00
Jukka Seppänen 0311fb8e79 Merge pull request #199 from jorismak/feature/fix-sm12
fallback for xformers (fixes SM12)
2026-02-04 16:46:18 +02:00
Joris Mak a9c2fc4115 cleanup try/catch location 2026-01-11 14:28:39 +01:00
Joris Mak 1caaaa50d9 Implement fallback for memory-efficient attention in xformer_attn_forward 2026-01-11 14:14:05 +01:00
kijai c5cb1ce099 Update requirements.txt 2025-09-24 16:51:11 +03:00
kijai 6fe7a3f856 bump version 2025-06-07 12:17:40 +03:00
kijai 29f2e8be0e Possible workaround for import issue in some configurations 2025-04-14 01:52:00 +03:00
jianghan01 a132c748ad Add dtype selection in decoder, aligning with encoder 2025-04-02 17:04:19 +08:00
snomiao d5b69963db chore(publish): update GitHub Actions workflow for node publishing
- Add permissions for issue writing
- Update action version to v1 for publish-node-action
- Add condition to run job only for 'kijai' repository owner
2025-01-20 21:36:40 +00:00
kijai 53fc4f82f1 clean some unnecessary dependencies 2024-07-07 02:44:51 +03:00
kijai 0597c9cdb6 Update pyproject.toml 2024-07-06 12:23:56 +03:00
kijai 59ca341c0a workaround for open-clip-torch update
fixes the attn_mask shape error
2024-07-06 12:22:30 +03:00
kijai a8780cd188 use more comfy ops 2024-07-06 12:20:21 +03:00
Jukka Seppänen 2726b6ef34 Update requirements.txt 2024-07-06 11:52:45 +03:00
kijai 006754633a Support SDXL latents directly
Bypassing need for SUPIR VAE
2024-06-27 16:40:45 +03:00
Jukka Seppänen c257cce555 Merge pull request #124 from haohaocreates/publish
Add Github Action for Publishing to Comfy Registry
2024-06-27 12:29:20 +03:00
kijai eda2cf504a Update pyproject.toml 2024-06-27 12:28:18 +03:00
Jukka Seppänen e1770b002a Merge pull request #125 from haohaocreates/pyproject
Add pyproject.toml for Custom Node Registry
2024-06-27 12:27:28 +03:00
haohaocreates 3320502310 Update pyproject.toml description 2024-05-21 10:56:33 -04:00
haohaocreates 91893f123d chore(pyproject): Add pyproject.toml for Custom Node Registry 2024-05-21 14:46:39 +00:00
haohaocreates 1db91b1510 chore(publish): Add Github Action for Publishing to Comfy Registry 2024-05-21 14:46:38 +00:00
kijai bbb2bd7e8f Add version of the loader node to load CLIP separately 2024-05-20 11:12:07 +03:00
Kijai 5518e00a14 Remove redundant req 2024-04-23 13:04:10 +03:00
kijai 656e55e815 accelerate fixes 2024-04-14 11:27:17 +03:00
kijai c97893850e Make accelerate model loading target choseable 2024-04-14 02:01:54 +03:00
kijai 7596566a89 Accelerate 2024-04-13 17:48:47 +03:00
kijai 49afedaddd Description for sampler 2024-04-08 21:10:46 +03:00
kijai 3a911c0cbd Merge branch 'main' of https://github.com/kijai/ComfyUI-SUPIR 2024-04-07 02:43:25 +03:00
kijai 84e67594d0 Initial DESCRIPTIONs 2024-04-07 02:43:23 +03:00
Jukka Seppänen 472dbce4dc Update README.md 2024-04-07 02:34:15 +03:00
kijai d20c5190a1 Update nodes_v2.py 2024-04-05 10:59:10 +03:00
kijai 30f60a3b03 clip decode on gpu 2024-04-05 10:51:32 +03:00
Jukka Seppänen e62f3c5dac Create LICENSE 2024-03-30 00:29:23 +02:00
Jukka Seppänen 91ecd6f8de Delete LICENSE 2024-03-30 00:28:57 +02:00
Jukka Seppänen ba7fceeaac Update LICENSE 2024-03-30 00:28:33 +02:00
kijai 2ce3ced581 Tiled sampler consequential runs workaround
Copy the conds so they are not permanently modified by the Tiled samplers
2024-03-26 10:34:17 +02:00
Kijai 3f340a6b96 update example 2024-03-25 18:12:55 +02:00
Kijai 203bc93933 Update nodes_v2.py 2024-03-25 18:06:11 +02:00
Kijai eb7d1e31ae Update nodes_v2.py 2024-03-25 17:54:24 +02:00
Kijai 61cbb153e6 Update nodes_v2.py 2024-03-25 17:47:48 +02:00
kijai 5c54bb1437 Better xformers check
Now relies in the comfy xformers check and can thus be disabled with the command line argument --disable-xformers
2024-03-25 10:46:36 +02:00
kijai 2cd64cdfce cleanup 2024-03-25 10:17:45 +02:00
kijai 80d20731a4 Update nodes_v2.py 2024-03-25 01:29:31 +02:00
kijai dced82b070 Smarter model loading and support comfy latents
- Less spiky memory usage when using v2 model loader node
- Support latents from other comfy nodes, when using latents from SUPIR nodes the behaviour is same as before: fully random noise
2024-03-24 15:45:10 +02:00
kijai e933093166 fix decoder dtype 2024-03-22 08:48:48 +02:00
kijai fb6f99e7d5 clip decoder output 2024-03-22 08:37:04 +02:00
Jukka Seppänen 4a10dd4da5 Update README.md 2024-03-22 00:40:05 +02:00
kijai adc82313eb Make model loader node without sdxl_model selection for clarity 2024-03-22 00:37:21 +02:00
Kijai 61942e250c Support using comfy model loading, including loras
These inputs are optional, when used the sdxl_model dropdown is ignored, I don't want to remove it as of yet as it would break old workflows.
2024-03-21 16:06:08 +02:00
Kijai 98291ac559 Update nodes_v2.py 2024-03-20 18:45:46 +02:00
Kijai d7ab37bed0 Update nodes_v2.py 2024-03-20 18:42:47 +02:00
Kijai 14480f926a Default to fp16 unet with 'auto' 2024-03-19 16:25:54 +02:00
kijai dbc22b88fb batch fixes 2024-03-19 11:02:54 +02:00
kijai 734054ea64 Update nodes_v2.py 2024-03-19 10:19:32 +02:00
Kijai e460953d7c Fix resize and batch captioning 2024-03-18 17:44:14 +02:00
Kijai 033f83ad17 Batch support for video 2024-03-18 16:49:57 +02:00
kijai 2bd6421b6f Flip cfg linear scale behaviour for v2 sampler
Makes more sense to me, scales cfg linearly from cfg_scale_start at first step to  cfg_scale_end at last
2024-03-18 01:48:19 +02:00
kijai b887b9e4be clean prints 2024-03-17 17:55:24 +02:00
kijai 166b5920d3 fix rescaling (again) 2024-03-17 17:50:58 +02:00
kijai 714256e04a Merge branch 'main' of https://github.com/kijai/ComfyUI-SUPIR 2024-03-17 16:39:22 +02:00
kijai 092c6b81dc ignore eta setting for EDM samplers 2024-03-17 16:39:20 +02:00
Jukka Seppänen a766cb0a9f Update README.md 2024-03-17 15:36:21 +02:00
kijai 747f07b99d Big update: Add v2 nodes
Separate the process to multiple nodes for efficiency and better understanding of the process.
2024-03-17 14:03:11 +02:00
kijai 2d1ecb1bf0 Revert resize method 2024-03-11 23:12:00 +02:00
kijai bda46b35b5 fix autoresize 2024-03-11 21:56:43 +02:00
kijai 8341b91e66 Update readme 2024-03-11 09:44:00 +02:00
kijai 8a4beaa547 Fix tiled sampling 2024-03-11 09:31:27 +02:00
kijai aadedb1d29 clean up 2024-03-10 14:59:56 +02:00
kijai c1e8bc5f80 Add RestoreDPMPP2MSampler
Better suited for lightning models
2024-03-10 14:25:50 +02:00
kijai e0324bed08 Merge branch 'main' of https://github.com/kijai/ComfyUI-SUPIR 2024-03-09 17:15:20 +02:00
kijai 24103daee0 Update nodes.py 2024-03-09 17:15:12 +02:00
Jukka Seppänen c5d1e1bebc Update README.md 2024-03-09 17:08:25 +02:00
Jukka Seppänen 78e947e7db Update README.md 2024-03-09 17:07:25 +02:00
kijai 35ba391507 Choice to use fp8 for unet and vae
Experimental, seems to work for saving memory, but there's a quality hit
2024-03-09 16:58:59 +02:00
kijai 763ab95734 Add some cpu offloading 2024-03-09 12:53:50 +02:00
23 changed files with 2804 additions and 902 deletions
+25
View File
@@ -0,0 +1,25 @@
name: Publish to Comfy registry
on:
workflow_dispatch:
push:
branches:
- main
paths:
- "pyproject.toml"
permissions:
issues: write
jobs:
publish-node:
name: Publish Custom Node to registry
runs-on: ubuntu-latest
if: ${{ github.repository_owner == 'kijai' }}
steps:
- name: Check out code
uses: actions/checkout@v4
- name: Publish Custom Node
uses: Comfy-Org/publish-node-action@v1
with:
## Add your own personal access token to your Github Repository secrets and reference it here.
personal_access_token: ${{ secrets.REGISTRY_ACCESS_TOKEN }}
+7 -668
View File
@@ -1,674 +1,13 @@
GNU GENERAL PUBLIC LICENSE License
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/> Copyright (c) 2024 XPixel Group, Especially the author team of SUPIR.
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble The SUPIR ("Software") is made available for use, reproduction, and distribution strictly for non-commercial purposes. For the purposes of this declaration, "non-commercial" is defined as not primarily intended for or directed towards commercial advantage or monetary compensation.
The GNU General Public License is a free, copyleft license for By using, reproducing, or distributing the Software, you agree to abide by this restriction and not to use the Software for any commercial purposes without obtaining prior written permission from Dr. Jinjin Gu.
software and other kinds of works.
The licenses for most software and other practical works are designed This declaration does not in any way limit the rights under any open source license that may apply to the Software; it solely adds a condition that the Software shall not be used for commercial purposes.
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you For inquiries or to obtain permission for commercial use, please contact Dr. Jinjin Gu (jinjin.gu@suppixel.ai).
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.
+28 -2
View File
@@ -1,7 +1,29 @@
# ComfyUI SUPIR upscaler wrapper node # ComfyUI SUPIR upscaler wrapper node
## WORK IN PROGRESS # FINAL update
![image](https://github.com/kijai/ComfyUI-SUPIR/assets/40791699/887898d3-afe5-45d1-be08-50f6620b70eb)
SUPIR is now available to use in ComfyUI core after this PR:
https://github.com/Comfy-Org/ComfyUI/pull/13250
These nodes won't be updated beyond simple breaking bugfixes.
# UPDATE3:
Pruned models in safetensors format now available here:
https://huggingface.co/Kijai/SUPIR_pruned/tree/main
# UPDATE2:
![image](https://github.com/kijai/ComfyUI-SUPIR/assets/40791699/65baec3e-cb4a-4eec-8d45-2b08157b1e86)
Added a better way to load the SDXL model, which also allows using LoRAs. The old node will remain for now to not break old workflows, and it is dubbed Legacy along with the single node, as I do not want to maintain those.
# UPDATE:
As I have learned a lot with this project, I have now separated the single node to multiple nodes that make more sense to use in ComfyUI, and makes it clearer how SUPIR works. This is still a wrapper, though the whole thing has deviated from the original with much wider hardware support, more efficient model loading, far less memory usage and more sampler options. Here's a quick example (workflow is included) of using a Ligntning model, quality suffers then but it's very fast and I recommend starting with it as faster sampling makes it a lot easier to learn what the settings do.
Under the hood SUPIR is SDXL img2img pipeline, the biggest custom part being their ControlNet. What they call "first stage" is a denoising process using their special "denoise encoder" VAE. This is not to be confused with the Gradio demo's "first stage" that's labeled as such for the Llava preprocessing, the Gradio "Stage2" still runs the denoising process anyway. This can be fully skipped with the nodes, or replaced with any other preprocessing node such as a model upscaler or anything you want.
https://github.com/kijai/ComfyUI-SUPIR/assets/40791699/5cae2a24-d425-462c-b89d-df7dcf01595c
# Installing # Installing
Either manager and install from git, or clone this repo to custom_nodes and run: Either manager and install from git, or clone this repo to custom_nodes and run:
@@ -25,6 +47,10 @@ I have not included llava in this, but you can input any captions to the node an
Memory requirements are directly related to the input image resolution, the "scale_by" in the node simply scales the input, you can leave it at 1.0 and size your input with any other node as well. In my testing I was able to run 512x512 to 1024x1024 with a 10GB 3080 GPU, and other tests on 24GB GPU to up 3072x3072. System RAM requirements are also hefty, don't know numbers but I would guess under 32GB is going to have issues, tested with 64GB. Memory requirements are directly related to the input image resolution, the "scale_by" in the node simply scales the input, you can leave it at 1.0 and size your input with any other node as well. In my testing I was able to run 512x512 to 1024x1024 with a 10GB 3080 GPU, and other tests on 24GB GPU to up 3072x3072. System RAM requirements are also hefty, don't know numbers but I would guess under 32GB is going to have issues, tested with 64GB.
## Updates:
- fp8 seems to work fine for the unet, I was able to do 512p to 2048 with under 10GB VRAM used. For the VAE it seems to cause artifacts, I recommend using tiled_vae instead.
- CLIP models are no longer needed separately, instead they are loaded from your selected SDXL checkpoint
______
Mirror for the models: https://huggingface.co/camenduru/SUPIR/tree/main Mirror for the models: https://huggingface.co/camenduru/SUPIR/tree/main
# Tests # Tests
+29 -37
View File
@@ -7,6 +7,7 @@ import random
from ...SUPIR.utils.colorfix import wavelet_reconstruction, adaptive_instance_normalization from ...SUPIR.utils.colorfix import wavelet_reconstruction, adaptive_instance_normalization
from pytorch_lightning import seed_everything from pytorch_lightning import seed_everything
from ...SUPIR.utils.tilevae import VAEHook from ...SUPIR.utils.tilevae import VAEHook
from ...SUPIR.util import convert_dtype
from contextlib import nullcontext from contextlib import nullcontext
import comfy.model_management import comfy.model_management
@@ -20,23 +21,8 @@ class SUPIRModel(DiffusionEngine):
self.first_stage_model.denoise_encoder = copy.deepcopy(self.first_stage_model.encoder) self.first_stage_model.denoise_encoder = copy.deepcopy(self.first_stage_model.encoder)
self.sampler_config = kwargs['sampler_config'] self.sampler_config = kwargs['sampler_config']
assert (ae_dtype in ['fp32', 'fp16', 'bf16']) and (diffusion_dtype in ['fp32', 'fp16', 'bf16']) self.ae_dtype = convert_dtype(ae_dtype)
if ae_dtype == 'fp32': self.model.dtype = convert_dtype(diffusion_dtype)
ae_dtype = torch.float32
elif ae_dtype == 'fp16':
raise RuntimeError('fp16 cause NaN in AE')
elif ae_dtype == 'bf16':
ae_dtype = torch.bfloat16
if diffusion_dtype == 'fp32':
diffusion_dtype = torch.float32
elif diffusion_dtype == 'fp16':
diffusion_dtype = torch.float16
elif diffusion_dtype == 'bf16':
diffusion_dtype = torch.bfloat16
self.ae_dtype = ae_dtype
self.model.dtype = diffusion_dtype
self.p_p = p_p self.p_p = p_p
self.n_p = n_p self.n_p = n_p
@@ -72,7 +58,6 @@ class SUPIRModel(DiffusionEngine):
@torch.no_grad() @torch.no_grad()
def decode_first_stage(self, z): def decode_first_stage(self, z):
z = 1.0 / self.scale_factor * z z = 1.0 / self.scale_factor * z
#with torch.autocast(device, dtype=self.ae_dtype):
autocast_condition = (self.ae_dtype == torch.float16 or self.ae_dtype == torch.bfloat16) and not comfy.model_management.is_device_mps(device) autocast_condition = (self.ae_dtype == torch.float16 or self.ae_dtype == torch.bfloat16) and not comfy.model_management.is_device_mps(device)
with torch.autocast(comfy.model_management.get_autocast_device(device), dtype=self.ae_dtype) if autocast_condition else nullcontext(): with torch.autocast(comfy.model_management.get_autocast_device(device), dtype=self.ae_dtype) if autocast_condition else nullcontext():
out = self.first_stage_model.decode(z) out = self.first_stage_model.decode(z)
@@ -120,29 +105,51 @@ class SUPIRModel(DiffusionEngine):
self.sampler_config.params.s_noise = s_noise self.sampler_config.params.s_noise = s_noise
self.sampler = instantiate_from_config(self.sampler_config) self.sampler = instantiate_from_config(self.sampler_config)
print("Sampler: ", self.sampler_config.target)
print("sampler_config: ", self.sampler_config.params) print("sampler_config: ", self.sampler_config.params)
if seed == -1: if seed == -1:
seed = random.randint(0, 65535) seed = random.randint(0, 65535)
seed_everything(seed) seed_everything(seed)
self.model.to('cpu')
self.conditioner.to('cpu')
# stage 1: encode/decode/encode
self.first_stage_model.to(device)
_z = self.encode_first_stage_with_denoise(x, use_sample=False) _z = self.encode_first_stage_with_denoise(x, use_sample=False)
x_stage1 = self.decode_first_stage(_z) x_stage1 = self.decode_first_stage(_z)
z_stage1 = self.encode_first_stage(x_stage1) z_stage1 = self.encode_first_stage(x_stage1)
self.first_stage_model.to('cpu')
#conditioning
self.conditioner.to(device)
c, uc = self.prepare_condition(_z, p, p_p, n_p, N) c, uc = self.prepare_condition(_z, p, p_p, n_p, N)
self.conditioner.to('cpu')
denoiser = lambda input, sigma, c, control_scale: self.denoiser( denoiser = lambda input, sigma, c, control_scale: self.denoiser(
self.model, input, sigma, c, control_scale, **kwargs self.model, input, sigma, c, control_scale, **kwargs
) )
noised_z = torch.randn_like(_z).to(_z.device) noised_z = torch.randn_like(_z).to(_z.device)
comfy.model_management.soft_empty_cache()
#sampling
self.model.diffusion_model.to(device)
self.model.control_model.to(device)
self.denoiser.to(device)
_samples = self.sampler(denoiser, noised_z, cond=c, uc=uc, x_center=z_stage1, control_scale=control_scale, _samples = self.sampler(denoiser, noised_z, cond=c, uc=uc, x_center=z_stage1, control_scale=control_scale,
use_linear_control_scale=use_linear_control_scale, control_scale_start=control_scale_start) use_linear_control_scale=use_linear_control_scale, control_scale_start=control_scale_start)
self.model.diffusion_model.to('cpu')
self.model.control_model.to('cpu')
#decoding
self.first_stage_model.to(device)
samples = self.decode_first_stage(_samples) samples = self.decode_first_stage(_samples)
self.first_stage_model.to('cpu')
if color_fix_type == 'Wavelet': if color_fix_type == 'Wavelet':
samples = wavelet_reconstruction(samples, x_stage1) samples = wavelet_reconstruction(samples, x_stage1)
elif color_fix_type == 'AdaIn': elif color_fix_type == 'AdaIn':
@@ -193,19 +200,4 @@ class SUPIRModel(DiffusionEngine):
else: else:
_c, _ = self.conditioner.get_unconditional_conditioning(batch, None) _c, _ = self.conditioner.get_unconditional_conditioning(batch, None)
c.append(_c) c.append(_c)
return c, uc return c, uc
# if __name__ == '__main__':
# from SUPIR.util import create_model, load_state_dict
# model = create_model('../../options/dev/SUPIR_paper_version.yaml')
# SDXL_CKPT = '/opt/data/private/AIGC_pretrain/SDXL_cache/sd_xl_base_1.0_0.9vae.safetensors'
# SUPIR_CKPT = '/opt/data/private/AIGC_pretrain/SUPIR_cache/SUPIR-paper.ckpt'
# model.load_state_dict(load_state_dict(SDXL_CKPT), strict=False)
# model.load_state_dict(load_state_dict(SUPIR_CKPT), strict=False)
# model = model.cuda()
# x = torch.randn(1, 3, 512, 512).cuda()
# p = ['a professional, detailed, high-quality photo']
# samples = model.batchify_sample(x, p, num_steps=50, restoration_scale=4.0, s_churn=0, cfg_scale=4.0, seed=-1, num_samples=1)
+11
View File
@@ -0,0 +1,11 @@
from ...sgm.models.diffusion import DiffusionEngine
from ...sgm.util import instantiate_from_config
import copy
class SUPIRModel(DiffusionEngine):
def __init__(self, control_stage_config, ae_dtype='fp32', diffusion_dtype='fp32', p_p='', n_p='', *args, **kwargs):
super().__init__(*args, **kwargs)
control_model = instantiate_from_config(control_stage_config)
self.model.load_control_model(control_model)
self.first_stage_model.denoise_encoder = copy.deepcopy(self.first_stage_model.encoder)
self.sampler_config = kwargs['sampler_config']
+9 -6
View File
@@ -27,6 +27,9 @@ from functools import partial
import comfy.model_management import comfy.model_management
device = comfy.model_management.get_torch_device() device = comfy.model_management.get_torch_device()
import comfy.ops
ops = comfy.ops.manual_cast
try: try:
import xformers import xformers
import xformers.ops import xformers.ops
@@ -77,13 +80,13 @@ class ZeroSFT(nn.Module):
nhidden = 128 nhidden = 128
self.mlp_shared = nn.Sequential( self.mlp_shared = nn.Sequential(
nn.Conv2d(label_nc, nhidden, kernel_size=ks, padding=pw), ops.Conv2d(label_nc, nhidden, kernel_size=ks, padding=pw),
nn.SiLU() nn.SiLU()
) )
self.zero_mul = zero_module(nn.Conv2d(nhidden, norm_nc + concat_channels, kernel_size=ks, padding=pw)) self.zero_mul = zero_module(ops.Conv2d(nhidden, norm_nc + concat_channels, kernel_size=ks, padding=pw))
self.zero_add = zero_module(nn.Conv2d(nhidden, norm_nc + concat_channels, kernel_size=ks, padding=pw)) self.zero_add = zero_module(ops.Conv2d(nhidden, norm_nc + concat_channels, kernel_size=ks, padding=pw))
# self.zero_mul = nn.Conv2d(nhidden, norm_nc + concat_channels, kernel_size=ks, padding=pw) # self.zero_mul = ops.Conv2d(nhidden, norm_nc + concat_channels, kernel_size=ks, padding=pw)
# self.zero_add = nn.Conv2d(nhidden, norm_nc + concat_channels, kernel_size=ks, padding=pw) # self.zero_add = ops.Conv2d(nhidden, norm_nc + concat_channels, kernel_size=ks, padding=pw)
self.zero_conv = zero_module(conv_nd(2, label_nc, norm_nc, 1, 1, 0)) self.zero_conv = zero_module(conv_nd(2, label_nc, norm_nc, 1, 1, 0))
self.pre_concat = bool(concat_channels != 0) self.pre_concat = bool(concat_channels != 0)
@@ -296,7 +299,7 @@ class GLVControl(nn.Module):
self.label_emb = nn.Embedding(num_classes, time_embed_dim) self.label_emb = nn.Embedding(num_classes, time_embed_dim)
elif self.num_classes == "continuous": elif self.num_classes == "continuous":
print("setting up linear c_adm embedding layer") print("setting up linear c_adm embedding layer")
self.label_emb = nn.Linear(1, time_embed_dim) self.label_emb = ops.Linear(1, time_embed_dim)
elif self.num_classes == "timestep": elif self.num_classes == "timestep":
self.label_emb = checkpoint_wrapper_fn( self.label_emb = checkpoint_wrapper_fn(
nn.Sequential( nn.Sequential(
+19 -12
View File
@@ -66,20 +66,20 @@ import torch
import torch.version import torch.version
import torch.nn.functional as F import torch.nn.functional as F
from einops import rearrange from einops import rearrange
#from diffusers.utils.import_utils import is_xformers_available
#import SUPIR.utils.devices as devices
import comfy.model_management import comfy.model_management
device = comfy.model_management.get_torch_device() device = comfy.model_management.get_torch_device()
try: if comfy.model_management.XFORMERS_IS_AVAILABLE:
import xformers try:
import xformers.ops import xformers
XFORMERS_IS_AVAILABLE = True import xformers.ops
except: XFORMERS_IS_AVAILABLE = True
except:
XFORMERS_IS_AVAILABLE = False
print("no module 'xformers'. Processing without...")
else:
XFORMERS_IS_AVAILABLE = False XFORMERS_IS_AVAILABLE = False
print("no module 'xformers'. Processing without...")
sd_flag = True sd_flag = True
@@ -368,8 +368,14 @@ def attn2task(task_queue, net):
task_queue.append(('pre_norm', net.norm)) task_queue.append(('pre_norm', net.norm))
if XFORMERS_IS_AVAILABLE: if XFORMERS_IS_AVAILABLE:
# task_queue.append(('attn', lambda x, net=net: attn_forward_new_xformers(net, x))) # task_queue.append(('attn', lambda x, net=net: attn_forward_new_xformers(net, x)))
task_queue.append( # Wrap xformer call with fallback to standard attention on NotImplementedError
('attn', lambda x, net=net: xformer_attn_forward(net, x))) # (e.g., new GPU architectures or unsupported dimensions)
def xformer_with_fallback(x, net=net):
try:
return xformer_attn_forward(net, x)
except NotImplementedError:
return attn_forward(net, x)
task_queue.append(('attn', xformer_with_fallback))
elif hasattr(F, "scaled_dot_product_attention"): elif hasattr(F, "scaled_dot_product_attention"):
task_queue.append(('attn', lambda x, net=net: attn_forward(net, x))) task_queue.append(('attn', lambda x, net=net: attn_forward(net, x)))
#task_queue.append(('attn', lambda x, net=net: attn_forward_new_pt2_0(net, x))) #task_queue.append(('attn', lambda x, net=net: attn_forward_new_pt2_0(net, x)))
@@ -895,7 +901,7 @@ class VAEHook:
# Task queue execution # Task queue execution
pbar = tqdm(total=num_tiles * len(task_queues[0]), desc=f"[Tiled VAE]: Executing {'Decoder' if is_decoder else 'Encoder'} Task Queue: ") pbar = tqdm(total=num_tiles * len(task_queues[0]), desc=f"[Tiled VAE]: Executing {'Decoder' if is_decoder else 'Encoder'} Task Queue: ")
pbar_comfy = comfy.utils.ProgressBar(num_tiles * len(task_queues[0]))
# execute the task back and forth when switch tiles so that we always # execute the task back and forth when switch tiles so that we always
# keep one tile on the GPU to reduce unnecessary data transfer # keep one tile on the GPU to reduce unnecessary data transfer
forward = True forward = True
@@ -937,6 +943,7 @@ class VAEHook:
tile = task[1](tile) tile = task[1](tile)
#print(tiles[i].shape, tile.shape, task) #print(tiles[i].shape, tile.shape, task)
pbar.update(1) pbar.update(1)
pbar_comfy.update(1)
if interrupted: break if interrupted: break
+26 -1
View File
@@ -1,3 +1,28 @@
from .nodes import NODE_CLASS_MAPPINGS, NODE_DISPLAY_NAME_MAPPINGS from .nodes import SUPIR_Upscale
from .nodes_v2 import SUPIR_sample, SUPIR_model_loader, SUPIR_first_stage, SUPIR_encode, SUPIR_decode, SUPIR_conditioner, SUPIR_tiles, SUPIR_model_loader_v2, SUPIR_model_loader_v2_clip
NODE_CLASS_MAPPINGS = {
"SUPIR_Upscale": SUPIR_Upscale,
"SUPIR_sample": SUPIR_sample,
"SUPIR_model_loader": SUPIR_model_loader,
"SUPIR_first_stage": SUPIR_first_stage,
"SUPIR_encode": SUPIR_encode,
"SUPIR_decode": SUPIR_decode,
"SUPIR_conditioner": SUPIR_conditioner,
"SUPIR_tiles": SUPIR_tiles,
"SUPIR_model_loader_v2": SUPIR_model_loader_v2,
"SUPIR_model_loader_v2_clip": SUPIR_model_loader_v2_clip
}
NODE_DISPLAY_NAME_MAPPINGS = {
"SUPIR_Upscale": "SUPIR Upscale (Legacy)",
"SUPIR_sample": "SUPIR Sampler",
"SUPIR_model_loader": "SUPIR Model Loader (Legacy)",
"SUPIR_first_stage": "SUPIR First Stage (Denoiser)",
"SUPIR_encode": "SUPIR Encode",
"SUPIR_decode": "SUPIR Decode",
"SUPIR_conditioner": "SUPIR Conditioner",
"SUPIR_tiles": "SUPIR Tiles Preview",
"SUPIR_model_loader_v2": "SUPIR Model Loader (v2)",
"SUPIR_model_loader_v2_clip": "SUPIR Model Loader (v2) (Clip)"
}
__all__ = ["NODE_CLASS_MAPPINGS", "NODE_DISPLAY_NAME_MAPPINGS"] __all__ = ["NODE_CLASS_MAPPINGS", "NODE_DISPLAY_NAME_MAPPINGS"]
File diff suppressed because it is too large Load Diff
+62 -51
View File
@@ -1,8 +1,6 @@
import os import os
import torch import torch
import torch.nn as nn
from torch.nn import functional as F from torch.nn import functional as F
from contextlib import nullcontext
from omegaconf import OmegaConf from omegaconf import OmegaConf
import comfy.utils import comfy.utils
import comfy.model_management as mm import comfy.model_management as mm
@@ -13,6 +11,7 @@ import torch.cuda
from .sgm.util import instantiate_from_config from .sgm.util import instantiate_from_config
from .SUPIR.util import convert_dtype, load_state_dict from .SUPIR.util import convert_dtype, load_state_dict
import open_clip import open_clip
from contextlib import contextmanager
from transformers import ( from transformers import (
CLIPTextModel, CLIPTextModel,
@@ -22,24 +21,24 @@ from transformers import (
) )
script_directory = os.path.dirname(os.path.abspath(__file__)) script_directory = os.path.dirname(os.path.abspath(__file__))
try:
import xformers
import xformers.ops
XFORMERS_IS_AVAILABLE = True
except:
XFORMERS_IS_AVAILABLE = False
def dummy_build_vision_tower(*args, **kwargs): def dummy_build_vision_tower(*args, **kwargs):
# Monkey patch the CLIP class before you create an instance. # Monkey patch the CLIP class before you create an instance.
return None return None
open_clip.model._build_vision_tower = dummy_build_vision_tower
@contextmanager
def patch_build_vision_tower():
original_build_vision_tower = open_clip.model._build_vision_tower
open_clip.model._build_vision_tower = dummy_build_vision_tower
try:
yield
finally:
open_clip.model._build_vision_tower = original_build_vision_tower
def build_text_model_from_openai_state_dict( def build_text_model_from_openai_state_dict(
state_dict: dict, state_dict: dict,
cast_dtype=torch.float16, cast_dtype=torch.float16,
): ):
embed_dim = state_dict["text_projection"].shape[1] embed_dim = state_dict["text_projection"].shape[1]
context_length = state_dict["positional_embedding"].shape[0] context_length = state_dict["positional_embedding"].shape[0]
@@ -56,13 +55,15 @@ def build_text_model_from_openai_state_dict(
heads=transformer_heads, heads=transformer_heads,
layers=transformer_layers, layers=transformer_layers,
) )
model = open_clip.CLIP(
embed_dim, with patch_build_vision_tower():
vision_cfg=vision_cfg, model = open_clip.CLIP(
text_cfg=text_cfg, embed_dim,
quick_gelu=True, # OpenAI models were trained with QuickGELU vision_cfg=vision_cfg,
cast_dtype=cast_dtype, text_cfg=text_cfg,
) quick_gelu=True,
cast_dtype=cast_dtype,
)
model.load_state_dict(state_dict, strict=False) model.load_state_dict(state_dict, strict=False)
model = model.eval() model = model.eval()
@@ -84,13 +85,13 @@ class SUPIR_Upscale:
"scale_by": ("FLOAT", {"default": 1.0, "min": 0.01, "max": 20.0, "step": 0.01}), "scale_by": ("FLOAT", {"default": 1.0, "min": 0.01, "max": 20.0, "step": 0.01}),
"steps": ("INT", {"default": 45, "min": 3, "max": 4096, "step": 1}), "steps": ("INT", {"default": 45, "min": 3, "max": 4096, "step": 1}),
"restoration_scale": ("FLOAT", {"default": -1.0, "min": -1.0, "max": 6.0, "step": 1.0}), "restoration_scale": ("FLOAT", {"default": -1.0, "min": -1.0, "max": 6.0, "step": 1.0}),
"cfg_scale": ("FLOAT", {"default": 4.0, "min": 0, "max": 20, "step": 0.01}), "cfg_scale": ("FLOAT", {"default": 4.0, "min": 0, "max": 100, "step": 0.01}),
"a_prompt": ("STRING", {"multiline": True, "default": "high quality, detailed", }), "a_prompt": ("STRING", {"multiline": True, "default": "high quality, detailed", }),
"n_prompt": ("STRING", {"multiline": True, "default": "bad quality, blurry, messy", }), "n_prompt": ("STRING", {"multiline": True, "default": "bad quality, blurry, messy", }),
"s_churn": ("INT", {"default": 5, "min": 0, "max": 40, "step": 1}), "s_churn": ("INT", {"default": 5, "min": 0, "max": 40, "step": 1}),
"s_noise": ("FLOAT", {"default": 1.003, "min": 1.0, "max": 1.1, "step": 0.001}), "s_noise": ("FLOAT", {"default": 1.003, "min": 1.0, "max": 1.1, "step": 0.001}),
"control_scale": ("FLOAT", {"default": 1.0, "min": 0, "max": 10.0, "step": 0.05}), "control_scale": ("FLOAT", {"default": 1.0, "min": 0, "max": 10.0, "step": 0.05}),
"cfg_scale_start": ("FLOAT", {"default": 4.0, "min": 0.0, "max": 9.0, "step": 0.05}), "cfg_scale_start": ("FLOAT", {"default": 4.0, "min": 0.0, "max": 100.0, "step": 0.05}),
"control_scale_start": ("FLOAT", {"default": 0.0, "min": 0, "max": 1.0, "step": 0.05}), "control_scale_start": ("FLOAT", {"default": 0.0, "min": 0, "max": 1.0, "step": 0.05}),
"color_fix_type": ( "color_fix_type": (
[ [
@@ -128,6 +129,15 @@ class SUPIR_Upscale:
"use_tiled_sampling": ("BOOLEAN", {"default": False}), "use_tiled_sampling": ("BOOLEAN", {"default": False}),
"sampler_tile_size": ("INT", {"default": 1024, "min": 64, "max": 4096, "step": 32}), "sampler_tile_size": ("INT", {"default": 1024, "min": 64, "max": 4096, "step": 32}),
"sampler_tile_stride": ("INT", {"default": 512, "min": 32, "max": 2048, "step": 32}), "sampler_tile_stride": ("INT", {"default": 512, "min": 32, "max": 2048, "step": 32}),
"fp8_unet": ("BOOLEAN", {"default": False}),
"fp8_vae": ("BOOLEAN", {"default": False}),
"sampler": (
[
'RestoreDPMPP2MSampler',
'RestoreEDMSampler',
], {
"default": 'RestoreEDMSampler'
}),
} }
} }
@@ -141,7 +151,7 @@ class SUPIR_Upscale:
encoder_tile_size_pixels, decoder_tile_size_latent, encoder_tile_size_pixels, decoder_tile_size_latent,
control_scale, cfg_scale_start, control_scale_start, restoration_scale, keep_model_loaded, control_scale, cfg_scale_start, control_scale_start, restoration_scale, keep_model_loaded,
a_prompt, n_prompt, sdxl_model, supir_model, use_tiled_vae, use_tiled_sampling=False, sampler_tile_size=128, sampler_tile_stride=64, captions="", diffusion_dtype="auto", a_prompt, n_prompt, sdxl_model, supir_model, use_tiled_vae, use_tiled_sampling=False, sampler_tile_size=128, sampler_tile_stride=64, captions="", diffusion_dtype="auto",
encoder_dtype="auto", batch_size=1): encoder_dtype="auto", batch_size=1, fp8_unet=False, fp8_vae=False, sampler="RestoreEDMSampler"):
device = mm.get_torch_device() device = mm.get_torch_device()
mm.unload_all_models() mm.unload_all_models()
@@ -160,18 +170,21 @@ class SUPIR_Upscale:
'use_tiled_vae': use_tiled_vae, 'use_tiled_vae': use_tiled_vae,
'supir_model': supir_model, 'supir_model': supir_model,
'use_tiled_sampling': use_tiled_sampling, 'use_tiled_sampling': use_tiled_sampling,
'fp8_unet': fp8_unet,
'fp8_vae': fp8_vae,
'sampler': sampler
} }
if diffusion_dtype == 'auto': if diffusion_dtype == 'auto':
try: try:
if mm.should_use_fp16():
print("Diffusion using fp16")
dtype = torch.float16
model_dtype = 'fp16'
if mm.should_use_bf16(): if mm.should_use_bf16():
print("Diffusion using bf16") print("Diffusion using bf16")
dtype = torch.bfloat16 dtype = torch.bfloat16
model_dtype = 'bf16' model_dtype = 'bf16'
elif mm.should_use_fp16():
print("Diffusion using using fp16")
dtype = torch.float16
model_dtype = 'fp16'
else: else:
print("Diffusion using using fp32") print("Diffusion using using fp32")
dtype = torch.float32 dtype = torch.float32
@@ -207,19 +220,21 @@ class SUPIR_Upscale:
config = OmegaConf.load(config_path_tiled) config = OmegaConf.load(config_path_tiled)
config.model.params.sampler_config.params.tile_size = sampler_tile_size // 8 config.model.params.sampler_config.params.tile_size = sampler_tile_size // 8
config.model.params.sampler_config.params.tile_stride = sampler_tile_stride // 8 config.model.params.sampler_config.params.tile_stride = sampler_tile_stride // 8
config.model.params.sampler_config.target = f".sgm.modules.diffusionmodules.sampling.Tiled{sampler}"
print("Using tiled sampling") print("Using tiled sampling")
else: else:
config = OmegaConf.load(config_path) config = OmegaConf.load(config_path)
config.model.params.sampler_config.target = f".sgm.modules.diffusionmodules.sampling.{sampler}"
print("Using non-tiled sampling") print("Using non-tiled sampling")
if XFORMERS_IS_AVAILABLE: if mm.XFORMERS_IS_AVAILABLE:
config.model.params.control_stage_config.params.spatial_transformer_attn_type = "softmax-xformers" config.model.params.control_stage_config.params.spatial_transformer_attn_type = "softmax-xformers"
config.model.params.network_config.params.spatial_transformer_attn_type = "softmax-xformers" config.model.params.network_config.params.spatial_transformer_attn_type = "softmax-xformers"
config.model.params.first_stage_config.params.ddconfig.attn_type = "vanilla-xformers" config.model.params.first_stage_config.params.ddconfig.attn_type = "vanilla-xformers"
config.model.params.ae_dtype = vae_dtype config.model.params.ae_dtype = vae_dtype
config.model.params.diffusion_dtype = model_dtype config.model.params.diffusion_dtype = model_dtype
self.model = instantiate_from_config(config.model).cpu() self.model = instantiate_from_config(config.model).cpu()
try: try:
@@ -267,35 +282,30 @@ class SUPIR_Upscale:
clip_g = build_text_model_from_openai_state_dict(sd, cast_dtype=dtype) clip_g = build_text_model_from_openai_state_dict(sd, cast_dtype=dtype)
self.model.conditioner.embedders[1].model = clip_g self.model.conditioner.embedders[1].model = clip_g
except: except:
raise Exception("Failed to load second clip model from SDXL checkpoint") raise Exception("Failed to load second clip model from SDXL checkpoint")
del sd, clip_g del sd, clip_g
mm.soft_empty_cache() mm.soft_empty_cache()
try: self.model.to(dtype)
self.model.to(dtype)
self.model.to(device) #only unets and/or vae to fp8
except Exception as e: if fp8_unet:
print("Failed to move model to device") self.model.model.to(torch.float8_e4m3fn)
print(e) if fp8_vae:
import gc self.model.first_stage_model.to(torch.float8_e4m3fn)
# unload everything and give up
self.model = None
del self.model
gc.collect()
mm.soft_empty_cache()
if use_tiled_vae: if use_tiled_vae:
self.model.init_tile_vae(encoder_tile_size=encoder_tile_size_pixels, decoder_tile_size=decoder_tile_size_latent) self.model.init_tile_vae(encoder_tile_size=encoder_tile_size_pixels, decoder_tile_size=decoder_tile_size_latent)
image, = ImageScaleBy.upscale(self, image, resize_method, scale_by) upscaled_image, = ImageScaleBy.upscale(self, image, resize_method, scale_by)
B, H, W, C = image.shape B, H, W, C = upscaled_image.shape
new_height = H // 64 * 64 new_height = H if H % 64 == 0 else ((H // 64) + 1) * 64
new_width = W // 64 * 64 new_width = W if W % 64 == 0 else ((W // 64) + 1) * 64
image = image.permute(0, 3, 1, 2).contiguous() upscaled_image = upscaled_image.permute(0, 3, 1, 2)
resized_image = F.interpolate(image, size=(new_height, new_width), mode='bicubic', align_corners=False) resized_image = F.interpolate(upscaled_image, size=(new_height, new_width), mode='bicubic', align_corners=False)
resized_image = resized_image.to(device) resized_image = resized_image.to(device)
captions_list = [] captions_list = []
captions_list.append(captions) captions_list.append(captions)
print("captions: ", captions_list) print("captions: ", captions_list)
@@ -329,7 +339,8 @@ class SUPIR_Upscale:
self.model = None self.model = None
mm.soft_empty_cache() mm.soft_empty_cache()
print("It's likely that too large of an image or batch_size for SUPIR was used," print("It's likely that too large of an image or batch_size for SUPIR was used,"
" and it has devoured all of the memory it had reserved, you may need to restart ComfyUI") " and it has devoured all of the memory it had reserved, you may need to restart ComfyUI. Make sure you are using tiled_vae, "
" you can also try using fp8 for reduced memory usage if your system supports it.")
raise e raise e
out.append(samples.squeeze(0).cpu()) out.append(samples.squeeze(0).cpu())
@@ -345,7 +356,7 @@ class SUPIR_Upscale:
else: else:
out_stacked = torch.stack(out, dim=0).cpu().to(torch.float32).permute(0, 2, 3, 1) out_stacked = torch.stack(out, dim=0).cpu().to(torch.float32).permute(0, 2, 3, 1)
final_image, = ImageScale.upscale(self, out_stacked, "lanczos", W, H, crop="disabled") final_image, = ImageScale.upscale(self, out_stacked, resize_method, W, H, crop="disabled")
return (final_image,) return (final_image,)
@@ -354,4 +365,4 @@ NODE_CLASS_MAPPINGS = {
} }
NODE_DISPLAY_NAME_MAPPINGS = { NODE_DISPLAY_NAME_MAPPINGS = {
"SUPIR_Upscale": "SUPIR_Upscale" "SUPIR_Upscale": "SUPIR_Upscale"
} }
+1224
View File
File diff suppressed because it is too large Load Diff
+14
View File
@@ -0,0 +1,14 @@
[project]
name = "comfyui-supir"
description = "Wrapper nodes to use SUPIR upscaling process in ComfyUI"
version = "1.0.4"
license = { file = "LICENSE" }
dependencies = ["transformers>=4.28.1", "fsspec>=2023.4.0", "kornia>=0.6.9", "open-clip-torch>=2.24.0", "Pillow>=9.4.0", "pytorch-lightning>=2.2.1", "omegaconf", "accelerate"]
[project.urls]
Repository = "https://github.com/kijai/ComfyUI-SUPIR"
[tool.comfy]
PublisherId = "kijai"
DisplayName = "ComfyUI-SUPIR"
Icon = ""
+4 -6
View File
@@ -1,8 +1,6 @@
transformers>=4.28.1 transformers>=4.28.1
openai-clip>=1.0.1 open-clip-torch>=2.24.0
fsspec>=2023.4.0
kornia>=0.6.9
open-clip-torch>=2.17.1
Pillow>=9.4.0 Pillow>=9.4.0
pytorch-lightning==2.1.2 pytorch-lightning>=2.5.5
omegaconf omegaconf
accelerate
+4 -5
View File
@@ -14,9 +14,8 @@ from ..modules.distributions.distributions import DiagonalGaussianDistribution
from ..modules.ema import LitEma from ..modules.ema import LitEma
from ..util import default, get_obj_from_str, instantiate_from_config from ..util import default, get_obj_from_str, instantiate_from_config
class Conv2d(torch.nn.Conv2d): import comfy.ops
def reset_parameters(self): ops = comfy.ops.manual_cast
return None
class AbstractAutoencoder(pl.LightningModule): class AbstractAutoencoder(pl.LightningModule):
""" """
@@ -297,8 +296,8 @@ class AutoencoderKL(AutoencodingEngine):
assert ddconfig["double_z"] assert ddconfig["double_z"]
self.encoder = Encoder(**ddconfig) self.encoder = Encoder(**ddconfig)
self.decoder = Decoder(**ddconfig) self.decoder = Decoder(**ddconfig)
self.quant_conv = Conv2d(2 * ddconfig["z_channels"], 2 * embed_dim, 1) self.quant_conv = ops.Conv2d(2 * ddconfig["z_channels"], 2 * embed_dim, 1)
self.post_quant_conv = Conv2d(embed_dim, ddconfig["z_channels"], 1) self.post_quant_conv = ops.Conv2d(embed_dim, ddconfig["z_channels"], 1)
self.embed_dim = embed_dim self.embed_dim = embed_dim
if ckpt_path is not None: if ckpt_path is not None:
+32 -37
View File
@@ -10,13 +10,8 @@ from einops import rearrange, repeat
from packaging import version from packaging import version
from torch import nn from torch import nn
class Conv2d(torch.nn.Conv2d): import comfy.ops
def reset_parameters(self): ops = comfy.ops.manual_cast
return None
class Linear(torch.nn.Linear):
def reset_parameters(self):
return None
if version.parse(torch.__version__) >= version.parse("2.0.0"): if version.parse(torch.__version__) >= version.parse("2.0.0"):
SDP_IS_AVAILABLE = True SDP_IS_AVAILABLE = True
@@ -92,7 +87,7 @@ def init_(tensor):
class GEGLU(nn.Module): class GEGLU(nn.Module):
def __init__(self, dim_in, dim_out): def __init__(self, dim_in, dim_out):
super().__init__() super().__init__()
self.proj = Linear(dim_in, dim_out * 2) self.proj = ops.Linear(dim_in, dim_out * 2)
def forward(self, x): def forward(self, x):
x, gate = self.proj(x).chunk(2, dim=-1) x, gate = self.proj(x).chunk(2, dim=-1)
@@ -105,13 +100,13 @@ class FeedForward(nn.Module):
inner_dim = int(dim * mult) inner_dim = int(dim * mult)
dim_out = default(dim_out, dim) dim_out = default(dim_out, dim)
project_in = ( project_in = (
nn.Sequential(Linear(dim, inner_dim), nn.GELU()) nn.Sequential(ops.Linear(dim, inner_dim), nn.GELU())
if not glu if not glu
else GEGLU(dim, inner_dim) else GEGLU(dim, inner_dim)
) )
self.net = nn.Sequential( self.net = nn.Sequential(
project_in, nn.Dropout(dropout), Linear(inner_dim, dim_out) project_in, nn.Dropout(dropout), ops.Linear(inner_dim, dim_out)
) )
def forward(self, x): def forward(self, x):
@@ -128,7 +123,7 @@ def zero_module(module):
def Normalize(in_channels): def Normalize(in_channels):
return torch.nn.GroupNorm( return ops.GroupNorm(
num_groups=32, num_channels=in_channels, eps=1e-6, affine=True num_groups=32, num_channels=in_channels, eps=1e-6, affine=True
) )
@@ -138,8 +133,8 @@ class LinearAttention(nn.Module):
super().__init__() super().__init__()
self.heads = heads self.heads = heads
hidden_dim = dim_head * heads hidden_dim = dim_head * heads
self.to_qkv = Conv2d(dim, hidden_dim * 3, 1, bias=False) self.to_qkv = ops.Conv2d(dim, hidden_dim * 3, 1, bias=False)
self.to_out = Conv2d(hidden_dim, dim, 1) self.to_out = ops.Conv2d(hidden_dim, dim, 1)
def forward(self, x): def forward(self, x):
b, c, h, w = x.shape b, c, h, w = x.shape
@@ -162,16 +157,16 @@ class SpatialSelfAttention(nn.Module):
self.in_channels = in_channels self.in_channels = in_channels
self.norm = Normalize(in_channels) self.norm = Normalize(in_channels)
self.q = Conv2d( self.q = ops.Conv2d(
in_channels, in_channels, kernel_size=1, stride=1, padding=0 in_channels, in_channels, kernel_size=1, stride=1, padding=0
) )
self.k = Conv2d( self.k = ops.Conv2d(
in_channels, in_channels, kernel_size=1, stride=1, padding=0 in_channels, in_channels, kernel_size=1, stride=1, padding=0
) )
self.v = Conv2d( self.v = ops.Conv2d(
in_channels, in_channels, kernel_size=1, stride=1, padding=0 in_channels, in_channels, kernel_size=1, stride=1, padding=0
) )
self.proj_out = Conv2d( self.proj_out = ops.Conv2d(
in_channels, in_channels, kernel_size=1, stride=1, padding=0 in_channels, in_channels, kernel_size=1, stride=1, padding=0
) )
@@ -218,12 +213,12 @@ class CrossAttention(nn.Module):
self.scale = dim_head**-0.5 self.scale = dim_head**-0.5
self.heads = heads self.heads = heads
self.to_q = Linear(query_dim, inner_dim, bias=False) self.to_q = ops.Linear(query_dim, inner_dim, bias=False)
self.to_k = Linear(context_dim, inner_dim, bias=False) self.to_k = ops.Linear(context_dim, inner_dim, bias=False)
self.to_v = Linear(context_dim, inner_dim, bias=False) self.to_v = ops.Linear(context_dim, inner_dim, bias=False)
self.to_out = nn.Sequential( self.to_out = nn.Sequential(
Linear(inner_dim, query_dim), nn.Dropout(dropout) ops.Linear(inner_dim, query_dim), nn.Dropout(dropout)
) )
self.backend = backend self.backend = backend
@@ -309,12 +304,12 @@ class MemoryEfficientCrossAttention(nn.Module):
self.heads = heads self.heads = heads
self.dim_head = dim_head self.dim_head = dim_head
self.to_q = Linear(query_dim, inner_dim, bias=False) self.to_q = ops.Linear(query_dim, inner_dim, bias=False)
self.to_k = Linear(context_dim, inner_dim, bias=False) self.to_k = ops.Linear(context_dim, inner_dim, bias=False)
self.to_v = Linear(context_dim, inner_dim, bias=False) self.to_v = ops.Linear(context_dim, inner_dim, bias=False)
self.to_out = nn.Sequential( self.to_out = nn.Sequential(
Linear(inner_dim, query_dim), nn.Dropout(dropout) ops.Linear(inner_dim, query_dim), nn.Dropout(dropout)
) )
self.attention_op: Optional[Any] = None self.attention_op: Optional[Any] = None
@@ -442,9 +437,9 @@ class BasicTransformerBlock(nn.Module):
dropout=dropout, dropout=dropout,
backend=sdp_backend, backend=sdp_backend,
) # is self-attn if context is none ) # is self-attn if context is none
self.norm1 = nn.LayerNorm(dim) self.norm1 = ops.LayerNorm(dim)
self.norm2 = nn.LayerNorm(dim) self.norm2 = ops.LayerNorm(dim)
self.norm3 = nn.LayerNorm(dim) self.norm3 = ops.LayerNorm(dim)
self.checkpoint = checkpoint self.checkpoint = checkpoint
#if self.checkpoint: #if self.checkpoint:
#print(f"{self.__class__.__name__} is using checkpointing") #print(f"{self.__class__.__name__} is using checkpointing")
@@ -523,8 +518,8 @@ class BasicTransformerSingleLayerBlock(nn.Module):
context_dim=context_dim, context_dim=context_dim,
) )
self.ff = FeedForward(dim, dropout=dropout, glu=gated_ff) self.ff = FeedForward(dim, dropout=dropout, glu=gated_ff)
self.norm1 = nn.LayerNorm(dim) self.norm1 = ops.LayerNorm(dim)
self.norm2 = nn.LayerNorm(dim) self.norm2 = ops.LayerNorm(dim)
self.checkpoint = checkpoint self.checkpoint = checkpoint
def forward(self, x, context=None): def forward(self, x, context=None):
@@ -564,9 +559,9 @@ class SpatialTransformer(nn.Module):
sdp_backend=None, sdp_backend=None,
): ):
super().__init__() super().__init__()
print( # print(
f"constructing {self.__class__.__name__} of depth {depth} w/ {in_channels} channels and {n_heads} heads" # f"constructing {self.__class__.__name__} of depth {depth} w/ {in_channels} channels and {n_heads} heads"
) # )
from omegaconf import ListConfig from omegaconf import ListConfig
if exists(context_dim) and not isinstance(context_dim, (list, ListConfig)): if exists(context_dim) and not isinstance(context_dim, (list, ListConfig)):
@@ -588,11 +583,11 @@ class SpatialTransformer(nn.Module):
inner_dim = n_heads * d_head inner_dim = n_heads * d_head
self.norm = Normalize(in_channels) self.norm = Normalize(in_channels)
if not use_linear: if not use_linear:
self.proj_in = Conv2d( self.proj_in = ops.Conv2d(
in_channels, inner_dim, kernel_size=1, stride=1, padding=0 in_channels, inner_dim, kernel_size=1, stride=1, padding=0
) )
else: else:
self.proj_in = Linear(in_channels, inner_dim) self.proj_in = ops.Linear(in_channels, inner_dim)
self.transformer_blocks = nn.ModuleList( self.transformer_blocks = nn.ModuleList(
[ [
@@ -612,11 +607,11 @@ class SpatialTransformer(nn.Module):
) )
if not use_linear: if not use_linear:
self.proj_out = zero_module( self.proj_out = zero_module(
Conv2d(inner_dim, in_channels, kernel_size=1, stride=1, padding=0) ops.Conv2d(inner_dim, in_channels, kernel_size=1, stride=1, padding=0)
) )
else: else:
# self.proj_out = zero_module(Linear(in_channels, inner_dim)) # self.proj_out = zero_module(Linear(in_channels, inner_dim))
self.proj_out = zero_module(Linear(inner_dim, in_channels)) self.proj_out = zero_module(ops.Linear(inner_dim, in_channels))
self.use_linear = use_linear self.use_linear = use_linear
def forward(self, x, context=None): def forward(self, x, context=None):
+3 -1
View File
@@ -8,6 +8,8 @@ from torchvision import models
from ..util import get_ckpt_path from ..util import get_ckpt_path
import comfy.ops
ops = comfy.ops.manual_cast
class LPIPS(nn.Module): class LPIPS(nn.Module):
# Learned perceptual metric # Learned perceptual metric
@@ -91,7 +93,7 @@ class NetLinLayer(nn.Module):
else [] else []
) )
layers += [ layers += [
nn.Conv2d(chn_in, chn_out, 1, stride=1, padding=0, bias=False), ops.Conv2d(chn_in, chn_out, 1, stride=1, padding=0, bias=False),
] ]
self.model = nn.Sequential(*layers) self.model = nn.Sequential(*layers)
@@ -3,7 +3,8 @@ import functools
import torch.nn as nn import torch.nn as nn
from ..util import ActNorm from ..util import ActNorm
import comfy.ops
ops = comfy.ops.manual_cast
def weights_init(m): def weights_init(m):
classname = m.__class__.__name__ classname = m.__class__.__name__
@@ -42,7 +43,7 @@ class NLayerDiscriminator(nn.Module):
kw = 4 kw = 4
padw = 1 padw = 1
sequence = [ sequence = [
nn.Conv2d(input_nc, ndf, kernel_size=kw, stride=2, padding=padw), ops.Conv2d(input_nc, ndf, kernel_size=kw, stride=2, padding=padw),
nn.LeakyReLU(0.2, True), nn.LeakyReLU(0.2, True),
] ]
nf_mult = 1 nf_mult = 1
@@ -51,7 +52,7 @@ class NLayerDiscriminator(nn.Module):
nf_mult_prev = nf_mult nf_mult_prev = nf_mult
nf_mult = min(2**n, 8) nf_mult = min(2**n, 8)
sequence += [ sequence += [
nn.Conv2d( ops.Conv2d(
ndf * nf_mult_prev, ndf * nf_mult_prev,
ndf * nf_mult, ndf * nf_mult,
kernel_size=kw, kernel_size=kw,
@@ -66,7 +67,7 @@ class NLayerDiscriminator(nn.Module):
nf_mult_prev = nf_mult nf_mult_prev = nf_mult
nf_mult = min(2**n_layers, 8) nf_mult = min(2**n_layers, 8)
sequence += [ sequence += [
nn.Conv2d( ops.Conv2d(
ndf * nf_mult_prev, ndf * nf_mult_prev,
ndf * nf_mult, ndf * nf_mult,
kernel_size=kw, kernel_size=kw,
@@ -79,7 +80,7 @@ class NLayerDiscriminator(nn.Module):
] ]
sequence += [ sequence += [
nn.Conv2d(ndf * nf_mult, 1, kernel_size=kw, stride=1, padding=padw) ops.Conv2d(ndf * nf_mult, 1, kernel_size=kw, stride=1, padding=padw)
] # output 1 channel prediction map ] # output 1 channel prediction map
self.main = nn.Sequential(*sequence) self.main = nn.Sequential(*sequence)
+26 -31
View File
@@ -19,13 +19,8 @@ except:
from ...modules.attention import LinearAttention, MemoryEfficientCrossAttention from ...modules.attention import LinearAttention, MemoryEfficientCrossAttention
class Conv2d(torch.nn.Conv2d): import comfy.ops
def reset_parameters(self): ops = comfy.ops.manual_cast
return None
class Linear(torch.nn.Linear):
def reset_parameters(self):
return None
def get_timestep_embedding(timesteps, embedding_dim): def get_timestep_embedding(timesteps, embedding_dim):
""" """
@@ -54,7 +49,7 @@ def nonlinearity(x):
def Normalize(in_channels, num_groups=32): def Normalize(in_channels, num_groups=32):
return torch.nn.GroupNorm( return ops.GroupNorm(
num_groups=num_groups, num_channels=in_channels, eps=1e-6, affine=True num_groups=num_groups, num_channels=in_channels, eps=1e-6, affine=True
) )
@@ -64,7 +59,7 @@ class Upsample(nn.Module):
super().__init__() super().__init__()
self.with_conv = with_conv self.with_conv = with_conv
if self.with_conv: if self.with_conv:
self.conv = Conv2d( self.conv = ops.Conv2d(
in_channels, in_channels, kernel_size=3, stride=1, padding=1 in_channels, in_channels, kernel_size=3, stride=1, padding=1
) )
@@ -91,7 +86,7 @@ class Downsample(nn.Module):
self.with_conv = with_conv self.with_conv = with_conv
if self.with_conv: if self.with_conv:
# no asymmetric padding in torch conv, must do it ourselves # no asymmetric padding in torch conv, must do it ourselves
self.conv = Conv2d( self.conv = ops.Conv2d(
in_channels, in_channels, kernel_size=3, stride=2, padding=0 in_channels, in_channels, kernel_size=3, stride=2, padding=0
) )
@@ -122,23 +117,23 @@ class ResnetBlock(nn.Module):
self.use_conv_shortcut = conv_shortcut self.use_conv_shortcut = conv_shortcut
self.norm1 = Normalize(in_channels) self.norm1 = Normalize(in_channels)
self.conv1 = Conv2d( self.conv1 = ops.Conv2d(
in_channels, out_channels, kernel_size=3, stride=1, padding=1 in_channels, out_channels, kernel_size=3, stride=1, padding=1
) )
if temb_channels > 0: if temb_channels > 0:
self.temb_proj = Linear(temb_channels, out_channels) self.temb_proj = ops.Linear(temb_channels, out_channels)
self.norm2 = Normalize(out_channels) self.norm2 = Normalize(out_channels)
self.dropout = torch.nn.Dropout(dropout) self.dropout = torch.nn.Dropout(dropout)
self.conv2 = Conv2d( self.conv2 = ops.Conv2d(
out_channels, out_channels, kernel_size=3, stride=1, padding=1 out_channels, out_channels, kernel_size=3, stride=1, padding=1
) )
if self.in_channels != self.out_channels: if self.in_channels != self.out_channels:
if self.use_conv_shortcut: if self.use_conv_shortcut:
self.conv_shortcut = Conv2d( self.conv_shortcut = ops.Conv2d(
in_channels, out_channels, kernel_size=3, stride=1, padding=1 in_channels, out_channels, kernel_size=3, stride=1, padding=1
) )
else: else:
self.nin_shortcut = Conv2d( self.nin_shortcut = ops.Conv2d(
in_channels, out_channels, kernel_size=1, stride=1, padding=0 in_channels, out_channels, kernel_size=1, stride=1, padding=0
) )
@@ -178,16 +173,16 @@ class AttnBlock(nn.Module):
self.in_channels = in_channels self.in_channels = in_channels
self.norm = Normalize(in_channels) self.norm = Normalize(in_channels)
self.q = Conv2d( self.q = ops.Conv2d(
in_channels, in_channels, kernel_size=1, stride=1, padding=0 in_channels, in_channels, kernel_size=1, stride=1, padding=0
) )
self.k = Conv2d( self.k = ops.Conv2d(
in_channels, in_channels, kernel_size=1, stride=1, padding=0 in_channels, in_channels, kernel_size=1, stride=1, padding=0
) )
self.v = Conv2d( self.v = ops.Conv2d(
in_channels, in_channels, kernel_size=1, stride=1, padding=0 in_channels, in_channels, kernel_size=1, stride=1, padding=0
) )
self.proj_out = Conv2d( self.proj_out = ops.Conv2d(
in_channels, in_channels, kernel_size=1, stride=1, padding=0 in_channels, in_channels, kernel_size=1, stride=1, padding=0
) )
@@ -228,16 +223,16 @@ class MemoryEfficientAttnBlock(nn.Module):
self.in_channels = in_channels self.in_channels = in_channels
self.norm = Normalize(in_channels) self.norm = Normalize(in_channels)
self.q = Conv2d( self.q = ops.Conv2d(
in_channels, in_channels, kernel_size=1, stride=1, padding=0 in_channels, in_channels, kernel_size=1, stride=1, padding=0
) )
self.k = Conv2d( self.k = ops.Conv2d(
in_channels, in_channels, kernel_size=1, stride=1, padding=0 in_channels, in_channels, kernel_size=1, stride=1, padding=0
) )
self.v = Conv2d( self.v = ops.Conv2d(
in_channels, in_channels, kernel_size=1, stride=1, padding=0 in_channels, in_channels, kernel_size=1, stride=1, padding=0
) )
self.proj_out = Conv2d( self.proj_out = ops.Conv2d(
in_channels, in_channels, kernel_size=1, stride=1, padding=0 in_channels, in_channels, kernel_size=1, stride=1, padding=0
) )
self.attention_op: Optional[Any] = None self.attention_op: Optional[Any] = None
@@ -354,13 +349,13 @@ class Model(nn.Module):
self.temb = nn.Module() self.temb = nn.Module()
self.temb.dense = nn.ModuleList( self.temb.dense = nn.ModuleList(
[ [
Linear(self.ch, self.temb_ch), ops.Linear(self.ch, self.temb_ch),
Linear(self.temb_ch, self.temb_ch), ops.Linear(self.temb_ch, self.temb_ch),
] ]
) )
# downsampling # downsampling
self.conv_in = Conv2d( self.conv_in = ops.Conv2d(
in_channels, self.ch, kernel_size=3, stride=1, padding=1 in_channels, self.ch, kernel_size=3, stride=1, padding=1
) )
@@ -439,7 +434,7 @@ class Model(nn.Module):
# end # end
self.norm_out = Normalize(block_in) self.norm_out = Normalize(block_in)
self.conv_out = Conv2d( self.conv_out = ops.Conv2d(
block_in, out_ch, kernel_size=3, stride=1, padding=1 block_in, out_ch, kernel_size=3, stride=1, padding=1
) )
@@ -526,7 +521,7 @@ class Encoder(nn.Module):
self.in_channels = in_channels self.in_channels = in_channels
# downsampling # downsampling
self.conv_in = Conv2d( self.conv_in = ops.Conv2d(
in_channels, self.ch, kernel_size=3, stride=1, padding=1 in_channels, self.ch, kernel_size=3, stride=1, padding=1
) )
@@ -577,7 +572,7 @@ class Encoder(nn.Module):
# end # end
self.norm_out = Normalize(block_in) self.norm_out = Normalize(block_in)
self.conv_out = Conv2d( self.conv_out = ops.Conv2d(
block_in, block_in,
2 * z_channels if double_z else z_channels, 2 * z_channels if double_z else z_channels,
kernel_size=3, kernel_size=3,
@@ -660,7 +655,7 @@ class Decoder(nn.Module):
make_resblock_cls = self._make_resblock() make_resblock_cls = self._make_resblock()
make_conv_cls = self._make_conv() make_conv_cls = self._make_conv()
# z to block_in # z to block_in
self.conv_in = Conv2d( self.conv_in = ops.Conv2d(
z_channels, block_in, kernel_size=3, stride=1, padding=1 z_channels, block_in, kernel_size=3, stride=1, padding=1
) )
@@ -719,7 +714,7 @@ class Decoder(nn.Module):
return ResnetBlock return ResnetBlock
def _make_conv(self) -> Callable: def _make_conv(self) -> Callable:
return Conv2d return ops.Conv2d
def get_last_layer(self, **kwargs): def get_last_layer(self, **kwargs):
return self.conv_out.weight return self.conv_out.weight
+7 -7
View File
@@ -186,13 +186,13 @@ class Downsample(nn.Module):
self.dims = dims self.dims = dims
stride = 2 if dims != 3 else ((1, 2, 2) if not third_down else (2, 2, 2)) stride = 2 if dims != 3 else ((1, 2, 2) if not third_down else (2, 2, 2))
if use_conv: if use_conv:
print(f"Building a Downsample layer with {dims} dims.") # print(f"Building a Downsample layer with {dims} dims.")
print( # print(
f" --> settings are: \n in-chn: {self.channels}, out-chn: {self.out_channels}, " # f" --> settings are: \n in-chn: {self.channels}, out-chn: {self.out_channels}, "
f"kernel-size: 3, stride: {stride}, padding: {padding}" # f"kernel-size: 3, stride: {stride}, padding: {padding}"
) # )
if dims == 3: # if dims == 3:
print(f" --> Downsampling third axis (time): {third_down}") # print(f" --> Downsampling third axis (time): {third_down}")
self.op = conv_nd( self.op = conv_nd(
dims, dims,
self.channels, self.channels,
+205 -11
View File
@@ -8,7 +8,8 @@ from typing import Dict, Union
import torch import torch
from omegaconf import ListConfig, OmegaConf from omegaconf import ListConfig, OmegaConf
from tqdm import tqdm from tqdm import tqdm
from comfy.k_diffusion.sampling import BrownianTreeNoiseSampler, get_sigmas_karras
from comfy.k_diffusion.sampling import BrownianTreeNoiseSampler, get_sigmas_karras
from ...modules.diffusionmodules.sampling_utils import ( from ...modules.diffusionmodules.sampling_utils import (
get_ancestral_step, get_ancestral_step,
linear_multistep_coeff, linear_multistep_coeff,
@@ -17,6 +18,7 @@ from ...modules.diffusionmodules.sampling_utils import (
to_sigma, to_sigma,
) )
from ...util import append_dims, default, instantiate_from_config from ...util import append_dims, default, instantiate_from_config
import copy
DEFAULT_GUIDER = {"target": ".sgm.modules.diffusionmodules.guiders.IdentityGuider"} DEFAULT_GUIDER = {"target": ".sgm.modules.diffusionmodules.guiders.IdentityGuider"}
@@ -461,18 +463,20 @@ class TiledRestoreEDMSampler(RestoreEDMSampler):
def __call__(self, denoiser, x, cond, uc=None, num_steps=None, x_center=None, control_scale=1.0, def __call__(self, denoiser, x, cond, uc=None, num_steps=None, x_center=None, control_scale=1.0,
use_linear_control_scale=False, control_scale_start=0.0): use_linear_control_scale=False, control_scale_start=0.0):
use_local_prompt = isinstance(cond, list) cond_copy = copy.deepcopy(cond)
uc_copy = copy.deepcopy(uc)
use_local_prompt = isinstance(cond_copy, list)
b, _, h, w = x.shape b, _, h, w = x.shape
latent_tiles_iterator = _sliding_windows(h, w, self.tile_size, self.tile_stride) latent_tiles_iterator = _sliding_windows(h, w, self.tile_size, self.tile_stride)
tile_weights = self.tile_weights.repeat(b, 1, 1, 1) tile_weights = self.tile_weights.repeat(b, 1, 1, 1)
if not use_local_prompt: if not use_local_prompt:
LQ_latent = cond['control'] LQ_latent = cond_copy['control']
else: else:
assert len(cond) == len(latent_tiles_iterator), "Number of local prompts should be equal to number of tiles" assert len(cond_copy) == len(latent_tiles_iterator), "Number of local prompts should be equal to number of tiles"
LQ_latent = cond[0]['control'] LQ_latent = cond_copy[0]['control']
clean_LQ_latent = x_center clean_LQ_latent = x_center
x, s_in, sigmas, num_sigmas, cond, uc = self.prepare_sampling_loop( x, s_in, sigmas, num_sigmas, cond_copy, uc_copy = self.prepare_sampling_loop(
x, cond, uc, num_steps x, cond_copy, uc_copy, num_steps
) )
pbar_comfy = comfy.utils.ProgressBar(num_sigmas) pbar_comfy = comfy.utils.ProgressBar(num_sigmas)
for _idx, i in enumerate(self.get_sigma_gen(num_sigmas)): for _idx, i in enumerate(self.get_sigma_gen(num_sigmas)):
@@ -489,18 +493,18 @@ class TiledRestoreEDMSampler(RestoreEDMSampler):
_eps_noise = eps_noise[:, :, hi:hi_end, wi:wi_end] _eps_noise = eps_noise[:, :, hi:hi_end, wi:wi_end]
x_center_tile = clean_LQ_latent[:, :, hi:hi_end, wi:wi_end] x_center_tile = clean_LQ_latent[:, :, hi:hi_end, wi:wi_end]
if use_local_prompt: if use_local_prompt:
_cond = cond[j] _cond = cond_copy[j]
else: else:
_cond = cond _cond = cond_copy
_cond['control'] = LQ_latent[:, :, hi:hi_end, wi:wi_end] _cond['control'] = LQ_latent[:, :, hi:hi_end, wi:wi_end]
uc['control'] = LQ_latent[:, :, hi:hi_end, wi:wi_end] uc_copy['control'] = LQ_latent[:, :, hi:hi_end, wi:wi_end]
_x = self.sampler_step( _x = self.sampler_step(
s_in * sigmas[i], s_in * sigmas[i],
s_in * sigmas[i + 1], s_in * sigmas[i + 1],
denoiser, denoiser,
x_tile, x_tile,
_cond, _cond,
uc, uc_copy,
gamma, gamma,
x_center_tile, x_center_tile,
eps_noise=_eps_noise, eps_noise=_eps_noise,
@@ -555,3 +559,193 @@ def _sliding_windows(h: int, w: int, tile_size: int, tile_stride: int):
coords.append((hi, hi + tile_size, wi, wi + tile_size)) coords.append((hi, hi + tile_size, wi, wi + tile_size))
return coords return coords
class RestoreDPMPP2MSampler(DPMPP2MSampler):
def __init__(self, s_churn=0.0, s_tmin=0.0, s_tmax=float("inf"), s_noise=1.0, restore_cfg=4.0,
restore_cfg_s_tmin=0.05, eta=1., *args, **kwargs):
self.s_noise = s_noise
self.eta = eta
self.restore_cfg = restore_cfg
self.restore_cfg_s_tmin = restore_cfg_s_tmin
self.sigma_max = 14.6146
super().__init__(*args, **kwargs)
def denoise(self, x, denoiser, sigma, cond, uc, control_scale=1.0):
denoised = denoiser(*self.guider.prepare_inputs(x, sigma, cond, uc), control_scale)
denoised = self.guider(denoised, sigma)
return denoised
def get_mult(self, h, r, t, t_next, previous_sigma):
eta_h = self.eta * h
mult1 = to_sigma(t_next) / to_sigma(t) * (-eta_h).exp()
mult2 = (-h -eta_h).expm1()
if previous_sigma is not None:
mult3 = 1 + 1 / (2 * r)
mult4 = 1 / (2 * r)
return mult1, mult2, mult3, mult4
else:
return mult1, mult2
def sampler_step(
self,
old_denoised,
previous_sigma,
sigma,
next_sigma,
denoiser,
x,
cond,
uc=None,
eps_noise=None,
x_center=None,
control_scale=1.0,
use_linear_control_scale=False,
control_scale_start=0.0
):
if use_linear_control_scale:
control_scale = (sigma[0].item() / self.sigma_max) * (control_scale_start - control_scale) + control_scale
denoised = self.denoise(x, denoiser, sigma, cond, uc, control_scale=control_scale)
if (next_sigma[0] > self.restore_cfg_s_tmin) and (self.restore_cfg > 0):
d_center = (denoised - x_center)
denoised = denoised - d_center * ((sigma.view(-1, 1, 1, 1) / self.sigma_max) ** self.restore_cfg)
h, r, t, t_next = self.get_variables(sigma, next_sigma, previous_sigma)
eta_h = self.eta * h
mult = [
append_dims(mult, x.ndim)
for mult in self.get_mult(h, r, t, t_next, previous_sigma)
]
x_standard = mult[0] * x - mult[1] * denoised
if old_denoised is None or torch.sum(next_sigma) < 1e-14:
# Save a network evaluation if all noise levels are 0 or on the first step
return x_standard, denoised
else:
denoised_d = mult[2] * denoised - mult[3] * old_denoised
x_advanced = mult[0] * x - mult[1] * denoised_d
# apply correction if noise level is not 0 and not first step
x = torch.where(
append_dims(next_sigma, x.ndim) > 0.0, x_advanced, x_standard
)
if self.eta:
x = x + eps_noise * next_sigma * (-2 * eta_h).expm1().neg().sqrt() * self.s_noise
return x, denoised
def __call__(self, denoiser, x, cond, uc=None, num_steps=None, x_center=None, control_scale=1.0,
use_linear_control_scale=False, control_scale_start=0.0, **kwargs):
x, s_in, sigmas, num_sigmas, cond, uc = self.prepare_sampling_loop(
x, cond, uc, num_steps
)
sigmas_min, sigmas_max = sigmas[-2].cpu(), sigmas[0].cpu()
sigmas_new = get_sigmas_karras(self.num_steps, sigmas_min, sigmas_max, device=x.device)
sigmas = sigmas_new
noise_sampler = BrownianTreeNoiseSampler(x, sigmas_min, sigmas_max)
old_denoised = None
pbar_comfy = comfy.utils.ProgressBar(num_sigmas)
for i in self.get_sigma_gen(num_sigmas):
if i > 0 and torch.sum(s_in * sigmas[i + 1]) > 1e-14:
eps_noise = noise_sampler(s_in * sigmas[i], s_in * sigmas[i + 1])
else:
eps_noise = None
x, old_denoised = self.sampler_step(
old_denoised,
None if i == 0 else s_in * sigmas[i - 1],
s_in * sigmas[i],
s_in * sigmas[i + 1],
denoiser,
x,
cond,
uc=uc,
eps_noise=eps_noise,
control_scale=control_scale,
x_center=x_center,
use_linear_control_scale=use_linear_control_scale,
control_scale_start=control_scale_start,
)
pbar_comfy.update(1)
return x
class TiledRestoreDPMPP2MSampler(RestoreDPMPP2MSampler):
def __init__(self, tile_size=128, tile_stride=64, *args, **kwargs):
super().__init__(*args, **kwargs)
self.tile_size = tile_size
self.tile_stride = tile_stride
self.tile_weights = gaussian_weights(self.tile_size, self.tile_size, 1)
def __call__(self, denoiser, x, cond, uc=None, num_steps=None, control_scale=1.0, **kwargs):
use_local_prompt = isinstance(cond, list)
b, _, h, w = x.shape
latent_tiles_iterator = _sliding_windows(h, w, self.tile_size, self.tile_stride)
print(f"Image divided into {len(latent_tiles_iterator)} tiles")
print("Conds received: ", len(cond))
cond_copy = copy.deepcopy(cond)
uc_copy = copy.deepcopy(uc)
tile_weights = self.tile_weights.repeat(b, 1, 1, 1)
if not use_local_prompt:
LQ_latent = cond['control']
else:
assert len(cond_copy) == len(latent_tiles_iterator), "Number of local prompts should be equal to number of tiles"
LQ_latent = cond_copy[0]['control']
print("LQ_latent shape: ",LQ_latent.shape)
x, s_in, sigmas, num_sigmas, cond_copy, uc_copy = self.prepare_sampling_loop(
x, cond_copy, uc_copy, num_steps
)
sigmas_min, sigmas_max = sigmas[-2].cpu(), sigmas[0].cpu()
sigmas_new = get_sigmas_karras(self.num_steps, sigmas_min, sigmas_max, device=x.device)
sigmas = sigmas_new
noise_sampler = BrownianTreeNoiseSampler(x, sigmas_min, sigmas_max)
old_denoised = None
pbar_comfy = comfy.utils.ProgressBar(num_sigmas)
for _idx, i in enumerate(self.get_sigma_gen(num_sigmas)):
if i > 0 and torch.sum(s_in * sigmas[i + 1]) > 1e-14:
eps_noise = noise_sampler(s_in * sigmas[i], s_in * sigmas[i + 1])
else:
eps_noise = torch.zeros_like(x)
x_next = torch.zeros_like(x)
old_denoised_next = torch.zeros_like(x)
count = torch.zeros_like(x)
for j, (hi, hi_end, wi, wi_end) in enumerate(latent_tiles_iterator):
x_tile = x[:, :, hi:hi_end, wi:wi_end]
_eps_noise = eps_noise[:, :, hi:hi_end, wi:wi_end]
if old_denoised is not None:
old_denoised_tile = old_denoised[:, :, hi:hi_end, wi:wi_end]
else:
old_denoised_tile = None
if use_local_prompt:
_cond = cond_copy[j]
else:
_cond = cond_copy
_cond['control'] = LQ_latent[:, :, hi:hi_end, wi:wi_end]
uc_copy['control'] = LQ_latent[:, :, hi:hi_end, wi:wi_end]
_x, _old_denoised = self.sampler_step(
old_denoised_tile,
None if i == 0 else s_in * sigmas[i - 1],
s_in * sigmas[i],
s_in * sigmas[i + 1],
denoiser,
x_tile,
_cond,
uc=uc_copy,
eps_noise=_eps_noise,
control_scale=control_scale,
)
x_next[:, :, hi:hi_end, wi:wi_end] += _x * tile_weights
old_denoised_next[:, :, hi:hi_end, wi:wi_end] += _old_denoised * tile_weights
count[:, :, hi:hi_end, wi:wi_end] += tile_weights
old_denoised_next /= count
x_next /= count
x = x_next
old_denoised = old_denoised_next
pbar_comfy.update(1)
return x
+7 -12
View File
@@ -19,6 +19,9 @@ import comfy.model_management
device = comfy.model_management.get_torch_device() device = comfy.model_management.get_torch_device()
from contextlib import nullcontext from contextlib import nullcontext
import comfy.ops
ops = comfy.ops.manual_cast
def make_beta_schedule( def make_beta_schedule(
schedule, schedule,
n_timestep, n_timestep,
@@ -278,25 +281,17 @@ class GroupNorm32(nn.GroupNorm):
def forward(self, x): def forward(self, x):
# return super().forward(x.float()).type(x.dtype) # return super().forward(x.float()).type(x.dtype)
return super().forward(x) return super().forward(x)
class Conv2d(torch.nn.Conv2d):
def reset_parameters(self):
return None
class Linear(torch.nn.Linear):
def reset_parameters(self):
return None
def conv_nd(dims, *args, **kwargs): def conv_nd(dims, *args, **kwargs):
""" """
Create a 1D, 2D, or 3D convolution module. Create a 1D, 2D, or 3D convolution module.
""" """
if dims == 1: if dims == 1:
return nn.Conv1d(*args, **kwargs) return ops.Conv1d(*args, **kwargs)
elif dims == 2: elif dims == 2:
return Conv2d(*args, **kwargs) return ops.Conv2d(*args, **kwargs)
elif dims == 3: elif dims == 3:
return nn.Conv3d(*args, **kwargs) return ops.Conv3d(*args, **kwargs)
raise ValueError(f"unsupported dimensions: {dims}") raise ValueError(f"unsupported dimensions: {dims}")
@@ -304,7 +299,7 @@ def linear(*args, **kwargs):
""" """
Create a linear module. Create a linear module.
""" """
return Linear(*args, **kwargs) return ops.Linear(*args, **kwargs)
def avg_pool_nd(dims, *args, **kwargs): def avg_pool_nd(dims, *args, **kwargs):
+29 -7
View File
@@ -2,7 +2,7 @@ from contextlib import nullcontext
from functools import partial from functools import partial
from typing import Dict, List, Optional, Tuple, Union from typing import Dict, List, Optional, Tuple, Union
import kornia #import kornia
import numpy as np import numpy as np
import open_clip import open_clip
import torch import torch
@@ -36,6 +36,9 @@ from ....CKPT_PTH import SDXL_CLIP1_PATH, SDXL_CLIP2_CKPT_PTH
import comfy.model_management import comfy.model_management
device = comfy.model_management.get_torch_device() device = comfy.model_management.get_torch_device()
import comfy.ops
ops = comfy.ops.manual_cast
class AbstractEmbModel(nn.Module): class AbstractEmbModel(nn.Module):
def __init__(self): def __init__(self):
super().__init__() super().__init__()
@@ -99,10 +102,10 @@ class GeneralConditioner(nn.Module):
for param in embedder.parameters(): for param in embedder.parameters():
param.requires_grad = False param.requires_grad = False
embedder.eval() embedder.eval()
print( # print(
f"Initialized embedder #{n}: {embedder.__class__.__name__} " # f"Initialized embedder #{n}: {embedder.__class__.__name__} "
f"with {count_params(embedder, False)} params. Trainable: {embedder.is_trainable}" # f"with {count_params(embedder, False)} params. Trainable: {embedder.is_trainable}"
) # )
if "input_key" in embconfig: if "input_key" in embconfig:
embedder.input_key = embconfig["input_key"] embedder.input_key = embconfig["input_key"]
@@ -577,7 +580,10 @@ class FrozenOpenCLIPEmbedder2(AbstractEmbModel):
x = self.model.token_embedding(text) # [batch_size, n_ctx, d_model] x = self.model.token_embedding(text) # [batch_size, n_ctx, d_model]
x = x + self.model.positional_embedding x = x + self.model.positional_embedding
x = x.permute(1, 0, 2) # NLD -> LND x = x.permute(1, 0, 2) # NLD -> LND
x = self.text_transformer_forward(x, attn_mask=self.model.attn_mask) try:
x = self.text_transformer_forward(x, attn_mask=self.model.attn_mask)
except:
x = self.text_transformer_forward_batch_first(x, attn_mask=self.model.attn_mask)
if self.legacy: if self.legacy:
x = x[self.layer] x = x[self.layer]
x = self.model.ln_final(x) x = self.model.ln_final(x)
@@ -612,6 +618,22 @@ class FrozenOpenCLIPEmbedder2(AbstractEmbModel):
x = r(x, attn_mask=attn_mask) x = r(x, attn_mask=attn_mask)
outputs["last"] = x.permute(1, 0, 2) # LND -> NLD outputs["last"] = x.permute(1, 0, 2) # LND -> NLD
return outputs return outputs
def text_transformer_forward_batch_first(self, x: torch.Tensor, attn_mask=None):
x = x.permute(1, 0, 2) # LND -> NLD
outputs = {}
for i, r in enumerate(self.model.transformer.resblocks):
if i == len(self.model.transformer.resblocks) - 1:
outputs["penultimate"] = x
if (
self.model.transformer.grad_checkpointing
and not torch.jit.is_scripting()
):
x = checkpoint(r, x, attn_mask)
else:
x = r(x, attn_mask=attn_mask)
outputs["last"] = x
return outputs
def encode(self, text): def encode(self, text):
return self(text) return self(text)
@@ -908,7 +930,7 @@ class SpatialRescaler(nn.Module):
print( print(
f"Spatial Rescaler mapping from {in_channels} to {out_channels} channels after resizing." f"Spatial Rescaler mapping from {in_channels} to {out_channels} channels after resizing."
) )
self.channel_mapper = nn.Conv2d( self.channel_mapper = ops.Conv2d(
in_channels, in_channels,
out_channels, out_channels,
kernel_size=kernel_size, kernel_size=kernel_size,
+6 -3
View File
@@ -4,7 +4,7 @@ import os
from functools import partial from functools import partial
from inspect import isfunction from inspect import isfunction
import fsspec #import fsspec
import numpy as np import numpy as np
import torch import torch
from PIL import Image, ImageDraw, ImageFont from PIL import Image, ImageDraw, ImageFont
@@ -177,14 +177,17 @@ def instantiate_from_config(config):
def get_obj_from_str(string, reload=False, invalidate_cache=True): def get_obj_from_str(string, reload=False, invalidate_cache=True):
package_directory_name = os.path.basename(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
module, cls = string.rsplit(".", 1) module, cls = string.rsplit(".", 1)
if invalidate_cache: if invalidate_cache:
importlib.invalidate_caches() importlib.invalidate_caches()
if reload: if reload:
module_imp = importlib.import_module(module) module_imp = importlib.import_module(module)
importlib.reload(module_imp) importlib.reload(module_imp)
return getattr(importlib.import_module(module, package=package_directory_name), cls) try:
obj = getattr(importlib.import_module(module, package=os.path.basename(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))), cls)
except:
obj = getattr(importlib.import_module(module, package=os.path.dirname(os.path.dirname(os.path.abspath( __file__ )))), cls)
return obj
def append_zero(x): def append_zero(x):