docs(comfyui): bind director SelfLift fixed reference batch141
Co-authored-by: multica-agent <github@multica.ai>
This commit is contained in:
@@ -0,0 +1,6 @@
|
||||
tree 668784f3dcf05f5adb6d12ee551dc476e2f56e46
|
||||
parent ddbaa8752874c275290d054ee4fddd6e004f5fdf
|
||||
author comfyanonymous <comfyanonymous@protonmail.com> 1786641622 -0400
|
||||
committer comfyanonymous <comfyanonymous@protonmail.com> 1786641622 -0400
|
||||
|
||||
ComfyUI v0.33.0
|
||||
@@ -0,0 +1,2 @@
|
||||
From https://github.com/Comfy-Org/ComfyUI
|
||||
* tag v0.33.0 -> FETCH_HEAD
|
||||
@@ -0,0 +1,5 @@
|
||||
{
|
||||
"object": "2f35f4a08176d993cded35dac3332be4f7287f41",
|
||||
"commit": "2f35f4a08176d993cded35dac3332be4f7287f41",
|
||||
"tag": "v0.33.0"
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
tree 668784f3dcf05f5adb6d12ee551dc476e2f56e46
|
||||
parent ddbaa8752874c275290d054ee4fddd6e004f5fdf
|
||||
author comfyanonymous <comfyanonymous@protonmail.com> 1786641622 -0400
|
||||
committer comfyanonymous <comfyanonymous@protonmail.com> 1786641622 -0400
|
||||
|
||||
ComfyUI v0.33.0
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,674 @@
|
||||
GNU GENERAL PUBLIC LICENSE
|
||||
Version 3, 29 June 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The GNU General Public License is a free, copyleft license for
|
||||
software and other kinds of works.
|
||||
|
||||
The licenses for most software and other practical works are designed
|
||||
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
|
||||
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
|
||||
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>.
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,177 @@
|
||||
from abc import ABC, abstractmethod
|
||||
from typing import TYPE_CHECKING
|
||||
from comfy_api.internal import ComfyAPIBase
|
||||
from comfy_api.internal.singleton import ProxiedSingleton
|
||||
from comfy_api.internal.async_to_sync import create_sync_class
|
||||
from ._input import ImageInput, AudioInput, MaskInput, LatentInput, VideoInput
|
||||
from ._input_impl import VideoFromFile, VideoFromComponents
|
||||
from ._util import VideoCodec, VideoContainer, VideoComponents, MESH, VOXEL, SPLAT, File3D
|
||||
from . import _io_public as io
|
||||
from . import _ui_public as ui
|
||||
from comfy_execution.utils import get_executing_context
|
||||
from comfy_execution.progress import get_progress_state, PreviewImageTuple
|
||||
from PIL import Image
|
||||
from comfy.cli_args import args
|
||||
import numpy as np
|
||||
|
||||
|
||||
class ComfyAPI_latest(ComfyAPIBase):
|
||||
VERSION = "latest"
|
||||
STABLE = False
|
||||
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self.node_replacement = self.NodeReplacement()
|
||||
self.execution = self.Execution()
|
||||
self.caching = self.Caching()
|
||||
|
||||
class NodeReplacement(ProxiedSingleton):
|
||||
async def register(self, node_replace: io.NodeReplace) -> None:
|
||||
"""Register a node replacement mapping."""
|
||||
from server import PromptServer
|
||||
PromptServer.instance.node_replace_manager.register(node_replace)
|
||||
|
||||
class Execution(ProxiedSingleton):
|
||||
async def set_progress(
|
||||
self,
|
||||
value: float,
|
||||
max_value: float,
|
||||
node_id: str | None = None,
|
||||
preview_image: Image.Image | ImageInput | None = None,
|
||||
ignore_size_limit: bool = False,
|
||||
) -> None:
|
||||
"""
|
||||
Update the progress bar displayed in the ComfyUI interface.
|
||||
|
||||
This function allows custom nodes and API calls to report their progress
|
||||
back to the user interface, providing visual feedback during long operations.
|
||||
|
||||
Migration from previous API: comfy.utils.PROGRESS_BAR_HOOK
|
||||
"""
|
||||
executing_context = get_executing_context()
|
||||
if node_id is None and executing_context is not None:
|
||||
node_id = executing_context.node_id
|
||||
if node_id is None:
|
||||
raise ValueError("node_id must be provided if not in executing context")
|
||||
|
||||
# Convert preview_image to PreviewImageTuple if needed
|
||||
to_display: PreviewImageTuple | Image.Image | ImageInput | None = preview_image
|
||||
if to_display is not None:
|
||||
# First convert to PIL Image if needed
|
||||
if isinstance(to_display, ImageInput):
|
||||
# Convert ImageInput (torch.Tensor) to PIL Image
|
||||
# Handle tensor shape [B, H, W, C] -> get first image if batch
|
||||
tensor = to_display
|
||||
if len(tensor.shape) == 4:
|
||||
tensor = tensor[0]
|
||||
|
||||
# Convert to numpy array and scale to 0-255
|
||||
image_np = (tensor.cpu().numpy() * 255).astype(np.uint8)
|
||||
to_display = Image.fromarray(image_np)
|
||||
|
||||
if isinstance(to_display, Image.Image):
|
||||
# Detect image format from PIL Image
|
||||
image_format = to_display.format if to_display.format else "JPEG"
|
||||
# Use None for preview_size if ignore_size_limit is True
|
||||
preview_size = None if ignore_size_limit else args.preview_size
|
||||
to_display = (image_format, to_display, preview_size)
|
||||
|
||||
get_progress_state().update_progress(
|
||||
node_id=node_id,
|
||||
value=value,
|
||||
max_value=max_value,
|
||||
image=to_display,
|
||||
)
|
||||
|
||||
class Caching(ProxiedSingleton):
|
||||
"""
|
||||
External cache provider API for sharing cached node outputs
|
||||
across ComfyUI instances.
|
||||
|
||||
Example::
|
||||
|
||||
from comfy_api.latest import Caching
|
||||
|
||||
class MyCacheProvider(Caching.CacheProvider):
|
||||
async def on_lookup(self, context):
|
||||
... # check external storage
|
||||
|
||||
async def on_store(self, context, value):
|
||||
... # store to external storage
|
||||
|
||||
Caching.register_provider(MyCacheProvider())
|
||||
"""
|
||||
from ._caching import CacheProvider, CacheContext, CacheValue
|
||||
|
||||
async def register_provider(self, provider: "ComfyAPI_latest.Caching.CacheProvider") -> None:
|
||||
"""Register an external cache provider. Providers are called in registration order."""
|
||||
from comfy_execution.cache_provider import register_cache_provider
|
||||
register_cache_provider(provider)
|
||||
|
||||
async def unregister_provider(self, provider: "ComfyAPI_latest.Caching.CacheProvider") -> None:
|
||||
"""Unregister a previously registered cache provider."""
|
||||
from comfy_execution.cache_provider import unregister_cache_provider
|
||||
unregister_cache_provider(provider)
|
||||
|
||||
class ComfyExtension(ABC):
|
||||
async def on_load(self) -> None:
|
||||
"""
|
||||
Called when an extension is loaded.
|
||||
This should be used to initialize any global resources needed by the extension.
|
||||
"""
|
||||
|
||||
@abstractmethod
|
||||
async def get_node_list(self) -> list[type[io.ComfyNode]]:
|
||||
"""
|
||||
Returns a list of nodes that this extension provides.
|
||||
"""
|
||||
|
||||
class Input:
|
||||
Image = ImageInput
|
||||
Audio = AudioInput
|
||||
Mask = MaskInput
|
||||
Latent = LatentInput
|
||||
Video = VideoInput
|
||||
|
||||
class InputImpl:
|
||||
VideoFromFile = VideoFromFile
|
||||
VideoFromComponents = VideoFromComponents
|
||||
|
||||
class Types:
|
||||
VideoCodec = VideoCodec
|
||||
VideoContainer = VideoContainer
|
||||
VideoComponents = VideoComponents
|
||||
MESH = MESH
|
||||
VOXEL = VOXEL
|
||||
SPLAT = SPLAT
|
||||
File3D = File3D
|
||||
|
||||
|
||||
Caching = ComfyAPI_latest.Caching
|
||||
|
||||
ComfyAPI = ComfyAPI_latest
|
||||
|
||||
# Create a synchronous version of the API
|
||||
if TYPE_CHECKING:
|
||||
import comfy_api.latest.generated.ComfyAPISyncStub # type: ignore
|
||||
|
||||
ComfyAPISync: type[comfy_api.latest.generated.ComfyAPISyncStub.ComfyAPISyncStub]
|
||||
ComfyAPISync = create_sync_class(ComfyAPI_latest)
|
||||
|
||||
# create new aliases for io and ui
|
||||
IO = io
|
||||
UI = ui
|
||||
|
||||
__all__ = [
|
||||
"ComfyAPI",
|
||||
"ComfyAPISync",
|
||||
"Input",
|
||||
"InputImpl",
|
||||
"Types",
|
||||
"Caching",
|
||||
"ComfyExtension",
|
||||
"io",
|
||||
"IO",
|
||||
"ui",
|
||||
"UI",
|
||||
]
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1 @@
|
||||
from ._io import * # noqa: F403
|
||||
+1232
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,37 @@
|
||||
comfyui-frontend-package==1.48.7
|
||||
comfyui-workflow-templates==0.11.41
|
||||
comfyui-embedded-docs==0.5.9
|
||||
torch
|
||||
torchsde
|
||||
torchvision
|
||||
torchaudio
|
||||
numpy>=1.25.0
|
||||
einops
|
||||
transformers>=4.50.3
|
||||
tokenizers>=0.13.3
|
||||
sentencepiece
|
||||
safetensors>=0.4.2
|
||||
aiohttp>=3.11.8
|
||||
yarl>=1.18.0
|
||||
pyyaml
|
||||
Pillow
|
||||
scipy
|
||||
tqdm
|
||||
psutil
|
||||
alembic
|
||||
SQLAlchemy>=2.0.0
|
||||
filelock
|
||||
av>=16.0.0
|
||||
comfy-kitchen==0.2.31
|
||||
comfy-aimdo==0.4.13
|
||||
requests
|
||||
simpleeval>=1.0.0
|
||||
blake3
|
||||
|
||||
#non essential dependencies:
|
||||
kornia>=0.7.1
|
||||
spandrel
|
||||
pydantic~=2.0
|
||||
pydantic-settings~=2.0
|
||||
PyOpenGL>=3.1.8
|
||||
comfy-angle
|
||||
@@ -0,0 +1,6 @@
|
||||
tree 17e7153e3d56c7398a918c6799e0ba99e873f9c9
|
||||
parent 7a8f3add240fff1399df6378636f3cd6a65ab3e3
|
||||
author comfyanonymous <comfyanonymous@protonmail.com> 1790707604 -0400
|
||||
committer comfyanonymous <comfyanonymous@protonmail.com> 1790707604 -0400
|
||||
|
||||
ComfyUI v0.38.0
|
||||
@@ -0,0 +1,2 @@
|
||||
From https://github.com/Comfy-Org/ComfyUI
|
||||
* tag v0.38.0 -> FETCH_HEAD
|
||||
@@ -0,0 +1,5 @@
|
||||
{
|
||||
"object": "6b747c0428c343e1417219641db93a4fb7cb69ae",
|
||||
"commit": "6b747c0428c343e1417219641db93a4fb7cb69ae",
|
||||
"tag": "v0.38.0"
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
tree 17e7153e3d56c7398a918c6799e0ba99e873f9c9
|
||||
parent 7a8f3add240fff1399df6378636f3cd6a65ab3e3
|
||||
author comfyanonymous <comfyanonymous@protonmail.com> 1790707604 -0400
|
||||
committer comfyanonymous <comfyanonymous@protonmail.com> 1790707604 -0400
|
||||
|
||||
ComfyUI v0.38.0
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,25 @@
|
||||
"""Colormap utilities for depth and geometry visualisation."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import torch
|
||||
|
||||
|
||||
def turbo(x: torch.Tensor) -> torch.Tensor:
|
||||
"""Anton Mikhailov polynomial approximation of the Turbo colormap.
|
||||
|
||||
Args:
|
||||
x: Float tensor with values in [0, 1].
|
||||
|
||||
Returns:
|
||||
RGB tensor of the same shape as ``x`` with a trailing size-3 dimension.
|
||||
"""
|
||||
x = x.clamp(0.0, 1.0)
|
||||
x2 = x * x
|
||||
x3 = x2 * x
|
||||
x4 = x2 * x2
|
||||
x5 = x4 * x
|
||||
r = 0.13572138 + 4.61539260*x - 42.66032258*x2 + 132.13108234*x3 - 152.94239396*x4 + 59.28637943*x5
|
||||
g = 0.09140261 + 2.19418839*x + 4.84296658*x2 - 14.18503333*x3 + 4.27729857*x4 + 2.82956604*x5
|
||||
b = 0.10667330 + 12.64194608*x - 60.58204836*x2 + 110.36276771*x3 - 89.90310912*x4 + 27.34824973*x5
|
||||
return torch.stack([r, g, b], dim=-1).clamp(0.0, 1.0)
|
||||
+1375
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,188 @@
|
||||
"""Pure-torch + scipy geometry helpers for MoGe inference and mesh export."""
|
||||
|
||||
|
||||
from typing import Optional, Tuple
|
||||
|
||||
import numpy as np
|
||||
import torch
|
||||
import torch.nn.functional as F
|
||||
|
||||
from scipy.optimize import least_squares
|
||||
|
||||
def normalized_view_plane_uv(width: int, height: int, aspect_ratio: Optional[float] = None,
|
||||
dtype: Optional[torch.dtype] = None, device: Optional[torch.device] = None) -> torch.Tensor:
|
||||
"""Normalized view-plane UV coordinates with corners at +/-(W, H)/diagonal."""
|
||||
if aspect_ratio is None:
|
||||
aspect_ratio = width / height
|
||||
span_x = aspect_ratio / (1 + aspect_ratio ** 2) ** 0.5
|
||||
span_y = 1.0 / (1 + aspect_ratio ** 2) ** 0.5
|
||||
u = torch.linspace(-span_x * (width - 1) / width, span_x * (width - 1) / width, width, dtype=dtype, device=device)
|
||||
v = torch.linspace(-span_y * (height - 1) / height, span_y * (height - 1) / height, height, dtype=dtype, device=device)
|
||||
u, v = torch.meshgrid(u, v, indexing="xy")
|
||||
return torch.stack([u, v], dim=-1)
|
||||
|
||||
|
||||
def intrinsics_from_focal_center(fx: torch.Tensor, fy: torch.Tensor, cx: torch.Tensor, cy: torch.Tensor) -> torch.Tensor:
|
||||
"""Assemble (..., 3, 3) intrinsics from broadcastable fx, fy, cx, cy."""
|
||||
fx, fy, cx, cy = [torch.as_tensor(v) for v in (fx, fy, cx, cy)]
|
||||
fx, fy, cx, cy = torch.broadcast_tensors(fx, fy, cx, cy)
|
||||
zero = torch.zeros_like(fx)
|
||||
one = torch.ones_like(fx)
|
||||
return torch.stack([
|
||||
torch.stack([fx, zero, cx], dim=-1),
|
||||
torch.stack([zero, fy, cy], dim=-1),
|
||||
torch.stack([zero, zero, one], dim=-1),
|
||||
], dim=-2)
|
||||
|
||||
|
||||
def depth_map_to_point_map(depth: torch.Tensor, intrinsics: torch.Tensor) -> torch.Tensor:
|
||||
"""Back-project a (..., H, W) depth map through K^-1 to (..., H, W, 3) camera-space points.
|
||||
|
||||
Intrinsics use normalized image coords (x in [0, 1] left->right, y in [0, 1] top->bottom).
|
||||
"""
|
||||
H, W = depth.shape[-2:]
|
||||
device, dtype = depth.device, depth.dtype
|
||||
u = (torch.arange(W, dtype=dtype, device=device) + 0.5) / W
|
||||
v = (torch.arange(H, dtype=dtype, device=device) + 0.5) / H
|
||||
grid_v, grid_u = torch.meshgrid(v, u, indexing="ij")
|
||||
pix = torch.stack([grid_u, grid_v, torch.ones_like(grid_u)], dim=-1)
|
||||
K_inv = torch.linalg.inv(intrinsics)
|
||||
rays = torch.einsum("...ij,hwj->...hwi", K_inv, pix)
|
||||
return rays * depth.unsqueeze(-1)
|
||||
|
||||
|
||||
def _solve_optimal_shift(uv: np.ndarray, xyz: np.ndarray,
|
||||
focal: Optional[float] = None) -> Tuple[float, float]:
|
||||
"""LM-solve for z-shift; when focal is None, also recovers the optimal focal."""
|
||||
uv = uv.reshape(-1, 2)
|
||||
xy = xyz[..., :2].reshape(-1, 2)
|
||||
z = xyz[..., 2].reshape(-1)
|
||||
|
||||
def fn(shift):
|
||||
xy_proj = xy / (z + shift)[:, None]
|
||||
f = focal if focal is not None else (xy_proj * uv).sum() / np.square(xy_proj).sum()
|
||||
return (f * xy_proj - uv).ravel()
|
||||
|
||||
sol = least_squares(fn, x0=0.0, ftol=1e-3, method="lm")
|
||||
shift = float(np.asarray(sol["x"]).squeeze())
|
||||
if focal is None:
|
||||
xy_proj = xy / (z + shift)[:, None]
|
||||
focal = float((xy_proj * uv).sum() / np.square(xy_proj).sum())
|
||||
return shift, focal
|
||||
|
||||
|
||||
def recover_focal_shift(points: torch.Tensor, mask: Optional[torch.Tensor] = None,
|
||||
focal: Optional[torch.Tensor] = None, downsample_size: Tuple[int, int] = (64, 64)
|
||||
) -> Tuple[torch.Tensor, torch.Tensor]:
|
||||
"""Recover the focal length and z-shift that turn points into a metric point map.
|
||||
|
||||
Optical center is at the image center; returned focal is relative to half the image diagonal.
|
||||
Returns (focal, shift) on the same device/dtype as points.
|
||||
"""
|
||||
shape = points.shape
|
||||
H, W = shape[-3], shape[-2]
|
||||
points_b = points.reshape(-1, H, W, 3)
|
||||
mask_b = None if mask is None else mask.reshape(-1, H, W)
|
||||
focal_b = None if focal is None else focal.reshape(-1)
|
||||
|
||||
uv = normalized_view_plane_uv(W, H, dtype=points.dtype, device=points.device)
|
||||
|
||||
points_lr = F.interpolate(points_b.permute(0, 3, 1, 2), downsample_size, mode="nearest").permute(0, 2, 3, 1)
|
||||
uv_lr = F.interpolate(uv.unsqueeze(0).permute(0, 3, 1, 2), downsample_size, mode="nearest").squeeze(0).permute(1, 2, 0)
|
||||
mask_lr = None
|
||||
if mask_b is not None:
|
||||
mask_lr = F.interpolate(mask_b.to(torch.float32).unsqueeze(1), downsample_size, mode="nearest").squeeze(1) > 0
|
||||
|
||||
uv_np = uv_lr.detach().cpu().numpy()
|
||||
points_np = points_lr.detach().cpu().numpy()
|
||||
mask_np = None if mask_lr is None else mask_lr.detach().cpu().numpy()
|
||||
focal_np = None if focal_b is None else focal_b.detach().cpu().numpy()
|
||||
|
||||
out_focal: list = []
|
||||
out_shift: list = []
|
||||
for i in range(points_b.shape[0]):
|
||||
if mask_np is None:
|
||||
xyz_i = points_np[i].reshape(-1, 3)
|
||||
uv_i = uv_np.reshape(-1, 2)
|
||||
else:
|
||||
sel = mask_np[i]
|
||||
if sel.sum() < 2:
|
||||
out_focal.append(1.0)
|
||||
out_shift.append(0.0)
|
||||
continue
|
||||
xyz_i = points_np[i][sel]
|
||||
uv_i = uv_np[sel]
|
||||
if focal_np is None:
|
||||
shift_i, focal_i = _solve_optimal_shift(uv_i, xyz_i)
|
||||
out_focal.append(focal_i)
|
||||
else:
|
||||
shift_i, _ = _solve_optimal_shift(uv_i, xyz_i, focal=float(focal_np[i]))
|
||||
out_shift.append(shift_i)
|
||||
|
||||
shift_t = torch.tensor(out_shift, device=points.device, dtype=points.dtype).reshape(shape[:-3])
|
||||
if focal is None:
|
||||
focal_t = torch.tensor(out_focal, device=points.device, dtype=points.dtype).reshape(shape[:-3])
|
||||
else:
|
||||
focal_t = focal.reshape(shape[:-3])
|
||||
return focal_t, shift_t
|
||||
|
||||
|
||||
def depth_map_edge(depth: torch.Tensor, atol: Optional[float] = None, rtol: Optional[float] = None, kernel_size: int = 3) -> torch.Tensor:
|
||||
"""Per-pixel boolean: True where the local depth window's max-min span exceeds atol or rtol*depth."""
|
||||
shape = depth.shape
|
||||
d = depth.reshape(-1, 1, *shape[-2:])
|
||||
pad = kernel_size // 2
|
||||
diff = F.max_pool2d(d, kernel_size, stride=1, padding=pad) + F.max_pool2d(-d, kernel_size, stride=1, padding=pad)
|
||||
edge = torch.zeros_like(d, dtype=torch.bool)
|
||||
if atol is not None:
|
||||
edge |= diff > atol
|
||||
if rtol is not None:
|
||||
edge |= (diff / d.clamp_min(1e-6)).nan_to_num_() > rtol
|
||||
return edge.reshape(*shape)
|
||||
|
||||
|
||||
def triangulate_grid_mesh(points: torch.Tensor, mask: Optional[torch.Tensor] = None, decimation: int = 1, discontinuity_threshold: float = 0.04,
|
||||
depth: Optional[torch.Tensor] = None) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
|
||||
"""Triangulate a (H, W, 3) point map into (vertices, faces, uvs) on CPU.
|
||||
|
||||
Vertices: pixels with finite coords (passing optional mask). Quads with four valid corners
|
||||
become two triangles. depth overrides the scalar used for the rtol edge check; pass radial
|
||||
depth for panoramas (the default points[..., 2] goes negative below the equator).
|
||||
"""
|
||||
points = points.detach().cpu()
|
||||
finite = torch.isfinite(points).all(dim=-1)
|
||||
if mask is None:
|
||||
mask = finite
|
||||
else:
|
||||
mask = mask.detach().cpu().to(torch.bool) & finite
|
||||
|
||||
if discontinuity_threshold > 0:
|
||||
d = depth.detach().cpu() if depth is not None else points[..., 2]
|
||||
# Replace inf with 0 so max-pool doesn't poison neighbourhoods (mask above already excludes those pixels).
|
||||
d_finite = torch.where(finite, d, torch.zeros_like(d))
|
||||
edge = depth_map_edge(d_finite, rtol=discontinuity_threshold)
|
||||
mask = mask & ~edge
|
||||
|
||||
if decimation > 1:
|
||||
points = points[::decimation, ::decimation].contiguous()
|
||||
mask = mask[::decimation, ::decimation].contiguous()
|
||||
H, W = points.shape[:2]
|
||||
|
||||
flat_mask = mask.reshape(-1)
|
||||
idx = torch.full((H * W,), -1, dtype=torch.long)
|
||||
n_valid = int(flat_mask.sum().item())
|
||||
idx[flat_mask] = torch.arange(n_valid, dtype=torch.long)
|
||||
idx = idx.reshape(H, W)
|
||||
|
||||
vertices = points.reshape(-1, 3)[flat_mask].contiguous()
|
||||
|
||||
yy, xx = torch.meshgrid(torch.arange(H), torch.arange(W), indexing="ij")
|
||||
u = xx.float() / max(W - 1, 1)
|
||||
v = yy.float() / max(H - 1, 1)
|
||||
uvs = torch.stack([u, v], dim=-1).reshape(-1, 2)[flat_mask].contiguous()
|
||||
|
||||
a, b, c, d = idx[:-1, :-1], idx[:-1, 1:], idx[1:, 1:], idx[1:, :-1]
|
||||
quad_ok = (a >= 0) & (b >= 0) & (c >= 0) & (d >= 0)
|
||||
a, b, c, d = a[quad_ok], b[quad_ok], c[quad_ok], d[quad_ok]
|
||||
faces = torch.cat([torch.stack([a, b, c], dim=-1), torch.stack([a, c, d], dim=-1)], dim=0).contiguous()
|
||||
return vertices, faces, uvs
|
||||
@@ -0,0 +1,425 @@
|
||||
"""MoGe v1 / v2 inference modules and a state-dict-driven builder.
|
||||
|
||||
V1: DINOv2 backbone + multi-output head (points, mask).
|
||||
V2: DINOv2 encoder + neck + per-output heads (points, mask, normal, optional metric-scale MLP).
|
||||
V3: V2 plus a sparse 3D UNet that iteratively refines the predicted log-depth.
|
||||
"""
|
||||
|
||||
|
||||
from numbers import Number
|
||||
from typing import Any, Dict, List, Optional, Tuple, Union
|
||||
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
import torch.nn.functional as F
|
||||
|
||||
import comfy.ops
|
||||
import comfy.model_management
|
||||
import comfy.model_patcher
|
||||
import comfy.storage
|
||||
|
||||
from comfy.image_encoders.dino2 import Dinov2Model
|
||||
|
||||
from .geometry import depth_map_to_point_map, intrinsics_from_focal_center, recover_focal_shift
|
||||
from .modules import ConvStack, DINOv2Encoder, HeadV1, MLP, Sparse3DUNet, _view_plane_uv_grid
|
||||
|
||||
|
||||
def _remap_points(points: torch.Tensor) -> torch.Tensor:
|
||||
"""Apply the exp remap: z -> exp(z), xy stays linear and gets scaled by the new z."""
|
||||
xy, z = points.split([2, 1], dim=-1)
|
||||
z = torch.exp(z)
|
||||
return torch.cat([xy * z, z], dim=-1)
|
||||
|
||||
|
||||
def _detect_dinov2(sd: dict, prefix: str) -> Dict[str, Any]:
|
||||
# All shipped MoGe checkpoints use plain DINOv2. ViT-g (MoGe-3) swaps the MLP for a fused SwiGLU.
|
||||
hidden = sd[prefix + "embeddings.cls_token"].shape[-1]
|
||||
layer_prefix = prefix + "encoder.layer."
|
||||
depth = 1 + max(int(k[len(layer_prefix):].split(".")[0]) for k in sd if k.startswith(layer_prefix))
|
||||
return {
|
||||
"hidden_size": hidden,
|
||||
"num_attention_heads": hidden // 64,
|
||||
"num_hidden_layers": depth,
|
||||
"layer_norm_eps": 1e-6,
|
||||
"use_swiglu_ffn": layer_prefix + "0.mlp.weights_in.weight" in sd,
|
||||
}
|
||||
|
||||
|
||||
class MoGeModelV1(nn.Module):
|
||||
"""MoGe v1: DINOv2 backbone + HeadV1 (points, mask)."""
|
||||
|
||||
image_mean: torch.Tensor
|
||||
image_std: torch.Tensor
|
||||
|
||||
intermediate_layers = 4
|
||||
num_tokens_range: Tuple[Number, Number] = (1200, 2500)
|
||||
mask_threshold = 0.5
|
||||
|
||||
def __init__(self, backbone: Dict[str, Any], dim_upsample: List[int] = (256, 128, 128),
|
||||
num_res_blocks: int = 1, dim_times_res_block_hidden: int = 1,
|
||||
dtype=None, device=None, operations=comfy.ops.manual_cast):
|
||||
super().__init__()
|
||||
self.backbone = Dinov2Model(backbone, dtype, device, operations)
|
||||
self.head = HeadV1(dim_in=backbone["hidden_size"], dim_upsample=list(dim_upsample),
|
||||
num_res_blocks=num_res_blocks, dim_times_res_block_hidden=dim_times_res_block_hidden,
|
||||
dtype=dtype, device=device, operations=operations)
|
||||
self.register_buffer("image_mean", torch.tensor([0.485, 0.456, 0.406]).view(1, 3, 1, 1))
|
||||
self.register_buffer("image_std", torch.tensor([0.229, 0.224, 0.225]).view(1, 3, 1, 1))
|
||||
|
||||
def forward(self, image: torch.Tensor, num_tokens: int) -> Dict[str, torch.Tensor]:
|
||||
H, W = image.shape[-2:]
|
||||
resize = ((num_tokens * 14 ** 2) / (H * W)) ** 0.5
|
||||
rh, rw = int(H * resize), int(W * resize)
|
||||
x = F.interpolate(image, (rh, rw), mode="bicubic", align_corners=False, antialias=True)
|
||||
x = (x - comfy.ops.cast_to_input(self.image_mean, x, copy=False)) / comfy.ops.cast_to_input(self.image_std, x, copy=False)
|
||||
x14 = F.interpolate(x, (rh // 14 * 14, rw // 14 * 14), mode="bilinear", align_corners=False, antialias=True)
|
||||
|
||||
n_layers = len(self.backbone.encoder.layer)
|
||||
indices = list(range(n_layers - self.intermediate_layers, n_layers))
|
||||
feats = self.backbone.get_intermediate_layers(x14, indices, apply_norm=True)
|
||||
|
||||
points, mask = self.head(feats, x)
|
||||
points = F.interpolate(points.float(), (H, W), mode="bilinear", align_corners=False)
|
||||
points = _remap_points(points.permute(0, 2, 3, 1))
|
||||
|
||||
mask = F.interpolate(mask.float(), (H, W), mode="bilinear", align_corners=False).squeeze(1)
|
||||
|
||||
return {"points": points, "mask": mask}
|
||||
|
||||
@classmethod
|
||||
def from_state_dict(cls, sd, dtype=None, device=None, operations=comfy.ops.manual_cast):
|
||||
"""Detect the v1 head config from sd, build a model, and load weights."""
|
||||
n_up = 1 + max(int(k.split(".")[2]) for k in sd if k.startswith("head.upsample_blocks."))
|
||||
dim_upsample = [sd[f"head.upsample_blocks.{i}.0.0.weight"].shape[1] for i in range(n_up)]
|
||||
# Each upsample stage is Sequential[upsampler, *res_blocks]; count res blocks at level 0.
|
||||
num_res_blocks = max({int(k.split(".")[3]) for k in sd if k.startswith("head.upsample_blocks.0.")})
|
||||
hidden_out = sd["head.upsample_blocks.0.1.layers.2.weight"].shape[0]
|
||||
dim_times = max(hidden_out // dim_upsample[0], 1)
|
||||
model = cls(backbone=_detect_dinov2(sd, prefix="backbone."),
|
||||
dim_upsample=dim_upsample, num_res_blocks=num_res_blocks, dim_times_res_block_hidden=dim_times,
|
||||
dtype=dtype, device=device, operations=operations)
|
||||
model.load_state_dict(sd, strict=True)
|
||||
return model
|
||||
|
||||
|
||||
class MoGeModelV2(nn.Module):
|
||||
"""MoGe v2: DINOv2 encoder + neck + per-output heads (points/mask/normal/metric-scale)."""
|
||||
|
||||
intermediate_layers = 4
|
||||
num_tokens_range: Tuple[Number, Number] = (1200, 3600)
|
||||
|
||||
def __init__(self,
|
||||
encoder: Dict[str, Any],
|
||||
neck: Dict[str, Any],
|
||||
points_head: Dict[str, Any],
|
||||
mask_head: Dict[str, Any],
|
||||
scale_head: Dict[str, Any],
|
||||
normal_head: Optional[Dict[str, Any]] = None,
|
||||
dtype=None, device=None, operations=comfy.ops.manual_cast):
|
||||
super().__init__()
|
||||
self.encoder = DINOv2Encoder(**encoder, dtype=dtype, device=device, operations=operations)
|
||||
self.neck = ConvStack(**neck, dtype=dtype, device=device, operations=operations)
|
||||
self.points_head = ConvStack(**points_head, dtype=dtype, device=device, operations=operations)
|
||||
self.mask_head = ConvStack(**mask_head, dtype=dtype, device=device, operations=operations)
|
||||
self.scale_head = MLP(**scale_head, dtype=dtype, device=device, operations=operations)
|
||||
if normal_head is not None:
|
||||
self.normal_head = ConvStack(**normal_head, dtype=dtype, device=device, operations=operations)
|
||||
|
||||
def _trunk(self, image: torch.Tensor, num_tokens: int) -> Tuple[List[torch.Tensor], torch.Tensor, torch.Tensor]:
|
||||
"""Encoder + neck. Returns (neck features, level-0 feature map, class token)."""
|
||||
B, _, H, W = image.shape
|
||||
device, dtype = image.device, image.dtype
|
||||
aspect_ratio = W / H
|
||||
base_h = round((num_tokens / aspect_ratio) ** 0.5)
|
||||
base_w = round((num_tokens * aspect_ratio) ** 0.5)
|
||||
|
||||
feat_top, cls_token = self.encoder(image, base_h, base_w, return_class_token=True)
|
||||
|
||||
# 5-level pyramid: feat at level 0 concatenated with UV, other levels UV-only.
|
||||
levels = [_view_plane_uv_grid(B, base_h * (2 ** L), base_w * (2 ** L), aspect_ratio, dtype, device)
|
||||
for L in range(5)]
|
||||
levels[0] = torch.cat([feat_top, levels[0]], dim=1)
|
||||
|
||||
return self.neck(levels), levels[0], cls_token
|
||||
|
||||
def _heads(self, feats: List[torch.Tensor], cls_token: torch.Tensor, raw_coord: torch.Tensor,
|
||||
size: Tuple[int, int]) -> Dict[str, torch.Tensor]:
|
||||
"""Resize the head outputs to the image size and remap them into the public dict."""
|
||||
def _resize(v):
|
||||
return F.interpolate(v, size, mode="bilinear", align_corners=False)
|
||||
|
||||
points = _remap_points(_resize(raw_coord).permute(0, 2, 3, 1))
|
||||
mask = _resize(self.mask_head(feats)[-1]).squeeze(1).sigmoid()
|
||||
metric_scale = self.scale_head(cls_token).squeeze(1).exp()
|
||||
|
||||
result = {"points": points, "mask": mask, "metric_scale": metric_scale}
|
||||
if hasattr(self, "normal_head"):
|
||||
normal = _resize(self.normal_head(feats)[-1])
|
||||
result["normal"] = F.normalize(normal.permute(0, 2, 3, 1), dim=-1)
|
||||
return result
|
||||
|
||||
def forward(self, image: torch.Tensor, num_tokens: int) -> Dict[str, torch.Tensor]:
|
||||
feats, _conditioning, cls_token = self._trunk(image, num_tokens)
|
||||
return self._heads(feats, cls_token, self.points_head(feats)[-1], image.shape[-2:])
|
||||
|
||||
@classmethod
|
||||
def from_state_dict(cls, sd, dtype=None, device=None, operations=comfy.ops.manual_cast):
|
||||
"""Detect the config from sd, build a model, and load weights."""
|
||||
model = cls(**cls._detect_config(sd), dtype=dtype, device=device, operations=operations)
|
||||
model.load_state_dict(sd, strict=True)
|
||||
return model
|
||||
|
||||
@classmethod
|
||||
def _detect_config(cls, sd) -> Dict[str, Any]:
|
||||
"""Reconstruct the v2 encoder/neck/heads config from the checkpoint keys."""
|
||||
backbone = _detect_dinov2(sd, prefix="encoder.backbone.")
|
||||
depth = backbone["num_hidden_layers"]
|
||||
n = cls.intermediate_layers
|
||||
encoder = {
|
||||
"backbone": backbone,
|
||||
"intermediate_layers": [(depth // n) * (i + 1) - 1 for i in range(n)],
|
||||
"dim_out": sd["encoder.output_projections.0.weight"].shape[0],
|
||||
}
|
||||
# scale_head is an MLP: Sequential of [Linear, ReLU, ..., Linear]; Linear weight is (out, in).
|
||||
scale_idxs = sorted({int(k.split(".")[1]) for k in sd if k.startswith("scale_head.")})
|
||||
scale_first = sd[f"scale_head.{scale_idxs[0]}.weight"]
|
||||
cfg: Dict[str, Any] = {
|
||||
"encoder": encoder,
|
||||
"neck": cls._detect_convstack(sd, "neck."),
|
||||
"points_head": cls._detect_convstack(sd, "points_head."),
|
||||
"mask_head": cls._detect_convstack(sd, "mask_head."),
|
||||
"scale_head": {"dims": [scale_first.shape[1]] + [sd[f"scale_head.{i}.weight"].shape[0] for i in scale_idxs]},
|
||||
}
|
||||
if any(k.startswith("normal_head.") for k in sd):
|
||||
cfg["normal_head"] = cls._detect_convstack(sd, "normal_head.")
|
||||
return cfg
|
||||
|
||||
@staticmethod
|
||||
def _detect_convstack(sd: dict, prefix: str) -> Dict[str, Any]:
|
||||
"""Reconstruct a ConvStack config from the keys under prefix"""
|
||||
in_keys = [k for k in sd if k.startswith(f"{prefix}input_blocks.") and k.endswith(".weight")]
|
||||
n = 1 + max(int(k[len(f"{prefix}input_blocks."):].split(".")[0]) for k in in_keys)
|
||||
|
||||
in_shapes = [sd[f"{prefix}input_blocks.{i}.weight"].shape for i in range(n)]
|
||||
has_out = lambda i: f"{prefix}output_blocks.{i}.weight" in sd
|
||||
has_norm = f"{prefix}res_blocks.0.0.layers.0.weight" in sd
|
||||
|
||||
def num_res_at(i):
|
||||
rb_prefix = f"{prefix}res_blocks.{i}."
|
||||
return len({int(k[len(rb_prefix):].split(".")[0]) for k in sd if k.startswith(rb_prefix)})
|
||||
|
||||
return {
|
||||
"dim_in": [s[1] for s in in_shapes],
|
||||
"dim_res_blocks": [s[0] for s in in_shapes],
|
||||
"dim_out": [sd[f"{prefix}output_blocks.{i}.weight"].shape[0] if has_out(i) else None for i in range(n)],
|
||||
"num_res_blocks": [num_res_at(i) for i in range(n)],
|
||||
"resamplers": ["conv_transpose" if f"{prefix}resamplers.{i}.0.weight" in sd else "bilinear"
|
||||
for i in range(n - 1)],
|
||||
"res_block_in_norm": "layer_norm" if has_norm else "none",
|
||||
"res_block_hidden_norm": "group_norm" if has_norm else "none",
|
||||
}
|
||||
|
||||
|
||||
class MoGeModelV3(MoGeModelV2):
|
||||
"""MoGe v3: the v2 architecture plus a sparse 3D UNet that iteratively refines the point map's log-depth."""
|
||||
|
||||
# Log-depth is binned at 1/256 to build the sparse volume, so the voxel grid stays finer
|
||||
# than the depth detail the refiner is meant to recover.
|
||||
refiner_depth_resolution = 256
|
||||
|
||||
def __init__(self, refiner: Dict[str, Any], dtype=None, device=None, operations=comfy.ops.manual_cast, **v2_kwargs):
|
||||
super().__init__(**v2_kwargs, dtype=dtype, device=device, operations=operations)
|
||||
self.refiner = Sparse3DUNet(**refiner, dtype=dtype, device=device, operations=operations)
|
||||
|
||||
def _refine_logz(self, coord: torch.Tensor, conditioning: torch.Tensor) -> torch.Tensor:
|
||||
"""One refinement pass over the point map at (x/z, y/z, logz), returning the updated logz."""
|
||||
B, H, W, _ = coord.shape
|
||||
device = coord.device
|
||||
logz = coord[..., 2]
|
||||
|
||||
# Bin in fp32: logz * 256 lands where fp16's ULP exceeds 1 for far geometry, which would
|
||||
# collapse neighbouring voxels. The refiner itself runs at the activation dtype.
|
||||
z_bin = torch.round(logz.float() * self.refiner_depth_resolution).long()
|
||||
z_bin = z_bin - z_bin.amin(dim=(1, 2), keepdim=True)
|
||||
|
||||
rows = torch.arange(H, device=device).view(1, H, 1).expand(B, H, W)
|
||||
cols = torch.arange(W, device=device).view(1, 1, W).expand(B, H, W)
|
||||
batch = torch.arange(B, device=device).view(B, 1, 1).expand(B, H, W)
|
||||
coords = torch.stack([batch, rows, cols, z_bin], dim=-1).reshape(-1, 4).to(torch.int32)
|
||||
spatial = (H, W, int(z_bin.amax()) + 1)
|
||||
|
||||
residual = self.refiner(coord.reshape(-1, 3), coords, spatial, conditioning)
|
||||
return logz + residual.reshape(B, H, W)
|
||||
|
||||
def forward(self, image: torch.Tensor, num_tokens: int, refine_steps: int = 3) -> Dict[str, torch.Tensor]:
|
||||
feats, conditioning, cls_token = self._trunk(image, num_tokens)
|
||||
|
||||
coord = self.points_head(feats)[-1].permute(0, 2, 3, 1)
|
||||
for _ in range(refine_steps):
|
||||
coord = torch.cat([coord[..., :2], self._refine_logz(coord, conditioning).unsqueeze(-1)], dim=-1)
|
||||
|
||||
# _remap_points takes exp(logz), which overflows fp16 past ~11.1, so hand the heads fp32.
|
||||
return self._heads(feats, cls_token, coord.permute(0, 3, 1, 2).float(), image.shape[-2:])
|
||||
|
||||
@classmethod
|
||||
def _detect_config(cls, sd) -> Dict[str, Any]:
|
||||
cfg = super()._detect_config(sd)
|
||||
# Both released MoGe-3 checkpoints share one refiner shape; only the conditioning
|
||||
# width follows the encoder (1026 for ViT-L, 1538 for ViT-g).
|
||||
cfg["refiner"] = {"encoder_channels": sd["refiner.encoder_fuse.weight"].shape[1]}
|
||||
return cfg
|
||||
|
||||
|
||||
# Translate the Meta-style DINOv2 keys MoGe ships to the naming ComfyUI DINOv2 port expects,
|
||||
# and split each fused qkv tensor into Q/K/V.
|
||||
_DINOV2_TOPLEVEL_RENAMES = {
|
||||
"patch_embed.proj.weight": "embeddings.patch_embeddings.projection.weight",
|
||||
"patch_embed.proj.bias": "embeddings.patch_embeddings.projection.bias",
|
||||
"cls_token": "embeddings.cls_token",
|
||||
"pos_embed": "embeddings.position_embeddings",
|
||||
"register_tokens": "embeddings.register_tokens",
|
||||
"mask_token": "embeddings.mask_token",
|
||||
"norm.weight": "layernorm.weight",
|
||||
"norm.bias": "layernorm.bias",
|
||||
}
|
||||
_DINOV2_BLOCK_RENAMES = [
|
||||
("ls1.gamma", "layer_scale1.lambda1"),
|
||||
("ls2.gamma", "layer_scale2.lambda1"),
|
||||
("attn.proj.", "attention.output.dense."),
|
||||
("mlp.w12.", "mlp.weights_in."),
|
||||
("mlp.w3.", "mlp.weights_out."),
|
||||
]
|
||||
|
||||
|
||||
def _remap_state_dict(sd: dict) -> dict:
|
||||
if "model" in sd and "model_config" in sd:
|
||||
sd = sd["model"]
|
||||
prefix = "encoder.backbone." if any(k.startswith("encoder.backbone.") for k in sd) else "backbone."
|
||||
out: dict = {}
|
||||
for k, v in sd.items():
|
||||
if not k.startswith(prefix):
|
||||
out[k] = v
|
||||
continue
|
||||
rel = k[len(prefix):]
|
||||
if rel in _DINOV2_TOPLEVEL_RENAMES:
|
||||
out[prefix + _DINOV2_TOPLEVEL_RENAMES[rel]] = v
|
||||
continue
|
||||
if not rel.startswith("blocks."):
|
||||
out[k] = v
|
||||
continue
|
||||
_, idx, sub = rel.split(".", 2)
|
||||
if sub in ("attn.qkv.weight", "attn.qkv.bias"):
|
||||
tail = sub.rsplit(".", 1)[1]
|
||||
q, kw, vw = v.chunk(3, dim=0)
|
||||
base = f"{prefix}encoder.layer.{idx}.attention.attention"
|
||||
out[f"{base}.query.{tail}"] = q
|
||||
out[f"{base}.key.{tail}"] = kw
|
||||
out[f"{base}.value.{tail}"] = vw
|
||||
continue
|
||||
for old, new in _DINOV2_BLOCK_RENAMES:
|
||||
sub = sub.replace(old, new)
|
||||
out[f"{prefix}encoder.layer.{idx}.{sub}"] = v
|
||||
return out
|
||||
|
||||
|
||||
def build_from_state_dict(sd: dict, dtype=None, device=None, operations=comfy.ops.manual_cast) -> nn.Module:
|
||||
"""Dispatch to v1, v2 or v3 based on the DINOv2 backbone prefix and the presence of the v3 refiner."""
|
||||
sd = _remap_state_dict(sd)
|
||||
if not any(k.startswith("encoder.backbone.") for k in sd):
|
||||
cls = MoGeModelV1
|
||||
elif any(k.startswith("refiner.") for k in sd):
|
||||
cls = MoGeModelV3
|
||||
else:
|
||||
cls = MoGeModelV2
|
||||
return cls.from_state_dict(sd, dtype=dtype, device=device, operations=operations)
|
||||
|
||||
|
||||
class MoGeModel:
|
||||
"""Loaded MoGe model + ComfyUI memory management."""
|
||||
|
||||
def __init__(self, state_dict: dict):
|
||||
self.load_device = comfy.model_management.text_encoder_device()
|
||||
offload_device = comfy.model_management.text_encoder_offload_device()
|
||||
self.dtype = comfy.model_management.text_encoder_dtype(self.load_device)
|
||||
|
||||
self.model = build_from_state_dict(state_dict, dtype=self.dtype, device=offload_device, operations=comfy.ops.manual_cast).eval()
|
||||
self.patcher = comfy.model_patcher.CoreModelPatcher(self.model, load_device=self.load_device, offload_device=offload_device, fast_disk=comfy.storage.state_dict_fast_disk(state_dict))
|
||||
if not hasattr(self.model, "encoder"):
|
||||
self.version = "v1"
|
||||
else:
|
||||
self.version = "v3" if hasattr(self.model, "refiner") else "v2"
|
||||
self.mask_threshold = float(getattr(self.model, "mask_threshold", 0.5))
|
||||
nt = getattr(self.model, "num_tokens_range", (1200, 2500 if self.version == "v1" else 3600))
|
||||
self.num_tokens_range = (int(nt[0]), int(nt[1]))
|
||||
|
||||
def infer(self, image: torch.Tensor, num_tokens: Optional[int] = None,
|
||||
resolution_level: int = 9, fov_x: Optional[Union[Number, torch.Tensor]] = None,
|
||||
force_projection: bool = True, apply_mask: bool = True,
|
||||
apply_metric_scale: bool = True, refine_steps: int = 3
|
||||
) -> Dict[str, torch.Tensor]:
|
||||
"""Run a single MoGe forward + post-process pass. image is (B, 3, H, W) in [0, 1]."""
|
||||
comfy.model_management.load_model_gpu(self.patcher)
|
||||
|
||||
# Compute is fp32 or fp16 only: bf16 would cost 4x the error at the same speed
|
||||
compute_dtype = self.dtype if self.dtype in (torch.float32, torch.float16) else torch.float16
|
||||
activation_dtype = compute_dtype if self.version == "v3" else torch.float32
|
||||
image = image.to(device=self.load_device, dtype=activation_dtype)
|
||||
H, W = image.shape[-2:]
|
||||
aspect_ratio = W / H
|
||||
|
||||
if num_tokens is None:
|
||||
lo, hi = self.num_tokens_range
|
||||
num_tokens = int(lo + (resolution_level / 9) * (hi - lo))
|
||||
|
||||
# refine_steps only exists on v3; v1/v2 have no refiner to run.
|
||||
extra = {"refine_steps": refine_steps} if self.version == "v3" else {}
|
||||
out = self.model.forward(image, num_tokens=num_tokens, **extra)
|
||||
points = out["points"].float() # recover_focal_shift goes through scipy on CPU; needs fp32.
|
||||
mask_binary = out["mask"] > self.mask_threshold
|
||||
normal = out.get("normal")
|
||||
normal = normal.float() if normal is not None else None
|
||||
metric_scale = out.get("metric_scale")
|
||||
|
||||
diag = (1 + aspect_ratio ** 2) ** 0.5
|
||||
|
||||
def focal_from_fov_deg(deg):
|
||||
fov = torch.as_tensor(deg, device=points.device, dtype=points.dtype)
|
||||
return aspect_ratio / diag / torch.tan(torch.deg2rad(fov / 2))
|
||||
|
||||
if fov_x is None:
|
||||
focal, shift = recover_focal_shift(points, mask_binary)
|
||||
# Fall back to 60 deg FoV when the least-squares solver flips the focal sign.
|
||||
bad = ~torch.isfinite(focal) | (focal <= 0)
|
||||
if bool(bad.any()):
|
||||
focal = torch.where(bad, focal_from_fov_deg(60.0), focal)
|
||||
_, shift = recover_focal_shift(points, mask_binary, focal=focal)
|
||||
else:
|
||||
focal = focal_from_fov_deg(fov_x).expand(points.shape[0])
|
||||
_, shift = recover_focal_shift(points, mask_binary, focal=focal)
|
||||
|
||||
f_diag = focal / 2 * diag
|
||||
half = torch.tensor(0.5, device=points.device, dtype=points.dtype)
|
||||
intrinsics = intrinsics_from_focal_center(f_diag / aspect_ratio, f_diag, half, half)
|
||||
points[..., 2] = points[..., 2] + shift[..., None, None]
|
||||
# v2/v3 only: filter mask by depth>0 to drop metric-scale negative-depth artifacts.
|
||||
if self.version != "v1":
|
||||
mask_binary = mask_binary & (points[..., 2] > 0)
|
||||
depth = points[..., 2].clone()
|
||||
|
||||
if force_projection:
|
||||
points = depth_map_to_point_map(depth, intrinsics=intrinsics)
|
||||
|
||||
if apply_metric_scale and metric_scale is not None:
|
||||
points = points * metric_scale[:, None, None, None]
|
||||
depth = depth * metric_scale[:, None, None]
|
||||
|
||||
if apply_mask:
|
||||
points = torch.where(mask_binary[..., None], points, torch.full_like(points, float("inf")))
|
||||
depth = torch.where(mask_binary, depth, torch.full_like(depth, float("inf")))
|
||||
if normal is not None:
|
||||
normal = torch.where(mask_binary[..., None], normal, torch.zeros_like(normal))
|
||||
|
||||
result = {"points": points, "depth": depth, "intrinsics": intrinsics, "mask": mask_binary}
|
||||
if normal is not None:
|
||||
result["normal"] = normal
|
||||
return result
|
||||
@@ -0,0 +1,331 @@
|
||||
"""Building blocks for MoGe: residual conv stack, resamplers, MLP, DINOv2 encoder, v1 head, v3 sparse refiner."""
|
||||
|
||||
|
||||
from typing import List, Optional, Sequence, Tuple, Union
|
||||
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
import torch.nn.functional as F
|
||||
|
||||
import comfy.ops
|
||||
from comfy.image_encoders.dino2 import Dinov2Model
|
||||
from comfy.ldm.trellis2.flexgemm import sparse_pool3d_mean, sparse_submanifold_conv3d, sparse_upsample3d_nearest
|
||||
|
||||
from .geometry import normalized_view_plane_uv
|
||||
|
||||
|
||||
def _conv2d(operations, c_in: int, c_out: int, k: int = 3, *, dtype=None, device=None):
|
||||
return operations.Conv2d(c_in, c_out, kernel_size=k, padding=k // 2, padding_mode="replicate", dtype=dtype, device=device)
|
||||
|
||||
|
||||
def _view_plane_uv_grid(batch: int, height: int, width: int, aspect_ratio: float, dtype, device) -> torch.Tensor:
|
||||
"""Batched normalized view-plane UV grid as a (B, 2, H, W) tensor."""
|
||||
uv = normalized_view_plane_uv(width, height, aspect_ratio=aspect_ratio, dtype=dtype, device=device)
|
||||
return uv.permute(2, 0, 1).unsqueeze(0).expand(batch, -1, -1, -1)
|
||||
|
||||
|
||||
def _concat_view_plane_uv(x: torch.Tensor, aspect_ratio: float) -> torch.Tensor:
|
||||
"""Append a 2-channel normalized view-plane UV grid to x along the channel dim."""
|
||||
uv = _view_plane_uv_grid(x.shape[0], x.shape[-2], x.shape[-1], aspect_ratio, x.dtype, x.device)
|
||||
return torch.cat([x, uv], dim=1)
|
||||
|
||||
|
||||
class ResidualConvBlock(nn.Module):
|
||||
def __init__(self, channels: int, hidden_channels: Optional[int] = None, in_norm: str = "layer_norm", hidden_norm: str = "group_norm",
|
||||
dtype=None, device=None, operations=comfy.ops.manual_cast):
|
||||
super().__init__()
|
||||
hidden_channels = hidden_channels if hidden_channels is not None else channels
|
||||
|
||||
in_norm_layer = operations.GroupNorm(1, channels, dtype=dtype, device=device) if in_norm == "layer_norm" else nn.Identity()
|
||||
hidden_norm_layer = (operations.GroupNorm(max(hidden_channels // 32, 1), hidden_channels, dtype=dtype, device=device)
|
||||
if hidden_norm == "group_norm" else nn.Identity())
|
||||
|
||||
self.layers = nn.Sequential(
|
||||
in_norm_layer, nn.ReLU(), _conv2d(operations, channels, hidden_channels, dtype=dtype, device=device),
|
||||
hidden_norm_layer, nn.ReLU(), _conv2d(operations, hidden_channels, channels, dtype=dtype, device=device),
|
||||
)
|
||||
|
||||
def forward(self, x):
|
||||
return self.layers(x) + x
|
||||
|
||||
|
||||
class Resampler(nn.Sequential):
|
||||
"""2x upsampler: ConvTranspose2d(2x2) or bilinear upsample, followed by a 3x3 conv."""
|
||||
|
||||
def __init__(self, in_channels: int, out_channels: int, type_: str, dtype=None, device=None, operations=comfy.ops.manual_cast):
|
||||
if type_ == "conv_transpose":
|
||||
up = operations.ConvTranspose2d(in_channels, out_channels, kernel_size=2, stride=2, dtype=dtype, device=device)
|
||||
conv_in = out_channels
|
||||
else: # "bilinear"
|
||||
up = nn.Upsample(scale_factor=2, mode="bilinear", align_corners=False)
|
||||
conv_in = in_channels
|
||||
super().__init__(up, _conv2d(operations, conv_in, out_channels, dtype=dtype, device=device))
|
||||
|
||||
|
||||
class MLP(nn.Sequential):
|
||||
def __init__(self, dims: Sequence[int], dtype=None, device=None, operations=comfy.ops.manual_cast):
|
||||
layers = []
|
||||
for d_in, d_out in zip(dims[:-2], dims[1:-1]):
|
||||
layers.append(operations.Linear(d_in, d_out, dtype=dtype, device=device))
|
||||
layers.append(nn.ReLU(inplace=True))
|
||||
layers.append(operations.Linear(dims[-2], dims[-1], dtype=dtype, device=device))
|
||||
super().__init__(*layers)
|
||||
|
||||
|
||||
class ConvStack(nn.Module):
|
||||
def __init__(self, dim_in: List[Optional[int]], dim_res_blocks: List[int], dim_out: List[Optional[int]], resamplers: List[str],
|
||||
num_res_blocks: List[int], dim_times_res_block_hidden: int = 1, res_block_in_norm: str = "layer_norm", res_block_hidden_norm: str = "group_norm",
|
||||
dtype=None, device=None, operations=comfy.ops.manual_cast):
|
||||
super().__init__()
|
||||
|
||||
self.input_blocks = nn.ModuleList([
|
||||
(_conv2d(operations, d_in, d_res, k=1, dtype=dtype, device=device)
|
||||
if d_in is not None else nn.Identity())
|
||||
for d_in, d_res in zip(dim_in, dim_res_blocks)
|
||||
])
|
||||
|
||||
self.resamplers = nn.ModuleList([
|
||||
Resampler(prev, succ, type_=r, dtype=dtype, device=device, operations=operations)
|
||||
for prev, succ, r in zip(dim_res_blocks[:-1], dim_res_blocks[1:], resamplers)
|
||||
])
|
||||
|
||||
self.res_blocks = nn.ModuleList([
|
||||
nn.Sequential(*[
|
||||
ResidualConvBlock(d_res, dim_times_res_block_hidden * d_res, in_norm=res_block_in_norm, hidden_norm=res_block_hidden_norm, dtype=dtype, device=device, operations=operations)
|
||||
for _ in range(num_res_blocks[i])
|
||||
])
|
||||
for i, d_res in enumerate(dim_res_blocks)
|
||||
])
|
||||
|
||||
self.output_blocks = nn.ModuleList([
|
||||
(_conv2d(operations, d_res, d_out, k=1, dtype=dtype, device=device)
|
||||
if d_out is not None else nn.Identity())
|
||||
for d_out, d_res in zip(dim_out, dim_res_blocks)
|
||||
])
|
||||
|
||||
def forward(self, in_features: List[Optional[torch.Tensor]]):
|
||||
out_features = []
|
||||
x = None
|
||||
for i in range(len(self.res_blocks)):
|
||||
feat = self.input_blocks[i](in_features[i]) if in_features[i] is not None else None
|
||||
if i == 0:
|
||||
x = feat
|
||||
elif feat is not None:
|
||||
x = x + feat
|
||||
x = self.res_blocks[i](x)
|
||||
out_features.append(self.output_blocks[i](x))
|
||||
if i < len(self.res_blocks) - 1:
|
||||
x = self.resamplers[i](x)
|
||||
return out_features
|
||||
|
||||
|
||||
class DINOv2Encoder(nn.Module):
|
||||
"""Comfy DINOv2 backbone with per-layer 1x1 projection heads."""
|
||||
|
||||
def __init__(self, backbone: dict, intermediate_layers: List[int], dim_out: int, dtype=None, device=None, operations=comfy.ops.manual_cast):
|
||||
super().__init__()
|
||||
self.intermediate_layers = list(intermediate_layers)
|
||||
dim_features = backbone["hidden_size"]
|
||||
self.backbone = Dinov2Model(backbone, dtype, device, operations)
|
||||
self.output_projections = nn.ModuleList([
|
||||
_conv2d(operations, dim_features, dim_out, k=1, dtype=dtype, device=device)
|
||||
for _ in range(len(self.intermediate_layers))
|
||||
])
|
||||
self.register_buffer("image_mean", torch.tensor([0.485, 0.456, 0.406]).view(1, 3, 1, 1))
|
||||
self.register_buffer("image_std", torch.tensor([0.229, 0.224, 0.225]).view(1, 3, 1, 1))
|
||||
|
||||
def forward(self, image: torch.Tensor, token_rows: int, token_cols: int,
|
||||
return_class_token: bool = False) -> Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]:
|
||||
image_14 = F.interpolate(image, (token_rows * 14, token_cols * 14), mode="bilinear", align_corners=False, antialias=True)
|
||||
image_14 = (image_14 - comfy.ops.cast_to_input(self.image_mean, image_14, copy=False)) / comfy.ops.cast_to_input(self.image_std, image_14, copy=False)
|
||||
feats = self.backbone.get_intermediate_layers(image_14, self.intermediate_layers, apply_norm=True)
|
||||
x = torch.stack([
|
||||
proj(feat.permute(0, 2, 1).unflatten(2, (token_rows, token_cols)).contiguous())
|
||||
for proj, (feat, _cls) in zip(self.output_projections, feats)
|
||||
], dim=1).sum(dim=1)
|
||||
if return_class_token:
|
||||
return x, feats[-1][1]
|
||||
return x
|
||||
|
||||
|
||||
class HeadV1(nn.Module):
|
||||
"""v1 head: 4 backbone-feature projections -> shared upsample stack -> per-target output convs (points, mask)."""
|
||||
|
||||
NUM_FEATURES = 4
|
||||
DIM_PROJ = 512
|
||||
DIM_OUT = (3, 1) # 3 channels for points, 1 for mask
|
||||
LAST_CONV_CHANNELS = 32
|
||||
|
||||
def __init__(self, dim_in: int, dim_upsample: List[int] = (256, 128, 128), num_res_blocks: int = 1, dim_times_res_block_hidden: int = 1,
|
||||
dtype=None, device=None, operations=comfy.ops.manual_cast):
|
||||
super().__init__()
|
||||
self.projects = nn.ModuleList([
|
||||
_conv2d(operations, dim_in, self.DIM_PROJ, k=1, dtype=dtype, device=device)
|
||||
for _ in range(self.NUM_FEATURES)
|
||||
])
|
||||
def upsampler(in_ch, out_ch):
|
||||
return nn.Sequential(
|
||||
operations.ConvTranspose2d(in_ch, out_ch, kernel_size=2, stride=2, dtype=dtype, device=device),
|
||||
_conv2d(operations, out_ch, out_ch, dtype=dtype, device=device),
|
||||
)
|
||||
|
||||
in_chs = [self.DIM_PROJ] + list(dim_upsample[:-1])
|
||||
self.upsample_blocks = nn.ModuleList([
|
||||
nn.Sequential(
|
||||
upsampler(in_ch + 2, out_ch),
|
||||
*(ResidualConvBlock(out_ch, dim_times_res_block_hidden * out_ch, dtype=dtype, device=device, operations=operations)
|
||||
for _ in range(num_res_blocks))
|
||||
)
|
||||
for in_ch, out_ch in zip(in_chs, dim_upsample)
|
||||
])
|
||||
self.output_block = nn.ModuleList([
|
||||
nn.Sequential(
|
||||
_conv2d(operations, dim_upsample[-1] + 2, self.LAST_CONV_CHANNELS, dtype=dtype, device=device),
|
||||
nn.ReLU(inplace=True),
|
||||
_conv2d(operations, self.LAST_CONV_CHANNELS, d_out, k=1, dtype=dtype, device=device),
|
||||
)
|
||||
for d_out in self.DIM_OUT
|
||||
])
|
||||
|
||||
def forward(self, hidden_states, image: torch.Tensor):
|
||||
img_h, img_w = image.shape[-2:]
|
||||
patch_h, patch_w = img_h // 14, img_w // 14
|
||||
aspect = img_w / img_h
|
||||
x = torch.stack([
|
||||
proj(feat.permute(0, 2, 1).unflatten(2, (patch_h, patch_w)).contiguous())
|
||||
for proj, (feat, _cls) in zip(self.projects, hidden_states)
|
||||
], dim=1).sum(dim=1)
|
||||
|
||||
for block in self.upsample_blocks:
|
||||
x = block(_concat_view_plane_uv(x, aspect))
|
||||
|
||||
x = F.interpolate(x, (img_h, img_w), mode="bilinear", align_corners=False)
|
||||
x = _concat_view_plane_uv(x, aspect)
|
||||
return [block(x) for block in self.output_block]
|
||||
|
||||
|
||||
class SubmanifoldConv3d(nn.Module):
|
||||
"""3x3x3 submanifold sparse conv. Weight is stored (C_out, K, K, K, C_in), as FlexGEMM writes it.
|
||||
|
||||
Kernel spatial axis i indexes coords column i + 1, matching FlexGEMM's neighbor map.
|
||||
"""
|
||||
|
||||
def __init__(self, in_channels: int, out_channels: int, kernel_size: int = 3, dtype=None, device=None):
|
||||
super().__init__()
|
||||
self.weight = nn.Parameter(torch.empty(out_channels, kernel_size, kernel_size, kernel_size, in_channels, dtype=dtype, device=device))
|
||||
self.bias = nn.Parameter(torch.empty(out_channels, dtype=dtype, device=device))
|
||||
|
||||
def forward(self, feats, coords, spatial, neighbor_cache=None):
|
||||
weight = comfy.ops.cast_to(self.weight, feats.dtype, feats.device)
|
||||
bias = comfy.ops.cast_to(self.bias, feats.dtype, feats.device)
|
||||
return sparse_submanifold_conv3d(feats, coords, spatial, weight, bias, neighbor_cache, (1, 1, 1))
|
||||
|
||||
|
||||
class SparseResBlock3d(nn.Module):
|
||||
def __init__(self, channels: int, dtype=None, device=None, operations=comfy.ops.manual_cast):
|
||||
super().__init__()
|
||||
self.norm1 = operations.LayerNorm(channels, eps=1e-6, dtype=dtype, device=device)
|
||||
self.conv1 = SubmanifoldConv3d(channels, channels, dtype=dtype, device=device)
|
||||
self.conv2 = SubmanifoldConv3d(channels, channels, dtype=dtype, device=device)
|
||||
|
||||
def forward(self, feats, coords, spatial, neighbor_cache=None):
|
||||
h = F.silu(self.norm1(feats))
|
||||
h, neighbor_cache = self.conv1(h, coords, spatial, neighbor_cache)
|
||||
h = F.silu(h)
|
||||
h, neighbor_cache = self.conv2(h, coords, spatial, neighbor_cache)
|
||||
return h + feats, neighbor_cache
|
||||
|
||||
|
||||
class PoolDown(nn.Module):
|
||||
def __init__(self, in_channels: int, out_channels: int, factor: int, dtype=None, device=None, operations=comfy.ops.manual_cast):
|
||||
super().__init__()
|
||||
self.factor = factor
|
||||
self.linear = operations.Linear(in_channels, out_channels, dtype=dtype, device=device)
|
||||
|
||||
def forward(self, feats, coords, spatial):
|
||||
feats, coords, spatial, pool_index = sparse_pool3d_mean(feats, coords, spatial, self.factor)
|
||||
return self.linear(feats), coords, spatial, pool_index
|
||||
|
||||
|
||||
class NearestUp(nn.Module):
|
||||
def __init__(self, in_channels: int, out_channels: int, dtype=None, device=None, operations=comfy.ops.manual_cast):
|
||||
super().__init__()
|
||||
self.linear = operations.Linear(in_channels, out_channels, dtype=dtype, device=device)
|
||||
|
||||
def forward(self, feats, pool_index):
|
||||
return sparse_upsample3d_nearest(self.linear(feats), pool_index)
|
||||
|
||||
|
||||
class Sparse3DUNet(nn.Module):
|
||||
"""MoGe v3 refiner: sparse 3D UNet over the voxelized point map, conditioned on the ViT feature map.
|
||||
|
||||
Takes the sparse volume as (feats, coords, spatial) where coords are (batch, row, col, z_bin),
|
||||
and returns one residual per input voxel.
|
||||
"""
|
||||
|
||||
def __init__(self, encoder_channels: int, in_channels: int = 3, out_channels: int = 1,
|
||||
model_channels: Sequence[int] = (32, 64, 128, 256, 512), blocks_per_level: int = 1,
|
||||
factor: int = 2, dtype=None, device=None, operations=comfy.ops.manual_cast):
|
||||
super().__init__()
|
||||
self.factor = factor
|
||||
kwargs = {"dtype": dtype, "device": device, "operations": operations}
|
||||
# (shallow, deep) channel pair per resolution transition
|
||||
pairs = list(zip(model_channels[:-1], model_channels[1:]))
|
||||
|
||||
def stage(channels):
|
||||
return nn.ModuleList([SparseResBlock3d(channels, **kwargs) for _ in range(blocks_per_level)])
|
||||
|
||||
self.input_proj = operations.Linear(in_channels, model_channels[0], dtype=dtype, device=device)
|
||||
self.encoder_fuse = operations.Linear(encoder_channels, model_channels[-1], dtype=dtype, device=device)
|
||||
self.fuse_proj = nn.Sequential(
|
||||
operations.Linear(model_channels[-1] * 2, model_channels[-1], dtype=dtype, device=device),
|
||||
nn.SiLU(),
|
||||
operations.Linear(model_channels[-1], model_channels[-1], dtype=dtype, device=device),
|
||||
)
|
||||
|
||||
self.down_stages = nn.ModuleList([stage(ch) for ch in model_channels])
|
||||
self.downsample_blocks = nn.ModuleList([PoolDown(lo, hi, factor, **kwargs) for lo, hi in pairs])
|
||||
self.bottleneck_stage = stage(model_channels[-1])
|
||||
# The decoder runs deepest-first, so it walks the transitions in reverse.
|
||||
self.upsample_blocks = nn.ModuleList([NearestUp(hi, lo, **kwargs) for lo, hi in reversed(pairs)])
|
||||
self.up_stages = nn.ModuleList([stage(lo) for lo, _ in reversed(pairs)])
|
||||
self.out_proj = operations.Linear(model_channels[0], out_channels, dtype=dtype, device=device)
|
||||
|
||||
def forward(self, feats, coords, spatial, encoder_feature):
|
||||
num_levels = len(self.down_stages)
|
||||
num_transitions = len(self.downsample_blocks)
|
||||
# Coords at level k are identical on the down and up passes, so the submanifold
|
||||
# neighbor map built on the way down is still valid on the way back up.
|
||||
conv_caches: List[Optional[torch.Tensor]] = [None] * num_levels
|
||||
pool_indices: List[Optional[torch.Tensor]] = [None] * num_transitions
|
||||
skips: List[Optional[Tuple[torch.Tensor, torch.Tensor, tuple]]] = [None] * num_transitions
|
||||
|
||||
feats = self.input_proj(feats)
|
||||
|
||||
for i, blocks in enumerate(self.down_stages):
|
||||
cache = conv_caches[i]
|
||||
for block in blocks:
|
||||
feats, cache = block(feats, coords, spatial, cache)
|
||||
conv_caches[i] = cache
|
||||
if i < num_transitions:
|
||||
skips[i] = (feats, coords, spatial)
|
||||
feats, coords, spatial, pool_indices[i] = self.downsample_blocks[i](feats, coords, spatial)
|
||||
|
||||
conditioning = encoder_feature[coords[:, 0].long(), :, coords[:, 1].long(), coords[:, 2].long()]
|
||||
feats = self.fuse_proj(torch.cat([feats, self.encoder_fuse(conditioning)], dim=-1))
|
||||
|
||||
cache = conv_caches[num_levels - 1]
|
||||
for block in self.bottleneck_stage:
|
||||
feats, cache = block(feats, coords, spatial, cache)
|
||||
conv_caches[num_levels - 1] = cache
|
||||
|
||||
for i, (upsample, blocks) in enumerate(zip(self.upsample_blocks, self.up_stages)):
|
||||
level = num_levels - 2 - i
|
||||
skip_feats, coords, spatial = skips[level]
|
||||
feats = upsample(feats, pool_indices[level]) + skip_feats
|
||||
cache = conv_caches[level]
|
||||
for block in blocks:
|
||||
feats, cache = block(feats, coords, spatial, cache)
|
||||
conv_caches[level] = cache
|
||||
|
||||
return self.out_proj(feats)
|
||||
@@ -0,0 +1,312 @@
|
||||
"""Panorama (equirectangular) inference helpers for MoGe.
|
||||
|
||||
Splits an equirect into 12 perspective views via an icosahedron camera rig, runs
|
||||
the model per view, and stitches per-view distance maps back into a single
|
||||
equirect distance map via a multi-scale Poisson + gradient sparse solve.
|
||||
Image sampling uses F.grid_sample (GPU); the sparse solve uses lsmr (CPU).
|
||||
"""
|
||||
|
||||
|
||||
from typing import Callable, List, Optional, Tuple
|
||||
|
||||
import numpy as np
|
||||
import torch
|
||||
import torch.nn.functional as F
|
||||
|
||||
from scipy.ndimage import convolve, map_coordinates
|
||||
from scipy.sparse import vstack, csr_array
|
||||
from scipy.sparse.linalg import lsmr
|
||||
|
||||
|
||||
def _icosahedron_directions() -> np.ndarray:
|
||||
"""12 icosahedron-vertex directions (non-normalised, matching upstream's vertex order)."""
|
||||
A = (1.0 + np.sqrt(5.0)) / 2.0
|
||||
return np.array([
|
||||
[0, 1, A], [0, -1, A], [0, 1, -A], [0, -1, -A],
|
||||
[1, A, 0], [-1, A, 0], [1, -A, 0], [-1, -A, 0],
|
||||
[A, 0, 1], [A, 0, -1], [-A, 0, 1], [-A, 0, -1],
|
||||
], dtype=np.float32)
|
||||
|
||||
|
||||
def _intrinsics_from_fov(fov_x_rad: float, fov_y_rad: float) -> np.ndarray:
|
||||
"""Normalised-image (unit-square) K matrix."""
|
||||
fx = 0.5 / np.tan(fov_x_rad / 2)
|
||||
fy = 0.5 / np.tan(fov_y_rad / 2)
|
||||
return np.array([[fx, 0, 0.5], [0, fy, 0.5], [0, 0, 1]], dtype=np.float32)
|
||||
|
||||
|
||||
def _extrinsics_look_at(eye: np.ndarray, target: np.ndarray, up: np.ndarray) -> np.ndarray:
|
||||
"""OpenCV-convention world->camera extrinsics for an array of look-at targets (N, 4, 4)."""
|
||||
eye = np.asarray(eye, dtype=np.float32)
|
||||
target = np.asarray(target, dtype=np.float32)
|
||||
up = np.asarray(up, dtype=np.float32)
|
||||
if target.ndim == 1:
|
||||
target = target[None]
|
||||
|
||||
fwd = target - eye
|
||||
fwd = fwd / np.linalg.norm(fwd, axis=-1, keepdims=True).clip(1e-12)
|
||||
right = np.cross(fwd, up)
|
||||
right_norm = np.linalg.norm(right, axis=-1, keepdims=True)
|
||||
# Fall back to an arbitrary perpendicular if forward is parallel to up.
|
||||
parallel = right_norm.squeeze(-1) < 1e-6
|
||||
if parallel.any():
|
||||
alt_up = np.array([1, 0, 0], dtype=np.float32)
|
||||
right = np.where(parallel[:, None], np.cross(fwd, alt_up), right)
|
||||
right_norm = np.linalg.norm(right, axis=-1, keepdims=True)
|
||||
right = right / right_norm.clip(1e-12)
|
||||
new_up = np.cross(fwd, right)
|
||||
|
||||
R = np.stack([right, new_up, fwd], axis=-2)
|
||||
t = -np.einsum("nij,j->ni", R, eye)
|
||||
E = np.zeros((R.shape[0], 4, 4), dtype=np.float32)
|
||||
E[:, :3, :3] = R
|
||||
E[:, :3, 3] = t
|
||||
E[:, 3, 3] = 1.0
|
||||
return E
|
||||
|
||||
|
||||
def get_panorama_cameras() -> Tuple[np.ndarray, List[np.ndarray]]:
|
||||
"""Returns (extrinsics (12, 4, 4), [intrinsics] * 12) for icosahedron views at 90 deg FoV."""
|
||||
targets = _icosahedron_directions()
|
||||
eye = np.zeros(3, dtype=np.float32)
|
||||
up = np.array([0, 0, 1], dtype=np.float32)
|
||||
extrinsics = _extrinsics_look_at(eye, targets, up)
|
||||
K = _intrinsics_from_fov(np.deg2rad(90.0), np.deg2rad(90.0))
|
||||
return extrinsics, [K] * len(targets)
|
||||
|
||||
|
||||
def spherical_uv_to_directions(uv: np.ndarray) -> np.ndarray:
|
||||
"""Equirect UV in [0, 1] -> 3D unit-direction (Z up)."""
|
||||
theta = (1 - uv[..., 0]) * (2 * np.pi)
|
||||
phi = uv[..., 1] * np.pi
|
||||
return np.stack([
|
||||
np.sin(phi) * np.cos(theta),
|
||||
np.sin(phi) * np.sin(theta),
|
||||
np.cos(phi),
|
||||
], axis=-1).astype(np.float32)
|
||||
|
||||
|
||||
def directions_to_spherical_uv(directions: np.ndarray) -> np.ndarray:
|
||||
"""3D direction -> equirect UV in [0, 1]."""
|
||||
n = np.linalg.norm(directions, axis=-1, keepdims=True).clip(1e-12)
|
||||
d = directions / n
|
||||
u = 1 - np.arctan2(d[..., 1], d[..., 0]) / (2 * np.pi) % 1.0
|
||||
v = np.arccos(d[..., 2].clip(-1, 1)) / np.pi
|
||||
return np.stack([u, v], axis=-1).astype(np.float32)
|
||||
|
||||
|
||||
def _uv_grid(H: int, W: int) -> np.ndarray:
|
||||
"""Pixel-center UV grid in [0, 1]; (H, W, 2)."""
|
||||
u = (np.arange(W, dtype=np.float32) + 0.5) / W
|
||||
v = (np.arange(H, dtype=np.float32) + 0.5) / H
|
||||
return np.stack(np.meshgrid(u, v, indexing="xy"), axis=-1)
|
||||
|
||||
|
||||
def _unproject_cv(uv: np.ndarray, depth: np.ndarray,
|
||||
extrinsics: np.ndarray, intrinsics: np.ndarray) -> np.ndarray:
|
||||
"""Back-project pixels into world coords (OpenCV convention)."""
|
||||
pix = np.concatenate([uv, np.ones_like(uv[..., :1])], axis=-1)
|
||||
K_inv = np.linalg.inv(intrinsics)
|
||||
cam = pix @ K_inv.T * depth[..., None]
|
||||
cam_h = np.concatenate([cam, np.ones_like(cam[..., :1])], axis=-1)
|
||||
E_inv = np.linalg.inv(extrinsics)
|
||||
return (cam_h @ E_inv.T)[..., :3]
|
||||
|
||||
|
||||
def _project_cv(points: np.ndarray, extrinsics: np.ndarray, intrinsics: np.ndarray) -> Tuple[np.ndarray, np.ndarray]:
|
||||
"""World coords -> (uv, depth) in the camera (OpenCV convention)."""
|
||||
pts_h = np.concatenate([points, np.ones_like(points[..., :1])], axis=-1)
|
||||
cam = pts_h @ extrinsics.T
|
||||
cam_xyz = cam[..., :3]
|
||||
depth = cam_xyz[..., 2]
|
||||
proj = cam_xyz @ intrinsics.T
|
||||
uv = proj[..., :2] / proj[..., 2:3].clip(1e-12)
|
||||
return uv.astype(np.float32), depth.astype(np.float32)
|
||||
|
||||
|
||||
def _grid_sample_uv(img_bchw: torch.Tensor, uv: torch.Tensor, mode: str = "bilinear") -> torch.Tensor:
|
||||
"""Sample img_bchw at UV-in-[0,1] coords uv of shape (B, H, W, 2); replicate-border."""
|
||||
grid = uv * 2.0 - 1.0
|
||||
return F.grid_sample(img_bchw, grid, mode=mode, padding_mode="border", align_corners=False)
|
||||
|
||||
|
||||
def split_panorama_image(image: torch.Tensor, extrinsics: np.ndarray, intrinsics: List[np.ndarray], resolution: int) -> torch.Tensor:
|
||||
"""(3, Hp, Wp) equirect on any device -> (N, 3, R, R) perspective crops on the same device."""
|
||||
device = image.device
|
||||
N = len(extrinsics)
|
||||
uv = _uv_grid(resolution, resolution)
|
||||
sample_uvs = []
|
||||
for i in range(N):
|
||||
world = _unproject_cv(uv, np.ones(uv.shape[:-1], dtype=np.float32), extrinsics[i], intrinsics[i])
|
||||
sample_uvs.append(directions_to_spherical_uv(world))
|
||||
sample_uvs = np.stack(sample_uvs, axis=0)
|
||||
|
||||
img_bchw = image.unsqueeze(0).expand(N, -1, -1, -1).contiguous()
|
||||
sample_uvs_t = torch.from_numpy(sample_uvs).to(device=device, dtype=image.dtype)
|
||||
return _grid_sample_uv(img_bchw, sample_uvs_t, mode="bilinear")
|
||||
|
||||
|
||||
def _poisson_equation(W: int, H: int, wrap_x: bool = False, wrap_y: bool = False):
|
||||
"""Sparse Laplacian operator over the H x W grid."""
|
||||
grid_index = np.arange(H * W).reshape(H, W)
|
||||
grid_index = np.pad(grid_index, ((0, 0), (1, 1)), mode="wrap" if wrap_x else "edge")
|
||||
grid_index = np.pad(grid_index, ((1, 1), (0, 0)), mode="wrap" if wrap_y else "edge")
|
||||
|
||||
data = np.array([[-4, 1, 1, 1, 1]], dtype=np.float32).repeat(H * W, axis=0).reshape(-1)
|
||||
indices = np.stack([
|
||||
grid_index[1:-1, 1:-1],
|
||||
grid_index[:-2, 1:-1], grid_index[2:, 1:-1],
|
||||
grid_index[1:-1, :-2], grid_index[1:-1, 2:],
|
||||
], axis=-1).reshape(-1)
|
||||
indptr = np.arange(0, H * W * 5 + 1, 5)
|
||||
return csr_array((data, indices, indptr), shape=(H * W, H * W))
|
||||
|
||||
|
||||
def _grad_equation(W: int, H: int, wrap_x: bool = False, wrap_y: bool = False):
|
||||
"""Sparse forward-difference operator over the H x W grid."""
|
||||
grid_index = np.arange(W * H).reshape(H, W)
|
||||
if wrap_x:
|
||||
grid_index = np.pad(grid_index, ((0, 0), (0, 1)), mode="wrap")
|
||||
if wrap_y:
|
||||
grid_index = np.pad(grid_index, ((0, 1), (0, 0)), mode="wrap")
|
||||
|
||||
data = np.concatenate([
|
||||
np.concatenate([
|
||||
np.ones((grid_index.shape[0], grid_index.shape[1] - 1), dtype=np.float32).reshape(-1, 1),
|
||||
-np.ones((grid_index.shape[0], grid_index.shape[1] - 1), dtype=np.float32).reshape(-1, 1),
|
||||
], axis=1).reshape(-1),
|
||||
np.concatenate([
|
||||
np.ones((grid_index.shape[0] - 1, grid_index.shape[1]), dtype=np.float32).reshape(-1, 1),
|
||||
-np.ones((grid_index.shape[0] - 1, grid_index.shape[1]), dtype=np.float32).reshape(-1, 1),
|
||||
], axis=1).reshape(-1),
|
||||
])
|
||||
indices = np.concatenate([
|
||||
np.concatenate([grid_index[:, :-1].reshape(-1, 1), grid_index[:, 1:].reshape(-1, 1)], axis=1).reshape(-1),
|
||||
np.concatenate([grid_index[:-1, :].reshape(-1, 1), grid_index[1:, :].reshape(-1, 1)], axis=1).reshape(-1),
|
||||
])
|
||||
nx = grid_index.shape[0] * (grid_index.shape[1] - 1)
|
||||
ny = (grid_index.shape[0] - 1) * grid_index.shape[1]
|
||||
indptr = np.arange(0, nx * 2 + ny * 2 + 1, 2)
|
||||
return csr_array((data, indices, indptr), shape=(nx + ny, H * W))
|
||||
|
||||
|
||||
def _scipy_remap_bilinear(img: np.ndarray, sample_pixels: np.ndarray, mode: str = "bilinear") -> np.ndarray:
|
||||
"""Bilinear/nearest sampling at fractional pixel coords; out-of-range clamps to nearest border."""
|
||||
H, W = img.shape[:2]
|
||||
yy = np.clip(sample_pixels[..., 1], 0, H - 1)
|
||||
xx = np.clip(sample_pixels[..., 0], 0, W - 1)
|
||||
order = 1 if mode == "bilinear" else 0
|
||||
if img.ndim == 2:
|
||||
return map_coordinates(img, [yy, xx], order=order, mode="nearest").astype(img.dtype)
|
||||
out = np.stack([
|
||||
map_coordinates(img[..., c], [yy, xx], order=order, mode="nearest")
|
||||
for c in range(img.shape[-1])
|
||||
], axis=-1)
|
||||
return out.astype(img.dtype)
|
||||
|
||||
|
||||
def merge_panorama_depth(width: int, height: int,
|
||||
distance_maps: List[np.ndarray], pred_masks: List[np.ndarray],
|
||||
extrinsics: List[np.ndarray], intrinsics: List[np.ndarray],
|
||||
on_view: Optional[Callable[[], None]] = None,
|
||||
on_solve_start: Optional[Callable[[int, int], None]] = None,
|
||||
on_solve_end: Optional[Callable[[int, int], None]] = None,
|
||||
) -> Tuple[np.ndarray, np.ndarray]:
|
||||
"""Stitch per-view distance maps into a single equirect distance map.
|
||||
|
||||
Recursive multi-scale solve: solves at half resolution first and uses that as the lsmr init
|
||||
for the full-resolution solve. Optional callbacks fire per view processed and around each
|
||||
lsmr solve so callers can drive a progress bar.
|
||||
"""
|
||||
|
||||
if max(width, height) > 256:
|
||||
coarse_depth, _ = merge_panorama_depth(width // 2, height // 2,
|
||||
distance_maps, pred_masks, extrinsics, intrinsics,
|
||||
on_view=on_view,
|
||||
on_solve_start=on_solve_start,
|
||||
on_solve_end=on_solve_end)
|
||||
t = torch.from_numpy(coarse_depth).unsqueeze(0).unsqueeze(0)
|
||||
t = F.interpolate(t, size=(height, width), mode="bilinear", align_corners=False)
|
||||
depth_init = t.squeeze().numpy().astype(np.float32)
|
||||
else:
|
||||
depth_init = None
|
||||
|
||||
spherical_directions = spherical_uv_to_directions(_uv_grid(height, width))
|
||||
|
||||
pano_log_grad_maps, pano_grad_masks = [], []
|
||||
pano_log_lap_maps, pano_lap_masks = [], []
|
||||
pano_pred_masks: List[np.ndarray] = []
|
||||
|
||||
for i in range(len(distance_maps)):
|
||||
proj_uv, proj_depth = _project_cv(spherical_directions, extrinsics[i], intrinsics[i])
|
||||
proj_valid = (proj_depth > 0) & (proj_uv > 0).all(axis=-1) & (proj_uv < 1).all(axis=-1)
|
||||
|
||||
Hd, Wd = distance_maps[i].shape[:2]
|
||||
proj_pixels = np.clip(proj_uv, 0, 1) * np.array([Wd - 1, Hd - 1], dtype=np.float32)
|
||||
|
||||
log_dist = np.log(np.clip(distance_maps[i], 1e-6, None))
|
||||
sampled = _scipy_remap_bilinear(log_dist, proj_pixels, mode="bilinear")
|
||||
pano_log = np.where(proj_valid, sampled, 0.0).astype(np.float32)
|
||||
|
||||
sampled_mask = _scipy_remap_bilinear(pred_masks[i].astype(np.uint8), proj_pixels, mode="nearest")
|
||||
pano_pred = proj_valid & (sampled_mask > 0)
|
||||
|
||||
# Equirect wraps horizontally but not vertically: wrap pad along x, edge pad along y.
|
||||
padded = np.pad(pano_log, ((0, 0), (0, 1)), mode="wrap")
|
||||
gx, gy = padded[:, :-1] - padded[:, 1:], padded[:-1, :] - padded[1:, :]
|
||||
padded_m = np.pad(pano_pred, ((0, 0), (0, 1)), mode="wrap")
|
||||
mx, my = padded_m[:, :-1] & padded_m[:, 1:], padded_m[:-1, :] & padded_m[1:, :]
|
||||
pano_log_grad_maps.append((gx, gy))
|
||||
pano_grad_masks.append((mx, my))
|
||||
|
||||
padded = np.pad(pano_log, ((1, 1), (0, 0)), mode="edge")
|
||||
padded = np.pad(padded, ((0, 0), (1, 1)), mode="wrap")
|
||||
lap_kernel = np.array([[0, 1, 0], [1, -4, 1], [0, 1, 0]], dtype=np.float32)
|
||||
lap = convolve(padded, lap_kernel)[1:-1, 1:-1]
|
||||
padded_m = np.pad(pano_pred, ((1, 1), (0, 0)), mode="edge")
|
||||
padded_m = np.pad(padded_m, ((0, 0), (1, 1)), mode="wrap")
|
||||
m_kernel = np.array([[0, 1, 0], [1, 1, 1], [0, 1, 0]], dtype=np.uint8)
|
||||
lap_mask = convolve(padded_m.astype(np.uint8), m_kernel)[1:-1, 1:-1] == 5
|
||||
pano_log_lap_maps.append(lap)
|
||||
pano_lap_masks.append(lap_mask)
|
||||
pano_pred_masks.append(pano_pred)
|
||||
|
||||
if on_view is not None:
|
||||
on_view()
|
||||
|
||||
gx = np.stack([m[0] for m in pano_log_grad_maps], axis=0)
|
||||
gy = np.stack([m[1] for m in pano_log_grad_maps], axis=0)
|
||||
mx = np.stack([m[0] for m in pano_grad_masks], axis=0)
|
||||
my = np.stack([m[1] for m in pano_grad_masks], axis=0)
|
||||
gx_avg = (gx * mx).sum(axis=0) / mx.sum(axis=0).clip(1e-3)
|
||||
gy_avg = (gy * my).sum(axis=0) / my.sum(axis=0).clip(1e-3)
|
||||
|
||||
laps = np.stack(pano_log_lap_maps, axis=0)
|
||||
lap_masks = np.stack(pano_lap_masks, axis=0)
|
||||
lap_avg = (laps * lap_masks).sum(axis=0) / lap_masks.sum(axis=0).clip(1e-3)
|
||||
|
||||
grad_x_mask = mx.any(axis=0).reshape(-1)
|
||||
grad_y_mask = my.any(axis=0).reshape(-1)
|
||||
grad_mask = np.concatenate([grad_x_mask, grad_y_mask])
|
||||
lap_mask_flat = lap_masks.any(axis=0).reshape(-1)
|
||||
|
||||
A = vstack([
|
||||
_grad_equation(width, height, wrap_x=True, wrap_y=False)[grad_mask],
|
||||
_poisson_equation(width, height, wrap_x=True, wrap_y=False)[lap_mask_flat],
|
||||
])
|
||||
b = np.concatenate([
|
||||
gx_avg.reshape(-1)[grad_x_mask],
|
||||
gy_avg.reshape(-1)[grad_y_mask],
|
||||
lap_avg.reshape(-1)[lap_mask_flat],
|
||||
])
|
||||
x0 = np.log(np.clip(depth_init, 1e-6, None)).reshape(-1) if depth_init is not None else None
|
||||
|
||||
if on_solve_start is not None:
|
||||
on_solve_start(width, height)
|
||||
x, *_ = lsmr(A, b, atol=1e-5, btol=1e-5, x0=x0, show=False)
|
||||
if on_solve_end is not None:
|
||||
on_solve_end(width, height)
|
||||
|
||||
pano_depth = np.exp(x).reshape(height, width).astype(np.float32)
|
||||
pano_mask = np.any(pano_pred_masks, axis=0)
|
||||
return pano_depth, pano_mask
|
||||
@@ -0,0 +1,462 @@
|
||||
import torch
|
||||
from comfy.ldm.modules.diffusionmodules.util import make_beta_schedule
|
||||
import math
|
||||
|
||||
def rescale_zero_terminal_snr_sigmas(sigmas):
|
||||
alphas_cumprod = 1 / ((sigmas * sigmas) + 1)
|
||||
alphas_bar_sqrt = alphas_cumprod.sqrt()
|
||||
|
||||
# Store old values.
|
||||
alphas_bar_sqrt_0 = alphas_bar_sqrt[0].clone()
|
||||
alphas_bar_sqrt_T = alphas_bar_sqrt[-1].clone()
|
||||
|
||||
# Shift so the last timestep is zero.
|
||||
alphas_bar_sqrt -= (alphas_bar_sqrt_T)
|
||||
|
||||
# Scale so the first timestep is back to the old value.
|
||||
alphas_bar_sqrt *= alphas_bar_sqrt_0 / (alphas_bar_sqrt_0 - alphas_bar_sqrt_T)
|
||||
|
||||
# Convert alphas_bar_sqrt to betas
|
||||
alphas_bar = alphas_bar_sqrt**2 # Revert sqrt
|
||||
alphas_bar[-1] = 4.8973451890853435e-08
|
||||
return ((1 - alphas_bar) / alphas_bar) ** 0.5
|
||||
|
||||
def reshape_sigma(sigma, noise_dim):
|
||||
if sigma.nelement() == 1:
|
||||
return sigma.view(())
|
||||
else:
|
||||
return sigma.view(sigma.shape[:1] + (1,) * (noise_dim - 1))
|
||||
|
||||
class EPS:
|
||||
def calculate_input(self, sigma, noise):
|
||||
sigma = reshape_sigma(sigma, noise.ndim)
|
||||
return noise / (sigma ** 2 + self.sigma_data ** 2) ** 0.5
|
||||
|
||||
def calculate_denoised(self, sigma, model_output, model_input):
|
||||
sigma = reshape_sigma(sigma, model_output.ndim)
|
||||
return model_input - model_output * sigma
|
||||
|
||||
def noise_scaling(self, sigma, noise, latent_image, max_denoise=False):
|
||||
sigma = reshape_sigma(sigma, noise.ndim)
|
||||
if max_denoise:
|
||||
noise = noise * torch.sqrt(1.0 + sigma ** 2.0)
|
||||
else:
|
||||
noise = noise * sigma
|
||||
|
||||
noise += latent_image
|
||||
return noise
|
||||
|
||||
def inverse_noise_scaling(self, sigma, latent):
|
||||
return latent
|
||||
|
||||
class V_PREDICTION(EPS):
|
||||
def calculate_denoised(self, sigma, model_output, model_input):
|
||||
sigma = reshape_sigma(sigma, model_output.ndim)
|
||||
return model_input * self.sigma_data ** 2 / (sigma ** 2 + self.sigma_data ** 2) - model_output * sigma * self.sigma_data / (sigma ** 2 + self.sigma_data ** 2) ** 0.5
|
||||
|
||||
class V_PREDICTION_DDPM:
|
||||
"""CogVideoX v-prediction: model receives raw x_t (unscaled), predicts velocity v.
|
||||
x_0 = sqrt(alpha) * x_t - sqrt(1-alpha) * v
|
||||
= x_t / sqrt(sigma^2 + 1) - v * sigma / sqrt(sigma^2 + 1)
|
||||
"""
|
||||
def calculate_input(self, sigma, noise):
|
||||
return noise
|
||||
|
||||
def calculate_denoised(self, sigma, model_output, model_input):
|
||||
sigma = reshape_sigma(sigma, model_output.ndim)
|
||||
return model_input / (sigma ** 2 + 1.0) ** 0.5 - model_output * sigma / (sigma ** 2 + 1.0) ** 0.5
|
||||
|
||||
def noise_scaling(self, sigma, noise, latent_image, max_denoise=False):
|
||||
sigma = reshape_sigma(sigma, noise.ndim)
|
||||
if max_denoise:
|
||||
noise = noise * torch.sqrt(1.0 + sigma ** 2.0)
|
||||
else:
|
||||
noise = noise * sigma
|
||||
noise += latent_image
|
||||
return noise
|
||||
|
||||
def inverse_noise_scaling(self, sigma, latent):
|
||||
return latent
|
||||
|
||||
class EDM(V_PREDICTION):
|
||||
def calculate_denoised(self, sigma, model_output, model_input):
|
||||
sigma = reshape_sigma(sigma, model_output.ndim)
|
||||
return model_input * self.sigma_data ** 2 / (sigma ** 2 + self.sigma_data ** 2) + model_output * sigma * self.sigma_data / (sigma ** 2 + self.sigma_data ** 2) ** 0.5
|
||||
|
||||
class CONST:
|
||||
def calculate_input(self, sigma, noise):
|
||||
return noise
|
||||
|
||||
def calculate_denoised(self, sigma, model_output, model_input):
|
||||
sigma = reshape_sigma(sigma, model_output.ndim)
|
||||
return model_input - model_output * sigma
|
||||
|
||||
def noise_scaling(self, sigma, noise, latent_image, max_denoise=False):
|
||||
sigma = reshape_sigma(sigma, noise.ndim)
|
||||
s = getattr(self, "noise_scale", 1.0)
|
||||
return sigma * (s * noise) + (1.0 - sigma) * latent_image
|
||||
|
||||
def inverse_noise_scaling(self, sigma, latent):
|
||||
sigma = reshape_sigma(sigma, latent.ndim)
|
||||
return latent / (1.0 - sigma)
|
||||
|
||||
class X0(EPS):
|
||||
def calculate_denoised(self, sigma, model_output, model_input):
|
||||
return model_output
|
||||
|
||||
class IMG_TO_IMG(X0):
|
||||
def calculate_input(self, sigma, noise):
|
||||
return noise
|
||||
|
||||
class IMG_TO_IMG_FLOW(CONST):
|
||||
def calculate_denoised(self, sigma, model_output, model_input):
|
||||
return model_output
|
||||
|
||||
def noise_scaling(self, sigma, noise, latent_image, max_denoise=False):
|
||||
return latent_image
|
||||
|
||||
def inverse_noise_scaling(self, sigma, latent):
|
||||
return 1.0 - latent
|
||||
|
||||
class IMG_TO_IMG_VELOCITY(CONST):
|
||||
def calculate_denoised(self, sigma, model_output, model_input):
|
||||
return model_input - model_output
|
||||
|
||||
def noise_scaling(self, sigma, noise, latent_image, max_denoise=False):
|
||||
return latent_image
|
||||
|
||||
def inverse_noise_scaling(self, sigma, latent):
|
||||
return latent
|
||||
|
||||
class COSMOS_RFLOW:
|
||||
def calculate_input(self, sigma, noise):
|
||||
sigma = (sigma / (sigma + 1))
|
||||
sigma = reshape_sigma(sigma, noise.ndim)
|
||||
return noise * (1.0 - sigma)
|
||||
|
||||
def calculate_denoised(self, sigma, model_output, model_input):
|
||||
sigma = (sigma / (sigma + 1))
|
||||
sigma = reshape_sigma(sigma, model_output.ndim)
|
||||
return model_input * (1.0 - sigma) - model_output * sigma
|
||||
|
||||
def noise_scaling(self, sigma, noise, latent_image, max_denoise=False):
|
||||
sigma = reshape_sigma(sigma, noise.ndim)
|
||||
noise = noise * sigma
|
||||
noise += latent_image
|
||||
return noise
|
||||
|
||||
def inverse_noise_scaling(self, sigma, latent):
|
||||
return latent
|
||||
|
||||
class ModelSamplingDiscrete(torch.nn.Module):
|
||||
def __init__(self, model_config=None, zsnr=None):
|
||||
super().__init__()
|
||||
|
||||
if model_config is not None:
|
||||
sampling_settings = model_config.sampling_settings
|
||||
else:
|
||||
sampling_settings = {}
|
||||
|
||||
beta_schedule = sampling_settings.get("beta_schedule", "linear")
|
||||
linear_start = sampling_settings.get("linear_start", 0.00085)
|
||||
linear_end = sampling_settings.get("linear_end", 0.012)
|
||||
timesteps = sampling_settings.get("timesteps", 1000)
|
||||
|
||||
if zsnr is None:
|
||||
zsnr = sampling_settings.get("zsnr", False)
|
||||
|
||||
self._register_schedule(given_betas=None, beta_schedule=beta_schedule, timesteps=timesteps, linear_start=linear_start, linear_end=linear_end, cosine_s=8e-3, zsnr=zsnr)
|
||||
self.sigma_data = 1.0
|
||||
|
||||
def _register_schedule(self, given_betas=None, beta_schedule="linear", timesteps=1000,
|
||||
linear_start=1e-4, linear_end=2e-2, cosine_s=8e-3, zsnr=False):
|
||||
if given_betas is not None:
|
||||
betas = given_betas
|
||||
else:
|
||||
betas = make_beta_schedule(beta_schedule, timesteps, linear_start=linear_start, linear_end=linear_end, cosine_s=cosine_s)
|
||||
alphas = 1. - betas
|
||||
alphas_cumprod = torch.cumprod(alphas, dim=0)
|
||||
|
||||
timesteps, = betas.shape
|
||||
self.num_timesteps = int(timesteps)
|
||||
self.linear_start = linear_start
|
||||
self.linear_end = linear_end
|
||||
self.zsnr = zsnr
|
||||
|
||||
# self.register_buffer('betas', torch.tensor(betas, dtype=torch.float32))
|
||||
# self.register_buffer('alphas_cumprod', torch.tensor(alphas_cumprod, dtype=torch.float32))
|
||||
# self.register_buffer('alphas_cumprod_prev', torch.tensor(alphas_cumprod_prev, dtype=torch.float32))
|
||||
|
||||
sigmas = ((1 - alphas_cumprod) / alphas_cumprod) ** 0.5
|
||||
if self.zsnr:
|
||||
sigmas = rescale_zero_terminal_snr_sigmas(sigmas)
|
||||
|
||||
self.set_sigmas(sigmas)
|
||||
|
||||
def set_sigmas(self, sigmas):
|
||||
self.register_buffer('sigmas', sigmas.float())
|
||||
self.register_buffer('log_sigmas', sigmas.log().float())
|
||||
|
||||
@property
|
||||
def sigma_min(self):
|
||||
return self.sigmas[0]
|
||||
|
||||
@property
|
||||
def sigma_max(self):
|
||||
return self.sigmas[-1]
|
||||
|
||||
def timestep(self, sigma):
|
||||
log_sigma = sigma.log()
|
||||
dists = log_sigma.to(self.log_sigmas.device) - self.log_sigmas[:, None]
|
||||
return dists.abs().argmin(dim=0).view(sigma.shape).to(sigma.device)
|
||||
|
||||
def sigma(self, timestep):
|
||||
t = torch.clamp(timestep.float().to(self.log_sigmas.device), min=0, max=(len(self.sigmas) - 1))
|
||||
low_idx = t.floor().long()
|
||||
high_idx = t.ceil().long()
|
||||
w = t.frac()
|
||||
log_sigma = (1 - w) * self.log_sigmas[low_idx] + w * self.log_sigmas[high_idx]
|
||||
return log_sigma.exp().to(timestep.device)
|
||||
|
||||
def percent_to_sigma(self, percent):
|
||||
if percent <= 0.0:
|
||||
return 999999999.9
|
||||
if percent >= 1.0:
|
||||
return 0.0
|
||||
percent = 1.0 - percent
|
||||
return self.sigma(torch.tensor(percent * 999.0)).item()
|
||||
|
||||
class ModelSamplingDiscreteEDM(ModelSamplingDiscrete):
|
||||
def timestep(self, sigma):
|
||||
return 0.25 * sigma.log()
|
||||
|
||||
def sigma(self, timestep):
|
||||
return (timestep / 0.25).exp()
|
||||
|
||||
class ModelSamplingContinuousEDM(torch.nn.Module):
|
||||
def __init__(self, model_config=None):
|
||||
super().__init__()
|
||||
if model_config is not None:
|
||||
sampling_settings = model_config.sampling_settings
|
||||
else:
|
||||
sampling_settings = {}
|
||||
|
||||
sigma_min = sampling_settings.get("sigma_min", 0.002)
|
||||
sigma_max = sampling_settings.get("sigma_max", 120.0)
|
||||
sigma_data = sampling_settings.get("sigma_data", 1.0)
|
||||
self.set_parameters(sigma_min, sigma_max, sigma_data)
|
||||
|
||||
def set_parameters(self, sigma_min, sigma_max, sigma_data):
|
||||
self.sigma_data = sigma_data
|
||||
sigmas = torch.linspace(math.log(sigma_min), math.log(sigma_max), 1000).exp()
|
||||
|
||||
self.register_buffer('sigmas', sigmas) #for compatibility with some schedulers
|
||||
self.register_buffer('log_sigmas', sigmas.log())
|
||||
|
||||
@property
|
||||
def sigma_min(self):
|
||||
return self.sigmas[0]
|
||||
|
||||
@property
|
||||
def sigma_max(self):
|
||||
return self.sigmas[-1]
|
||||
|
||||
def timestep(self, sigma):
|
||||
return 0.25 * sigma.log()
|
||||
|
||||
def sigma(self, timestep):
|
||||
return (timestep / 0.25).exp()
|
||||
|
||||
def percent_to_sigma(self, percent):
|
||||
if percent <= 0.0:
|
||||
return 999999999.9
|
||||
if percent >= 1.0:
|
||||
return 0.0
|
||||
percent = 1.0 - percent
|
||||
|
||||
log_sigma_min = math.log(self.sigma_min)
|
||||
return math.exp((math.log(self.sigma_max) - log_sigma_min) * percent + log_sigma_min)
|
||||
|
||||
|
||||
class ModelSamplingContinuousV(ModelSamplingContinuousEDM):
|
||||
def timestep(self, sigma):
|
||||
return sigma.atan() / math.pi * 2
|
||||
|
||||
def sigma(self, timestep):
|
||||
return (timestep * math.pi / 2).tan()
|
||||
|
||||
|
||||
def time_snr_shift(alpha, t):
|
||||
if alpha == 1.0:
|
||||
return t
|
||||
return alpha * t / (1 + (alpha - 1) * t)
|
||||
|
||||
class ModelSamplingDiscreteFlow(torch.nn.Module):
|
||||
def __init__(self, model_config=None):
|
||||
super().__init__()
|
||||
if model_config is not None:
|
||||
sampling_settings = model_config.sampling_settings
|
||||
else:
|
||||
sampling_settings = {}
|
||||
|
||||
self.set_noise_scale(sampling_settings.get("noise_scale", 1.0))
|
||||
self.set_parameters(
|
||||
shift=sampling_settings.get("shift", 1.0),
|
||||
multiplier=sampling_settings.get("multiplier", 1000),
|
||||
)
|
||||
|
||||
def set_parameters(self, shift=1.0, timesteps=1000, multiplier=1000):
|
||||
self.shift = shift
|
||||
self.multiplier = multiplier
|
||||
ts = self.sigma((torch.arange(1, timesteps + 1, 1) / timesteps) * multiplier)
|
||||
self.register_buffer('sigmas', ts)
|
||||
|
||||
def set_noise_scale(self, noise_scale):
|
||||
self.noise_scale = float(noise_scale)
|
||||
|
||||
@property
|
||||
def sigma_min(self):
|
||||
return self.sigmas[0]
|
||||
|
||||
@property
|
||||
def sigma_max(self):
|
||||
return self.sigmas[-1]
|
||||
|
||||
def timestep(self, sigma):
|
||||
return sigma * self.multiplier
|
||||
|
||||
def sigma(self, timestep):
|
||||
return time_snr_shift(self.shift, timestep / self.multiplier)
|
||||
|
||||
def percent_to_sigma(self, percent):
|
||||
if percent <= 0.0:
|
||||
return 1.0
|
||||
if percent >= 1.0:
|
||||
return 0.0
|
||||
return time_snr_shift(self.shift, 1.0 - percent)
|
||||
|
||||
class ModelSamplingAV(ModelSamplingDiscreteFlow):
|
||||
"""Flow sampling for packed audio-video latents whose audio stream has its own flow shift.
|
||||
|
||||
Carrying the audio latent scaled onto the video schedule makes the pack an ordinary
|
||||
single-schedule flow latent whose audio target is scaled by audio_scale.
|
||||
"""
|
||||
def __init__(self, model_config=None):
|
||||
super().__init__(model_config)
|
||||
sampling_settings = model_config.sampling_settings if model_config is not None else {}
|
||||
self.audio_shift = sampling_settings.get("audio_shift", None)
|
||||
|
||||
def set_parameters(self, shift=1.0, audio_shift=None, timesteps=1000, multiplier=1000):
|
||||
self.audio_shift = audio_shift
|
||||
super().set_parameters(shift=shift, timesteps=timesteps, multiplier=multiplier)
|
||||
|
||||
@property
|
||||
def audio_scale(self):
|
||||
if self.audio_shift is None:
|
||||
return 1.0
|
||||
return self.shift / self.audio_shift
|
||||
|
||||
class StableCascadeSampling(ModelSamplingDiscrete):
|
||||
def __init__(self, model_config=None):
|
||||
super().__init__()
|
||||
|
||||
if model_config is not None:
|
||||
sampling_settings = model_config.sampling_settings
|
||||
else:
|
||||
sampling_settings = {}
|
||||
|
||||
self.set_parameters(sampling_settings.get("shift", 1.0))
|
||||
|
||||
def set_parameters(self, shift=1.0, cosine_s=8e-3):
|
||||
self.shift = shift
|
||||
self.cosine_s = torch.tensor(cosine_s)
|
||||
self._init_alpha_cumprod = torch.cos(self.cosine_s / (1 + self.cosine_s) * torch.pi * 0.5) ** 2
|
||||
|
||||
#This part is just for compatibility with some schedulers in the codebase
|
||||
self.num_timesteps = 10000
|
||||
sigmas = torch.empty((self.num_timesteps), dtype=torch.float32)
|
||||
for x in range(self.num_timesteps):
|
||||
t = (x + 1) / self.num_timesteps
|
||||
sigmas[x] = self.sigma(t)
|
||||
|
||||
self.set_sigmas(sigmas)
|
||||
|
||||
def sigma(self, timestep):
|
||||
alpha_cumprod = (torch.cos((timestep + self.cosine_s) / (1 + self.cosine_s) * torch.pi * 0.5) ** 2 / self._init_alpha_cumprod)
|
||||
|
||||
if self.shift != 1.0:
|
||||
var = alpha_cumprod
|
||||
logSNR = (var/(1-var)).log()
|
||||
logSNR += 2 * torch.log(1.0 / torch.tensor(self.shift))
|
||||
alpha_cumprod = logSNR.sigmoid()
|
||||
|
||||
alpha_cumprod = alpha_cumprod.clamp(0.0001, 0.9999)
|
||||
return ((1 - alpha_cumprod) / alpha_cumprod) ** 0.5
|
||||
|
||||
def timestep(self, sigma):
|
||||
var = 1 / ((sigma * sigma) + 1)
|
||||
var = var.clamp(0, 1.0)
|
||||
s, min_var = self.cosine_s.to(var.device), self._init_alpha_cumprod.to(var.device)
|
||||
t = (((var * min_var) ** 0.5).acos() / (torch.pi * 0.5)) * (1 + s) - s
|
||||
return t
|
||||
|
||||
def percent_to_sigma(self, percent):
|
||||
if percent <= 0.0:
|
||||
return 999999999.9
|
||||
if percent >= 1.0:
|
||||
return 0.0
|
||||
|
||||
percent = 1.0 - percent
|
||||
return self.sigma(torch.tensor(percent))
|
||||
|
||||
|
||||
def flux_time_shift(mu: float, sigma: float, t):
|
||||
return math.exp(mu) / (math.exp(mu) + (1 / t - 1) ** sigma)
|
||||
|
||||
class ModelSamplingFlux(torch.nn.Module):
|
||||
def __init__(self, model_config=None):
|
||||
super().__init__()
|
||||
if model_config is not None:
|
||||
sampling_settings = model_config.sampling_settings
|
||||
else:
|
||||
sampling_settings = {}
|
||||
|
||||
self.set_parameters(shift=sampling_settings.get("shift", 1.15))
|
||||
|
||||
def set_parameters(self, shift=1.15, timesteps=10000):
|
||||
self.shift = shift
|
||||
ts = self.sigma((torch.arange(1, timesteps + 1, 1) / timesteps))
|
||||
self.register_buffer('sigmas', ts)
|
||||
|
||||
@property
|
||||
def sigma_min(self):
|
||||
return self.sigmas[0]
|
||||
|
||||
@property
|
||||
def sigma_max(self):
|
||||
return self.sigmas[-1]
|
||||
|
||||
def timestep(self, sigma):
|
||||
return sigma
|
||||
|
||||
def sigma(self, timestep):
|
||||
return flux_time_shift(self.shift, 1.0, timestep)
|
||||
|
||||
def percent_to_sigma(self, percent):
|
||||
if percent <= 0.0:
|
||||
return 1.0
|
||||
if percent >= 1.0:
|
||||
return 0.0
|
||||
return flux_time_shift(self.shift, 1.0, 1.0 - percent)
|
||||
|
||||
|
||||
class ModelSamplingCosmosRFlow(ModelSamplingContinuousEDM):
|
||||
def timestep(self, sigma):
|
||||
return sigma / (sigma + 1)
|
||||
|
||||
def sigma(self, timestep):
|
||||
sigma_max = self.sigma_max
|
||||
if timestep >= (sigma_max / (sigma_max + 1)):
|
||||
return sigma_max
|
||||
|
||||
return timestep / (1 - timestep)
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,637 @@
|
||||
"""MiniMax H3 nodes: AV latent creation and task conditioning (t2va / fl2va / ref2va).
|
||||
|
||||
The H3 packed-DiT consumes, via conditioning:
|
||||
- Qwen3-VL-32B hidden states with per-token modality tags (from the minimax CLIP)
|
||||
- keyframe / reference condition latents, re-injected every step (never denoised)
|
||||
|
||||
Latents are NestedTensor pairs (video [B,24,T,H/16,W/16], audio [B,32,2,T40]);
|
||||
sampling runs on the flat pack with any stock sampler (the model handles the
|
||||
audio stream's shifted schedule internally).
|
||||
"""
|
||||
|
||||
import math
|
||||
|
||||
import torch
|
||||
import torch.nn.functional as F
|
||||
import comfy.audio
|
||||
|
||||
import nodes
|
||||
import comfy.model_management
|
||||
import comfy.model_prefetch
|
||||
import comfy.model_sampling
|
||||
import comfy.nested_tensor
|
||||
import comfy.patcher_extension
|
||||
import comfy.utils
|
||||
import node_helpers
|
||||
from comfy.ldm.minimax.model import FRAME_PER_TOKEN, FRAME_RESCALE
|
||||
from comfy.ldm.minimax.vae import IMAGENET_MEAN
|
||||
from comfy_api.latest import ComfyExtension, io
|
||||
|
||||
CANVAS_MULTIPLE = 32
|
||||
BASE_SHORT_EDGE = 768
|
||||
MAX_PIXELS = 768 * 1344
|
||||
REF_IMAGE_SHORT_EDGE = 2048
|
||||
FPS = 24
|
||||
AUDIO_LATENT_FPS = 40
|
||||
|
||||
|
||||
def align_frame_count(n):
|
||||
while n % 17 != 5:
|
||||
n += 1
|
||||
return n
|
||||
|
||||
|
||||
def video_latent_t(frame_count):
|
||||
return 2 if frame_count <= 5 else ((frame_count - 5) // 17) * 5 + 2
|
||||
|
||||
|
||||
def temporal_shape(length):
|
||||
frame_count = align_frame_count(max(5, length))
|
||||
duration = frame_count / FPS
|
||||
return frame_count, video_latent_t(frame_count), round(duration * AUDIO_LATENT_FPS)
|
||||
|
||||
|
||||
def adapt_canvas(width, height):
|
||||
"""768-short-edge canvas with 768*1344 area cap, per-axis round to 32."""
|
||||
ratio = width / height
|
||||
if ratio >= 1.0:
|
||||
nom_w, nom_h = BASE_SHORT_EDGE * ratio, BASE_SHORT_EDGE
|
||||
else:
|
||||
nom_w, nom_h = BASE_SHORT_EDGE, BASE_SHORT_EDGE / ratio
|
||||
if nom_w * nom_h > MAX_PIXELS:
|
||||
s = math.sqrt(MAX_PIXELS / (nom_w * nom_h))
|
||||
nom_w, nom_h = nom_w * s, nom_h * s
|
||||
return (max(CANVAS_MULTIPLE, round(nom_w / CANVAS_MULTIPLE) * CANVAS_MULTIPLE),
|
||||
max(CANVAS_MULTIPLE, round(nom_h / CANVAS_MULTIPLE) * CANVAS_MULTIPLE))
|
||||
|
||||
|
||||
def _resize(image, width, height, crop):
|
||||
# image [B, H, W, C] -> [B, height, width, 3]
|
||||
samples = image[..., :3].movedim(-1, 1)
|
||||
samples = comfy.utils.common_upscale(samples, width, height, "lanczos", crop)
|
||||
return samples.movedim(1, -1)
|
||||
|
||||
|
||||
def _encode_ref_audio(audio_vae, audio):
|
||||
waveform = audio["waveform"] # [B, C, L]
|
||||
sr = audio["sample_rate"]
|
||||
vae_sr = getattr(audio_vae, "audio_sample_rate", 32000)
|
||||
if sr != vae_sr:
|
||||
waveform = comfy.audio.resample(waveform, sr, vae_sr)
|
||||
z = audio_vae.encode(waveform[:1].movedim(1, -1)) # [1, 32, 2, T]
|
||||
return z, z.shape[-1]
|
||||
|
||||
|
||||
def _empty_av_latent(width, height, length, batch_size=1):
|
||||
frame_count, latent_t, audio_t = temporal_shape(length)
|
||||
video = torch.zeros([batch_size, 24, latent_t, height // 16, width // 16],
|
||||
device=comfy.model_management.intermediate_device())
|
||||
audio = torch.zeros([batch_size, 32, 2, audio_t],
|
||||
device=comfy.model_management.intermediate_device())
|
||||
return {"samples": comfy.nested_tensor.NestedTensor((video, audio))}, frame_count
|
||||
|
||||
|
||||
class EmptyMiniMaxH3LatentAV(io.ComfyNode):
|
||||
@classmethod
|
||||
def define_schema(cls):
|
||||
return io.Schema(
|
||||
node_id="EmptyMiniMaxH3LatentAV",
|
||||
display_name="Empty MiniMax H3 AV Latent",
|
||||
category="model/latent/minimax",
|
||||
description="Joint video+audio latent for MiniMax H3. Duration snaps to the model's 17k+5 frame grid at 24 fps.",
|
||||
inputs=[
|
||||
io.Int.Input("width", default=1344, min=32, max=nodes.MAX_RESOLUTION, step=32),
|
||||
io.Int.Input("height", default=768, min=32, max=nodes.MAX_RESOLUTION, step=32),
|
||||
io.Int.Input("length", default=124, min=5, max=3600, step=17, tooltip="Frame count at 24 fps, snapped up to the model's 17k+5 grid (124 = ~5s; trained range is ~124-362, longer is untested)"),
|
||||
],
|
||||
outputs=[io.Latent.Output()],
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def execute(cls, width, height, length) -> io.NodeOutput:
|
||||
latent, _ = _empty_av_latent(width, height, length)
|
||||
return io.NodeOutput(latent)
|
||||
|
||||
|
||||
class MiniMaxH3ImageToVideo(io.ComfyNode):
|
||||
"""t2va and fl2va: prompt (+ optional first/last keyframes) -> conditioning + AV latent."""
|
||||
|
||||
@classmethod
|
||||
def define_schema(cls):
|
||||
return io.Schema(
|
||||
node_id="MiniMaxH3ImageToVideo",
|
||||
display_name="MiniMax H3 Image to Video",
|
||||
category="model/conditioning/minimax",
|
||||
inputs=[
|
||||
io.Clip.Input("clip"),
|
||||
io.Vae.Input("vae"),
|
||||
io.String.Input("prompt", multiline=True, dynamic_prompts=True),
|
||||
io.Int.Input("width", default=1344, min=32, max=nodes.MAX_RESOLUTION, step=32),
|
||||
io.Int.Input("height", default=768, min=32, max=nodes.MAX_RESOLUTION, step=32),
|
||||
io.Int.Input("length", default=124, min=5, max=3600, step=17, tooltip="Frame count at 24 fps, snapped up to the model's 17k+5 grid (124 = ~5s; trained range is ~124-362, longer is untested)"),
|
||||
io.Image.Input("first_frame", optional=True),
|
||||
io.Image.Input("last_frame", optional=True),
|
||||
],
|
||||
outputs=[io.Conditioning.Output(display_name="positive"), io.Latent.Output()],
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def execute(cls, clip, vae, prompt, width, height, length,
|
||||
first_frame=None, last_frame=None) -> io.NodeOutput:
|
||||
latent, frame_count = _empty_av_latent(width, height, length)
|
||||
|
||||
images = []
|
||||
keyframes = []
|
||||
if first_frame is not None:
|
||||
# geometry anchor: plain stretch to canvas
|
||||
img = _resize(first_frame[:1], width, height, "disabled")
|
||||
images.append(img)
|
||||
keyframes.append({"resolved_frame_index": 0, "image": img})
|
||||
if last_frame is not None:
|
||||
# follower: aspect-preserving cover-crop
|
||||
img = _resize(last_frame[:1], width, height, "center")
|
||||
images.append(img)
|
||||
keyframes.append({"resolved_frame_index": frame_count - 1, "image": img})
|
||||
|
||||
tokens = clip.tokenize(prompt, images=images)
|
||||
cond = clip.encode_from_tokens_scheduled(tokens)
|
||||
|
||||
if keyframes:
|
||||
for kf in keyframes:
|
||||
kf["latent"] = vae.encode(kf.pop("image"))
|
||||
cond = node_helpers.conditioning_set_values(cond, {"minimax_keyframes": keyframes})
|
||||
return io.NodeOutput(cond, latent)
|
||||
|
||||
|
||||
class MiniMaxH3AddGuide(io.ComfyNode):
|
||||
"""Anchor image and/or audio guides at an arbitrary pixel frame of the target video."""
|
||||
|
||||
@classmethod
|
||||
def define_schema(cls):
|
||||
return io.Schema(
|
||||
node_id="MiniMaxH3AddGuide",
|
||||
display_name="Add Guide for MiniMax H3",
|
||||
category="model/conditioning/minimax",
|
||||
description="Anchor an image, a short clip, audio, or a clip with its soundtrack at any frame of a MiniMax H3 video. Chain several nodes to anchor several frames.",
|
||||
inputs=[
|
||||
io.Conditioning.Input("positive"),
|
||||
io.Vae.Input("vae", optional=True, tooltip="Video VAE, needed when an image is connected."),
|
||||
io.Vae.Input("audio_vae", optional=True, tooltip="Audio VAE, needed when an audio is connected."),
|
||||
io.Latent.Input("latent"),
|
||||
io.Image.Input("image", optional=True, tooltip="Image or video frames to anchor. Multi-frame batches are anchored as a clip and cropped down to the model's valid clip lengths: 5, 22, 39... (17k + 5) frames. Batches shorter than 5 frames use only the first image."),
|
||||
io.Audio.Input("audio", optional=True,
|
||||
tooltip="Soundtrack to anchor starting at the same frame index, cropped to the video's remaining duration."),
|
||||
io.Int.Input("frame_idx", default=0, min=-9999, max=9999,
|
||||
tooltip="Frame index to anchor the image or the clip's first frame at. Negative values are counted from the end of the video."),
|
||||
],
|
||||
outputs=[io.Conditioning.Output(display_name="positive")],
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def execute(cls, positive, latent, frame_idx, vae=None, audio_vae=None, image=None, audio=None) -> io.NodeOutput:
|
||||
samples = latent["samples"]
|
||||
if not samples.is_nested or len(samples.tensors) != 2 or samples.tensors[0].ndim != 5 or samples.tensors[0].shape[1] != 24:
|
||||
raise ValueError("MiniMaxH3AddGuide expects a MiniMax H3 AV latent")
|
||||
if image is None and audio is None:
|
||||
raise ValueError("MiniMaxH3AddGuide needs an image or an audio to anchor")
|
||||
video = samples.tensors[0]
|
||||
height = video.shape[3] * 16
|
||||
width = video.shape[4] * 16
|
||||
frame_count = sum(FRAME_PER_TOKEN[k % 5] for k in range(video.shape[2]))
|
||||
|
||||
guide_frames = 1
|
||||
if image is not None:
|
||||
if vae is None:
|
||||
raise ValueError("anchoring guide frames needs the vae input")
|
||||
guide_frames = image.shape[0]
|
||||
if guide_frames < 5:
|
||||
guide_frames = 1
|
||||
else:
|
||||
while guide_frames % 17 != 5:
|
||||
guide_frames -= 1
|
||||
|
||||
resolved_frame_index = frame_idx if frame_idx >= 0 else frame_count + frame_idx
|
||||
if resolved_frame_index < 0 or resolved_frame_index + guide_frames > frame_count:
|
||||
if guide_frames == 1:
|
||||
raise ValueError("frame_idx {} is outside the video's {} frames".format(frame_idx, frame_count))
|
||||
raise ValueError("a {} frame guide clip at frame_idx {} does not fit in the video's {} frames".format(
|
||||
guide_frames, frame_idx, frame_count))
|
||||
|
||||
keyframe = {"resolved_frame_index": resolved_frame_index}
|
||||
if image is not None:
|
||||
frames = _resize(image[:guide_frames], width, height, "center")
|
||||
keyframe["latent"] = vae.encode(frames)
|
||||
|
||||
if audio is not None:
|
||||
if audio_vae is None:
|
||||
raise ValueError("anchoring guide audio needs the audio_vae input")
|
||||
audio_latent, audio_rt = _encode_ref_audio(audio_vae, audio)
|
||||
# the streams share one time axis: FRAME_RESCALE per pixel frame, 1.0 per audio latent frame
|
||||
max_rt = math.floor(samples.tensors[1].shape[-1] - FRAME_RESCALE * resolved_frame_index)
|
||||
if max_rt < 1:
|
||||
raise ValueError("frame_idx {} is past the end of the video's audio track".format(frame_idx))
|
||||
if audio_rt > max_rt:
|
||||
audio_latent = audio_latent[..., :max_rt].clone()
|
||||
keyframe["audio_latent"] = audio_latent
|
||||
|
||||
keyframes = list(positive[0][1].get("minimax_keyframes", []))
|
||||
keyframes.append(keyframe)
|
||||
positive = node_helpers.conditioning_set_values(positive, {"minimax_keyframes": keyframes})
|
||||
return io.NodeOutput(positive)
|
||||
|
||||
|
||||
class MiniMaxH3ReferenceToVideo(io.ComfyNode):
|
||||
"""ref2va: prompt + reference images / videos / audio -> conditioning + AV latent.
|
||||
|
||||
References enter the presentation in fixed order: images, then videos (each
|
||||
soundtrack's <Audio j> label right before its <Video k>), then standalone
|
||||
audio. Ordinals are 1-based per type, so the prompt refers to them as
|
||||
<Picture i> / <Video k> / <Audio j>.
|
||||
"""
|
||||
|
||||
@classmethod
|
||||
def define_schema(cls):
|
||||
return io.Schema(
|
||||
node_id="MiniMaxH3ReferenceToVideo",
|
||||
description="<Picture i> / <Video k> / <Audio j> reference conditioning for MiniMax H3. Use the same tags when prompting.",
|
||||
display_name="MiniMax H3 Reference to Video",
|
||||
category="model/conditioning/minimax",
|
||||
inputs=[
|
||||
io.Clip.Input("clip"),
|
||||
io.Vae.Input("vae", optional=True, tooltip="Video VAE. Without it reference images/videos only condition the text encoder."),
|
||||
io.Vae.Input("audio_vae", optional=True, tooltip="Audio VAE. Without it reference audio only conditions the text encoder."),
|
||||
io.String.Input("prompt", multiline=True, dynamic_prompts=True),
|
||||
io.Int.Input("width", default=1344, min=32, max=nodes.MAX_RESOLUTION, step=32),
|
||||
io.Int.Input("height", default=768, min=32, max=nodes.MAX_RESOLUTION, step=32),
|
||||
io.Int.Input("length", default=124, min=5, max=3600, step=17, tooltip="Frame count at 24 fps, (124 = ~5s, trained range is ~124-362)"),
|
||||
io.Combo.Input("ref_image_size", options=["match", "max"], default="match",
|
||||
tooltip="Reference image sizing. 'match' scales each ref (down only, keeping aspect) to the generation's pixel area; 'max' uses the reference pipeline's 2048px short edge for best identity fidelity. Reference tokens ride through every sampling step, so 'max' can be several times slower."),
|
||||
io.Autogrow.Input("ref_images", optional=True,
|
||||
template=io.Autogrow.TemplatePrefix(
|
||||
input=io.Image.Input("ref_image", tooltip="Reference image (downscaled to 2048 short edge if larger, never upscaled)"),
|
||||
prefix="ref_image_", min=0, max=9)),
|
||||
io.Autogrow.Input("ref_videos", optional=True,
|
||||
template=io.Autogrow.TemplatePrefix(
|
||||
input=io.Image.Input("ref_video", tooltip="Reference video frames at 24 fps (2-15s)"),
|
||||
prefix="ref_video_", min=0, max=3)),
|
||||
io.Autogrow.Input("ref_video_audios", optional=True,
|
||||
template=io.Autogrow.TemplatePrefix(
|
||||
input=io.Audio.Input("ref_video_audio", tooltip="Soundtrack of the same-numbered reference video"),
|
||||
prefix="ref_video_audio_", min=0, max=3)),
|
||||
io.Autogrow.Input("ref_audios", optional=True,
|
||||
template=io.Autogrow.TemplatePrefix(
|
||||
input=io.Audio.Input("ref_audio", tooltip="Standalone reference audio"),
|
||||
prefix="ref_audio_", min=0, max=3)),
|
||||
],
|
||||
outputs=[io.Conditioning.Output(display_name="positive"), io.Latent.Output()],
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def execute(cls, clip, prompt, width, height, length, ref_image_size="match", vae=None, audio_vae=None,
|
||||
ref_images=None, ref_videos=None, ref_video_audios=None, ref_audios=None) -> io.NodeOutput:
|
||||
latent, frame_count = _empty_av_latent(width, height, length)
|
||||
|
||||
ref_items = [] # for the tokenizer presentation, in request order
|
||||
ref_blocks = [] # for the DiT payload, same order
|
||||
|
||||
for img in (ref_images or {}).values():
|
||||
if img is None:
|
||||
continue
|
||||
h, w = img.shape[1], img.shape[2]
|
||||
if ref_image_size == "match":
|
||||
# aspect-preserving scale (down only) to the generation's pixel area
|
||||
scale = min(1.0, math.sqrt((width * height) / (w * h)))
|
||||
else:
|
||||
scale = min(1.0, REF_IMAGE_SHORT_EDGE / min(w, h))
|
||||
tw = max(CANVAS_MULTIPLE, round(w * scale / CANVAS_MULTIPLE) * CANVAS_MULTIPLE)
|
||||
th = max(CANVAS_MULTIPLE, round(h * scale / CANVAS_MULTIPLE) * CANVAS_MULTIPLE)
|
||||
resized = _resize(img[:1], tw, th, "disabled")
|
||||
ref_items.append({"type": "image", "data": resized})
|
||||
if vae is not None:
|
||||
z = vae.encode(resized)
|
||||
ref_blocks.append({"kind": "image", "latent_h": th // 16, "latent_w": tw // 16, "latent": z})
|
||||
|
||||
ref_video_audios = ref_video_audios or {}
|
||||
for name, video_frames in (ref_videos or {}).items():
|
||||
if video_frames is None:
|
||||
continue
|
||||
# index-paired soundtrack: ref_video_audio_N belongs to ref_video_N
|
||||
soundtrack = ref_video_audios.get("ref_video_audio_" + name.rsplit("_", 1)[-1])
|
||||
vh, vw = video_frames.shape[1], video_frames.shape[2]
|
||||
cw, ch = adapt_canvas(vw, vh)
|
||||
if vw * vh < cw * ch:
|
||||
cw = max(CANVAS_MULTIPLE, round(vw / CANVAS_MULTIPLE) * CANVAS_MULTIPLE)
|
||||
ch = max(CANVAS_MULTIPLE, round(vh / CANVAS_MULTIPLE) * CANVAS_MULTIPLE)
|
||||
frames = _resize(video_frames, cw, ch, "disabled")
|
||||
if frames.shape[0] > frame_count:
|
||||
frames = frames[:frame_count]
|
||||
n = frames.shape[0]
|
||||
if n < 5:
|
||||
raise ValueError("MiniMax H3 reference videos need at least 5 frames (~0.2s at 24 fps)")
|
||||
while n % 17 != 5:
|
||||
n -= 1
|
||||
frames = frames[:n]
|
||||
if soundtrack is not None:
|
||||
# the soundtrack gets its own <Audio j> label, emitted before <Video k>
|
||||
ref_items.append({"type": "audio"})
|
||||
# Qwen sees the video at 2 fps with timestamps
|
||||
sample_idx = list(range(0, frames.shape[0], FPS // 2))
|
||||
qwen_frames = frames[sample_idx]
|
||||
ref_items.append({"type": "video", "data": qwen_frames,
|
||||
"timestamps": [i / 2.0 for i in range(len(sample_idx))]})
|
||||
if vae is None:
|
||||
continue
|
||||
z = vae.encode(frames)
|
||||
audio_latent, ref_audio_t = (None, 0)
|
||||
if soundtrack is not None and audio_vae is not None:
|
||||
audio_latent, ref_audio_t = _encode_ref_audio(audio_vae, soundtrack)
|
||||
ref_blocks.append({"kind": "video_audio" if ref_audio_t else "video",
|
||||
"latent_t": z.shape[2], "latent_h": ch // 16, "latent_w": cw // 16,
|
||||
"ref_audio_t": ref_audio_t, "latent": z, "audio_latent": audio_latent})
|
||||
|
||||
for audio in (ref_audios or {}).values():
|
||||
if audio is None:
|
||||
continue
|
||||
ref_items.append({"type": "audio"})
|
||||
if audio_vae is not None:
|
||||
audio_latent, ref_audio_t = _encode_ref_audio(audio_vae, audio)
|
||||
ref_blocks.append({"kind": "audio", "ref_audio_t": ref_audio_t, "audio_latent": audio_latent})
|
||||
|
||||
tokens = clip.tokenize(prompt, minimax_ref_items=ref_items)
|
||||
cond = clip.encode_from_tokens_scheduled(tokens)
|
||||
if ref_blocks:
|
||||
cond = node_helpers.conditioning_set_values(cond, {"minimax_refs": ref_blocks})
|
||||
return io.NodeOutput(cond, latent)
|
||||
|
||||
|
||||
class MiniMaxH3SigmaShift(io.ComfyNode):
|
||||
"""Set the video/audio flow shifts coherently.
|
||||
|
||||
The video shift drives the sampler's sigma schedule (ModelSamplingAV); both
|
||||
values are also handed to the DiT, which inverts the video schedule to the
|
||||
shared base grid and derives the audio schedule from it.
|
||||
"""
|
||||
|
||||
@classmethod
|
||||
def define_schema(cls):
|
||||
return io.Schema(
|
||||
node_id="MiniMaxH3SigmaShift",
|
||||
description="Set the video/audio flow shifts.",
|
||||
display_name="ModelSamplingMiniMaxH3",
|
||||
search_aliases=["sigma shift", "minimax shift"],
|
||||
category="model/patch/minimax",
|
||||
inputs=[
|
||||
io.Model.Input("model"),
|
||||
io.Float.Input("shift_video", default=12.0, min=0.01, max=100.0, step=0.01),
|
||||
io.Float.Input("shift_audio", default=3.0, min=0.01, max=100.0, step=0.01),
|
||||
],
|
||||
outputs=[io.Model.Output()],
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def execute(cls, model, shift_video, shift_audio) -> io.NodeOutput:
|
||||
m = model.clone()
|
||||
|
||||
class ModelSamplingAdvanced(comfy.model_sampling.ModelSamplingAV, comfy.model_sampling.CONST):
|
||||
pass
|
||||
|
||||
original = m.get_model_object("model_sampling")
|
||||
model_sampling = ModelSamplingAdvanced(model.model.model_config)
|
||||
model_sampling.set_parameters(shift=shift_video, audio_shift=shift_audio)
|
||||
if hasattr(original, "noise_scale"):
|
||||
model_sampling.set_noise_scale(original.noise_scale)
|
||||
m.add_object_patch("model_sampling", model_sampling)
|
||||
|
||||
to = m.model_options["transformer_options"] = m.model_options.get("transformer_options", {}).copy()
|
||||
to["minimax_h3_sigma_shift_video"] = shift_video
|
||||
to["minimax_h3_sigma_shift_audio"] = shift_audio
|
||||
return io.NodeOutput(m)
|
||||
|
||||
|
||||
class MiniMaxH3FunControlPatch:
|
||||
def __init__(self, model_patch, vae, control_video, mask, source_video, strength, sigma_start, sigma_end):
|
||||
self.model_patch = model_patch
|
||||
self.vae = vae
|
||||
self.control_video = control_video
|
||||
self.mask = mask
|
||||
self.source_video = source_video
|
||||
self.strength = strength
|
||||
self.sigma_start = sigma_start
|
||||
self.sigma_end = sigma_end
|
||||
self.control_latent = None
|
||||
self.control_latent_shape = None
|
||||
self.control_stream = None
|
||||
self.pristine_stream = None
|
||||
self.active = False
|
||||
|
||||
def _fit_frames(self, frames, frame_count, width, height):
|
||||
indices = torch.arange(frame_count, device=frames.device).clamp(max=frames.shape[0] - 1)
|
||||
return comfy.utils.common_upscale(frames[indices], width, height, "bilinear", "center")
|
||||
|
||||
def _encode(self, frames, target_shape):
|
||||
latent = self.vae.encode(frames.movedim(1, -1)).to(torch.float32)
|
||||
if tuple(latent.shape) != target_shape:
|
||||
raise ValueError("MiniMax H3 Fun VAE output shape {} does not match the target {}".format(tuple(latent.shape), target_shape))
|
||||
return latent
|
||||
|
||||
def prepare_control_latent(self, target_shape):
|
||||
target_shape = tuple(target_shape)
|
||||
if self.control_latent is not None and self.control_latent_shape == target_shape:
|
||||
return
|
||||
|
||||
latent_frames, latent_height, latent_width = target_shape[2:]
|
||||
frame_count = max((latent_frames - 2) // 5, 0) * 17 + 5
|
||||
spatial_compression = self.vae.spacial_compression_encode()
|
||||
width = latent_width * spatial_compression
|
||||
height = latent_height * spatial_compression
|
||||
loaded_models = comfy.model_management.loaded_models(only_currently_used=True)
|
||||
|
||||
try:
|
||||
hint = None
|
||||
if self.control_video is not None:
|
||||
frames = self._fit_frames(self.control_video, frame_count, width, height)
|
||||
hint = self._encode(frames, target_shape)
|
||||
|
||||
if self.mask is not None:
|
||||
mask = (self.mask.reshape(-1, 1, self.mask.shape[-2], self.mask.shape[-1]) > 0.5).to(torch.float32)
|
||||
indices = torch.arange(frame_count, device=mask.device).clamp(max=mask.shape[0] - 1)
|
||||
mask = comfy.utils.common_upscale(mask[indices], width, height, "bilinear", "center")
|
||||
visibility = 1.0 - (mask > 0.5).to(torch.float32)
|
||||
if self.source_video is None:
|
||||
source = torch.zeros(frame_count, 3, height, width, dtype=visibility.dtype, device=visibility.device)
|
||||
else:
|
||||
source = self._fit_frames(self.source_video, frame_count, width, height)
|
||||
visibility = visibility.to(source.device)
|
||||
masked = source * visibility
|
||||
if self.model_patch.model.inpaint_post_norm:
|
||||
# the pixel the VAE normalizes to zero, i.e. holes at mid-gray instead of black
|
||||
masked += (1.0 - visibility) * torch.tensor(IMAGENET_MEAN, dtype=source.dtype, device=source.device).view(1, 3, 1, 1)
|
||||
masked_latent = self._encode(masked, target_shape)
|
||||
if hint is None:
|
||||
hint = torch.zeros_like(masked_latent)
|
||||
visibility_latent = F.interpolate(
|
||||
visibility.squeeze(1)[None, None], size=(latent_frames, latent_height, latent_width),
|
||||
mode="trilinear", align_corners=False)
|
||||
hint = torch.cat([hint, visibility_latent.to(hint.device), masked_latent.to(hint.device)], dim=1)
|
||||
finally:
|
||||
comfy.model_management.load_models_gpu(loaded_models)
|
||||
|
||||
self.control_latent = hint
|
||||
self.control_latent_shape = target_shape
|
||||
|
||||
def diffusion_model_wrapper(self, executor, x, timestep, context, transformer_options={}, **kwargs):
|
||||
sigmas = transformer_options.get("sigmas")
|
||||
sigma = float(sigmas[0]) if sigmas is not None else float(timestep.flatten()[0]) / 1000.0
|
||||
self.active = self.sigma_end <= sigma <= self.sigma_start
|
||||
self.control_stream = None
|
||||
if self.active:
|
||||
with comfy.model_prefetch.pause_malloc_graph():
|
||||
self.prepare_control_latent(x[0].shape)
|
||||
try:
|
||||
return executor(x, timestep, context, transformer_options, **kwargs)
|
||||
finally:
|
||||
self.control_stream = None
|
||||
self.pristine_stream = None
|
||||
|
||||
def before_block(self, block_index, args):
|
||||
if not self.active or block_index != self.model_patch.model.injection_layers[0]:
|
||||
return
|
||||
# stash only: control weight loads here would clobber the base block's freshly staged weights
|
||||
self.pristine_stream = args["img"].clone()
|
||||
|
||||
def after_block(self, block_index, args, out):
|
||||
if not self.active:
|
||||
return out
|
||||
control_index = self.model_patch.model.injection_layers.index(block_index)
|
||||
if control_index == 0:
|
||||
self.control_latent = self.control_latent.to(out["img"].device)
|
||||
self.control_stream = self.model_patch.model.init_stream(
|
||||
self.pristine_stream, self.control_latent, args["layout"], args["t_emb"])
|
||||
self.pristine_stream = None
|
||||
self.control_stream, skip = self.model_patch.model.step(
|
||||
control_index, self.control_stream, args["t_emb"], args["mod_segments"], args["rope_freqs"],
|
||||
transformer_options=args["transformer_options"])
|
||||
skip[args["layout"].audio_pos.to(skip.device)] = 0
|
||||
out["img"].add_(skip, alpha=self.strength)
|
||||
return out
|
||||
|
||||
def to(self, device_or_dtype):
|
||||
if isinstance(device_or_dtype, torch.device):
|
||||
if self.control_latent is not None:
|
||||
self.control_latent = self.control_latent.to(device_or_dtype)
|
||||
self.control_stream = None
|
||||
return self
|
||||
|
||||
def cleanup(self):
|
||||
self.control_latent = None
|
||||
self.control_latent_shape = None
|
||||
self.control_stream = None
|
||||
self.pristine_stream = None
|
||||
self.active = False
|
||||
|
||||
def models(self):
|
||||
return [self.model_patch]
|
||||
|
||||
def register(self, model):
|
||||
model.add_wrapper(comfy.patcher_extension.WrappersMP.DIFFUSION_MODEL, self.diffusion_model_wrapper)
|
||||
for block_index in self.model_patch.model.injection_layers:
|
||||
blocks_replace = model.model_options.get("transformer_options", {}).get("patches_replace", {}).get("dit", {})
|
||||
previous = blocks_replace.get(("double_block", block_index))
|
||||
model.set_model_patch_replace(
|
||||
MiniMaxH3FunControlBlockPatch(self, block_index, previous), "dit", "double_block", block_index)
|
||||
|
||||
|
||||
class MiniMaxH3FunControlBlockPatch:
|
||||
def __init__(self, control_patch, block_index, previous):
|
||||
self.control_patch = control_patch
|
||||
self.block_index = block_index
|
||||
self.previous = previous
|
||||
|
||||
def __call__(self, args, extra_args):
|
||||
# Control state must stay outside the base block's allocation scope.
|
||||
with comfy.model_prefetch.pause_malloc_graph():
|
||||
self.control_patch.before_block(self.block_index, args)
|
||||
if self.previous is None:
|
||||
out = extra_args["original_block"](args)
|
||||
else:
|
||||
out = self.previous(args, extra_args)
|
||||
with comfy.model_prefetch.pause_malloc_graph():
|
||||
return self.control_patch.after_block(self.block_index, args, out)
|
||||
|
||||
def to(self, device_or_dtype):
|
||||
self.control_patch.to(device_or_dtype)
|
||||
if hasattr(self.previous, "to"):
|
||||
self.previous = self.previous.to(device_or_dtype)
|
||||
return self
|
||||
|
||||
def cleanup(self):
|
||||
self.control_patch.cleanup()
|
||||
if hasattr(self.previous, "cleanup"):
|
||||
self.previous.cleanup()
|
||||
|
||||
def models(self):
|
||||
models = self.control_patch.models()
|
||||
if hasattr(self.previous, "models"):
|
||||
models += self.previous.models()
|
||||
return models
|
||||
|
||||
|
||||
class MiniMaxH3FunControlNetApply(io.ComfyNode):
|
||||
@classmethod
|
||||
def define_schema(cls):
|
||||
return io.Schema(
|
||||
node_id="MiniMaxH3FunControlNetApply",
|
||||
description="Apply a MiniMax H3 Fun ControlNet to a text-to-video model as a model patch.",
|
||||
display_name="Apply MiniMax H3 Fun ControlNet",
|
||||
search_aliases=["minimax controlnet", "h3 controlnet", "video inpaint controlnet"],
|
||||
category="model/patch/minimax",
|
||||
inputs=[
|
||||
io.Model.Input("model"),
|
||||
io.ModelPatch.Input("model_patch"),
|
||||
io.Vae.Input("vae"),
|
||||
io.Float.Input("strength", default=1.0, min=0.0, max=10.0, step=0.01),
|
||||
io.Float.Input("start_percent", default=0.0, min=0.0, max=1.0, step=0.001, advanced=True),
|
||||
io.Float.Input("end_percent", default=1.0, min=0.0, max=1.0, step=0.001, advanced=True),
|
||||
io.Image.Input("control_video", optional=True),
|
||||
io.Mask.Input("mask", optional=True, tooltip="1 marks the regions to regenerate."),
|
||||
io.Image.Input("source_video", optional=True, tooltip="Video behind the mask; only read when a mask is given."),
|
||||
],
|
||||
outputs=[io.Model.Output()],
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def execute(cls, model, model_patch, vae, strength, start_percent, end_percent,
|
||||
control_video=None, mask=None, source_video=None) -> io.NodeOutput:
|
||||
if strength == 0 or (control_video is None and mask is None):
|
||||
return io.NodeOutput(model)
|
||||
|
||||
model_patched = model.clone()
|
||||
model_sampling = model.get_model_object("model_sampling")
|
||||
patch = MiniMaxH3FunControlPatch(
|
||||
model_patch,
|
||||
vae,
|
||||
control_video[..., :3].movedim(-1, 1) if control_video is not None else None,
|
||||
mask,
|
||||
source_video[..., :3].movedim(-1, 1) if mask is not None and source_video is not None else None,
|
||||
strength,
|
||||
float(model_sampling.percent_to_sigma(start_percent)),
|
||||
float(model_sampling.percent_to_sigma(end_percent)),
|
||||
)
|
||||
patch.register(model_patched)
|
||||
return io.NodeOutput(model_patched)
|
||||
|
||||
|
||||
class MiniMaxH3Extension(ComfyExtension):
|
||||
async def get_node_list(self):
|
||||
return [
|
||||
EmptyMiniMaxH3LatentAV,
|
||||
MiniMaxH3ImageToVideo,
|
||||
MiniMaxH3AddGuide,
|
||||
MiniMaxH3ReferenceToVideo,
|
||||
MiniMaxH3SigmaShift,
|
||||
MiniMaxH3FunControlNetApply,
|
||||
]
|
||||
|
||||
|
||||
async def comfy_entrypoint() -> MiniMaxH3Extension:
|
||||
return MiniMaxH3Extension()
|
||||
+428
@@ -0,0 +1,428 @@
|
||||
import logging
|
||||
|
||||
import comfy.sd
|
||||
import comfy.model_sampling
|
||||
import comfy.latent_formats
|
||||
import comfy.ldm.modules.attention
|
||||
import nodes
|
||||
import torch
|
||||
import node_helpers
|
||||
from comfy_api.latest import io
|
||||
|
||||
|
||||
class LCM(comfy.model_sampling.EPS):
|
||||
def calculate_denoised(self, sigma, model_output, model_input):
|
||||
timestep = self.timestep(sigma).view(sigma.shape[:1] + (1,) * (model_output.ndim - 1))
|
||||
sigma = sigma.view(sigma.shape[:1] + (1,) * (model_output.ndim - 1))
|
||||
x0 = model_input - model_output * sigma
|
||||
|
||||
sigma_data = 0.5
|
||||
scaled_timestep = timestep * 10.0 #timestep_scaling
|
||||
|
||||
c_skip = sigma_data**2 / (scaled_timestep**2 + sigma_data**2)
|
||||
c_out = scaled_timestep / (scaled_timestep**2 + sigma_data**2) ** 0.5
|
||||
|
||||
return c_out * x0 + c_skip * model_input
|
||||
|
||||
class ModelSamplingDiscreteDistilled(comfy.model_sampling.ModelSamplingDiscrete):
|
||||
original_timesteps = 50
|
||||
|
||||
def __init__(self, model_config=None, zsnr=None):
|
||||
super().__init__(model_config, zsnr=zsnr)
|
||||
|
||||
self.skip_steps = self.num_timesteps // self.original_timesteps
|
||||
|
||||
sigmas_valid = torch.zeros((self.original_timesteps), dtype=torch.float32)
|
||||
for x in range(self.original_timesteps):
|
||||
sigmas_valid[self.original_timesteps - 1 - x] = self.sigmas[self.num_timesteps - 1 - x * self.skip_steps]
|
||||
|
||||
self.set_sigmas(sigmas_valid)
|
||||
|
||||
def timestep(self, sigma):
|
||||
log_sigma = sigma.log()
|
||||
dists = log_sigma.to(self.log_sigmas.device) - self.log_sigmas[:, None]
|
||||
return (dists.abs().argmin(dim=0).view(sigma.shape) * self.skip_steps + (self.skip_steps - 1)).to(sigma.device)
|
||||
|
||||
def sigma(self, timestep):
|
||||
t = torch.clamp(((timestep.float().to(self.log_sigmas.device) - (self.skip_steps - 1)) / self.skip_steps).float(), min=0, max=(len(self.sigmas) - 1))
|
||||
low_idx = t.floor().long()
|
||||
high_idx = t.ceil().long()
|
||||
w = t.frac()
|
||||
log_sigma = (1 - w) * self.log_sigmas[low_idx] + w * self.log_sigmas[high_idx]
|
||||
return log_sigma.exp().to(timestep.device)
|
||||
|
||||
|
||||
class ModelSamplingDiscrete:
|
||||
@classmethod
|
||||
def INPUT_TYPES(s):
|
||||
return {"required": { "model": ("MODEL",),
|
||||
"sampling": (["eps", "v_prediction", "lcm", "x0", "img_to_img", "img_to_img_flow"],),
|
||||
"zsnr": ("BOOLEAN", {"default": False, "advanced": True}),
|
||||
}}
|
||||
|
||||
RETURN_TYPES = ("MODEL",)
|
||||
FUNCTION = "patch"
|
||||
|
||||
CATEGORY = "model/patch"
|
||||
|
||||
def patch(self, model, sampling, zsnr):
|
||||
m = model.clone()
|
||||
|
||||
sampling_base = comfy.model_sampling.ModelSamplingDiscrete
|
||||
if sampling == "eps":
|
||||
sampling_type = comfy.model_sampling.EPS
|
||||
elif sampling == "v_prediction":
|
||||
sampling_type = comfy.model_sampling.V_PREDICTION
|
||||
elif sampling == "lcm":
|
||||
sampling_type = LCM
|
||||
sampling_base = ModelSamplingDiscreteDistilled
|
||||
elif sampling == "x0":
|
||||
sampling_type = comfy.model_sampling.X0
|
||||
elif sampling == "img_to_img":
|
||||
sampling_type = comfy.model_sampling.IMG_TO_IMG
|
||||
elif sampling == "img_to_img_flow":
|
||||
sampling_type = comfy.model_sampling.IMG_TO_IMG_FLOW
|
||||
|
||||
class ModelSamplingAdvanced(sampling_base, sampling_type):
|
||||
pass
|
||||
|
||||
model_sampling = ModelSamplingAdvanced(model.model.model_config, zsnr=zsnr)
|
||||
|
||||
m.add_object_patch("model_sampling", model_sampling)
|
||||
return (m, )
|
||||
|
||||
class ModelSamplingStableCascade:
|
||||
@classmethod
|
||||
def INPUT_TYPES(s):
|
||||
return {"required": { "model": ("MODEL",),
|
||||
"shift": ("FLOAT", {"default": 2.0, "min": 0.0, "max": 100.0, "step":0.01}),
|
||||
}}
|
||||
|
||||
RETURN_TYPES = ("MODEL",)
|
||||
FUNCTION = "patch"
|
||||
|
||||
CATEGORY = "model/patch/stable cascade"
|
||||
|
||||
def patch(self, model, shift):
|
||||
m = model.clone()
|
||||
|
||||
sampling_base = comfy.model_sampling.StableCascadeSampling
|
||||
sampling_type = comfy.model_sampling.EPS
|
||||
|
||||
class ModelSamplingAdvanced(sampling_base, sampling_type):
|
||||
pass
|
||||
|
||||
model_sampling = ModelSamplingAdvanced(model.model.model_config)
|
||||
model_sampling.set_parameters(shift)
|
||||
m.add_object_patch("model_sampling", model_sampling)
|
||||
return (m, )
|
||||
|
||||
class ModelSamplingSD3:
|
||||
@classmethod
|
||||
def INPUT_TYPES(s):
|
||||
return {"required": { "model": ("MODEL",),
|
||||
"shift": ("FLOAT", {"default": 3.0, "min": 0.0, "max": 100.0, "step":0.01}),
|
||||
}}
|
||||
|
||||
RETURN_TYPES = ("MODEL",)
|
||||
FUNCTION = "patch"
|
||||
|
||||
CATEGORY = "model/patch/stable diffusion"
|
||||
|
||||
def patch(self, model, shift, multiplier=1000, sampling="flow"):
|
||||
m = model.clone()
|
||||
|
||||
sampling_base = comfy.model_sampling.ModelSamplingDiscreteFlow
|
||||
sampling_type = comfy.model_sampling.CONST
|
||||
if sampling == "img_to_img_velocity":
|
||||
sampling_type = comfy.model_sampling.IMG_TO_IMG_VELOCITY
|
||||
|
||||
class ModelSamplingAdvanced(sampling_base, sampling_type):
|
||||
pass
|
||||
|
||||
original = m.get_model_object("model_sampling")
|
||||
model_sampling = ModelSamplingAdvanced(model.model.model_config)
|
||||
model_sampling.set_parameters(shift=shift, multiplier=multiplier)
|
||||
if hasattr(original, "noise_scale"):
|
||||
model_sampling.set_noise_scale(original.noise_scale)
|
||||
m.add_object_patch("model_sampling", model_sampling)
|
||||
return (m, )
|
||||
|
||||
class ModelSamplingAuraFlow(ModelSamplingSD3):
|
||||
@classmethod
|
||||
def INPUT_TYPES(s):
|
||||
return {"required": { "model": ("MODEL",),
|
||||
"shift": ("FLOAT", {"default": 1.73, "min": 0.0, "max": 100.0, "step":0.01}),
|
||||
},
|
||||
"optional": { "sampling": (["flow", "img_to_img_velocity"], {"default": "flow", "advanced": True}),
|
||||
}}
|
||||
|
||||
FUNCTION = "patch_aura"
|
||||
CATEGORY = "model/patch"
|
||||
|
||||
def patch_aura(self, model, shift, sampling="flow"):
|
||||
return self.patch(model, shift, multiplier=1.0, sampling=sampling)
|
||||
|
||||
class ModelSamplingFlux:
|
||||
@classmethod
|
||||
def INPUT_TYPES(s):
|
||||
return {"required": { "model": ("MODEL",),
|
||||
"max_shift": ("FLOAT", {"default": 1.15, "min": 0.0, "max": 100.0, "step":0.01, "advanced": True}),
|
||||
"base_shift": ("FLOAT", {"default": 0.5, "min": 0.0, "max": 100.0, "step":0.01, "advanced": True}),
|
||||
"width": ("INT", {"default": 1024, "min": 16, "max": nodes.MAX_RESOLUTION, "step": 8}),
|
||||
"height": ("INT", {"default": 1024, "min": 16, "max": nodes.MAX_RESOLUTION, "step": 8}),
|
||||
}}
|
||||
|
||||
RETURN_TYPES = ("MODEL",)
|
||||
FUNCTION = "patch"
|
||||
|
||||
CATEGORY = "model/patch/flux"
|
||||
|
||||
def patch(self, model, max_shift, base_shift, width, height):
|
||||
m = model.clone()
|
||||
|
||||
x1 = 256
|
||||
x2 = 4096
|
||||
mm = (max_shift - base_shift) / (x2 - x1)
|
||||
b = base_shift - mm * x1
|
||||
shift = (width * height / (8 * 8 * 2 * 2)) * mm + b
|
||||
|
||||
sampling_base = comfy.model_sampling.ModelSamplingFlux
|
||||
sampling_type = comfy.model_sampling.CONST
|
||||
|
||||
class ModelSamplingAdvanced(sampling_base, sampling_type):
|
||||
pass
|
||||
|
||||
model_sampling = ModelSamplingAdvanced(model.model.model_config)
|
||||
model_sampling.set_parameters(shift=shift)
|
||||
m.add_object_patch("model_sampling", model_sampling)
|
||||
return (m, )
|
||||
|
||||
|
||||
class ModelSamplingContinuousEDM:
|
||||
@classmethod
|
||||
def INPUT_TYPES(s):
|
||||
return {"required": { "model": ("MODEL",),
|
||||
"sampling": (["v_prediction", "edm", "edm_playground_v2.5", "eps", "cosmos_rflow"],),
|
||||
"sigma_max": ("FLOAT", {"default": 120.0, "min": 0.0, "max": 1000.0, "step":0.001, "round": False, "advanced": True}),
|
||||
"sigma_min": ("FLOAT", {"default": 0.002, "min": 0.0, "max": 1000.0, "step":0.001, "round": False, "advanced": True}),
|
||||
}}
|
||||
|
||||
RETURN_TYPES = ("MODEL",)
|
||||
FUNCTION = "patch"
|
||||
|
||||
CATEGORY = "model/patch"
|
||||
|
||||
def patch(self, model, sampling, sigma_max, sigma_min):
|
||||
m = model.clone()
|
||||
|
||||
sampling_base = comfy.model_sampling.ModelSamplingContinuousEDM
|
||||
latent_format = None
|
||||
sigma_data = 1.0
|
||||
if sampling == "eps":
|
||||
sampling_type = comfy.model_sampling.EPS
|
||||
elif sampling == "edm":
|
||||
sampling_type = comfy.model_sampling.EDM
|
||||
sigma_data = 0.5
|
||||
elif sampling == "v_prediction":
|
||||
sampling_type = comfy.model_sampling.V_PREDICTION
|
||||
elif sampling == "edm_playground_v2.5":
|
||||
sampling_type = comfy.model_sampling.EDM
|
||||
sigma_data = 0.5
|
||||
latent_format = comfy.latent_formats.SDXL_Playground_2_5()
|
||||
elif sampling == "cosmos_rflow":
|
||||
sampling_type = comfy.model_sampling.COSMOS_RFLOW
|
||||
sampling_base = comfy.model_sampling.ModelSamplingCosmosRFlow
|
||||
|
||||
class ModelSamplingAdvanced(sampling_base, sampling_type):
|
||||
pass
|
||||
|
||||
model_sampling = ModelSamplingAdvanced(model.model.model_config)
|
||||
model_sampling.set_parameters(sigma_min, sigma_max, sigma_data)
|
||||
m.add_object_patch("model_sampling", model_sampling)
|
||||
if latent_format is not None:
|
||||
m.add_object_patch("latent_format", latent_format)
|
||||
return (m, )
|
||||
|
||||
class ModelSamplingContinuousV:
|
||||
@classmethod
|
||||
def INPUT_TYPES(s):
|
||||
return {"required": { "model": ("MODEL",),
|
||||
"sampling": (["v_prediction"],),
|
||||
"sigma_max": ("FLOAT", {"default": 500.0, "min": 0.0, "max": 1000.0, "step":0.001, "round": False, "advanced": True}),
|
||||
"sigma_min": ("FLOAT", {"default": 0.03, "min": 0.0, "max": 1000.0, "step":0.001, "round": False, "advanced": True}),
|
||||
}}
|
||||
|
||||
RETURN_TYPES = ("MODEL",)
|
||||
FUNCTION = "patch"
|
||||
|
||||
CATEGORY = "model/patch"
|
||||
|
||||
def patch(self, model, sampling, sigma_max, sigma_min):
|
||||
m = model.clone()
|
||||
|
||||
sigma_data = 1.0
|
||||
if sampling == "v_prediction":
|
||||
sampling_type = comfy.model_sampling.V_PREDICTION
|
||||
|
||||
class ModelSamplingAdvanced(comfy.model_sampling.ModelSamplingContinuousV, sampling_type):
|
||||
pass
|
||||
|
||||
model_sampling = ModelSamplingAdvanced(model.model.model_config)
|
||||
model_sampling.set_parameters(sigma_min, sigma_max, sigma_data)
|
||||
m.add_object_patch("model_sampling", model_sampling)
|
||||
return (m, )
|
||||
|
||||
class RescaleCFG:
|
||||
@classmethod
|
||||
def INPUT_TYPES(s):
|
||||
return {"required": { "model": ("MODEL",),
|
||||
"multiplier": ("FLOAT", {"default": 0.7, "min": 0.0, "max": 1.0, "step": 0.01}),
|
||||
}}
|
||||
RETURN_TYPES = ("MODEL",)
|
||||
FUNCTION = "patch"
|
||||
|
||||
CATEGORY = "model/patch"
|
||||
|
||||
def patch(self, model, multiplier):
|
||||
model_sampling = model.get_model_object("model_sampling")
|
||||
is_flow = isinstance(model_sampling, comfy.model_sampling.CONST)
|
||||
|
||||
def rescale_cfg(args):
|
||||
x_orig = args["input"]
|
||||
cond_scale = args["cond_scale"]
|
||||
|
||||
if is_flow:
|
||||
# Flow-matching models: cond_denoised/uncond_denoised are x_0 estimates,
|
||||
# so the eps↔v conversion below would be wrong. Rescale directly in x_0 space.
|
||||
x_0_cond = args["cond_denoised"]
|
||||
x_0_uncond = args["uncond_denoised"]
|
||||
x_0_cfg = x_0_uncond + cond_scale * (x_0_cond - x_0_uncond)
|
||||
dims = tuple(range(1, x_0_cond.ndim))
|
||||
ro_pos = x_0_cond.std(dim=dims, keepdim=True)
|
||||
ro_cfg = x_0_cfg.std(dim=dims, keepdim=True).clamp(min=1e-8)
|
||||
x_0_rescaled = x_0_cfg * (ro_pos / ro_cfg)
|
||||
x_0_final = multiplier * x_0_rescaled + (1.0 - multiplier) * x_0_cfg
|
||||
return x_orig - x_0_final
|
||||
|
||||
cond = args["cond"]
|
||||
uncond = args["uncond"]
|
||||
sigma = args["sigma"]
|
||||
sigma = sigma.view(sigma.shape[:1] + (1,) * (cond.ndim - 1))
|
||||
|
||||
#rescale cfg has to be done on v-pred model output
|
||||
x = x_orig / (sigma * sigma + 1.0)
|
||||
cond = ((x - (x_orig - cond)) * (sigma ** 2 + 1.0) ** 0.5) / (sigma)
|
||||
uncond = ((x - (x_orig - uncond)) * (sigma ** 2 + 1.0) ** 0.5) / (sigma)
|
||||
|
||||
#rescalecfg
|
||||
x_cfg = uncond + cond_scale * (cond - uncond)
|
||||
ro_pos = torch.std(cond, dim=(1,2,3), keepdim=True)
|
||||
ro_cfg = torch.std(x_cfg, dim=(1,2,3), keepdim=True)
|
||||
|
||||
x_rescaled = x_cfg * (ro_pos / ro_cfg)
|
||||
x_final = multiplier * x_rescaled + (1.0 - multiplier) * x_cfg
|
||||
|
||||
return x_orig - (x - x_final * sigma / (sigma * sigma + 1.0) ** 0.5)
|
||||
|
||||
m = model.clone()
|
||||
m.set_model_sampler_cfg_function(rescale_cfg)
|
||||
return (m, )
|
||||
|
||||
class ModelNoiseScale:
|
||||
@classmethod
|
||||
def INPUT_TYPES(s):
|
||||
return {"required": { "model": ("MODEL",),
|
||||
"noise_scale": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 64.0, "step": 0.01,
|
||||
"tooltip": "Absolute training noise scale. For example HiDream-O1 base: 8.0, dev: 7.5."}),
|
||||
}}
|
||||
|
||||
RETURN_TYPES = ("MODEL",)
|
||||
FUNCTION = "patch"
|
||||
|
||||
CATEGORY = "model/patch"
|
||||
|
||||
def patch(self, model, noise_scale):
|
||||
m = model.clone()
|
||||
original = m.get_model_object("model_sampling")
|
||||
ms = type(original)(m.model.model_config)
|
||||
ms.set_parameters(shift=original.shift, multiplier=original.multiplier)
|
||||
ms.set_noise_scale(noise_scale)
|
||||
m.add_object_patch("model_sampling", ms)
|
||||
return (m, )
|
||||
|
||||
|
||||
class ModelComputeDtype:
|
||||
SEARCH_ALIASES = ["model precision", "change dtype"]
|
||||
@classmethod
|
||||
def INPUT_TYPES(s):
|
||||
return {"required": { "model": ("MODEL",),
|
||||
"dtype": (["default", "fp32", "fp16", "bf16"], {"advanced": True}),
|
||||
}}
|
||||
|
||||
RETURN_TYPES = ("MODEL",)
|
||||
FUNCTION = "patch"
|
||||
|
||||
CATEGORY = "advanced/debug"
|
||||
|
||||
def patch(self, model, dtype):
|
||||
m = model.clone()
|
||||
m.set_model_compute_dtype(node_helpers.string_to_torch_dtype(dtype))
|
||||
return (m, )
|
||||
|
||||
|
||||
class ModelAttentionBackend(io.ComfyNode):
|
||||
@classmethod
|
||||
def define_schema(cls):
|
||||
backends = ["pytorch attention"]
|
||||
if comfy.ldm.modules.attention.COMFY_KITCHEN_INT8_ATTENTION_IS_AVAILABLE:
|
||||
backends.append("comfy kitchen attention")
|
||||
return io.Schema(
|
||||
node_id="ModelAttentionBackend",
|
||||
display_name="Model Attention Backend",
|
||||
search_aliases=["comfy kitchen", "attention", "pytorch", "kitchen attention"],
|
||||
category="model/patch",
|
||||
is_experimental=True,
|
||||
description="Selects the dense attention implementation for the model. When used with Block Sparse Attention, this backend is used whenever sparse attention is inactive or unsupported.",
|
||||
inputs=[
|
||||
io.Model.Input("model", tooltip="The model to patch."),
|
||||
io.Combo.Input("attention", display_name="backend", options=backends, default="pytorch attention",
|
||||
tooltip="The dense attention backend. Comfy Kitchen attention uses quantized INT8 attention and is available only on Nvidia and AMD GPUs."),
|
||||
],
|
||||
outputs=[
|
||||
io.Model.Output(display_name="model", tooltip="The model with the selected attention backend."),
|
||||
],
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def validate_inputs(cls, attention):
|
||||
return True
|
||||
|
||||
@classmethod
|
||||
def execute(cls, model, attention):
|
||||
attention_name = {
|
||||
"comfy kitchen attention": "comfy_kitchen_int8",
|
||||
"pytorch attention": "pytorch",
|
||||
}.get(attention)
|
||||
attention_function = comfy.ldm.modules.attention.get_attention_function(attention_name, None)
|
||||
if attention_function is None:
|
||||
logging.warning("Attention backend '%s' is unavailable; using PyTorch attention.", attention)
|
||||
attention_function = comfy.ldm.modules.attention.get_attention_function("pytorch")
|
||||
m = model.clone()
|
||||
m.set_model_optimized_attention(attention_function)
|
||||
return io.NodeOutput(m)
|
||||
|
||||
|
||||
NODE_CLASS_MAPPINGS = {
|
||||
"ModelSamplingDiscrete": ModelSamplingDiscrete,
|
||||
"ModelSamplingContinuousEDM": ModelSamplingContinuousEDM,
|
||||
"ModelSamplingContinuousV": ModelSamplingContinuousV,
|
||||
"ModelSamplingStableCascade": ModelSamplingStableCascade,
|
||||
"ModelSamplingSD3": ModelSamplingSD3,
|
||||
"ModelSamplingAuraFlow": ModelSamplingAuraFlow,
|
||||
"ModelSamplingFlux": ModelSamplingFlux,
|
||||
"ModelNoiseScale": ModelNoiseScale,
|
||||
"RescaleCFG": RescaleCFG,
|
||||
"ModelComputeDtype": ModelComputeDtype,
|
||||
"ModelAttentionBackend": ModelAttentionBackend,
|
||||
}
|
||||
@@ -0,0 +1,455 @@
|
||||
"""ComfyUI nodes for the native MoGe (Monocular Geometry Estimation) integration."""
|
||||
|
||||
|
||||
import torch
|
||||
import math
|
||||
|
||||
import comfy.utils
|
||||
import folder_paths
|
||||
from comfy_api.latest import ComfyExtension, Types, io
|
||||
from typing_extensions import override
|
||||
|
||||
from comfy.ldm.colormap import turbo as _turbo
|
||||
from comfy.ldm.moge.model import MoGeModel
|
||||
from comfy.ldm.moge.geometry import triangulate_grid_mesh
|
||||
from comfy.ldm.moge.panorama import get_panorama_cameras, split_panorama_image, merge_panorama_depth, spherical_uv_to_directions, _uv_grid
|
||||
import comfy.model_management
|
||||
from tqdm.auto import tqdm
|
||||
|
||||
MoGeModelType = io.Custom("MOGE_MODEL")
|
||||
MoGeGeometry = io.Custom("MOGE_GEOMETRY")
|
||||
|
||||
|
||||
# MOGE_GEOMETRY is a dict with these optional keys (absent when the upstream model didn't produce them):
|
||||
# "points": torch.Tensor (B, H, W, 3)
|
||||
# "depth": torch.Tensor (B, H, W)
|
||||
# "intrinsics": torch.Tensor (B, 3, 3) -- perspective only
|
||||
# "mask": torch.Tensor (B, H, W) bool
|
||||
# "normal": torch.Tensor (B, H, W, 3) -- v2 only
|
||||
# "image": torch.Tensor (B, H, W, 3) in [0, 1], CPU (always present)
|
||||
|
||||
|
||||
def _normals_from_points(points: torch.Tensor) -> torch.Tensor:
|
||||
"""Camera-space surface normals from a (B, H, W, 3) point map (v1 fallback)."""
|
||||
finite = torch.isfinite(points).all(dim=-1)
|
||||
pts = torch.where(finite.unsqueeze(-1), points, torch.zeros_like(points))
|
||||
dx = pts[..., :, 2:, :] - pts[..., :, :-2, :]
|
||||
dy = pts[..., 2:, :, :] - pts[..., :-2, :, :]
|
||||
dx = torch.nn.functional.pad(dx.permute(0, 3, 1, 2), (1, 1, 0, 0)).permute(0, 2, 3, 1)
|
||||
dy = torch.nn.functional.pad(dy.permute(0, 3, 1, 2), (0, 0, 1, 1)).permute(0, 2, 3, 1)
|
||||
# dy x dx (not dx x dy) so the result is outward-facing in OpenCV (Y-down flips the right-hand rule), matching v2's predicted normals.
|
||||
n = torch.cross(dy, dx, dim=-1)
|
||||
n = torch.nn.functional.normalize(n, dim=-1)
|
||||
return torch.where(finite.unsqueeze(-1), n, torch.zeros_like(n))
|
||||
|
||||
|
||||
def _normalize_disparity(depth: torch.Tensor) -> torch.Tensor:
|
||||
"""Per-batch normalize 1/depth to [0, 1] using 0.1/99.9 percentile clipping."""
|
||||
out = torch.zeros_like(depth)
|
||||
for i in range(depth.shape[0]):
|
||||
d = depth[i]
|
||||
valid = torch.isfinite(d) & (d > 0)
|
||||
if not valid.any():
|
||||
continue
|
||||
disp = torch.where(valid, 1.0 / d.clamp_min(1e-6), torch.zeros_like(d))
|
||||
disp_valid = disp[valid]
|
||||
lo = torch.quantile(disp_valid, 0.001)
|
||||
hi = torch.quantile(disp_valid, 0.999)
|
||||
scale = (hi - lo).clamp_min(1e-6)
|
||||
norm = ((disp - lo) / scale).clamp(0.0, 1.0)
|
||||
out[i] = torch.where(valid, norm, torch.zeros_like(norm))
|
||||
return out
|
||||
|
||||
|
||||
class LoadMoGeModel(io.ComfyNode):
|
||||
@classmethod
|
||||
def define_schema(cls):
|
||||
return io.Schema(
|
||||
node_id="LoadMoGeModel",
|
||||
display_name="Load MoGe Model",
|
||||
category="model/loaders",
|
||||
inputs=[
|
||||
io.Combo.Input("model_name", options=folder_paths.get_filename_list("geometry_estimation")),
|
||||
],
|
||||
outputs=[MoGeModelType.Output()],
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def execute(cls, model_name) -> io.NodeOutput:
|
||||
path = folder_paths.get_full_path_or_raise("geometry_estimation", model_name)
|
||||
sd = comfy.utils.load_torch_file(path, safe_load=True)
|
||||
return io.NodeOutput(MoGeModel(sd))
|
||||
|
||||
|
||||
class MoGePanoramaInference(io.ComfyNode):
|
||||
"""Equirectangular panorama inference: split into 12 perspective views, run
|
||||
MoGe at fov_x=90 on each, merge via multi-scale Poisson + gradient solve.
|
||||
v2's predicted normals and metric scale are ignored (per-view scales would not align across seams).
|
||||
"""
|
||||
|
||||
@classmethod
|
||||
def define_schema(cls):
|
||||
return io.Schema(
|
||||
node_id="MoGePanoramaInference",
|
||||
search_aliases=["moge", "panorama", "depth", "geometry", "depth estimation", "geometry estimation"],
|
||||
display_name="Run MoGe Panorama Inference",
|
||||
category="image/geometry estimation",
|
||||
description="Run MoGe on an equirectangular panorama by splitting it into 12 perspective views, running inference on each, and merging the results into a single depth map.",
|
||||
inputs=[
|
||||
MoGeModelType.Input("moge_model"),
|
||||
io.Image.Input("image", tooltip="Equirectangular panorama (any aspect)."),
|
||||
io.Int.Input("resolution_level", default=9, min=0, max=9,
|
||||
tooltip="Per-view detail (0 = fastest, 9 = most detailed)."),
|
||||
io.Int.Input("split_resolution", default=512, min=256, max=1024,
|
||||
tooltip="Resolution of each perspective split."),
|
||||
io.Int.Input("merge_resolution", default=1920, min=256, max=8192,
|
||||
tooltip="Long-side resolution of the merged equirect distance map."),
|
||||
io.Int.Input("batch_size", default=4, min=1, max=12,
|
||||
tooltip="Views per inference batch (12 splits total)."),
|
||||
io.Int.Input("refine_steps", default=3, min=0, max=8, advanced=True,
|
||||
tooltip="MoGe-3 only: sparse volumetric refinement passes over the predicted depth. More passes sharpen fine detail and edges at a roughly linear cost. 0 disables refinement. Ignored by MoGe-1 / MoGe-2."),
|
||||
],
|
||||
outputs=[MoGeGeometry.Output(display_name="moge_geometry")],
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def execute(cls, moge_model, image, resolution_level, split_resolution, merge_resolution, batch_size, refine_steps) -> io.NodeOutput:
|
||||
|
||||
if image.shape[0] != 1:
|
||||
raise ValueError(f"MoGePanoramaInference takes a single image (got batch of {image.shape[0]})")
|
||||
|
||||
image = image[..., :3]
|
||||
H, W = int(image.shape[1]), int(image.shape[2])
|
||||
scale = min(merge_resolution / max(H, W), 1.0)
|
||||
merge_h, merge_w = max(int(H * scale), 32), max(int(W * scale), 32)
|
||||
|
||||
extrinsics, intrinsics = get_panorama_cameras()
|
||||
|
||||
comfy.model_management.load_model_gpu(moge_model.patcher)
|
||||
device = moge_model.load_device
|
||||
img_chw = image[0].movedim(-1, -3).to(device=device, dtype=moge_model.dtype)
|
||||
splits = split_panorama_image(img_chw, extrinsics, intrinsics, split_resolution)
|
||||
|
||||
n_views = splits.shape[0]
|
||||
|
||||
# Weight each lsmr solve by 4^level so the final-resolution solve doesn't leave the bar idle.
|
||||
merge_levels: list[tuple[int, int]] = []
|
||||
w_, h_ = merge_w, merge_h
|
||||
while True:
|
||||
merge_levels.append((w_, h_))
|
||||
if max(w_, h_) <= 256:
|
||||
break
|
||||
w_, h_ = w_ // 2, h_ // 2
|
||||
merge_levels.reverse()
|
||||
|
||||
solve_weight = {wh: 4 ** i for i, wh in enumerate(merge_levels)}
|
||||
n_merge_view_units = n_views * len(merge_levels)
|
||||
n_merge_solve_units = sum(solve_weight.values())
|
||||
|
||||
pbar = comfy.utils.ProgressBar(n_views + n_merge_view_units + n_merge_solve_units)
|
||||
done = 0
|
||||
|
||||
distance_maps: list = []
|
||||
masks: list = []
|
||||
with tqdm(total=n_views, desc="MoGe panorama inference") as tq:
|
||||
for i in range(0, n_views, batch_size):
|
||||
batch = splits[i:i + batch_size]
|
||||
# apply_metric_scale=False: per-view scales would not align across overlap seams.
|
||||
result = moge_model.infer(batch, resolution_level=resolution_level,
|
||||
fov_x=90.0, force_projection=True,
|
||||
apply_mask=False, apply_metric_scale=False,
|
||||
refine_steps=refine_steps)
|
||||
distance_maps.extend(list(result["points"].float().norm(dim=-1).cpu().numpy()))
|
||||
masks.extend(list(result["mask"].cpu().numpy()))
|
||||
n = batch.shape[0]
|
||||
done += n
|
||||
pbar.update_absolute(done)
|
||||
tq.update(n)
|
||||
|
||||
with tqdm(total=n_merge_view_units + n_merge_solve_units, desc="MoGe panorama merge: views") as tq:
|
||||
def _on_merge_view():
|
||||
nonlocal done
|
||||
done += 1
|
||||
pbar.update_absolute(done)
|
||||
tq.update(1)
|
||||
|
||||
def _on_solve_start(w, h):
|
||||
tq.set_description(f"MoGe panorama merge: solving {w}x{h}")
|
||||
|
||||
def _on_solve_end(w, h):
|
||||
nonlocal done
|
||||
weight = solve_weight[(w, h)]
|
||||
done += weight
|
||||
pbar.update_absolute(done)
|
||||
tq.update(weight)
|
||||
tq.set_description("MoGe panorama merge: views")
|
||||
|
||||
pano_depth, pano_mask = merge_panorama_depth(
|
||||
merge_w, merge_h, distance_maps, masks, list(extrinsics), intrinsics,
|
||||
on_view=_on_merge_view, on_solve_start=_on_solve_start, on_solve_end=_on_solve_end)
|
||||
|
||||
pano_depth = torch.from_numpy(pano_depth)
|
||||
pano_mask = torch.from_numpy(pano_mask)
|
||||
|
||||
if (merge_h, merge_w) != (H, W):
|
||||
pano_depth = torch.nn.functional.interpolate(pano_depth[None, None], size=(H, W), mode="bilinear", align_corners=False).squeeze()
|
||||
pano_mask = torch.nn.functional.interpolate(pano_mask[None, None].float(), size=(H, W), mode="nearest").squeeze() > 0
|
||||
|
||||
# Pixels uncovered by any view's predicted foreground are unconstrained in the lsmr solve and stay at log_depth=0 (depth=1)
|
||||
if pano_mask.any() and not pano_mask.all():
|
||||
far = torch.quantile(pano_depth[pano_mask], 0.95) * 5.0
|
||||
pano_depth = torch.where(pano_mask, pano_depth, far)
|
||||
|
||||
directions = torch.from_numpy(spherical_uv_to_directions(_uv_grid(H, W)))
|
||||
points = (directions * pano_depth[..., None]).unsqueeze(0)
|
||||
depth = pano_depth.unsqueeze(0)
|
||||
mask = pano_mask.unsqueeze(0)
|
||||
|
||||
# Points stay in MoGe spherical coords; MoGePointMapToMesh applies the spherical->glTF rotation after triangulation
|
||||
moge_geometry = {"points": points, "depth": depth, "mask": mask, "image": image.cpu()}
|
||||
return io.NodeOutput(moge_geometry)
|
||||
|
||||
|
||||
class MoGeInference(io.ComfyNode):
|
||||
@classmethod
|
||||
def define_schema(cls):
|
||||
return io.Schema(
|
||||
node_id="MoGeInference",
|
||||
search_aliases=["moge", "depth", "geometry", "depth estimation", "geometry estimation"],
|
||||
display_name="Run MoGe Inference",
|
||||
description="Run MoGe on a single image to estimate depth and geometry.",
|
||||
category="image/geometry estimation",
|
||||
inputs=[
|
||||
MoGeModelType.Input("moge_model"),
|
||||
io.Image.Input("image"),
|
||||
io.Int.Input("resolution_level", default=9, min=0, max=9,
|
||||
tooltip="0 = fastest, 9 = most detail."),
|
||||
io.Float.Input("fov_x_degrees", default=0.0, min=0.0, max=170.0, step=0.1, advanced=True,
|
||||
tooltip="Horizontal field of view of the source camera. Sets the focal length used to unproject the depth map into 3D. 0 = auto-recover from the predicted points."),
|
||||
io.Int.Input("batch_size", default=4, min=1, max=64,
|
||||
tooltip="Images per inference call. Lower if you OOM on a long video / image set."),
|
||||
io.Boolean.Input("force_projection", default=True, advanced=True),
|
||||
io.Boolean.Input("apply_mask", default=True, advanced=True,
|
||||
tooltip="Set masked-out (sky / invalid) pixels to inf in points and depth so meshing culls them. Disable to keep the raw predicted geometry everywhere; the mask is still returned separately."),
|
||||
io.Int.Input("refine_steps", default=3, min=0, max=8, advanced=True,
|
||||
tooltip="MoGe-3 only: sparse volumetric refinement passes over the predicted depth. More passes sharpen fine detail and edges at a roughly linear cost. 0 disables refinement. Ignored by MoGe-1 / MoGe-2."),
|
||||
],
|
||||
outputs=[MoGeGeometry.Output(display_name="moge_geometry")],
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def execute(cls, moge_model, image, resolution_level, fov_x_degrees, batch_size, force_projection, apply_mask, refine_steps) -> io.NodeOutput:
|
||||
|
||||
image = image[..., :3]
|
||||
bchw = image.movedim(-1, -3).contiguous()
|
||||
B = bchw.shape[0]
|
||||
fov = None if fov_x_degrees <= 0 else float(fov_x_degrees)
|
||||
|
||||
pbar = comfy.utils.ProgressBar(B)
|
||||
chunks: list[dict] = []
|
||||
with tqdm(total=B, desc="MoGe inference") as tq:
|
||||
for i in range(0, B, batch_size):
|
||||
chunk = bchw[i:i + batch_size]
|
||||
chunks.append(moge_model.infer(chunk, resolution_level=resolution_level, fov_x=fov,
|
||||
force_projection=force_projection, apply_mask=apply_mask,
|
||||
refine_steps=refine_steps))
|
||||
pbar.update_absolute(min(i + batch_size, B))
|
||||
tq.update(chunk.shape[0])
|
||||
|
||||
def stack(field):
|
||||
vals = [c[field] for c in chunks if field in c]
|
||||
return torch.cat(vals, dim=0) if vals else None
|
||||
|
||||
moge_geometry = {"image": image.cpu()}
|
||||
for field in ("points", "depth", "intrinsics", "mask", "normal"):
|
||||
v = stack(field)
|
||||
if v is not None:
|
||||
moge_geometry[field] = v
|
||||
return io.NodeOutput(moge_geometry)
|
||||
|
||||
|
||||
class MoGeRender(io.ComfyNode):
|
||||
"""Render a visualization or mask from a MOGE_GEOMETRY packet."""
|
||||
|
||||
@classmethod
|
||||
def define_schema(cls):
|
||||
return io.Schema(
|
||||
node_id="MoGeRender",
|
||||
search_aliases=["moge", "render", "geometry", "depth", "normal"],
|
||||
display_name="Render MoGe Geometry",
|
||||
description="Render a depth map or normal map from geometry data",
|
||||
category="image/geometry estimation",
|
||||
inputs=[
|
||||
MoGeGeometry.Input("moge_geometry"),
|
||||
io.Combo.Input("output", options=["depth", "depth_colored", "normal_opengl", "normal_directx", "mask"], default="depth",
|
||||
tooltip="DirectX vs OpenGL controls the normal-map green-channel convention. DirectX: green = -Y down (Unreal). OpenGL: green = +Y up (Blender, Substance, Unity, glTF)."),
|
||||
],
|
||||
outputs=[io.Image.Output()],
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def execute(cls, moge_geometry, output) -> io.NodeOutput:
|
||||
is_normal = output in ("normal_directx", "normal_opengl")
|
||||
opengl = output.endswith("_opengl")
|
||||
|
||||
# Pick the input tensor for the chosen mode and validate availability.
|
||||
if output in ("depth", "depth_colored"):
|
||||
if "depth" not in moge_geometry:
|
||||
raise ValueError("moge_geometry has no depth output.")
|
||||
src = moge_geometry["depth"]
|
||||
elif is_normal:
|
||||
if "normal" in moge_geometry:
|
||||
src = moge_geometry["normal"]
|
||||
elif "points" in moge_geometry:
|
||||
src = moge_geometry["points"]
|
||||
else:
|
||||
raise ValueError("moge_geometry has neither normals nor points to derive normals from.")
|
||||
elif output == "mask":
|
||||
if "mask" not in moge_geometry:
|
||||
raise ValueError("moge_geometry has no mask output.")
|
||||
src = moge_geometry["mask"]
|
||||
else:
|
||||
raise ValueError(f"Unknown output mode: {output}")
|
||||
|
||||
B = src.shape[0]
|
||||
pbar = comfy.utils.ProgressBar(B)
|
||||
out: list[torch.Tensor] = []
|
||||
with tqdm(total=B, desc=f"MoGe render: {output}") as tq:
|
||||
for i in range(B):
|
||||
slc = src[i:i + 1].float()
|
||||
if output in ("depth", "depth_colored"):
|
||||
d = _normalize_disparity(slc)
|
||||
out.append(_turbo(d) if output == "depth_colored"
|
||||
else d.unsqueeze(-1).expand(*d.shape, 3).contiguous())
|
||||
elif is_normal:
|
||||
n = slc if "normal" in moge_geometry else _normals_from_points(slc)
|
||||
# MoGe is OpenCV (Z+ into scene); normal-map convention is Z+ out of surface, so flip Z.
|
||||
y_sign = -1.0 if opengl else 1.0
|
||||
n = n * n.new_tensor([1.0, y_sign, -1.0])
|
||||
out.append((n * 0.5 + 0.5).clamp(0.0, 1.0))
|
||||
elif output == "mask":
|
||||
out.append(slc.unsqueeze(-1).expand(*slc.shape, 3).contiguous())
|
||||
pbar.update_absolute(i + 1)
|
||||
tq.update(1)
|
||||
result = torch.cat(out, dim=0).to(device=comfy.model_management.intermediate_device(), dtype=comfy.model_management.intermediate_dtype())
|
||||
return io.NodeOutput(result)
|
||||
|
||||
|
||||
class MoGePointMapToMesh(io.ComfyNode):
|
||||
"""Triangulate one image of a MoGe point map into a Types.MESH (UVs + texture)."""
|
||||
|
||||
@classmethod
|
||||
def define_schema(cls):
|
||||
return io.Schema(
|
||||
node_id="MoGePointMapToMesh",
|
||||
search_aliases=["moge", "mesh", "geometry", "point map"],
|
||||
display_name="Convert MoGe Point Map to Mesh",
|
||||
description="Convert a MoGe point map into a 3D mesh.",
|
||||
category="image/geometry estimation",
|
||||
inputs=[
|
||||
MoGeGeometry.Input("moge_geometry"),
|
||||
io.Int.Input("batch_index", default=0, min=0, max=4096,
|
||||
tooltip="Which image of a batched MoGe geometry to mesh. Per-image vertex counts "
|
||||
"differ, so batches can't be stacked into a single MESH."),
|
||||
io.Int.Input("decimation", default=1, min=1, max=8,
|
||||
tooltip="Vertex stride; 1 = full resolution."),
|
||||
io.Float.Input("discontinuity_threshold", default=0.04, min=0.0, max=1.0, step=0.01,
|
||||
tooltip="Drop pixels whose 3x3 depth span exceeds this fraction. 0 = off."),
|
||||
io.Boolean.Input("texture", default=True,
|
||||
tooltip="Carry the source image through as the baseColor texture."),
|
||||
],
|
||||
outputs=[io.Mesh.Output()],
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def execute(cls, moge_geometry, batch_index, decimation, discontinuity_threshold, texture) -> io.NodeOutput:
|
||||
if "points" not in moge_geometry:
|
||||
raise ValueError("moge_geometry has no points output.")
|
||||
points = moge_geometry["points"]
|
||||
B = points.shape[0]
|
||||
if batch_index >= B:
|
||||
raise ValueError(f"batch_index {batch_index} out of range; moge_geometry has batch size {B}.")
|
||||
|
||||
# Pass depth so the rtol edge check sees radial depth -- for panoramas
|
||||
# points[..., 2] = cos(phi)*r goes negative below the equator and the rtol clamp would drop the bottom half.
|
||||
edge_depth = moge_geometry["depth"][batch_index] if "depth" in moge_geometry else None
|
||||
verts, faces, uvs = triangulate_grid_mesh(
|
||||
points[batch_index], decimation=decimation,
|
||||
discontinuity_threshold=discontinuity_threshold, depth=edge_depth,
|
||||
)
|
||||
if verts.shape[0] == 0 or faces.shape[0] == 0:
|
||||
raise ValueError("MoGe produced an empty mesh; try discontinuity_threshold=0 or apply_mask=False.")
|
||||
|
||||
if "intrinsics" not in moge_geometry:
|
||||
# Panorama: rotate MoGe spherical (Z up) -> glTF (Y up, Z back), correct for inside-the-sphere viewing)
|
||||
verts = verts[:, [1, 2, 0]].contiguous()
|
||||
else:
|
||||
# Perspective MoGe (X right, Y down, Z forward) -> glTF; face flip keeps winding CCW after the Y/Z flip.
|
||||
verts = verts * torch.tensor([1.0, -1.0, -1.0], dtype=verts.dtype)
|
||||
faces = faces[:, [0, 2, 1]].contiguous()
|
||||
|
||||
tex = moge_geometry["image"][batch_index:batch_index + 1] if texture else None
|
||||
mesh = Types.MESH(
|
||||
vertices=verts.unsqueeze(0),
|
||||
faces=faces.unsqueeze(0),
|
||||
uvs=uvs.unsqueeze(0),
|
||||
texture=tex,
|
||||
)
|
||||
return io.NodeOutput(mesh)
|
||||
|
||||
|
||||
class MoGeGeometryToFOV(io.ComfyNode):
|
||||
"""Extract horizontal/vertical FOV from MoGe intrinsics, e.g. fov_y to feed SAM3DBody_Predict."""
|
||||
|
||||
@classmethod
|
||||
def define_schema(cls):
|
||||
return io.Schema(
|
||||
node_id="MoGeGeometryToFOV",
|
||||
search_aliases=["moge", "fov", "geometry", "intrinsics", "field of view"],
|
||||
display_name="Get FoV from MoGe Geometry",
|
||||
description="Derive the field of view and focal length from MoGe intrinsics.",
|
||||
category="image/geometry estimation",
|
||||
inputs=[
|
||||
MoGeGeometry.Input("moge_geometry"),
|
||||
io.Combo.Input("axis", options=["vertical", "horizontal", "diagonal"], default="vertical",
|
||||
tooltip="'vertical' (fov_y), 'horizontal' (fov_x), or 'diagonal'."),
|
||||
io.Combo.Input("unit", options=["degrees", "radians"], default="degrees",
|
||||
tooltip="Output unit for the FOV."),
|
||||
],
|
||||
outputs=[
|
||||
io.Float.Output(display_name="fov"),
|
||||
io.Float.Output(display_name="focal_pixels"),
|
||||
],
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def execute(cls, moge_geometry, axis, unit) -> io.NodeOutput:
|
||||
K = moge_geometry.get("intrinsics") if isinstance(moge_geometry, dict) else None
|
||||
if K is None:
|
||||
raise ValueError("moge_geometry has no intrinsics (panorama geometry has none).")
|
||||
if K.ndim == 3:
|
||||
K = K[0]
|
||||
# MoGe normalizes fx by width and fy by height; with cx=cy=0.5 the half-extent
|
||||
# in normalized units is 0.5, so fov = 2*atan(0.5 / f) per axis (hypot for diagonal).
|
||||
hx = 0.5 / float(K[0, 0].item())
|
||||
hy = 0.5 / float(K[1, 1].item())
|
||||
half_tan = {"horizontal": hx, "vertical": hy, "diagonal": math.hypot(hx, hy)}[axis]
|
||||
fov_radians = 2.0 * math.atan(half_tan)
|
||||
fov = fov_radians if unit == "radians" else math.degrees(fov_radians)
|
||||
# Pixels are square here, so fy*H == fx*W is the single lens focal in pixels.
|
||||
src = next((moge_geometry[k] for k in ("image", "points", "depth") if k in moge_geometry), None)
|
||||
if src is None:
|
||||
raise ValueError("moge_geometry has no image/points/depth to read the pixel height from.")
|
||||
H = int(src.shape[1])
|
||||
focal_pixels = float(K[1, 1].item()) * H
|
||||
return io.NodeOutput(fov, focal_pixels)
|
||||
|
||||
|
||||
class MoGeExtension(ComfyExtension):
|
||||
@override
|
||||
async def get_node_list(self) -> list[type[io.ComfyNode]]:
|
||||
return [LoadMoGeModel, MoGeInference, MoGePanoramaInference, MoGeRender, MoGePointMapToMesh, MoGeGeometryToFOV]
|
||||
|
||||
|
||||
async def comfy_entrypoint() -> MoGeExtension:
|
||||
return MoGeExtension()
|
||||
+439
@@ -0,0 +1,439 @@
|
||||
"""Block-sparse attention on comfy_kitchen's sparse attention kernels (Sol-Attn adaptive
|
||||
threshold, SLA-style top-k, or FastVideo's VSA). Generic models go through the
|
||||
attention override; MiniMax-H3 gets the chunked qkv producer through block patches."""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import re
|
||||
import weakref
|
||||
|
||||
import comfy_kitchen as ck
|
||||
import torch
|
||||
|
||||
import comfy.model_management
|
||||
import comfy.model_prefetch
|
||||
import comfy.patcher_extension
|
||||
from comfy.ldm.minimax.model import MiniMaxH3Model
|
||||
from comfy_api.latest import ComfyExtension, io
|
||||
|
||||
HEAD_DIM = 128
|
||||
BLOCK_SIZE = 64
|
||||
PRODUCER_CHUNK = 4096
|
||||
VSA_CUBE = (4, 4, 4)
|
||||
VSA_PLAN_CACHE = 4
|
||||
|
||||
|
||||
def parse_block_list(text):
|
||||
"""'0, 1, 47-49' -> {0, 1, 47, 48, 49}."""
|
||||
blocks = set()
|
||||
for part in re.findall(r"\d+\s*-\s*\d+|\d+", text or ""):
|
||||
if "-" in part:
|
||||
a, b = (int(x) for x in part.split("-"))
|
||||
blocks.update(range(min(a, b), max(a, b) + 1))
|
||||
else:
|
||||
blocks.add(int(part))
|
||||
return blocks
|
||||
|
||||
|
||||
class SparseAttnPatch:
|
||||
"""Options plus runtime state for one patched model; an ON_CLEANUP callback
|
||||
resets the state when the sampling run ends."""
|
||||
|
||||
def __init__(self, tau, topk_ratio, vsa, sigma_start, sigma_end, min_tokens,
|
||||
dense_blocks, sink_conditioning, extra_tokens, verbose):
|
||||
self.tau = tau
|
||||
self.topk_ratio = topk_ratio
|
||||
self.extra_tokens = extra_tokens
|
||||
self.vsa = vsa
|
||||
self.sigma_start = sigma_start
|
||||
self.sigma_end = sigma_end
|
||||
self.min_tokens = min_tokens
|
||||
self.dense_blocks = dense_blocks
|
||||
self.sink_conditioning = sink_conditioning
|
||||
self.verbose = verbose
|
||||
self.installed = set() # the override closures this patch has put on the hook
|
||||
self.reset()
|
||||
|
||||
def reset(self):
|
||||
self.pooled = {} # (block, rows) -> (kmean, vscale) from the previous step
|
||||
self.vsa_plans = {} # small LRU of tiling plans
|
||||
self.vsa_rope = None
|
||||
self._logged = set()
|
||||
|
||||
def log_once(self, key, message):
|
||||
if self.verbose and key not in self._logged:
|
||||
self._logged.add(key)
|
||||
logging.info(f"BlockSparseAttention: {message}")
|
||||
|
||||
def dense_reason(self, transformer_options, tokens, block_index):
|
||||
"""Why this call stays dense regardless of its tensors, or None."""
|
||||
sigmas = transformer_options.get("sigmas")
|
||||
if sigmas is not None:
|
||||
sigma = float(sigmas[0])
|
||||
if sigma > self.sigma_start or sigma < self.sigma_end:
|
||||
return f"sigma {sigma:.3g} outside the start/end window"
|
||||
if tokens < self.min_tokens:
|
||||
return f"{tokens} tokens < min_tokens {self.min_tokens}"
|
||||
if self.dense_blocks:
|
||||
if block_index is None:
|
||||
self.log_once("no_block_index", "this model does not report block indices; dense_blocks ignored")
|
||||
elif block_index in self.dense_blocks:
|
||||
return f"block {block_index} in dense_blocks"
|
||||
return None
|
||||
|
||||
def sinks(self, transformer_options, tokens):
|
||||
"""MiniMax-H3 conditioning rows as (exact-KV blocks, dense-query blocks):
|
||||
the packed prefix stays exact for every query, and optionally the
|
||||
target-audio query rows run dense."""
|
||||
layout = transformer_options.get("minimax_h3_layout")
|
||||
if self.sink_conditioning == "off" or layout is None or layout.seq_len != tokens:
|
||||
return (0, 0), (0, 0)
|
||||
video = next(((a, b) for a, b, kind in layout.segments if kind == "video"), None)
|
||||
if video is None or video[0] <= 0:
|
||||
return (0, 0), (0, 0)
|
||||
blocks = (0, (video[0] + BLOCK_SIZE - 1) // BLOCK_SIZE)
|
||||
if self.sink_conditioning != "exact_kv_and_rows":
|
||||
return blocks, (0, 0)
|
||||
audio = next(((a, b) for a, b, kind in layout.segments if kind == "audio"), None)
|
||||
if audio is None:
|
||||
return blocks, blocks
|
||||
return blocks, (audio[0] // BLOCK_SIZE, blocks[1])
|
||||
|
||||
def vsa_plan(self, layout, device):
|
||||
"""Padded tile order: prefix segments in their own zero-padded 64-row
|
||||
tiles, video in 4x4x4 cubes. `src` maps padded row -> source row (-1 =
|
||||
pad), `inv` the reverse."""
|
||||
key = (tuple(layout.signature), tuple(layout.segments), str(device))
|
||||
plan = self.vsa_plans.get(key)
|
||||
if plan is not None:
|
||||
return plan
|
||||
_text_len, latent_t, latent_h, latent_w, _audio_t = layout.signature
|
||||
grid = (int(latent_t), int(latent_h) // 2, int(latent_w) // 2)
|
||||
tiles, n_prefix = [], 0
|
||||
for a, b, kind in layout.segments:
|
||||
n = b - a
|
||||
if kind != "video":
|
||||
m = (n + BLOCK_SIZE - 1) // BLOCK_SIZE
|
||||
seg = torch.full((m * BLOCK_SIZE,), -1, dtype=torch.int64, device=device)
|
||||
seg[:n] = torch.arange(a, b, device=device)
|
||||
tiles.append(seg.view(m, BLOCK_SIZE))
|
||||
n_prefix += m
|
||||
continue
|
||||
if grid[0] * grid[1] * grid[2] != n:
|
||||
raise RuntimeError(f"VSA: video segment of {n} rows does not match the latent grid {grid}")
|
||||
ct, ch, cw = VSA_CUBE
|
||||
pt, ph, pw = ((g + c - 1) // c * c for g, c in zip(grid, VSA_CUBE))
|
||||
padded = torch.full((pt, ph, pw), -1, dtype=torch.int64, device=device)
|
||||
padded[:grid[0], :grid[1], :grid[2]] = torch.arange(a, b, device=device).view(*grid)
|
||||
cubes = (padded.view(pt // ct, ct, ph // ch, ch, pw // cw, cw)
|
||||
.permute(0, 2, 4, 1, 3, 5).reshape(-1, BLOCK_SIZE))
|
||||
order = torch.argsort((cubes < 0).to(torch.int8), dim=1, stable=True)
|
||||
tiles.append(torch.gather(cubes, 1, order))
|
||||
tiles = torch.cat(tiles)
|
||||
src = tiles.reshape(-1)
|
||||
live = src >= 0
|
||||
inv = torch.empty(layout.seq_len, dtype=torch.int64, device=device)
|
||||
inv[src[live]] = torch.nonzero(live).flatten()
|
||||
plan = {"n": int(src.numel()), "n_prefix": n_prefix, "src": src, "inv": inv,
|
||||
"block_len": (tiles >= 0).sum(1).to(torch.int32)}
|
||||
while len(self.vsa_plans) >= VSA_PLAN_CACHE:
|
||||
del self.vsa_plans[next(iter(self.vsa_plans))]
|
||||
self.vsa_plans[key] = plan
|
||||
return plan
|
||||
|
||||
def vsa_rope_freqs(self, rope_freqs, plan):
|
||||
hit = self.vsa_rope
|
||||
if hit is not None and hit[0]() is rope_freqs and hit[1] is plan:
|
||||
return hit[2]
|
||||
padded = rope_freqs.new_zeros((1, plan["n"]) + tuple(rope_freqs.shape[2:]))
|
||||
padded[0, plan["inv"]] = rope_freqs[0]
|
||||
self.vsa_rope = (weakref.ref(rope_freqs), plan, padded)
|
||||
return padded
|
||||
|
||||
|
||||
def _ineligible(q, k, v, dim_head):
|
||||
"""Why these tensors can't go through the kernel, or None. q/k/v are BTHD."""
|
||||
if q.device.type != "cuda":
|
||||
return "not on CUDA"
|
||||
if not ck.sol_attn_is_available(q.device):
|
||||
return "no compiled sol_attn kernel for this GPU"
|
||||
if q.dtype not in (torch.bfloat16, torch.float16, torch.float32):
|
||||
return f"dtype {q.dtype} (kernel takes bf16/fp16)"
|
||||
if dim_head != HEAD_DIM:
|
||||
return f"head_dim {dim_head} != {HEAD_DIM}"
|
||||
if q.shape != k.shape or q.shape != v.shape:
|
||||
return "cross-attention or GQA (kept dense)"
|
||||
if k.dtype != q.dtype or v.dtype != q.dtype:
|
||||
return f"mixed dtypes {q.dtype}/{k.dtype}/{v.dtype}"
|
||||
return None
|
||||
|
||||
|
||||
def make_attention_override(patch: SparseAttnPatch, previous):
|
||||
"""Attention override; declined calls run ``previous`` (the override that was
|
||||
on the hook before this one) or ``func``. Dense-only in VSA mode: a
|
||||
VSA-trained model must never see plain block-sparse attention."""
|
||||
def override(func, q, k, v, heads, mask=None, attn_precision=None,
|
||||
skip_reshape=False, skip_output_reshape=False, **kwargs):
|
||||
transformer_options = kwargs.get("transformer_options") or {}
|
||||
|
||||
def dense():
|
||||
args = (q, k, v, heads)
|
||||
kw = dict(mask=mask, attn_precision=attn_precision, skip_reshape=skip_reshape,
|
||||
skip_output_reshape=skip_output_reshape, **kwargs)
|
||||
return func(*args, **kw) if previous is None else previous(func, *args, **kw)
|
||||
|
||||
if mask is not None or patch.vsa:
|
||||
return dense()
|
||||
tokens = q.shape[2] if skip_reshape else q.shape[1]
|
||||
reason = patch.dense_reason(transformer_options, tokens, transformer_options.get("block_index"))
|
||||
if reason is not None:
|
||||
patch.log_once(("dense", tokens, reason), f"dense ({tokens} tokens): {reason}")
|
||||
return dense()
|
||||
if skip_reshape:
|
||||
b, _, _, dim_head = q.shape # BHND
|
||||
qs, ks, vs = (t.transpose(1, 2) for t in (q, k, v))
|
||||
else:
|
||||
b, _, dim_head = q.shape # B, N, heads*dim_head
|
||||
dim_head //= heads
|
||||
qs, ks, vs = (t.view(b, -1, heads, dim_head) for t in (q, k, v))
|
||||
reason = _ineligible(qs, ks, vs, dim_head)
|
||||
if reason is not None:
|
||||
patch.log_once(("ineligible", tuple(qs.shape), reason), f"dense {tuple(qs.shape)}: {reason}")
|
||||
return dense()
|
||||
sink, sink_q = patch.sinks(transformer_options, tokens)
|
||||
if q.dtype == torch.float32: # the kernel quantizes to int8 anyway; bf16 keeps the fp32 range
|
||||
qs, ks, vs = (t.to(torch.bfloat16) for t in (qs, ks, vs))
|
||||
out = ck.sol_attn(qs, ks, vs, tau=patch.tau, scale=kwargs.get("scale"),
|
||||
sink_blocks=list(sink), sink_q=list(sink_q), topk_ratio=patch.topk_ratio,
|
||||
token_aug=patch.extra_tokens).to(q.dtype)
|
||||
patch.log_once(("sparse", tuple(qs.shape)), f"sparse {tuple(qs.shape)}, sinks {sink}/{sink_q}")
|
||||
if skip_output_reshape:
|
||||
return out.transpose(1, 2)
|
||||
return out.reshape(b, -1, heads * dim_head)
|
||||
|
||||
return override
|
||||
|
||||
|
||||
def install_override(patch: SparseAttnPatch, transformer_options):
|
||||
"""Put this patch's override on top of whatever attention override is on the
|
||||
hook. Runs at patch time and again from ON_PREPARE_STATE each step, so a node
|
||||
applied later cannot silently replace it; idempotent once it is on top."""
|
||||
current = transformer_options.get("optimized_attention_override")
|
||||
if current in patch.installed:
|
||||
return
|
||||
override = make_attention_override(patch, current)
|
||||
patch.installed.add(override)
|
||||
transformer_options["optimized_attention_override"] = override
|
||||
|
||||
|
||||
def h3_eligible(attn, x, rope_freqs, transformer_options, patch: SparseAttnPatch, block_index):
|
||||
"""Whether this H3 block call takes the sparse producer (decided before any work)."""
|
||||
n_tokens = x.shape[0]
|
||||
if rope_freqs is None or x.dtype != torch.bfloat16 or x.device.type != "cuda" or attn.head_dim != HEAD_DIM:
|
||||
return False
|
||||
reason = patch.dense_reason(transformer_options, n_tokens, block_index)
|
||||
if reason is None and not ck.sol_attn_is_available(x.device):
|
||||
reason = "no compiled sol_attn kernel for this GPU"
|
||||
if reason is not None:
|
||||
patch.log_once(("dense", n_tokens, reason), f"dense ({n_tokens} tokens): {reason}")
|
||||
return False
|
||||
if patch.vsa:
|
||||
layout = transformer_options.get("minimax_h3_layout")
|
||||
if layout is None or layout.seq_len != n_tokens:
|
||||
patch.log_once("no_layout", "no H3 layout for this call; running dense")
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def h3_sparse_attention(attn, x, rope_freqs, transformer_options, patch: SparseAttnPatch, block_index):
|
||||
"""H3 attention through the chunked producer: qkv projected in 4K-token
|
||||
slices straight into the kernel's int8 carriers, full Q/K/V never built."""
|
||||
n_tokens = x.shape[0]
|
||||
heads, head_dim = attn.heads, attn.head_dim
|
||||
qw = comfy.model_management.cast_to(attn.q_norm.weight, device=x.device)
|
||||
kw = comfy.model_management.cast_to(attn.k_norm.weight, device=x.device)
|
||||
extra, plan, gate = {}, None, None
|
||||
n, freqs = n_tokens, rope_freqs
|
||||
with comfy.model_prefetch.pause_malloc_graph():
|
||||
if patch.vsa:
|
||||
plan = patch.vsa_plan(transformer_options["minimax_h3_layout"], x.device)
|
||||
n = plan["n"]
|
||||
freqs = patch.vsa_rope_freqs(rope_freqs, plan)
|
||||
|
||||
key = (block_index, n, tuple(transformer_options.get("uuids", ()))) # statistics per conditioning branch
|
||||
pooled = patch.pooled.get(key)
|
||||
first = pooled is None
|
||||
if first:
|
||||
pooled = (
|
||||
torch.empty((heads, head_dim), dtype=torch.float32, device=x.device),
|
||||
torch.empty((heads, head_dim), dtype=torch.float32, device=x.device),
|
||||
)
|
||||
|
||||
if patch.vsa:
|
||||
sink = sink_q = (0, plan["n_prefix"])
|
||||
extra = {"tail": False, "block_len": plan["block_len"]}
|
||||
gate = attn.to_gate_compress
|
||||
if gate is not None:
|
||||
extra["coarse_gate"] = x.new_empty(n, heads * head_dim).view(1, n, heads, head_dim)
|
||||
else:
|
||||
sink, sink_q = patch.sinks(transformer_options, n_tokens)
|
||||
|
||||
def chunks():
|
||||
for i in range(0, n, PRODUCER_CHUNK):
|
||||
if plan is None:
|
||||
yield attn.qkv_proj(x[i:i + PRODUCER_CHUNK])
|
||||
continue
|
||||
idx = plan["src"][i:i + PRODUCER_CHUNK]
|
||||
xc = x[idx.clamp_min(0)] * (idx >= 0).unsqueeze(1).to(x.dtype) # pad rows zero
|
||||
if gate is not None:
|
||||
extra["coarse_gate"].view(n, heads * head_dim)[i:i + xc.shape[0]] = gate(xc)
|
||||
yield attn.qkv_proj(xc)
|
||||
|
||||
out, kmean, vscale = ck.sol_attn_chunked(
|
||||
chunks, n, heads, freqs, (qw, kw),
|
||||
kmean=None if first else pooled[0],
|
||||
vscale=None if first else pooled[1],
|
||||
tau=patch.tau, topk_ratio=patch.topk_ratio, token_aug=patch.extra_tokens,
|
||||
sink_blocks=list(sink), sink_q=list(sink_q),
|
||||
rope_eps=attn.q_norm.eps, **extra)
|
||||
pooled[0].copy_(kmean)
|
||||
pooled[1].copy_(vscale)
|
||||
patch.pooled[key] = pooled
|
||||
mode = f"VSA tiles ({n} padded rows, {sink[1]} prefix tiles)" if plan is not None else f"sinks {sink}/{sink_q}"
|
||||
patch.log_once(("producer", n), f"sparse producer path: {n_tokens} tokens, {mode}")
|
||||
out = out.view(n, heads * head_dim)
|
||||
if plan is not None:
|
||||
out = out[plan["inv"]]
|
||||
return attn.out_proj(out)
|
||||
|
||||
|
||||
def make_h3_block_patch(block, block_index, patch: SparseAttnPatch):
|
||||
"""Runs the block with its attention swapped for the sparse producer."""
|
||||
def attention(h, rope_freqs=None, transformer_options={}):
|
||||
return h3_sparse_attention(block.attn, h, rope_freqs, transformer_options, patch, block_index)
|
||||
|
||||
def block_patch(args, extra):
|
||||
if h3_eligible(block.attn, args["img"], args["rope_freqs"], args["transformer_options"], patch, block_index):
|
||||
args = {**args, "attention": attention}
|
||||
return extra["original_block"](args)
|
||||
|
||||
return block_patch
|
||||
|
||||
|
||||
def apply_block_sparse_attention(model, *, tau, topk_ratio, vsa, start_percent, end_percent, min_tokens,
|
||||
dense_blocks, sink_conditioning, extra_tokens, verbose):
|
||||
model_sampling = model.get_model_object("model_sampling")
|
||||
if vsa and extra_tokens:
|
||||
# VSA weights were trained against their sparse pattern, don't pull the attention toward dense
|
||||
logging.info("VSA: extra_tokens ignored (the trained sparse pattern is the target)")
|
||||
extra_tokens = 0
|
||||
patch = SparseAttnPatch(tau=tau, topk_ratio=topk_ratio, vsa=vsa,
|
||||
sigma_start=float(model_sampling.percent_to_sigma(start_percent)),
|
||||
sigma_end=float(model_sampling.percent_to_sigma(end_percent)),
|
||||
min_tokens=min_tokens, dense_blocks=dense_blocks,
|
||||
sink_conditioning=sink_conditioning, extra_tokens=extra_tokens, verbose=verbose)
|
||||
m = model.clone()
|
||||
install_override(patch, m.model_options["transformer_options"])
|
||||
m.add_callback_with_key(comfy.patcher_extension.CallbacksMP.ON_PREPARE_STATE, "block_sparse_attention",
|
||||
lambda model_patcher, timestep, model_options: install_override(patch, model_options["transformer_options"]))
|
||||
m.add_callback_with_key(comfy.patcher_extension.CallbacksMP.ON_CLEANUP,
|
||||
"block_sparse_attention", lambda model_patcher: patch.reset())
|
||||
|
||||
diffusion_model = model.get_model_object("diffusion_model")
|
||||
if isinstance(diffusion_model, MiniMaxH3Model):
|
||||
for i, block in enumerate(diffusion_model.blocks):
|
||||
m.set_model_patch_replace(make_h3_block_patch(block, i, patch), "dit", "double_block", i)
|
||||
if vsa and diffusion_model.blocks[0].attn.to_gate_compress is None:
|
||||
logging.warning("VSA: the model has no to_gate_compress layers; running the fine stage without the coarse branch")
|
||||
elif vsa:
|
||||
raise ValueError("VSA selection needs a MiniMax-H3 model")
|
||||
return m
|
||||
|
||||
|
||||
class BlockSparseAttention(io.ComfyNode):
|
||||
@classmethod
|
||||
def define_schema(cls):
|
||||
return io.Schema(
|
||||
node_id="BlockSparseAttention",
|
||||
display_name="Model Sparse Attention",
|
||||
category="model/patch",
|
||||
is_experimental=True,
|
||||
search_aliases=["Block Sparse Attention"],
|
||||
description="Applies block-sparse attention to eligible model attention layers, reducing compute for long sequences. "
|
||||
"The speed gain grows with sequence length since short sequences are usually faster dense. "
|
||||
"Outside the start/end_percent, dense_blocks and under min_tokens, the model uses the dense model attention backend. "
|
||||
"Use the node Model Attention Backend to select that fallback.",
|
||||
inputs=[
|
||||
io.Model.Input("model", tooltip="The model to patch."),
|
||||
io.DynamicCombo.Input("selection", display_name="method", options=[
|
||||
io.DynamicCombo.Option("sol-attn", [
|
||||
io.Float.Input("tau", default=1.3, min=0.0, max=4.0, step=0.05,
|
||||
tooltip="Threshold in score-distribution sigmas. Higher is sparser: "
|
||||
"1.0 keeps ~16% of key blocks exact, 1.5 ~7%, 2.0 ~2.7%."),
|
||||
]),
|
||||
io.DynamicCombo.Option("sla", [
|
||||
io.Float.Input("keep_percent", default=10.0, min=0.5, max=95.0, step=0.5,
|
||||
tooltip="Percent of key blocks each query block keeps exactly (sinks and "
|
||||
"the diagonal ride on top). The selection SLA-style LoRAs are "
|
||||
"distilled against; without such a LoRA higher is closer to dense."),
|
||||
]),
|
||||
io.DynamicCombo.Option("vsa", [
|
||||
io.Float.Input("keep_percent", default=10.0, min=0.5, max=95.0, step=0.5,
|
||||
tooltip="Percent of video cubes each query cube keeps; FastH3-VSA "
|
||||
"checkpoints are trained at 10. Uses the model's to_gate_compress "
|
||||
"layers for the coarse branch when present."),
|
||||
]),
|
||||
], tooltip="Method used to choose key blocks for full token-level attention. "
|
||||
"sol-attn: Sparsifying Online Attention uses a training-free adaptive threshold for each attention head and query block. "
|
||||
"sla: Sparse-Linear Attention keeps a fixed percentage of the highest-scoring key blocks; use only with model weights trained for this pattern. "
|
||||
"vsa: Video Sparse Attention (FastVideo) uses 3D video-cube tiling and a learned coarse attention branch; requires FastH3 model weights."),
|
||||
io.Float.Input("start_percent", default=0.2, min=0.0, max=1.0, step=0.01,
|
||||
tooltip="Percentage point when sparse attention begins. Before this point, attention stays dense."),
|
||||
io.Float.Input("end_percent", default=1.0, min=0.0, max=1.0, step=0.01,
|
||||
tooltip="Percentage point when sparse attention ends. After this point, attention returns to dense."),
|
||||
io.String.Input("dense_blocks", default="", advanced=True,
|
||||
tooltip="Transformer blocks that always run dense, e.g. '0, 1, 47-49'."),
|
||||
io.Int.Input("min_tokens", default=12288, min=0, max=1 << 20, step=512, advanced=True,
|
||||
tooltip="Sequences shorter than this stay dense."),
|
||||
io.Int.Input("extra_tokens", default=256, min=0, max=256, step=64, advanced=True,
|
||||
tooltip="Extra top-scoring tokens each query block attends beyond its selected "
|
||||
"blocks. Closer to dense for more attention time; 256 recommended, 0 disables. "
|
||||
"Ignored for VSA."),
|
||||
io.Combo.Input("sink_conditioning", options=["exact_kv", "exact_kv_and_rows", "off"],
|
||||
default="exact_kv_and_rows", advanced=True,
|
||||
tooltip="MiniMax-H3 only. exact_kv: every query attends the packed text/audio/"
|
||||
"reference rows exactly (~3% cost). exact_kv_and_rows: additionally runs "
|
||||
"the target-audio query rows dense (keeps generated audio intact)."),
|
||||
io.Boolean.Input("verbose", default=False, advanced=True,
|
||||
tooltip="Logs whether each attention shape used sparse attention or why it stayed dense."),
|
||||
],
|
||||
outputs=[io.Model.Output(display_name="model", tooltip="The model with block-sparse attention applied.")],
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def execute(cls, model, selection, start_percent, end_percent, dense_blocks="", min_tokens=12288,
|
||||
extra_tokens=0, sink_conditioning="exact_kv_and_rows", verbose=False) -> io.NodeOutput:
|
||||
mode = selection["selection"]
|
||||
patched_model = apply_block_sparse_attention(
|
||||
model,
|
||||
tau=selection.get("tau", 1.3),
|
||||
topk_ratio=0.0 if mode == "sol-attn" else selection["keep_percent"] / 100.0,
|
||||
vsa=mode == "vsa",
|
||||
start_percent=start_percent,
|
||||
end_percent=end_percent,
|
||||
min_tokens=min_tokens,
|
||||
dense_blocks=parse_block_list(dense_blocks),
|
||||
sink_conditioning=sink_conditioning,
|
||||
extra_tokens=extra_tokens,
|
||||
verbose=verbose,
|
||||
)
|
||||
return io.NodeOutput(patched_model)
|
||||
|
||||
|
||||
class BlockSparseAttentionExtension(ComfyExtension):
|
||||
async def get_node_list(self):
|
||||
return [BlockSparseAttention]
|
||||
|
||||
|
||||
async def comfy_entrypoint() -> BlockSparseAttentionExtension:
|
||||
return BlockSparseAttentionExtension()
|
||||
@@ -0,0 +1,6 @@
|
||||
tree e29e75597cbb495c73fdfd87d9da5e31e451e4e4
|
||||
parent 1f3d58c1dcbc20b2c5f1c3c6f79cb3dc4097530c
|
||||
author slmonker <184187107+slmonker@users.noreply.github.com> 1789423935 +0800
|
||||
committer slmonker <184187107+slmonker@users.noreply.github.com> 1789423935 +0800
|
||||
|
||||
Document public v0.1.1 release and audio-driven workflow
|
||||
@@ -0,0 +1,2 @@
|
||||
From https://github.com/slmonker/selflift-Avatar
|
||||
* branch 5df288a083fa8585a563c9c2af7ebfa0e79188c7 -> FETCH_HEAD
|
||||
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"url": "https://api.comfy.org/nodes/selflift-avatar",
|
||||
"status": 404,
|
||||
"time": "2026-11-01T02:16:10.321465+00:00",
|
||||
"basis": "graph has aux only, bounded slug derived from repo name; not authoritative registry identity if unavailable",
|
||||
"sha256": "94fd27e893abbba909fe91abbe3143a4ff94afb8ce37685a735b5ce4dce55089"
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
{"error":"","message":"Node not found"}
|
||||
@@ -0,0 +1,5 @@
|
||||
{
|
||||
"object": "5df288a083fa8585a563c9c2af7ebfa0e79188c7",
|
||||
"commit": "5df288a083fa8585a563c9c2af7ebfa0e79188c7",
|
||||
"tag": "5df288a083fa8585a563c9c2af7ebfa0e79188c7"
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
tree e29e75597cbb495c73fdfd87d9da5e31e451e4e4
|
||||
parent 1f3d58c1dcbc20b2c5f1c3c6f79cb3dc4097530c
|
||||
author slmonker <184187107+slmonker@users.noreply.github.com> 1789423935 +0800
|
||||
committer slmonker <184187107+slmonker@users.noreply.github.com> 1789423935 +0800
|
||||
|
||||
Document public v0.1.1 release and audio-driven workflow
|
||||
@@ -0,0 +1,102 @@
|
||||
{
|
||||
"sha": "e29e75597cbb495c73fdfd87d9da5e31e451e4e4",
|
||||
"truncated": false,
|
||||
"tree": [
|
||||
{
|
||||
"path": ".gitignore",
|
||||
"mode": "100644",
|
||||
"type": "blob",
|
||||
"sha": "97cd174cacefd39648c5860101eb2ffce2c220cd"
|
||||
},
|
||||
{
|
||||
"path": "CHANGELOG.md",
|
||||
"mode": "100644",
|
||||
"type": "blob",
|
||||
"sha": "6a7347c0e52cf486fd92d6ac11f4823dfaf7587b"
|
||||
},
|
||||
{
|
||||
"path": "PROVENANCE.json",
|
||||
"mode": "100644",
|
||||
"type": "blob",
|
||||
"sha": "9a6443ebeddef56b644d88153b31f1896882196b"
|
||||
},
|
||||
{
|
||||
"path": "README.md",
|
||||
"mode": "100644",
|
||||
"type": "blob",
|
||||
"sha": "24da2bc8d45235dd6fe7aa6c8da59c2d06771786"
|
||||
},
|
||||
{
|
||||
"path": "__init__.py",
|
||||
"mode": "100644",
|
||||
"type": "blob",
|
||||
"sha": "39a8c6bf593f484470ded4f9172655157d6845db"
|
||||
},
|
||||
{
|
||||
"path": "avatar_masks.py",
|
||||
"mode": "100644",
|
||||
"type": "blob",
|
||||
"sha": "67c3f49f995854ef4ab7628dd8d6606a3ad1c77a"
|
||||
},
|
||||
{
|
||||
"path": "avatar_sampling.py",
|
||||
"mode": "100644",
|
||||
"type": "blob",
|
||||
"sha": "6d1c1e0e62fb35f983325d45fe95c01dc7ae281c"
|
||||
},
|
||||
{
|
||||
"path": "diagnostics.py",
|
||||
"mode": "100644",
|
||||
"type": "blob",
|
||||
"sha": "430f540b2ae689cb6e47a6dbeaa25ccafeba44a5"
|
||||
},
|
||||
{
|
||||
"path": "docs/upstream/README.md",
|
||||
"mode": "100644",
|
||||
"type": "blob",
|
||||
"sha": "ed95e5546f042357370266d0eef36ee249ebccda"
|
||||
},
|
||||
{
|
||||
"path": "docs/upstream/README_CN.md",
|
||||
"mode": "100644",
|
||||
"type": "blob",
|
||||
"sha": "42dedbf7a84456da91e3047cf194eed68a675ac3"
|
||||
},
|
||||
{
|
||||
"path": "h3_tiling.py",
|
||||
"mode": "100644",
|
||||
"type": "blob",
|
||||
"sha": "147224b5ec292c1b8036c3d98f30e734374af8da"
|
||||
},
|
||||
{
|
||||
"path": "h3_tst.py",
|
||||
"mode": "100644",
|
||||
"type": "blob",
|
||||
"sha": "987993b2e8cbe8bf5c36434caa221c977f7dc186"
|
||||
},
|
||||
{
|
||||
"path": "h3_upscaler.py",
|
||||
"mode": "100644",
|
||||
"type": "blob",
|
||||
"sha": "37505fb8da50e8d94dff711a59c406e687a36d72"
|
||||
},
|
||||
{
|
||||
"path": "nodes.py",
|
||||
"mode": "100644",
|
||||
"type": "blob",
|
||||
"sha": "c14cf22eaf6cd95f1b714877872b5b3fc0e00d9c"
|
||||
},
|
||||
{
|
||||
"path": "selflift.py",
|
||||
"mode": "100644",
|
||||
"type": "blob",
|
||||
"sha": "556cb82cc57d32e6e7d0414be456eece7f0719be"
|
||||
},
|
||||
{
|
||||
"path": "tests/test_avatar.py",
|
||||
"mode": "100644",
|
||||
"type": "blob",
|
||||
"sha": "669cff6c808d08c1a6b9379da322d5bbff4b9e65"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
{
|
||||
"upstream": "https://github.com/facok/comfyui-SelfLift",
|
||||
"basis": "Local installed snapshot; upstream commit not recorded.",
|
||||
"upstream_sha256": {
|
||||
"__init__.py": "4c0f96b0f0006df5a559d09d44b8d521a32d7992383223310b5ba2a3f88e3e42",
|
||||
"diagnostics.py": "a4a81b2ddc6a2f8b4cf6be040c184e0b0b848513ed21a332a7169215f5f55641",
|
||||
"h3_tiling.py": "dd285f1af595c945d974de8e734b779bc4dad5bf125bc312895070bfa31a83bd",
|
||||
"h3_tst.py": "20fd3def8a1d172abb2ee2563ef5f83af28d006300f43a92d1abef244651af13",
|
||||
"h3_upscaler.py": "63d0683e04ed81dbfb2fcc6a61fa55cf742d6c04a87455fbf1f2353b1239322a",
|
||||
"nodes.py": "61c222493b07ba7075878a047387dfe8224e04ff3d88c605dd916254c6d7f14e",
|
||||
"selflift.py": "866ccdbe6dc37797cef6d36a8f823836d80e141891b38b0a457b4e9cc8f998ce"
|
||||
},
|
||||
"published_python_sha256": {
|
||||
"avatar_masks.py": "658b1a3ec989cf04428581cb425262e433327d5480ad8ce1dcfaa8fb1cbf3a6c",
|
||||
"avatar_sampling.py": "332af14067de704d4d0ee12cd61bc5e040d59068a5dcd9fb6c7ef84676a41735",
|
||||
"diagnostics.py": "a4a81b2ddc6a2f8b4cf6be040c184e0b0b848513ed21a332a7169215f5f55641",
|
||||
"h3_tiling.py": "dd285f1af595c945d974de8e734b779bc4dad5bf125bc312895070bfa31a83bd",
|
||||
"h3_tst.py": "20fd3def8a1d172abb2ee2563ef5f83af28d006300f43a92d1abef244651af13",
|
||||
"h3_upscaler.py": "63d0683e04ed81dbfb2fcc6a61fa55cf742d6c04a87455fbf1f2353b1239322a",
|
||||
"nodes.py": "5a3da7667259f2e83a7e2c15c4c8fd283d7f69a5b875a7fc07bf4f44ecd6b4e6",
|
||||
"selflift.py": "5949d89bd3fa2a9f8a64574cb13a0ae0339164270e9f8282c90373aa18ce1ebb",
|
||||
"__init__.py": "4c0f96b0f0006df5a559d09d44b8d521a32d7992383223310b5ba2a3f88e3e42",
|
||||
"tests/test_avatar.py": "9cc4eded3d302344430c2c29a129c8fd09d3599660e62d99cea493b647a03e98"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
# selflift-Avatar
|
||||
|
||||
**当前公开版本:`v0.1.1-experimental`** · [发布说明](https://github.com/slmonker/selflift-Avatar/releases/tag/v0.1.1-experimental) · [下载 ZIP](https://github.com/slmonker/selflift-Avatar/releases/download/v0.1.1-experimental/selflift-Avatar-v0.1.1-experimental.zip) · [更新记录](CHANGELOG.md)
|
||||
|
||||
用于 ComfyUI / MiniMax H3 的 **SelfLift 独立实验分支**,重点适配音视频双流遮罩和原始音频保留。与原版节点使用不同的注册 ID,可以并存。
|
||||
|
||||
> **实验版本,非官方项目。** v0.1.1 已通过 28 项 CPU 测试;维护者反馈当前工作流试用可用。尚无系统性的口型准确率、性能或多模型组合验证,不保证所有音频与角色都能准确同步。
|
||||
|
||||
## v0.1.1 的重点
|
||||
|
||||
上一版能够解析遮罩并保留输出音频,但缺少 H3 原生音频条件标签和模型输入侧的已知音频注入。本版补齐这条路径:让音频在低清与高清采样时都参与条件输入,而不只是最终恢复声音。
|
||||
|
||||
同时分离高清阶段的带噪恢复状态和干净音频约束。此修复解决的是条件传递问题,不代表上采样器、模型、提示词或其他设置对口型的影响已经消除。
|
||||
|
||||
## 安装
|
||||
|
||||
需要一套已经能够运行 MiniMax H3 的 ComfyUI,以及该工作流本来需要的模型、VAE 和可选 latent upscaler。此项目不包含模型权重,也不安装新的依赖。
|
||||
|
||||
在 `ComfyUI/custom_nodes` 下执行:
|
||||
|
||||
```bash
|
||||
git clone https://github.com/slmonker/selflift-Avatar.git
|
||||
```
|
||||
|
||||
或下载 Release 中的 ZIP,将其中的 `selflift-Avatar` 文件夹放入 `ComfyUI/custom_nodes`。之后重启 ComfyUI 后端并刷新页面。
|
||||
|
||||
## 更新
|
||||
|
||||
**Git 安装:**在本插件目录执行 `git pull --ff-only`,然后重启 ComfyUI 后端。若有自己的代码修改,请先备份或提交,不要强制覆盖。
|
||||
|
||||
**ZIP 安装:**先将旧版备份到 `custom_nodes` 之外,再把新版 `selflift-Avatar` 文件夹放回 `custom_nodes` 并重启。不要将两个 Avatar 副本同时放在 `custom_nodes` 下,以免节点重复注册。原版 SelfLift 使用不同的节点 ID,可以保留。
|
||||
|
||||
从 v0.1.0 升级时,已有 Avatar 节点的 ID 和输入接口不变,不需要重新接线;只刷新网页不足以加载新的 Python 代码。
|
||||
|
||||
## 使用
|
||||
|
||||
1. 搜索 `selflift-Avatar`,添加 **selflift-Avatar Sampler (MiniMax H3)**。
|
||||
2. 把原 SelfLift 采样器的输入和输出改接到新节点。原节点和工作流不会自动替换。
|
||||
3. 使用标准 **Euler**;带 `noise_mask` 时设置 **`highres_tiling=false`**。
|
||||
4. 建议复制工作流,以固定 seed、短片段、相同其他参数进行对比。
|
||||
5. 如果采用外部 H3 latent upscaler,可保留 `rho=0`;`upscaler_model=none` 时,H3 节点仍要求 `rho>0`。
|
||||
|
||||
| 注册 ID | 显示名称 |
|
||||
| --- | --- |
|
||||
| `SelfLiftAvatarH3Sampler` | selflift-Avatar Sampler (MiniMax H3) |
|
||||
| `SelfLiftAvatarImageSampler` | selflift-Avatar Sampler (Image) |
|
||||
| `SelfLiftAvatarH3TST` | selflift-Avatar H3 TST |
|
||||
|
||||
音频遮罩仍通过 latent 字典的 `noise_mask` 提供,没有新增单独的 mask 输入端口。
|
||||
|
||||
## 使用输入音频驱动角色
|
||||
|
||||
典型连接方式如下(节点显示名称可能随 ComfyUI 版本变化):
|
||||
|
||||
```text
|
||||
输入音频 → 裁剪到目标片段 → H3 音频 VAE 编码
|
||||
↓
|
||||
SolidMask(value=0) → SetLatentNoiseMask
|
||||
↓
|
||||
H3 视频 latent ──────────→ 合并音视频 latent
|
||||
↓
|
||||
selflift-Avatar Sampler (MiniMax H3)
|
||||
```
|
||||
|
||||
- 音频 mask 为 0 时,保留输入音频;为 1 时,允许生成音频。视频和音频可以使用不同遮罩。
|
||||
- 音频长度、视频帧数和最终输出 FPS 应对应同一目标片段。编码音频与最终合成的音频也应来自同一次裁剪。
|
||||
- 若最终合成节点直接使用原音频,听到正确声音不等于采样时音频条件正确;判断口型需要看实际生成的视频。
|
||||
- 与 H3 条件节点配套连接模型、正负条件及视频 VAE;本插件不是独立的后期对口型工具。
|
||||
|
||||
## 遮罩支持
|
||||
|
||||
- 普通视频/图片 Tensor:BHW、BCHW、BCTHW;通道为 1 或实际 latent 通道数。
|
||||
- H3 `NestedTensor(video_mask, audio_mask)`:分别解析音视频,保留多通道权重。
|
||||
- 严格匹配音视频展平尺寸的 `[B,1,N]` 遮罩。
|
||||
- 音频 T、BT、BST、BCST 布局;维度为 1 可广播。
|
||||
- 视频空间尺寸不匹配时进行双线性缩放;不猜测时间轴、不对音频时间轴自动重采样。
|
||||
- 普通 Tensor 默认只约束视频,缺省音频遮罩按全 1 处理。
|
||||
|
||||
**0=保留原内容,1=生成,0~1=软约束。** 必须有对应的已初始化 latent 才能保留实际内容。
|
||||
|
||||
### SolidMask 加到音频的兼容处理
|
||||
|
||||
`SolidMask → SetLatentNoiseMask → 合并音视频 latent` 可能给音频附加图像尺寸的恒定遮罩,例如 `[1,1,928,1664]` 全零。
|
||||
|
||||
本版本确认每个批次/通道在空间上严格恒定后,压缩为 `[B,C,1,1]` 广播到音频 latent。全零保留整段输入音频,全一生成音频,恒定软权重也不变。非恒定图像图案不擅自解释为音频时间遮罩。
|
||||
|
||||
## 采样约束与修复
|
||||
|
||||
- 低清和高清阶段分别应用对应视频 mask;音频 mask 不随空间分辨率缩放。
|
||||
- v0.1.1 在条件构建前通过 ModelPatcher 的 OUTER_SAMPLE wrapper 传入正确打包的 mask,让 H3 生成 `audio_denoise_mask` 条件标签。
|
||||
- 使用原生 `KSamplerX0Inpaint` 和 H3 `scale_latent_inpaint` 在模型输入侧注入已知音频,不再只在预测后恢复音频。
|
||||
- 高清阶段把带噪 resume 状态与干净 inpaint anchor 分开,保留原始采样状态,避免将残余噪声当成原音频。
|
||||
- 约束原内容时调用实际采样模型的 `process_latent_in`,包含 H3 的音频尺度转换。
|
||||
- 返回前仅对 `mask==0` 的位置恢复原始 latent,不重复混合软遮罩。
|
||||
- 修复纯像素 anchor 模式(`rho=w_min=w_max=1`)带 mask 时的 None 运算问题。
|
||||
- 报错包含实际 mask 类型、各流形状和 latent 形状。
|
||||
|
||||
## 口型效果排查
|
||||
|
||||
音频保留不等于口型质量保证。外部 latent upscaler 包含时间卷积且不直接接收目标音频,放大过程和剩余高清采样步数可能影响嘴部细节;当前没有量化归因。
|
||||
|
||||
固定模型、音频片段、seed、提示词、帧数及输出 FPS,先与原生全分辨率采样比较,再分别测试更多高清采样步数或不使用外部 upscaler 的像素 anchor 路径,避免同时更改多个参数。不同路径随机数消耗可能不同,需多个 seed 复核。
|
||||
|
||||
## 已知限制
|
||||
|
||||
- 带 mask 时不支持 `highres_tiling`。
|
||||
- 只应用静态输入遮罩,不执行上游 `denoise_mask_function` 的动态调度;检测到时会警告。
|
||||
- `model_hires` 必须使用兼容架构、latent 格式和采样尺度设置;跨架构/尺度切换未验证。
|
||||
- 保留的是输出 latent 区域,不承诺 VAE 解码后像素或波形逐点相同。
|
||||
- TST、分块和外部 upscaler 继承上游的实验限制;没有重新验证这些功能的所有组合。
|
||||
|
||||
## 测试
|
||||
|
||||
从安装在 ComfyUI 下的插件目录运行,使用 ComfyUI 对应的 Python:
|
||||
|
||||
```bash
|
||||
python tests/test_avatar.py
|
||||
```
|
||||
|
||||
28 项 CPU 测试包括音视频打包、真实 H3 音频尺度转换、全零/全一遮罩、前段保留、软遮罩、多通道、恒定图像尺寸音频遮罩和两阶段流程。
|
||||
|
||||
两阶段测试使用真实 Euler、原生 inpaint 调用链、合成 denoiser 与模拟 VAE lift。新增检查确认低清/高清阶段均产生音频遮罩条件,且模型输入在撤销音频 carry 变换后与被保留的音频一致。测试不加载大模型权重,也不衡量实际口型质量。
|
||||
|
||||
## 来源与许可说明
|
||||
|
||||
基于 [facok/comfyui-SelfLift](https://github.com/facok/comfyui-SelfLift) 的本地副本修改,保留[上游说明](docs/upstream/README.md)和[中文说明](docs/upstream/README_CN.md)。来源哈希见 `PROVENANCE.json`。
|
||||
|
||||
上游包含 SelfLift、TST 和可选 MiniMax H3 latent upscaler 的参考与致谢;这些研究和权重不由本项目声明所有权。本次上传检查时,上游未声明许可证;本项目未擅自新增开源许可证,不能仅凭本仓库存在推断获得原代码或模型的再分发授权。
|
||||
|
||||
## 回退
|
||||
|
||||
[v0.1.0-experimental](https://github.com/slmonker/selflift-Avatar/releases/tag/v0.1.0-experimental) 保留供对比和回退,但不包含本版原生音频条件修复。也可在工作流中换回原版 SelfLift 节点。
|
||||
|
||||
卸载时关闭 ComfyUI,将本文件夹移出 `custom_nodes`。本项目不会修改原版插件或 ComfyUI 核心文件。
|
||||
@@ -0,0 +1,3 @@
|
||||
from .nodes import NODE_CLASS_MAPPINGS, NODE_DISPLAY_NAME_MAPPINGS
|
||||
|
||||
__all__ = ["NODE_CLASS_MAPPINGS", "NODE_DISPLAY_NAME_MAPPINGS"]
|
||||
@@ -0,0 +1,108 @@
|
||||
"""Static video/audio masks for the selflift-Avatar experiment."""
|
||||
|
||||
import logging
|
||||
import math
|
||||
|
||||
import torch
|
||||
import torch.nn.functional as F
|
||||
|
||||
|
||||
def _description(value):
|
||||
if getattr(value, "is_nested", False):
|
||||
return f"{type(value).__name__}({[tuple(s.shape) for s in value.unbind()]})"
|
||||
return f"{type(value).__name__}(shape={getattr(value, 'shape', None)})"
|
||||
|
||||
|
||||
def resize_spatial(mask, size):
|
||||
if tuple(mask.shape[-2:]) == tuple(size):
|
||||
return mask
|
||||
lead = mask.shape[:-2]
|
||||
return F.interpolate(
|
||||
mask.reshape(-1, 1, *mask.shape[-2:]).float(),
|
||||
size=size, mode="bilinear", align_corners=False,
|
||||
).reshape(*lead, *size)
|
||||
|
||||
|
||||
def _normalize_video(mask, shape):
|
||||
video = len(shape) == 5
|
||||
if mask.ndim == 3: # BHW
|
||||
mask = mask[:, None]
|
||||
if video and mask.ndim == 4: # BCHW, constant over time
|
||||
mask = mask[:, :, None]
|
||||
if mask.ndim != len(shape):
|
||||
raise ValueError("video mask must be BHW, BCHW or BCTHW (C=1 or latent channels)")
|
||||
for axis in range(len(shape) - 2):
|
||||
if mask.shape[axis] not in (1, shape[axis]):
|
||||
raise ValueError(f"video mask axis {axis} has size {mask.shape[axis]}, expected 1 or {shape[axis]}")
|
||||
if mask.shape[-2] in (1, shape[-2]) and mask.shape[-1] in (1, shape[-1]):
|
||||
return mask.expand(shape[0], *mask.shape[1:-2], *shape[-2:])
|
||||
return resize_spatial(mask, shape[-2:]).expand(shape[0], *mask.shape[1:-2], *shape[-2:])
|
||||
|
||||
|
||||
def _normalize_audio(mask, shape):
|
||||
if len(shape) != 4:
|
||||
raise ValueError(f"audio latent must be BCST, received {shape}")
|
||||
if mask.ndim == 1: # T
|
||||
mask = mask[None, None, None]
|
||||
elif mask.ndim == 2: # BT
|
||||
mask = mask[:, None, None]
|
||||
elif mask.ndim == 3: # BST
|
||||
mask = mask[:, None]
|
||||
if mask.ndim != 4:
|
||||
raise ValueError("audio mask must be T, BT, BST or BCST")
|
||||
if (mask.shape[0] in (1, shape[0]) and mask.shape[1] in (1, shape[1])
|
||||
and mask.shape[2] not in (1, shape[2])):
|
||||
# SetLatentNoiseMask stores SolidMask at image resolution, even for audio.
|
||||
# A spatial constant can broadcast without inventing a time mapping.
|
||||
constant = mask[:, :, :1, :1]
|
||||
if not torch.equal(mask, constant.expand_as(mask)):
|
||||
raise ValueError("audio mask has a non-uniform image grid; use a constant SolidMask for whole-audio control or a BCST audio mask")
|
||||
original_shape = tuple(mask.shape)
|
||||
mask = constant.clone()
|
||||
logging.info("selflift-Avatar: constant audio mask %s -> %s (0=keep, 1=generate)",
|
||||
original_shape, tuple(mask.shape))
|
||||
for axis, target in enumerate(shape):
|
||||
if mask.shape[axis] not in (1, target):
|
||||
raise ValueError(f"audio mask axis {axis} has size {mask.shape[axis]}, expected 1 or {target}; audio is not time-resampled")
|
||||
return mask.expand(shape[0], *mask.shape[1:])
|
||||
|
||||
|
||||
def normalize_masks(mask, streams):
|
||||
if mask is None:
|
||||
return None
|
||||
description = _description(mask)
|
||||
shapes = [tuple(s.shape) for s in streams]
|
||||
if getattr(mask, "is_nested", False):
|
||||
masks = list(mask.unbind())
|
||||
if len(masks) != len(streams):
|
||||
raise ValueError(f"selflift-Avatar: mask stream count does not match {shapes}; received {description}")
|
||||
elif isinstance(mask, torch.Tensor):
|
||||
sizes = [math.prod(s[1:]) for s in shapes]
|
||||
if len(streams) > 1 and mask.ndim == 3 and mask.shape[1:] == (1, sum(sizes)):
|
||||
masks = [part.reshape(mask.shape[0], *shape[1:])
|
||||
for part, shape in zip(mask.split(sizes, dim=-1), shapes)]
|
||||
else:
|
||||
masks = [mask] + [None] * (len(streams) - 1)
|
||||
else:
|
||||
raise ValueError(f"selflift-Avatar: unsupported noise_mask {description}")
|
||||
normalized = []
|
||||
for index, (m, stream) in enumerate(zip(masks, streams)):
|
||||
if m is None:
|
||||
normalized.append(stream.new_ones((1,) * stream.ndim, dtype=torch.float32))
|
||||
continue
|
||||
if not isinstance(m, torch.Tensor) or m.is_nested or m.numel() == 0:
|
||||
raise ValueError(f"selflift-Avatar: mask stream {index} must be a nonempty Tensor; received {description}")
|
||||
if not torch.isfinite(m).all():
|
||||
raise ValueError(f"selflift-Avatar: mask stream {index} contains NaN/Inf; received {description}")
|
||||
m = m.float().clamp(0.0, 1.0)
|
||||
normalizer = _normalize_video if index == 0 else _normalize_audio
|
||||
try:
|
||||
normalized.append(normalizer(m, tuple(stream.shape)))
|
||||
except ValueError as exc:
|
||||
raise ValueError(f"selflift-Avatar: {exc}; received {description}; latent shapes={shapes}") from exc
|
||||
return normalized
|
||||
|
||||
|
||||
def restore_kept(outputs, anchors, masks):
|
||||
return [torch.where(mask.to(out.device) == 0, anchor.to(out), out)
|
||||
for out, anchor, mask in zip(outputs, anchors, masks)]
|
||||
@@ -0,0 +1,44 @@
|
||||
"""Use ComfyUI's native mask conditioning with a separate clean inpaint anchor."""
|
||||
|
||||
import logging
|
||||
|
||||
import comfy.patcher_extension
|
||||
import comfy.samplers
|
||||
import comfy.utils
|
||||
|
||||
|
||||
def anchored_sampler(sampler, anchor):
|
||||
def sample_with_anchor(model_k, x, sigmas, **kwargs):
|
||||
# KSAMPLER already built x from the (possibly noisy) resume latent.
|
||||
# Only the native inpaint anchor is replaced, not that initial state.
|
||||
model_k.latent_image = model_k.inner_model.inner_model.process_latent_in(anchor.to(x))
|
||||
return sampler.sampler_function(model_k, x, sigmas, **kwargs)
|
||||
|
||||
return comfy.samplers.KSAMPLER(sample_with_anchor, sampler.extra_options.copy(), sampler.inpaint_options.copy())
|
||||
|
||||
|
||||
def native_mask_model(base, anchors, masks, nested):
|
||||
if masks is None:
|
||||
return base
|
||||
if nested:
|
||||
anchor, _ = comfy.utils.pack_latents(anchors)
|
||||
mask, _ = comfy.utils.pack_latents([m.to(a.device).expand_as(a) for m, a in zip(masks, anchors)])
|
||||
else:
|
||||
anchor, mask = anchors[0], masks[0].expand_as(anchors[0])
|
||||
patched = base.clone()
|
||||
if "denoise_mask_function" in patched.model_options:
|
||||
patched.model_options.pop("denoise_mask_function")
|
||||
logging.warning("selflift-Avatar: uses static input masks; dynamic denoise_mask_function is not applied")
|
||||
|
||||
def inject_mask(executor, noise, latent_image, sampler, sigmas, denoise_mask=None,
|
||||
callback=None, disable_pbar=False, seed=None, latent_shapes=None):
|
||||
# Inject before inner_sample/process_conds, after generic mask reshaping.
|
||||
# This preserves audio channels and supplies H3 audio_denoise_mask labels.
|
||||
device = executor.class_obj.model_patcher.load_device
|
||||
return executor(noise, latent_image, anchored_sampler(sampler, anchor), sigmas,
|
||||
mask.to(device=device), callback, disable_pbar, seed,
|
||||
latent_shapes=latent_shapes)
|
||||
|
||||
patched.add_wrapper_with_key(comfy.patcher_extension.WrappersMP.OUTER_SAMPLE,
|
||||
"selflift_avatar_static_mask", inject_mask)
|
||||
return patched
|
||||
@@ -0,0 +1,32 @@
|
||||
"""Optional memory snapshots without resetting shared allocator statistics."""
|
||||
|
||||
import logging
|
||||
import os
|
||||
|
||||
import psutil
|
||||
import torch
|
||||
|
||||
|
||||
def log_memory(label, device):
|
||||
if os.environ.get("SELFLIFT_MEMORY_LOG", "0") != "1":
|
||||
return
|
||||
device = torch.device(device)
|
||||
fields = []
|
||||
try:
|
||||
fields.append(f"process_rss={psutil.Process().memory_info().rss / 2**20:.2f} MiB")
|
||||
fields.append(f"system_available={psutil.virtual_memory().available / 2**20:.2f} MiB")
|
||||
except (psutil.Error, OSError) as error:
|
||||
fields.append(f"host_memory_unavailable={error}")
|
||||
if device.type == "cuda" and torch.cuda.is_initialized():
|
||||
try:
|
||||
free, total = torch.cuda.mem_get_info(device)
|
||||
fields.extend([
|
||||
f"allocated={torch.cuda.memory_allocated(device) / 2**20:.2f} MiB",
|
||||
f"reserved={torch.cuda.memory_reserved(device) / 2**20:.2f} MiB",
|
||||
f"process_peak_allocated={torch.cuda.max_memory_allocated(device) / 2**20:.2f} MiB",
|
||||
f"device_used={((total - free) / 2**20):.2f} MiB",
|
||||
f"device_free={free / 2**20:.2f} MiB",
|
||||
])
|
||||
except RuntimeError as error:
|
||||
fields.append(f"cuda_memory_unavailable={error}")
|
||||
logging.info("[SelfLift memory] %s device=%s; %s", label, device, "; ".join(fields))
|
||||
@@ -0,0 +1,218 @@
|
||||
"""Experimental spatial tiling of H3 high-resolution model evaluations."""
|
||||
|
||||
from functools import partial
|
||||
import inspect
|
||||
import logging
|
||||
import math
|
||||
|
||||
import torch
|
||||
|
||||
import comfy.ldm.common_dit
|
||||
from comfy.ldm.minimax.model import PackedLayout
|
||||
import comfy.model_base
|
||||
import comfy.patcher_extension
|
||||
import comfy.sampler_helpers
|
||||
|
||||
|
||||
def _regions(length, tile_count=2):
|
||||
patches = (length + 1) // 2
|
||||
tile_count = max(1, min(tile_count, max(1, patches // 2)))
|
||||
if patches < 4 or tile_count <= 1:
|
||||
return [(0, length)]
|
||||
overlap = min(4, max(1, patches // 8))
|
||||
regions = []
|
||||
for index in range(tile_count):
|
||||
start = max(0, index * patches // tile_count - overlap) * 2
|
||||
end = min(patches, (index + 1) * patches // tile_count + overlap) * 2
|
||||
end = min(end, length)
|
||||
regions.append((start, end))
|
||||
regions[-1] = (regions[-1][0], length)
|
||||
return regions
|
||||
|
||||
|
||||
def _packed_layout(signature, payload):
|
||||
options = {"keyframes": payload.get("keyframes"), "refs": payload.get("refs")}
|
||||
if "frame_count" in inspect.signature(PackedLayout).parameters:
|
||||
options["frame_count"] = payload.get("frame_count")
|
||||
return PackedLayout(*signature, **options)
|
||||
|
||||
|
||||
def _tile_payload(payload, context, video, audio, axis, start, end):
|
||||
height, width = video.shape[-2:]
|
||||
padded_height, padded_width = (height + 1) // 2 * 2, (width + 1) // 2 * 2
|
||||
full_layout = payload.get("layout")
|
||||
signature = (context.shape[1], video.shape[2], padded_height, padded_width, audio.shape[-1])
|
||||
if full_layout is None or full_layout.signature != signature:
|
||||
full_layout = _packed_layout(signature, payload)
|
||||
tiled = payload.copy()
|
||||
if payload.get("keyframes"):
|
||||
keyframes = []
|
||||
for keyframe in payload["keyframes"]:
|
||||
latent = keyframe["latent"]
|
||||
if latent.shape[-2:] != (height, width):
|
||||
raise ValueError("SelfLift: tiled H3 keyframes must match the target latent height and width")
|
||||
region = latent.narrow(axis, start, end - start)
|
||||
keyframes.append({**keyframe, "latent": comfy.ldm.common_dit.pad_to_patch_size(
|
||||
region, (1, 2, 2)).contiguous()})
|
||||
tiled["keyframes"] = keyframes
|
||||
if not payload.get("refs"):
|
||||
tiled["cond_video_latents"] = [keyframe["latent"] for keyframe in keyframes]
|
||||
tile_height = end - start if axis == 3 else height
|
||||
tile_width = end - start if axis == 4 else width
|
||||
layout = _packed_layout((context.shape[1], video.shape[2], (tile_height + 1) // 2 * 2,
|
||||
(tile_width + 1) // 2 * 2, audio.shape[-1]), tiled)
|
||||
for (source_start, source_end, kind), (target_start, target_end, _) in zip(full_layout.segments, layout.segments):
|
||||
positions = full_layout.position_ids[source_start:source_end]
|
||||
if kind in ("cond", "video"):
|
||||
positions = positions.reshape(-1, padded_height // 2, padded_width // 2, 3)
|
||||
positions = positions.narrow(axis - 2, start // 2, (end - start + 1) // 2).reshape(-1, 3)
|
||||
layout.position_ids[target_start:target_end].copy_(positions)
|
||||
tiled["layout"] = layout
|
||||
return tiled
|
||||
|
||||
|
||||
def _tiled_forward(executor, streams, timestep, context, transformer_options, minimax_payload=None,
|
||||
n_tiles=2, plan=None, **kwargs):
|
||||
video, audio = streams
|
||||
axis = 3 if (video.shape[3] + 1) // 2 >= (video.shape[4] + 1) // 2 else 4
|
||||
length = video.shape[axis]
|
||||
regions = _regions(length, plan['tiles'] if plan is not None else n_tiles)
|
||||
if len(regions) == 1:
|
||||
return executor(streams, timestep, context, transformer_options, minimax_payload=minimax_payload, **kwargs)
|
||||
if kwargs.get("control") is not None:
|
||||
raise ValueError("SelfLift: high-resolution H3 tiling does not support ControlNet")
|
||||
# Keep the stitched accumulator on CPU so previous tiles do not remain on
|
||||
# the accelerator while the next tile is evaluated.
|
||||
video_output = torch.zeros(video.shape, dtype=torch.float32, device="cpu")
|
||||
audio_output = None
|
||||
weights = torch.zeros(length, dtype=torch.float32, device="cpu")
|
||||
for index, (start, end) in enumerate(regions):
|
||||
tile = video.narrow(axis, start, end - start).contiguous()
|
||||
payload = _tile_payload(minimax_payload or {}, context, video, audio, axis, start, end)
|
||||
predicted_video, predicted_audio = executor(
|
||||
[tile, audio], timestep, context, transformer_options.copy(), minimax_payload=payload, **kwargs)
|
||||
window = torch.ones(end - start, device=video.device, dtype=torch.float32)
|
||||
if index > 0:
|
||||
overlap = min(end, regions[index - 1][1]) - start
|
||||
window[:overlap] *= (torch.arange(overlap, device=video.device, dtype=torch.float32) + 0.5) / overlap
|
||||
if index + 1 < len(regions):
|
||||
overlap = end - regions[index + 1][0]
|
||||
window[-overlap:] *= 1.0 - (torch.arange(overlap, device=video.device, dtype=torch.float32) + 0.5) / overlap
|
||||
predicted_video = predicted_video.float().cpu()
|
||||
window = window.cpu()
|
||||
weights[start:end].add_(window)
|
||||
window_shape = [1] * video.ndim
|
||||
window_shape[axis] = end - start
|
||||
video_output.narrow(axis, start, end - start).addcmul_(predicted_video.float(), window.view(window_shape))
|
||||
if audio_output is None:
|
||||
audio_output = predicted_audio.float().clone()
|
||||
del tile, payload, predicted_video, predicted_audio, window
|
||||
window_shape[axis] = length
|
||||
video_output.div_(weights.view(window_shape))
|
||||
return [video_output.to(device=video.device, dtype=video.dtype), audio_output.to(audio.dtype)]
|
||||
|
||||
|
||||
def _condition_elements(condition, tile_height, tile_width, channels):
|
||||
text = condition.get("cross_attn")
|
||||
elements = text.shape[-2] * channels * 4 if text is not None else 0
|
||||
for keyframe in condition.get("minimax_keyframes") or []:
|
||||
shape = keyframe["latent"].shape
|
||||
elements += shape[1] * shape[2] * tile_height * tile_width
|
||||
for reference in condition.get("minimax_refs") or []:
|
||||
latent = reference.get("latent")
|
||||
if latent is not None:
|
||||
shape = latent.shape
|
||||
elements += shape[1] * shape[2] * ((shape[3] + 1) // 2 * 2) * ((shape[4] + 1) // 2 * 2)
|
||||
audio = reference.get("audio_latent")
|
||||
if audio is not None:
|
||||
elements += math.prod(audio.shape[1:])
|
||||
return elements
|
||||
|
||||
|
||||
def _budget(model, noise_shape, conds, latent_shapes, regions, axis):
|
||||
video_shape, audio_shape = latent_shapes
|
||||
full_elements = math.prod(video_shape[1:]) + math.prod(audio_shape[1:])
|
||||
tile_shape = list(video_shape)
|
||||
tile_shape[axis] = max(end - start for start, end in regions)
|
||||
tile_shape[3] = (tile_shape[3] + 1) // 2 * 2
|
||||
tile_shape[4] = (tile_shape[4] + 1) // 2 * 2
|
||||
tile_elements = math.prod(tile_shape[1:]) + math.prod(audio_shape[1:])
|
||||
condition_elements = max((_condition_elements(condition, tile_shape[3], tile_shape[4], video_shape[1])
|
||||
for group in conds.values() for condition in (group or [])), default=0)
|
||||
buffer_bytes = full_elements * 4 * 8
|
||||
bytes_per_element = model.model.memory_required((1, 1, 1))
|
||||
budget_elements = tile_elements + condition_elements + math.ceil(buffer_bytes / bytes_per_element)
|
||||
budget_shape = (noise_shape[0], 1, budget_elements)
|
||||
preferred, minimum = comfy.sampler_helpers.estimate_memory(model, budget_shape, conds)
|
||||
return budget_shape, tuple(tile_shape), buffer_bytes, preferred, minimum
|
||||
|
||||
|
||||
def _prepare_tiled_sampling(executor, model, noise_shape, conds, model_options=None,
|
||||
force_full_load=False, force_offload=False, *, latent_shapes, plan=None):
|
||||
video_shape, audio_shape = latent_shapes
|
||||
axis = 3 if (video_shape[3] + 1) // 2 >= (video_shape[4] + 1) // 2 else 4
|
||||
full_elements = math.prod(video_shape[1:]) + math.prod(audio_shape[1:])
|
||||
if tuple(noise_shape) != (video_shape[0], 1, full_elements):
|
||||
raise ValueError("SelfLift: tiled memory planning received a different latent shape than the sampling input")
|
||||
count = 2
|
||||
if plan is not None:
|
||||
available = _available_workspace(model)
|
||||
for count in range(1, 9):
|
||||
regions = _regions(video_shape[axis], count)
|
||||
_, _, _, _, minimum = _budget(model, noise_shape, conds, latent_shapes, regions, axis)
|
||||
if minimum <= available:
|
||||
break
|
||||
count = len(regions)
|
||||
plan['tiles'] = count
|
||||
logging.info("[SelfLift tiling plan] axis=%s tiles=%d target=%.2f MiB estimate_fits=%s",
|
||||
'H' if axis == 3 else 'W', plan['tiles'], available / 2**20, minimum <= available)
|
||||
regions = _regions(video_shape[axis], count)
|
||||
if len(regions) == 1 or force_offload:
|
||||
return executor(model, noise_shape, conds, model_options=model_options,
|
||||
force_full_load=force_full_load, force_offload=force_offload)
|
||||
budget_shape, tile_shape, buffer_bytes, preferred, minimum = _budget(
|
||||
model, noise_shape, conds, latent_shapes, regions, axis)
|
||||
logging.info("[SelfLift tiling memory] largest_tile=%s full_audio=%s full_state_buffers=%.2f MiB "
|
||||
"minimum=%.2f MiB preferred=%.2f MiB (ComfyUI estimates; additional models and reserves excluded)",
|
||||
tuple(tile_shape), audio_shape, buffer_bytes * noise_shape[0] / 2**20,
|
||||
minimum / 2**20, preferred / 2**20)
|
||||
return executor(model, budget_shape, conds, model_options=model_options,
|
||||
force_full_load=force_full_load, force_offload=force_offload)
|
||||
|
||||
|
||||
def _available_workspace(model):
|
||||
manager = comfy.model_management
|
||||
free = manager.get_free_memory(model.load_device)
|
||||
reclaimable = 0
|
||||
seen = set()
|
||||
for loaded in manager.loaded_models():
|
||||
patcher = loaded if callable(getattr(loaded, "loaded_size", None)) else loaded.model
|
||||
load_device = getattr(patcher, "load_device", None)
|
||||
identity = id(patcher.model)
|
||||
if load_device == model.load_device and identity not in seen:
|
||||
seen.add(identity)
|
||||
size_fn = getattr(patcher, "loaded_size", None)
|
||||
if callable(size_fn):
|
||||
reclaimable += size_fn()
|
||||
pool = min(manager.get_total_memory(model.load_device), free + reclaimable)
|
||||
weights = min(model.model_size(), pool * manager.MIN_WEIGHT_MEMORY_RATIO)
|
||||
available = max(0, pool - weights - manager.minimum_inference_memory())
|
||||
logging.info("[SelfLift tiling capacity] free=%.2f MiB reclaimable_weights=%.2f MiB "
|
||||
"weight_allowance=%.2f MiB workspace=%.2f MiB",
|
||||
free / 2**20, reclaimable / 2**20, weights / 2**20, available / 2**20)
|
||||
return available
|
||||
|
||||
|
||||
def tiled_model(model, latent_shapes):
|
||||
if not isinstance(model.model, comfy.model_base.MiniMaxH3):
|
||||
raise ValueError("SelfLift: high-resolution tiling requires a MiniMax H3 model")
|
||||
if len(latent_shapes) != 2 or len(latent_shapes[0]) != 5 or len(latent_shapes[1]) != 4:
|
||||
raise ValueError("SelfLift: high-resolution tiling requires H3 video and audio latent streams")
|
||||
plan = {}
|
||||
patched = model.clone()
|
||||
patched.add_wrapper_with_key(comfy.patcher_extension.WrappersMP.DIFFUSION_MODEL,
|
||||
"selflift_high_resolution_tiling", partial(_tiled_forward, plan=plan))
|
||||
patched.add_wrapper_with_key(comfy.patcher_extension.WrappersMP.PREPARE_SAMPLING,
|
||||
"selflift_high_resolution_tiling",
|
||||
partial(_prepare_tiled_sampling, latent_shapes=tuple(tuple(shape) for shape in latent_shapes), plan=plan))
|
||||
return patched
|
||||
@@ -0,0 +1,224 @@
|
||||
"""Temporal State Transport (TST) correction for MiniMax H3 joint attention.
|
||||
|
||||
Inference-time port of TST (arXiv:2609.08505) to H3's single-stream packed
|
||||
attention. H3 has no separate temporal attention, so per-head frame-level
|
||||
transport operators A (F x F) are built from spatial mean-pooled post-RoPE
|
||||
queries/keys of the video segment, which is always the last packed segment.
|
||||
Spectral Tension T = H_row - H_vN diagnoses fragmented (T<0) versus over-mixed
|
||||
(T>0) temporal states; the homeostatic query temperature gamma =
|
||||
exp(tau_eff * T) rescales only video-row queries. tau_eff follows the paper's
|
||||
cosine schedules: stronger in deeper layers and earlier denoising steps.
|
||||
|
||||
Anchored to ComfyUI sources:
|
||||
- video segment last: comfy/ldm/minimax/model.py PackedLayout ("target audio
|
||||
then target video, always the last two segments")
|
||||
- injection point: comfy/ldm/modules/attention.py wrap_attn, which checks
|
||||
transformer_options["optimized_attention_override"] in every backend (and
|
||||
take()s AttentionTensorContainers before calling the override)
|
||||
- per-forward video shape: WrappersMP.DIFFUSION_MODEL wraps MiniMaxH3Model._forward
|
||||
|
||||
Known limitation: not compatible with SelfLift highres_tiling. Wrappers run in
|
||||
registration order, so the TST wrapper sits outside the tiling wrapper and only
|
||||
sees the full-resolution shape; tile attention calls fail the length guard and
|
||||
TST skips with a warning instead of mislocating the tile's video rows.
|
||||
"""
|
||||
|
||||
import logging
|
||||
import math
|
||||
import os
|
||||
import time
|
||||
from functools import partial
|
||||
|
||||
import torch
|
||||
|
||||
import comfy.patcher_extension
|
||||
from comfy.ldm.modules.attention import AttentionTensorContainer
|
||||
|
||||
|
||||
def _unwrap(tensor):
|
||||
# H3 wraps q/k/v in AttentionTensorContainer, but wrap_attn take()s them
|
||||
# before calling this override (it has no container_function attribute),
|
||||
# so plain tensors are the common case here.
|
||||
return tensor.peek() if isinstance(tensor, AttentionTensorContainer) else tensor
|
||||
|
||||
|
||||
def _spectral_tension(q, k, v0, frames, rows_per_frame, eps=1e-8):
|
||||
"""Per-head signed Spectral Tension of the frame-level transport operator.
|
||||
|
||||
q, k: [1, heads, S, head_dim] post-norm post-RoPE; video rows start at v0.
|
||||
Returns [heads] fp32; T>0 over-mixing, T<0 fragmented (paper Eqs. 1-3).
|
||||
"""
|
||||
heads = q.shape[1]
|
||||
head_dim = q.shape[-1]
|
||||
qv = q[0, :, v0:].reshape(heads, frames, rows_per_frame, head_dim).mean(dim=2).float()
|
||||
kv = k[0, :, v0:].reshape(heads, frames, rows_per_frame, head_dim).mean(dim=2).float()
|
||||
a = (qv @ kv.transpose(-2, -1) * head_dim**-0.5).softmax(dim=-1).clamp(min=eps)
|
||||
log_f = math.log(frames)
|
||||
h_row = -(a * a.log()).sum(dim=-1).mean(dim=-1) / log_f
|
||||
gram = a @ a.transpose(-2, -1)
|
||||
trace = gram.diagonal(dim1=-2, dim2=-1).sum(dim=-1).clamp(min=eps)
|
||||
eig = torch.linalg.eigvalsh(gram / trace[:, None, None]).clamp(min=eps)
|
||||
eig = eig / eig.sum(dim=-1, keepdim=True).clamp(min=eps)
|
||||
h_vn = -(eig * eig.log()).sum(dim=-1) / log_f
|
||||
return h_row - h_vn
|
||||
|
||||
|
||||
def _exact_tension(q, k, v0, frames, rows_per_frame, eps=1e-8, chunk=64):
|
||||
"""Exact frame-mass operator tension, for calibrating the pooled prototype.
|
||||
|
||||
Per query token: full-row softmax over the whole packed sequence, video-key
|
||||
mass summed per frame, averaged over the frame's query rows, rows
|
||||
renormalized over frames (the true joint-attention transport operator).
|
||||
q, k: [1, heads, S, head_dim]; returns [heads] fp32 like _spectral_tension.
|
||||
"""
|
||||
heads = q.shape[1]
|
||||
head_dim = q.shape[-1]
|
||||
qv = q[0, :, v0:]
|
||||
k_all = k[0].float()
|
||||
log_f = math.log(frames)
|
||||
a = q.new_zeros(heads, frames, frames, dtype=torch.float32)
|
||||
for start in range(0, frames * rows_per_frame, chunk):
|
||||
stop = min(start + chunk, frames * rows_per_frame)
|
||||
logits = (qv[:, start:stop].float() @ k_all.transpose(-2, -1)) * head_dim**-0.5
|
||||
m = logits.softmax(dim=-1)[..., v0:]
|
||||
m = m.reshape(heads, stop - start, frames, rows_per_frame).sum(dim=-1)
|
||||
idx = torch.arange(start, stop, device=m.device) // rows_per_frame
|
||||
a.scatter_add_(1, idx.view(1, -1, 1).expand(heads, -1, frames), m)
|
||||
del logits, m
|
||||
a = a / rows_per_frame
|
||||
a = (a / a.sum(dim=-1, keepdim=True).clamp(min=eps)).clamp(min=eps)
|
||||
h_row = -(a * a.log()).sum(dim=-1).mean(dim=-1) / log_f
|
||||
gram = a @ a.transpose(-2, -1)
|
||||
trace = gram.diagonal(dim1=-2, dim2=-1).sum(dim=-1).clamp(min=eps)
|
||||
eig = torch.linalg.eigvalsh(gram / trace[:, None, None]).clamp(min=eps)
|
||||
eig = eig / eig.sum(dim=-1, keepdim=True).clamp(min=eps)
|
||||
h_vn = -(eig * eig.log()).sum(dim=-1) / log_f
|
||||
return h_row - h_vn
|
||||
|
||||
|
||||
def _attention_override(state):
|
||||
def override(func, q, k, v, heads, mask=None, **kwargs):
|
||||
frames = state["frames"]
|
||||
rows = state["rows_per_frame"]
|
||||
qt = _unwrap(q)
|
||||
s = qt.shape[2]
|
||||
# video rows are the last frames*rows of the packed sequence; the guard
|
||||
# also rejects token-refiner calls (text length is far below frames*rows).
|
||||
# Only video attention calls advance the layer counter, so a refiner
|
||||
# running inside a forward cannot shift the layer schedule.
|
||||
if frames is None or frames < 2 or s <= frames * rows:
|
||||
if frames is not None and frames >= 2:
|
||||
state["guard_misses"] += 1
|
||||
return func(q, k, v, heads, mask=mask, **kwargs)
|
||||
state["calls_this_forward"] += 1
|
||||
# GPU time via events: host-side perf_counter would absorb the sync stall
|
||||
# from the float() conversions below (they wait on the whole GPU queue,
|
||||
# not just TST's kernels) and report the forward's runtime as TST's
|
||||
timed = state["log_diagnostics"]
|
||||
if timed and qt.is_cuda:
|
||||
tst_start, tst_end = torch.cuda.Event(enable_timing=True), torch.cuda.Event(enable_timing=True)
|
||||
tst_start.record()
|
||||
elif timed:
|
||||
tst_start = time.perf_counter()
|
||||
layers = state["layers"]
|
||||
layer = (state["calls_this_forward"] - 1) % layers
|
||||
total_steps = state["total_steps"]
|
||||
step = min(state["step"], total_steps - 1)
|
||||
layer_weight = 0.5 - 0.5 * math.cos(math.pi * layer / (layers - 1)) if layers > 1 else 1.0
|
||||
step_weight = 0.5 + 0.5 * math.cos(math.pi * step / (total_steps - 1)) if total_steps > 1 else 1.0
|
||||
tension = _spectral_tension(qt, _unwrap(k), s - frames * rows, frames, rows)
|
||||
gamma = torch.exp(tension * (state["tau"] * layer_weight * step_weight))
|
||||
# calibration probe needs pre-correction q; the scaling below is in place
|
||||
exact_probe = state["exact_debug"] and layer == layers // 2
|
||||
q_pre = qt.clone() if exact_probe else None
|
||||
if state["tau"] != 0.0:
|
||||
qt[0, :, s - frames * rows:].mul_(gamma.to(qt.dtype)[:, None, None])
|
||||
if state["log_diagnostics"]:
|
||||
if qt.is_cuda:
|
||||
tst_end.record()
|
||||
state["fw_events"].append((tst_start, tst_end))
|
||||
else:
|
||||
state["fw_tst_time"].append(time.perf_counter() - tst_start)
|
||||
state["fw_abs_tension"].append(float(tension.abs().mean()))
|
||||
# within-call check (paper appendix Figure A): tension of the corrected
|
||||
# operator must drop below the pre-correction value
|
||||
post = _spectral_tension(qt, _unwrap(k), s - frames * rows, frames, rows) if state["tau"] != 0.0 else tension
|
||||
state["fw_abs_tension_post"].append(float(post.abs().mean()))
|
||||
state["fw_gamma"].append(float(gamma.mean()))
|
||||
state["fw_active"].append(float(((gamma - 1.0).abs() > 0.03).float().mean()))
|
||||
if layer == layers - 1 and state["fw_gamma"]:
|
||||
tst_ms = 1000.0 * sum(state["fw_tst_time"])
|
||||
for ev_start, ev_end in state["fw_events"]:
|
||||
ev_end.synchronize()
|
||||
tst_ms += ev_start.elapsed_time(ev_end)
|
||||
n = len(state["fw_abs_tension"])
|
||||
logging.info(
|
||||
"[H3 TST] step %d/%d frames=%d grid_rows=%d pre|T|=%.4f post|T|=%.4f mean_gamma=%.4f active_heads=%.0f%% tst_time=%.2fs",
|
||||
state["step"], total_steps, frames, rows,
|
||||
sum(state["fw_abs_tension"]) / n,
|
||||
sum(state["fw_abs_tension_post"]) / len(state["fw_abs_tension_post"]),
|
||||
sum(state["fw_gamma"]) / len(state["fw_gamma"]),
|
||||
100.0 * sum(state["fw_active"]) / len(state["fw_active"]),
|
||||
tst_ms / 1000.0)
|
||||
state["fw_abs_tension"].clear()
|
||||
state["fw_abs_tension_post"].clear()
|
||||
state["fw_gamma"].clear()
|
||||
state["fw_active"].clear()
|
||||
state["fw_tst_time"].clear()
|
||||
state["fw_events"].clear()
|
||||
if exact_probe:
|
||||
exact = _exact_tension(q_pre, _unwrap(k), s - frames * rows, frames, rows)
|
||||
del q_pre
|
||||
logging.info(
|
||||
"[H3 TST exact] step %d layer %d/%d: proto_T=%+.4f exact_T=%+.4f proto|T|=%.4f exact|T|=%.4f sign_agree=%.0f%%",
|
||||
state["step"], layer, layers,
|
||||
float(tension.mean()), float(exact.mean()),
|
||||
float(tension.abs().mean()), float(exact.abs().mean()),
|
||||
100.0 * float(((exact > 0) == (tension > 0)).float().mean()))
|
||||
return func(q, k, v, heads, mask=mask, **kwargs)
|
||||
return override
|
||||
|
||||
|
||||
def _forward_wrapper(state, executor, x, timestep, context, transformer_options, minimax_payload=None, **kwargs):
|
||||
if state["calls_this_forward"] > 0:
|
||||
state["layers"] = state["calls_this_forward"]
|
||||
elif state["guard_misses"] > 0 and not state["warned_inactive"]:
|
||||
# every attention call of the previous forward was shorter than the
|
||||
# registered video segment: the wrapper sits outside a spatial-tiling
|
||||
# wrapper (wrappers run in registration order) and only saw the
|
||||
# full-resolution shape, so TST cannot locate the tile's video rows
|
||||
logging.warning("[H3 TST] inactive: packed sequence shorter than the expected video segment; "
|
||||
"TST is not compatible with highres_tiling and was skipped")
|
||||
state["warned_inactive"] = True
|
||||
state["calls_this_forward"] = 0
|
||||
state["guard_misses"] = 0
|
||||
# diagnostics off leaves fw_tst_time/fw_events unreported; drop them per forward instead of leaking
|
||||
state["fw_tst_time"].clear()
|
||||
state["fw_events"].clear()
|
||||
video = x[0] if isinstance(x, (list, tuple)) else x
|
||||
if isinstance(video, torch.Tensor) and video.ndim == 5:
|
||||
state["frames"] = int(video.shape[2])
|
||||
state["rows_per_frame"] = ((video.shape[3] + 1) // 2) * ((video.shape[4] + 1) // 2)
|
||||
else:
|
||||
state["frames"] = None
|
||||
sigmas = transformer_options.get("sample_sigmas")
|
||||
if sigmas is not None:
|
||||
sigma = float(timestep.flatten()[0]) / 1000.0
|
||||
state["total_steps"] = max(1, int(sigmas.numel()) - 1)
|
||||
state["step"] = int((sigmas.float().cpu() - sigma).abs().argmin())
|
||||
return executor(x, timestep, context, transformer_options, minimax_payload=minimax_payload, **kwargs)
|
||||
|
||||
|
||||
def patch_model(model, tau, log_diagnostics=True):
|
||||
state = {"tau": float(tau), "log_diagnostics": bool(log_diagnostics),
|
||||
"exact_debug": os.environ.get("SELFLIFT_TST_EXACT", "0") == "1",
|
||||
"frames": None, "rows_per_frame": None,
|
||||
"step": 0, "total_steps": 1, "layers": 50, "calls_this_forward": 0,
|
||||
"guard_misses": 0, "warned_inactive": False,
|
||||
"fw_abs_tension": [], "fw_abs_tension_post": [], "fw_gamma": [], "fw_active": [],
|
||||
"fw_tst_time": [], "fw_events": []}
|
||||
patched = model.clone()
|
||||
patched.add_wrapper_with_key(comfy.patcher_extension.WrappersMP.DIFFUSION_MODEL,
|
||||
"selflift_h3_tst", partial(_forward_wrapper, state))
|
||||
patched.model_options.setdefault("transformer_options", {})["optimized_attention_override"] = _attention_override(state)
|
||||
return patched
|
||||
@@ -0,0 +1,390 @@
|
||||
"""Learned latent-space lifter for MiniMax H3 (3D-conv upscaler).
|
||||
|
||||
Bundles the inference architecture of the Minimax H3 Latent Upscaler
|
||||
(LBH-123-AI/Minimax_h3_latent_Upscaler, architecture drawing on the LTX 2.3
|
||||
spatial upscaler) as an optional experimental replacement for SelfLift-zero's
|
||||
nearest-neighbor latent lift. This external model is not the SelfLift-rich
|
||||
lifter described by the paper. The checkpoint is expected under
|
||||
ComfyUI/models/latent_upscale_models/.
|
||||
"""
|
||||
|
||||
import logging
|
||||
import os
|
||||
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
import torch.nn.functional as F
|
||||
|
||||
import comfy.model_management
|
||||
import comfy.model_patcher
|
||||
import folder_paths
|
||||
|
||||
from comfy.ldm.minimax.vae import LATENTS_MEAN, LATENTS_STD
|
||||
|
||||
from .diagnostics import log_memory
|
||||
|
||||
_FOLDER = "latent_upscale_models"
|
||||
|
||||
if _FOLDER not in folder_paths.folder_names_and_paths:
|
||||
folder_paths.add_model_folder_path(_FOLDER, os.path.join(folder_paths.models_dir, _FOLDER))
|
||||
|
||||
|
||||
def _normalization(channels):
|
||||
return nn.GroupNorm(32, channels)
|
||||
|
||||
|
||||
def _zero_module(module):
|
||||
for p in module.parameters():
|
||||
p.detach().zero_()
|
||||
return module
|
||||
|
||||
|
||||
def _temporal_windows(length, chunk, overlap):
|
||||
for start in range(0, length, chunk):
|
||||
end = min(length, start + chunk)
|
||||
yield start, end, max(0, start - overlap), min(length, end + overlap)
|
||||
|
||||
|
||||
class AttnBlock3D(nn.Module):
|
||||
def __init__(self, in_channels):
|
||||
super().__init__()
|
||||
self.norm = _normalization(in_channels)
|
||||
self.q = nn.Conv3d(in_channels, in_channels, 1)
|
||||
self.k = nn.Conv3d(in_channels, in_channels, 1)
|
||||
self.v = nn.Conv3d(in_channels, in_channels, 1)
|
||||
self.proj_out = nn.Conv3d(in_channels, in_channels, 1)
|
||||
|
||||
def forward(self, x):
|
||||
h = self.norm(x)
|
||||
q = self.q(h).flatten(2).movedim(-1, 1).unsqueeze(1)
|
||||
k = self.k(h).flatten(2).movedim(-1, 1).unsqueeze(1)
|
||||
v = self.v(h).flatten(2).movedim(-1, 1).unsqueeze(1)
|
||||
h = F.scaled_dot_product_attention(q, k, v)
|
||||
h = h.squeeze(1).movedim(1, -1).reshape(x.shape)
|
||||
return x + self.proj_out(h)
|
||||
|
||||
|
||||
class ResBlockEmb3D(nn.Module):
|
||||
def __init__(self, channels, emb_channels, dropout=0, out_channels=None):
|
||||
super().__init__()
|
||||
self.out_channels = out_channels or channels
|
||||
self.in_layers = nn.Sequential(
|
||||
_normalization(channels), nn.SiLU(),
|
||||
nn.Conv3d(channels, self.out_channels, 3, padding=1),
|
||||
)
|
||||
self.emb_layers = nn.Sequential(
|
||||
nn.SiLU(), nn.Linear(emb_channels, 2 * self.out_channels),
|
||||
)
|
||||
self.out_norm = _normalization(self.out_channels)
|
||||
self.out_layers = nn.Sequential(
|
||||
nn.SiLU(), nn.Dropout(p=dropout),
|
||||
_zero_module(nn.Conv3d(self.out_channels, self.out_channels, 3, padding=1)),
|
||||
)
|
||||
self.skip = (
|
||||
nn.Conv3d(channels, self.out_channels, 1)
|
||||
if self.out_channels != channels else nn.Identity()
|
||||
)
|
||||
|
||||
def forward(self, x, emb):
|
||||
h = self.in_layers(x)
|
||||
emb_out = self.emb_layers(emb).type(h.dtype)
|
||||
while len(emb_out.shape) < len(h.shape):
|
||||
emb_out = emb_out[..., None]
|
||||
scale, shift = torch.chunk(emb_out, 2, dim=1)
|
||||
h = self.out_norm(h) * (1 + scale) + shift
|
||||
h = self.out_layers(h)
|
||||
return self.skip(x) + h
|
||||
|
||||
|
||||
class TemporalConv(nn.Module):
|
||||
def __init__(self, channels, kernel_size=5):
|
||||
super().__init__()
|
||||
padding = kernel_size // 2
|
||||
self.norm = _normalization(channels)
|
||||
self.dwconv = nn.Conv3d(channels, channels,
|
||||
kernel_size=(kernel_size, 1, 1),
|
||||
padding=(padding, 0, 0),
|
||||
groups=channels)
|
||||
self.pwconv = nn.Conv3d(channels, channels, kernel_size=1)
|
||||
nn.init.zeros_(self.pwconv.weight)
|
||||
nn.init.zeros_(self.pwconv.bias)
|
||||
|
||||
def forward(self, x):
|
||||
identity = x
|
||||
h = self.norm(x)
|
||||
h = F.silu(h)
|
||||
h = self.dwconv(h)
|
||||
h = self.pwconv(h)
|
||||
return identity + h
|
||||
|
||||
|
||||
class LatentResizer3D(nn.Module):
|
||||
"""Pure-3D upscaler backbone with optional temporal chunking (LBH-123-AI architecture)."""
|
||||
|
||||
def __init__(self, in_channels=24, in_blocks=12, out_blocks=12,
|
||||
channels=512, dropout=0.1, attn=False,
|
||||
temporal_every=2, temporal_kernel=5):
|
||||
super().__init__()
|
||||
self.conv_in = nn.Conv3d(in_channels, channels, 3, padding=1)
|
||||
embed_dim = 64
|
||||
self.embed = nn.Sequential(
|
||||
nn.Linear(1, embed_dim), nn.SiLU(), nn.Linear(embed_dim, embed_dim))
|
||||
|
||||
self.in_blocks = nn.ModuleList()
|
||||
for b in range(in_blocks):
|
||||
if (b == 1 or b == in_blocks - 1) and attn:
|
||||
self.in_blocks.append(AttnBlock3D(channels))
|
||||
self.in_blocks.append(ResBlockEmb3D(channels, embed_dim, dropout))
|
||||
if temporal_every > 0 and b % temporal_every == 0:
|
||||
self.in_blocks.append(TemporalConv(channels, temporal_kernel))
|
||||
|
||||
self.out_blocks = nn.ModuleList()
|
||||
for b in range(out_blocks):
|
||||
if (b == 1 or b == out_blocks - 1) and attn:
|
||||
self.out_blocks.append(AttnBlock3D(channels))
|
||||
self.out_blocks.append(ResBlockEmb3D(channels, embed_dim, dropout))
|
||||
if temporal_every > 0 and b % temporal_every == 0:
|
||||
self.out_blocks.append(TemporalConv(channels, temporal_kernel))
|
||||
|
||||
self.norm_out = _normalization(channels)
|
||||
self.conv_out = nn.Conv3d(channels, in_channels, 3, padding=1)
|
||||
|
||||
def temporal_chunk_settings(self):
|
||||
for block in self.in_blocks:
|
||||
if isinstance(block, TemporalConv):
|
||||
return 32, block.dwconv.weight.shape[2]
|
||||
return 32, 0
|
||||
|
||||
def temporal_window_budget(self, length):
|
||||
chunk, overlap = self.temporal_chunk_settings()
|
||||
return length if length <= chunk else min(length + 2 * overlap, chunk + 4 * overlap)
|
||||
|
||||
def forward(self, x, scale=None, target_size=None, enable_chunking=True):
|
||||
if target_size is not None:
|
||||
size = target_size
|
||||
elif scale is not None:
|
||||
size = tuple(int(round(s * scale)) for s in x.shape[-3:])
|
||||
else:
|
||||
return x
|
||||
|
||||
if size == x.shape[-3:]:
|
||||
return x
|
||||
|
||||
B, C, T, H, W = x.shape
|
||||
|
||||
chunk, overlap = self.temporal_chunk_settings()
|
||||
|
||||
if not enable_chunking or T <= chunk:
|
||||
return self._forward_seg(x, scale, size)
|
||||
|
||||
x_padded = F.pad(x, (0, 0, 0, 0, overlap, overlap), mode='replicate')
|
||||
|
||||
out_full = torch.zeros(B, C, T, size[-2], size[-1], device=x.device, dtype=x.dtype)
|
||||
weight_full = torch.zeros(1, 1, T, 1, 1, device=x.device, dtype=x.dtype)
|
||||
|
||||
for seg_start, seg_end, out_start, out_end in _temporal_windows(T, chunk, overlap):
|
||||
lo = out_start
|
||||
hi = out_end + 2 * overlap
|
||||
|
||||
seg = x_padded[:, :, lo:hi].contiguous()
|
||||
seg_size = (hi - lo, size[-2], size[-1])
|
||||
seg_out = self._forward_seg(seg, scale, seg_size)
|
||||
|
||||
s0 = (out_start + overlap) - lo
|
||||
s1 = s0 + (out_end - out_start)
|
||||
valid_out = seg_out[:, :, s0:s1]
|
||||
n_valid = out_end - out_start
|
||||
|
||||
weight = torch.ones(n_valid, device=x.device, dtype=x.dtype)
|
||||
if seg_start > out_start:
|
||||
blend_len = seg_start - out_start
|
||||
weight[:blend_len] = torch.arange(1, blend_len + 1, device=x.device, dtype=x.dtype) / (blend_len + 1)
|
||||
if out_end > seg_end:
|
||||
blend_len = out_end - seg_end
|
||||
weight[-blend_len:] = torch.arange(blend_len, 0, -1, device=x.device, dtype=x.dtype) / (blend_len + 1)
|
||||
|
||||
out_full[:, :, out_start:out_end] += valid_out * weight.view(1, 1, n_valid, 1, 1)
|
||||
weight_full[:, :, out_start:out_end] += weight.view(1, 1, n_valid, 1, 1)
|
||||
|
||||
del seg, seg_out, valid_out
|
||||
|
||||
return out_full / weight_full.clamp(min=1e-8)
|
||||
|
||||
def _forward_seg(self, x, scale, size):
|
||||
scale_emb = torch.tensor(
|
||||
[scale - 1 if scale is not None else 0.0],
|
||||
dtype=x.dtype, device=x.device).unsqueeze(0)
|
||||
emb = self.embed(scale_emb)
|
||||
|
||||
x = self.conv_in(x)
|
||||
for b in self.in_blocks:
|
||||
if isinstance(b, ResBlockEmb3D):
|
||||
x = b(x, emb.expand(x.shape[0], -1))
|
||||
else:
|
||||
x = b(x)
|
||||
|
||||
x = F.interpolate(x, size=size, mode="trilinear", align_corners=False)
|
||||
|
||||
for b in self.out_blocks:
|
||||
if isinstance(b, ResBlockEmb3D):
|
||||
x = b(x, emb.expand(x.shape[0], -1))
|
||||
else:
|
||||
x = b(x)
|
||||
|
||||
x = self.norm_out(x)
|
||||
x = F.silu(x)
|
||||
return self.conv_out(x)
|
||||
|
||||
|
||||
_model_cache = {}
|
||||
|
||||
|
||||
def list_upscaler_models():
|
||||
try:
|
||||
paths = folder_paths.get_folder_paths(_FOLDER)
|
||||
except KeyError:
|
||||
return []
|
||||
names = []
|
||||
for p in paths:
|
||||
for root, _, files in os.walk(p):
|
||||
for f in files:
|
||||
if os.path.splitext(f)[1].lower() in (".pth", ".safetensors"):
|
||||
names.append(os.path.relpath(os.path.join(root, f), p))
|
||||
return sorted(names)
|
||||
|
||||
|
||||
def _detect_arch(sd):
|
||||
import re
|
||||
cfg = {"in_channels": 24, "in_blocks": 12, "out_blocks": 12, "channels": 512,
|
||||
"dropout": 0.1, "attn": False, "temporal_every": 2, "temporal_kernel": 5}
|
||||
if 'conv_in.weight' in sd:
|
||||
cfg["in_channels"] = sd['conv_in.weight'].shape[1]
|
||||
cfg["channels"] = sd['conv_in.weight'].shape[0]
|
||||
in_ids, out_ids, tin, tout = set(), set(), set(), set()
|
||||
for k in sd:
|
||||
m = re.match(r'in_blocks\.(\d+)\.in_layers\.', k)
|
||||
if m: in_ids.add(int(m.group(1)))
|
||||
m = re.match(r'out_blocks\.(\d+)\.in_layers\.', k)
|
||||
if m: out_ids.add(int(m.group(1)))
|
||||
m = re.match(r'in_blocks\.(\d+)\.dwconv\.weight', k)
|
||||
if m: tin.add(int(m.group(1)))
|
||||
m = re.match(r'out_blocks\.(\d+)\.dwconv\.weight', k)
|
||||
if m: tout.add(int(m.group(1)))
|
||||
if in_ids: cfg["in_blocks"] = len(in_ids)
|
||||
if out_ids: cfg["out_blocks"] = len(out_ids)
|
||||
if tin or tout:
|
||||
cfg["temporal_every"] = 2
|
||||
for k in sd:
|
||||
if k.endswith('dwconv.weight'):
|
||||
cfg["temporal_kernel"] = sd[k].shape[2]
|
||||
break
|
||||
else:
|
||||
cfg["temporal_every"] = 0
|
||||
cfg["attn"] = False
|
||||
return cfg
|
||||
|
||||
|
||||
def _normalize_checkpoint_dtype(state_dict):
|
||||
weight = state_dict.get("conv_in.weight")
|
||||
if weight is None:
|
||||
raise ValueError("SelfLift: upscaler checkpoint is missing conv_in.weight")
|
||||
dtype = weight.dtype
|
||||
if str(dtype).startswith("torch.float8_"):
|
||||
dtype = torch.bfloat16 if any(value.dtype == torch.bfloat16 for value in state_dict.values()) else torch.float16
|
||||
if dtype not in (torch.float16, torch.bfloat16, torch.float32, torch.float64):
|
||||
raise ValueError(f"SelfLift: unsupported upscaler weight dtype {dtype}")
|
||||
if any(value.is_floating_point() and value.dtype != dtype for value in state_dict.values()):
|
||||
logging.info("SelfLift: normalizing mixed upscaler floating-point tensors to %s", dtype)
|
||||
return {name: value.to(dtype=dtype) if value.is_floating_point() else value
|
||||
for name, value in state_dict.items()}
|
||||
|
||||
|
||||
def _load_model(model_name, device):
|
||||
key = (model_name, str(device))
|
||||
if key in _model_cache:
|
||||
return _model_cache[key]
|
||||
|
||||
path = None
|
||||
for p in folder_paths.get_folder_paths(_FOLDER):
|
||||
candidate = os.path.join(p, model_name)
|
||||
if os.path.isfile(candidate):
|
||||
path = candidate
|
||||
break
|
||||
if path is None:
|
||||
raise FileNotFoundError(f"latent upscaler model not found: {model_name} (place it under ComfyUI/models/{_FOLDER}/)")
|
||||
|
||||
import comfy.utils
|
||||
sd = comfy.utils.load_torch_file(path)
|
||||
if isinstance(sd, dict) and 'model' in sd:
|
||||
sd = sd['model']
|
||||
if any(k.startswith("upscaler.") for k in sd):
|
||||
sd = {k[len("upscaler."):]: v for k, v in sd.items() if k.startswith("upscaler.")}
|
||||
sd = _normalize_checkpoint_dtype(sd)
|
||||
|
||||
cfg = _detect_arch(sd)
|
||||
with torch.device("meta"):
|
||||
model = LatentResizer3D(
|
||||
in_channels=cfg["in_channels"], in_blocks=cfg["in_blocks"], out_blocks=cfg["out_blocks"],
|
||||
channels=cfg["channels"], dropout=cfg["dropout"], attn=cfg["attn"],
|
||||
temporal_every=cfg["temporal_every"], temporal_kernel=cfg["temporal_kernel"],
|
||||
)
|
||||
model.load_state_dict(sd, strict=True, assign=True)
|
||||
model = model.eval().requires_grad_(False)
|
||||
patcher = comfy.model_patcher.CoreModelPatcher(
|
||||
model, load_device=device,
|
||||
offload_device=comfy.model_management.unet_offload_device())
|
||||
_model_cache[key] = patcher
|
||||
return patcher
|
||||
|
||||
|
||||
def _inference_memory_required(model, z0_low, out_hw):
|
||||
H, W = out_hw
|
||||
T = z0_low.shape[2]
|
||||
temporal_window = model.temporal_window_budget(T)
|
||||
feature_elements = z0_low.shape[0] * model.conv_in.out_channels * temporal_window * H * W
|
||||
return feature_elements * model.conv_in.weight.element_size() * 8
|
||||
|
||||
|
||||
def learned_latent_lift(z0_low, out_hw, model_name, device=None):
|
||||
"""2D/3D learned upsample of the low-res clean endpoint to the target latent size.
|
||||
|
||||
z0_low: [B, 24, T, h, w] H3 video latent in VAE space. Returns [B, 24, T, H, W].
|
||||
"""
|
||||
H, W = out_hw
|
||||
if device is None:
|
||||
device = comfy.model_management.get_torch_device()
|
||||
h, w = z0_low.shape[-2], z0_low.shape[-1]
|
||||
scale = (H / h + W / w) / 2.0
|
||||
|
||||
log_memory("upscaler before_load", device)
|
||||
patcher = _load_model(model_name, device)
|
||||
model = patcher.model
|
||||
memory_required = _inference_memory_required(model, z0_low, (H, W))
|
||||
length = z0_low.shape[2]
|
||||
chunk, overlap = model.temporal_chunk_settings()
|
||||
identity = (H, W) == (h, w)
|
||||
chunked = not identity and length > chunk
|
||||
windows = list(_temporal_windows(length, chunk, overlap)) if chunked else []
|
||||
actual_window = max(end - start + 2 * overlap for _, _, start, end in windows) if chunked else length
|
||||
budget_window = model.temporal_window_budget(length)
|
||||
logging.info("[SelfLift upscaler] model=%s dtype=%s input=%s target_hw=%s "
|
||||
"spatial_lift=(%.4f, %.4f) scale_embedding=%.4f mode=%s "
|
||||
"chunk=%d overlap=%d windows=%d max_input_window=%d budget_window=%d "
|
||||
"estimated_workspace=%.2f MiB",
|
||||
model_name, model.conv_in.weight.dtype, tuple(z0_low.shape), (H, W),
|
||||
H / h, W / w, scale - 1.0, "identity" if identity else "chunked" if chunked else "full",
|
||||
chunk, overlap if chunked else 0, len(windows) if chunked else int(not identity),
|
||||
actual_window if not identity else 0, budget_window, memory_required / 2**20)
|
||||
comfy.model_management.load_models_gpu([patcher], memory_required=memory_required)
|
||||
log_memory("upscaler after_load", device)
|
||||
dtype = model.conv_in.weight.dtype
|
||||
mean = torch.tensor(LATENTS_MEAN, dtype=dtype, device=device).view(1, -1, 1, 1, 1)
|
||||
std = torch.tensor(LATENTS_STD, dtype=dtype, device=device).view(1, -1, 1, 1, 1)
|
||||
|
||||
x = z0_low.to(device=device, dtype=dtype)
|
||||
with torch.no_grad():
|
||||
x = (x - mean) / std
|
||||
out = model(x, scale=scale, target_size=(z0_low.shape[2], H, W))
|
||||
out = (out * std + mean).float().to(comfy.model_management.intermediate_device())
|
||||
log_memory("upscaler end", device)
|
||||
return out
|
||||
@@ -0,0 +1,516 @@
|
||||
"""SelfLift progressive-resolution sampler nodes.
|
||||
|
||||
Run the first sampling steps on a spatially downscaled latent, lift the clean
|
||||
endpoint to the target resolution with the training-free Artifact-Aware
|
||||
Consistency Lift (arXiv:2609.02036), re-noise it at the transition sigma, and
|
||||
finish the schedule at full resolution.
|
||||
|
||||
Two front-ends share the same engine:
|
||||
- SelfLiftAvatarH3Sampler: MiniMax H3 audio-video (nested AV latents; the audio stream
|
||||
has no spatial dimensions and continues through the reused Euler boundary step).
|
||||
This is an experimental extension beyond the paper's image-model evaluation.
|
||||
- SelfLiftAvatarImageSampler: compatible rectified-flow image models.
|
||||
"""
|
||||
|
||||
import logging
|
||||
import os
|
||||
import time
|
||||
|
||||
import torch
|
||||
|
||||
import comfy.k_diffusion.sampling
|
||||
import comfy.model_management
|
||||
import comfy.model_patcher
|
||||
import comfy.model_sampling
|
||||
import comfy.nested_tensor
|
||||
import comfy.sample
|
||||
import comfy.samplers
|
||||
import comfy.utils
|
||||
import latent_preview
|
||||
|
||||
from . import selflift
|
||||
from . import avatar_masks
|
||||
from .avatar_sampling import native_mask_model
|
||||
from . import h3_upscaler
|
||||
from . import h3_tiling
|
||||
from . import h3_tst
|
||||
from .diagnostics import log_memory
|
||||
|
||||
|
||||
class _StageTimer:
|
||||
def __init__(self, stage, device, resolution=None, pixel_scale=1):
|
||||
self.stage = stage
|
||||
self.resolution = resolution
|
||||
self.pixel_scale = pixel_scale
|
||||
self.device = torch.device(device)
|
||||
self.synchronize = os.environ.get("SELFLIFT_AVATAR_TIMING_SYNC", "0") == "1" and self.device.type == "cuda"
|
||||
self.started = self.previous = self._now()
|
||||
timing_mode = "CUDA-synchronized wall time" if self.synchronize else "wall time; no forced CUDA sync"
|
||||
suffix = ""
|
||||
if resolution is not None:
|
||||
pixels = tuple(int(value * self.pixel_scale) for value in resolution)
|
||||
suffix = f" latent={resolution} pixels={pixels}"
|
||||
logging.info("[selflift-Avatar timing] %s start (%s)%s", stage, timing_mode, suffix)
|
||||
|
||||
def _now(self):
|
||||
if self.synchronize:
|
||||
torch.cuda.synchronize(self.device)
|
||||
return time.perf_counter()
|
||||
|
||||
def mark(self, label):
|
||||
current = self._now()
|
||||
logging.info("[selflift-Avatar timing] %s %s: %.3fs", self.stage, label, current - self.previous)
|
||||
self.previous = current
|
||||
|
||||
def finish(self):
|
||||
current = self._now()
|
||||
logging.info("[selflift-Avatar timing] %s total: %.3fs; after last mark: %.3fs",
|
||||
self.stage, current - self.started, current - self.previous)
|
||||
|
||||
|
||||
def _upscaler_input():
|
||||
models = ["none"] + h3_upscaler.list_upscaler_models()
|
||||
h3_models = [name for name in models[1:] if "h3" in name.lower()]
|
||||
default = h3_models[0] if h3_models else "none"
|
||||
return (models, {"default": default,
|
||||
"tooltip": "External H3 latent upscaler (models/latent_upscale_models). The first detected H3 model is selected by default; 'none' uses nearest-neighbor lifting."})
|
||||
|
||||
|
||||
def _streams(samples):
|
||||
if samples.is_nested:
|
||||
return list(samples.unbind()), True
|
||||
return [samples], False
|
||||
|
||||
|
||||
def _pack(streams, nested):
|
||||
if nested:
|
||||
return comfy.nested_tensor.NestedTensor(streams)
|
||||
return streams[0]
|
||||
|
||||
|
||||
def _validate_sampling(model_sampling, sampler):
|
||||
if not isinstance(model_sampling, comfy.model_sampling.CONST):
|
||||
raise ValueError("SelfLift requires a rectified-flow model")
|
||||
if not isinstance(sampler, comfy.samplers.KSAMPLER) or sampler.sampler_function is not comfy.k_diffusion.sampling.sample_euler:
|
||||
raise ValueError("SelfLift requires the standard Euler sampler")
|
||||
if sampler.extra_options.get("s_churn", 0.0) != 0.0:
|
||||
raise ValueError("SelfLift requires Euler with s_churn=0")
|
||||
|
||||
|
||||
def _validate_schedule(sigmas, transition_step):
|
||||
if sigmas.ndim != 1 or not sigmas.is_floating_point():
|
||||
raise ValueError("selflift-Avatar: sigmas must be a one-dimensional floating-point tensor")
|
||||
if not torch.isfinite(sigmas).all() or (sigmas < 0).any():
|
||||
raise ValueError("selflift-Avatar: sigmas must be finite and nonnegative")
|
||||
if sigmas.numel() < 2:
|
||||
return
|
||||
if not isinstance(transition_step, int) or not 1 <= transition_step <= sigmas.numel() - 2:
|
||||
raise ValueError(f"selflift-Avatar: transition_step {transition_step} out of range for {sigmas.numel() - 1} steps")
|
||||
if (sigmas[1:] > sigmas[:-1]).any():
|
||||
raise ValueError("selflift-Avatar: sigmas must be non-increasing")
|
||||
if (sigmas[:-1] <= 0).any():
|
||||
raise ValueError("selflift-Avatar: only the final sigma may be zero")
|
||||
if sigmas[transition_step] >= 1:
|
||||
raise ValueError("selflift-Avatar: the high-resolution starting sigma must be less than 1")
|
||||
|
||||
|
||||
def _validate_latent_input(latent_image):
|
||||
streams, _ = _streams(latent_image["samples"])
|
||||
if not streams or streams[0].ndim not in (4, 5):
|
||||
raise ValueError("selflift-Avatar: expected an image or video latent")
|
||||
for stream in streams:
|
||||
if stream.ndim == 0 or any(size == 0 for size in stream.shape) or stream.shape[0] != streams[0].shape[0]:
|
||||
raise ValueError("selflift-Avatar: latent streams must be nonempty with matching batches")
|
||||
return avatar_masks.normalize_masks(latent_image.get("noise_mask"), streams)
|
||||
|
||||
|
||||
def _euler_step(state, denoised, sigma, sigma_next):
|
||||
step = ((sigma_next - sigma) / sigma).to(device=state.device, dtype=state.dtype)
|
||||
return state + (state - denoised.to(state)) * step
|
||||
|
||||
|
||||
def _resize_keyframes(cond, h, w):
|
||||
"""Keyframe cond latents share the generation grid; resize them to the low-res one."""
|
||||
out = []
|
||||
for tensor, d in cond:
|
||||
kfs = d.get("minimax_keyframes")
|
||||
if kfs is None:
|
||||
out.append((tensor, d))
|
||||
continue
|
||||
d = d.copy()
|
||||
resized = []
|
||||
for kf in kfs:
|
||||
kf = dict(kf)
|
||||
lat = kf.get("latent")
|
||||
if lat is not None and (lat.shape[-2] != h or lat.shape[-1] != w):
|
||||
if lat.ndim == 5:
|
||||
# spatial-only resize per frame; never interpolates across time
|
||||
batch, channels, frames = lat.shape[:3]
|
||||
resized_latent = torch.nn.functional.interpolate(
|
||||
lat.float().permute(0, 2, 1, 3, 4).reshape(batch * frames, channels, lat.shape[-2], lat.shape[-1]),
|
||||
size=(h, w), mode="bilinear", align_corners=False
|
||||
)
|
||||
resized_latent = resized_latent.reshape(batch, frames, channels, h, w).permute(0, 2, 1, 3, 4)
|
||||
else:
|
||||
resized_latent = torch.nn.functional.interpolate(
|
||||
lat.float(), size=(h, w), mode="bilinear", align_corners=False
|
||||
)
|
||||
# per-channel, per-frame mean match: fixes bilinear's color drift without
|
||||
# restoring variance the low-res grid cannot represent
|
||||
source_mean = lat.float().mean(dim=(-2, -1), keepdim=True)
|
||||
resized_mean = resized_latent.mean(dim=(-2, -1), keepdim=True)
|
||||
kf["latent"] = (resized_latent + (source_mean - resized_mean)).to(lat)
|
||||
resized.append(kf)
|
||||
d["minimax_keyframes"] = resized
|
||||
out.append((tensor, d))
|
||||
return out
|
||||
|
||||
|
||||
def _debug_dump(vae, latents):
|
||||
"""Decode transition intermediates to PNGs when SELFLIFT_AVATAR_DEBUG=1."""
|
||||
if os.environ.get("SELFLIFT_AVATAR_DEBUG", "0") != "1":
|
||||
return
|
||||
out_dir = os.path.join(os.path.dirname(__file__), "debug")
|
||||
os.makedirs(out_dir, exist_ok=True)
|
||||
logging.warning("selflift-Avatar: debug decoding enabled; intermediate video decodes can substantially increase time and memory")
|
||||
from PIL import Image
|
||||
for name, lat in latents.items():
|
||||
if lat is None:
|
||||
continue
|
||||
img = vae.decode(lat)
|
||||
if img.ndim == 5:
|
||||
img = img.reshape(-1, img.shape[-3], img.shape[-2], img.shape[-1])
|
||||
frame = (img[0].float().cpu().numpy().clip(0.0, 1.0) * 255).round().astype("uint8")
|
||||
Image.fromarray(frame).save(os.path.join(out_dir, name + ".png"))
|
||||
|
||||
|
||||
def progressive_sample(model, positive, negative, vae, latent_image, sampler, sigmas, seed, cfg,
|
||||
transition_step, lowres_scale, rho, w_min, w_max, latent_upsample, latent_lifter=None,
|
||||
highres_tiling=False, model_hires=None):
|
||||
_validate_schedule(sigmas, transition_step)
|
||||
if sigmas.numel() < 2:
|
||||
return latent_image
|
||||
if not 0.25 <= lowres_scale <= 1.0:
|
||||
raise ValueError("selflift-Avatar: lowres_scale must be between 0.25 and 1")
|
||||
if not 0.0 <= rho <= 1.0:
|
||||
raise ValueError("selflift-Avatar: rho must be between 0 and 1")
|
||||
if not 0.0 <= w_min <= w_max <= 1.0:
|
||||
raise ValueError("selflift-Avatar: weights must satisfy 0 <= w_min <= w_max <= 1")
|
||||
noise_masks = _validate_latent_input(latent_image)
|
||||
if highres_tiling and noise_masks is not None:
|
||||
raise ValueError("selflift-Avatar: noise_mask is not compatible with highres_tiling")
|
||||
|
||||
model_sampling = model.get_model_object("model_sampling")
|
||||
_validate_sampling(model_sampling, sampler)
|
||||
|
||||
streams, nested = _streams(comfy.sample.fix_empty_latent_channels(
|
||||
model, latent_image["samples"], latent_image.get("downscale_ratio_spacial", None),
|
||||
latent_image.get("downscale_ratio_temporal", None)))
|
||||
hires_base = model_hires if model_hires is not None else model
|
||||
high_model = h3_tiling.tiled_model(hires_base, [tuple(stream.shape) for stream in streams]) if highres_tiling else hires_base
|
||||
video = streams[0].ndim == 5
|
||||
if video:
|
||||
b, c, t, H, W = streams[0].shape
|
||||
else:
|
||||
b, c, H, W = streams[0].shape
|
||||
t = None
|
||||
h = max(2, round(H * lowres_scale / 2) * 2)
|
||||
w = max(2, round(W * lowres_scale / 2) * 2)
|
||||
low_shape = (b, c, t, h, w) if video else (b, c, h, w)
|
||||
logging.info("[selflift-Avatar plan] low_latent=%s target_latent=%s spatial_lift=(%.4f, %.4f) "
|
||||
"low_nfe=%d high_nfe=%d sigma_prediction=%.8g sigma_resume=%.8g "
|
||||
"rho=%.4f weights=(%.4f, %.4f) direct_lift=%s pixel_anchor=%s cfg=%.4f mask=%s hires_model=%s",
|
||||
low_shape, tuple(streams[0].shape), H / h, W / w,
|
||||
transition_step, sigmas.numel() - 1 - transition_step,
|
||||
sigmas[transition_step - 1].item(), sigmas[transition_step].item(),
|
||||
rho, w_min, w_max,
|
||||
"skipped" if rho == 1.0 and w_min == 1.0 else "external" if latent_lifter is not None else latent_upsample,
|
||||
rho > 0.0 and w_max > 0.0, cfg,
|
||||
"none" if noise_masks is None else str([tuple(m.shape) for m in noise_masks]),
|
||||
"custom" if model_hires is not None else "same")
|
||||
|
||||
device = comfy.model_management.intermediate_device()
|
||||
source_video = streams[0].to(device)
|
||||
audio_streams = [s.to(device) for s in streams[1:]]
|
||||
|
||||
if video:
|
||||
low_video = torch.nn.functional.interpolate(
|
||||
source_video.float(), size=(t, h, w), mode="trilinear", align_corners=False
|
||||
).to(dtype=source_video.dtype)
|
||||
else:
|
||||
low_video = torch.nn.functional.interpolate(
|
||||
source_video.float(), size=(h, w), mode="bilinear", align_corners=False
|
||||
).to(dtype=source_video.dtype)
|
||||
m_full = m_low = None
|
||||
low_masks = None
|
||||
if noise_masks is not None:
|
||||
m_full = noise_masks[0]
|
||||
m_low = avatar_masks.resize_spatial(m_full, (h, w))
|
||||
low_masks = [m_low] + noise_masks[1:]
|
||||
video_anchor = source_video
|
||||
low_latent = _pack([low_video] + audio_streams, nested)
|
||||
low_model = native_mask_model(model, [low_video] + audio_streams, low_masks, nested)
|
||||
high_model = native_mask_model(high_model, [video_anchor] + audio_streams, noise_masks, nested)
|
||||
del source_video, low_video
|
||||
del streams
|
||||
noise_low = comfy.sample.prepare_noise(low_latent, seed, latent_image.get("batch_index", None))
|
||||
|
||||
total_steps = sigmas.shape[-1] - 1
|
||||
callback = latent_preview.prepare_callback(model, total_steps)
|
||||
disable_pbar = not comfy.utils.PROGRESS_BAR_ENABLED
|
||||
if video: # keyframe cond latents share the generation grid on MiniMax H3
|
||||
positive_low = _resize_keyframes(positive, h, w)
|
||||
negative_low = _resize_keyframes(negative, h, w)
|
||||
else:
|
||||
positive_low, negative_low = positive, negative
|
||||
|
||||
transition = {}
|
||||
low_evaluations = 0
|
||||
|
||||
def callback_low(step, x0, x, total):
|
||||
nonlocal low_evaluations
|
||||
step = low_evaluations
|
||||
low_evaluations += 1
|
||||
if low_evaluations > transition_step:
|
||||
raise RuntimeError("selflift-Avatar: too many low-resolution callbacks for the Euler schedule")
|
||||
if step == transition_step - 1:
|
||||
transition["state"] = x
|
||||
transition["x0"] = x0
|
||||
# Preview decoders expect the target grid. Decode a temporary lifted
|
||||
# preview while keeping the sampler state at its true low resolution.
|
||||
preview_x0 = x0
|
||||
if video:
|
||||
preview_streams, preview_nested = _streams(x0)
|
||||
preview_video = torch.nn.functional.interpolate(
|
||||
preview_streams[0].float(), size=(t, H, W), mode="trilinear", align_corners=False
|
||||
).to(preview_streams[0].dtype)
|
||||
preview_x0 = _pack([preview_video] + preview_streams[1:], preview_nested)
|
||||
del preview_video, preview_streams
|
||||
elif x0.ndim == 4:
|
||||
preview_x0 = torch.nn.functional.interpolate(
|
||||
x0.float(), size=(H, W), mode="bilinear", align_corners=False
|
||||
).to(x0.dtype)
|
||||
result = callback(step, preview_x0, preview_x0, total_steps)
|
||||
del preview_x0
|
||||
low_timer.mark(f"step {step + 1}/{transition_step}" + (" (includes setup)" if step == 0 else ""))
|
||||
return result
|
||||
|
||||
# The final low-resolution model evaluation is the Eq. 3 prediction. Its Euler
|
||||
# update is discarded and rebuilt after the resolution transition, preserving NFE.
|
||||
resolution_scale = (getattr(model.get_model_object("latent_format"), "spacial_downscale_ratio", 1)
|
||||
if video else getattr(model.get_model_object("latent_format"), "spacial_downscale_ratio", 1))
|
||||
low_timer = _StageTimer("low_resolution", low_model.load_device, (h, w), resolution_scale)
|
||||
log_memory("low_resolution start", low_model.load_device)
|
||||
comfy.samplers.sample(low_model, noise_low, positive_low, negative_low, cfg, low_model.load_device,
|
||||
sampler, sigmas[:transition_step + 1], low_model.model_options,
|
||||
latent_image=low_latent, callback=callback_low,
|
||||
disable_pbar=disable_pbar, seed=seed)
|
||||
if low_evaluations != transition_step:
|
||||
raise RuntimeError(f"selflift-Avatar: expected {transition_step} low-resolution callbacks, received {low_evaluations}; check sampler wrappers")
|
||||
low_timer.finish()
|
||||
log_memory("low_resolution end", model.load_device)
|
||||
transition_timer = _StageTimer("transition", model.load_device, (H, W), resolution_scale)
|
||||
low_streams, nested = _streams(transition.pop("state"))
|
||||
x0_streams, _ = _streams(transition.pop("x0"))
|
||||
sigma_k = sigmas[transition_step - 1]
|
||||
sigma_next = sigmas[transition_step]
|
||||
auxiliary_next = [_euler_step(state.to(device), denoised.to(device), sigma_k, sigma_next)
|
||||
for state, denoised in zip(low_streams[1:], x0_streams[1:])]
|
||||
latent_format = model.get_model_object("latent_format")
|
||||
z0_low_vae = latent_format.process_out(x0_streams[0].float()).to(device)
|
||||
del low_latent, noise_low, low_streams, x0_streams, positive_low, negative_low
|
||||
transition_timer.mark("prepare_endpoint")
|
||||
log_memory("transition endpoint_ready", model.load_device)
|
||||
|
||||
# Artifact-Aware Consistency Lift (Eqs. 4-9); skip branches the weights discard
|
||||
need_pix = rho > 0.0 and w_max > 0.0
|
||||
need_lat = not (rho >= 1.0 and w_min >= 1.0 and w_max >= 1.0)
|
||||
z_lat_vae, z_pix_vae = selflift.paired_lifts(
|
||||
z0_low_vae, vae, (H, W), latent_upsample, latent_lifter,
|
||||
need_lat=need_lat, need_pix=need_pix)
|
||||
transition_timer.mark("paired_lifts")
|
||||
log_memory("transition lifts_ready", model.load_device)
|
||||
z_lat = latent_format.process_in(z_lat_vae) if z_lat_vae is not None else None
|
||||
z_pix = latent_format.process_in(z_pix_vae) if z_pix_vae is not None else None
|
||||
z0_high = selflift.artifact_aware_consistency_lift(z_lat, z_pix, rho, w_min, w_max, mask=m_full)
|
||||
if m_full is not None:
|
||||
# restore the keep-region with the true original instead of any lifted estimate
|
||||
m_cast = m_full.to(device=z0_high.device, dtype=z0_high.dtype)
|
||||
clean_anchor = latent_format.process_in(video_anchor.to(z0_high))
|
||||
z0_high = z0_high * m_cast + clean_anchor * (1.0 - m_cast)
|
||||
if os.environ.get("SELFLIFT_AVATAR_DEBUG", "0") == "1":
|
||||
_debug_dump(vae, {
|
||||
"z0_low": z0_low_vae,
|
||||
"z_lat": z_lat_vae,
|
||||
"z_pix": z_pix_vae,
|
||||
"z0_high": latent_format.process_out(z0_high),
|
||||
})
|
||||
z0_high = z0_high.to(device)
|
||||
del z0_low_vae, z_lat_vae, z_pix_vae, z_lat, z_pix
|
||||
transition_timer.mark("correction_and_debug")
|
||||
log_memory("transition correction_ready", model.load_device)
|
||||
|
||||
# Re-noise the corrected video/image endpoint at the sigma of the reused model
|
||||
# evaluation, then complete that Euler interval without another denoiser call.
|
||||
video_noise = comfy.sample.prepare_noise(z0_high, (seed + 1) % (1 << 64),
|
||||
latent_image.get("batch_index", None)).to(z0_high)
|
||||
video_state = model_sampling.noise_scaling(sigma_k, video_noise, z0_high)
|
||||
next_streams = [_euler_step(video_state, z0_high, sigma_k, sigma_next)] + auxiliary_next
|
||||
del z0_high, video_noise, video_state, auxiliary_next
|
||||
resume_streams = [model_sampling.inverse_noise_scaling(sigma_next, s) for s in next_streams]
|
||||
resume_latent = model.model.process_latent_out(_pack(resume_streams, nested))
|
||||
resume_noise = _pack([torch.zeros_like(s) for s in resume_streams], nested)
|
||||
del next_streams, resume_streams
|
||||
transition_timer.mark("renoise")
|
||||
transition_timer.finish()
|
||||
log_memory("transition end / high_resolution start", model.load_device)
|
||||
|
||||
high_evaluations = 0
|
||||
|
||||
def callback_high(step, x0, x, total):
|
||||
nonlocal high_evaluations
|
||||
step = high_evaluations
|
||||
high_evaluations += 1
|
||||
if high_evaluations > total_steps - transition_step:
|
||||
raise RuntimeError("selflift-Avatar: too many high-resolution callbacks for the Euler schedule")
|
||||
result = callback(step + transition_step, x0, x, total_steps)
|
||||
high_timer.mark(f"step {step + 1}/{total_steps - transition_step}" + (" (includes setup)" if step == 0 else ""))
|
||||
return result
|
||||
|
||||
high_timer = _StageTimer("high_resolution", model.load_device, (H, W), resolution_scale)
|
||||
if highres_tiling:
|
||||
logging.info("[selflift-Avatar plan] automatic high-resolution tiling enabled; preparation selects the tile count")
|
||||
out = comfy.samplers.sample(high_model, resume_noise, positive, negative, cfg, model.load_device,
|
||||
sampler, sigmas[transition_step:], high_model.model_options,
|
||||
latent_image=resume_latent, callback=callback_high,
|
||||
disable_pbar=disable_pbar, seed=seed)
|
||||
del resume_latent, resume_noise
|
||||
if high_evaluations != total_steps - transition_step:
|
||||
raise RuntimeError(f"selflift-Avatar: expected {total_steps - transition_step} high-resolution callbacks, received {high_evaluations}; check sampler wrappers")
|
||||
|
||||
result = latent_image.copy()
|
||||
if noise_masks is not None:
|
||||
# Only exact keep-regions are restored here; do not blend soft masks twice.
|
||||
out_streams, _ = _streams(out)
|
||||
out = _pack(avatar_masks.restore_kept(
|
||||
out_streams, [video_anchor] + audio_streams, noise_masks), nested)
|
||||
result["samples"] = out.to(device=comfy.model_management.intermediate_device(),
|
||||
dtype=comfy.model_management.intermediate_dtype())
|
||||
high_timer.finish()
|
||||
log_memory("high_resolution end", model.load_device)
|
||||
return result
|
||||
|
||||
|
||||
class SelfLiftAvatarH3Sampler:
|
||||
@classmethod
|
||||
def INPUT_TYPES(cls):
|
||||
return {"required": {
|
||||
"model": ("MODEL",),
|
||||
"positive": ("CONDITIONING",),
|
||||
"negative": ("CONDITIONING",),
|
||||
"vae": ("VAE", {"tooltip": "Video VAE used for the pixel re-encode anchor at the resolution transition."}),
|
||||
"latent_image": ("LATENT", {"tooltip": "Target-resolution H3 AV latent defining size and duration. Experimental: accepts existing latents, Tensor masks and H3 NestedTensor video/audio masks. 0 keeps content; 1 generates. Disable highres_tiling when masked."}),
|
||||
"sampler": ("SAMPLER", {"tooltip": "Standard Euler only; SelfLift reuses its transition-step prediction to keep the original NFE count."}),
|
||||
"sigmas": ("SIGMAS",),
|
||||
"seed": ("INT", {"default": 0, "min": 0, "max": 0xffffffffffffffff, "control_after_generate": True}),
|
||||
"cfg": ("FLOAT", {"default": 5.0, "min": 0.0, "max": 100.0, "step": 0.1, "round": 0.01}),
|
||||
"transition_step": ("INT", {"default": 6, "min": 1, "max": 10000, "tooltip": "Number of low-resolution denoiser evaluations. The paper uses 6 of 8 NFEs for its 8-step image model; H3 requires independent validation."}),
|
||||
"lowres_scale": ("FLOAT", {"default": 0.5, "min": 0.25, "max": 1.0, "step": 0.05, "tooltip": "Spatial scale of the low-resolution prefix (paper: 0.5)."}),
|
||||
"rho": ("FLOAT", {"default": 0.0, "min": 0.0, "max": 1.0, "step": 0.05, "tooltip": "Fraction of highest-risk spatiotemporal locations corrected toward the pixel-VAE anchor. The H3 default 0 uses only the external latent upscaler and skips the VAE round trip. For SelfLift-zero with upscaler_model=none, start near 0.6."}),
|
||||
"w_min": ("FLOAT", {"default": 0.5, "min": 0.0, "max": 1.0, "step": 0.05, "tooltip": "Correction-strength floor. H3's widespread nearest-lift error can require 1.0; 0.5 is the paper's image-model setting."}),
|
||||
"w_max": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 1.0, "step": 0.05, "tooltip": "Correction-strength ceiling. Keep at 1.0 for the H3 SelfLift-zero diagnostic."}),
|
||||
"upscaler_model": _upscaler_input(),
|
||||
}, "optional": {
|
||||
"model_hires": ("MODEL", {"tooltip": "Optional: model used for the high-resolution stage instead of `model` (e.g. a different checkpoint or LoRA stack). Must share the same architecture and latent format. The low-resolution prefix always runs on `model`."}),
|
||||
"highres_tiling": ("BOOLEAN", {"default": False, "label_on": "高分辨率分块:开启", "label_off": "高分辨率分块:关闭", "tooltip": "Experimental: select 1–8 spatial tiles from available memory at high-resolution preparation. Audio input and references remain complete; only the first tile's audio prediction is retained. Quality and speed may change."}),
|
||||
}}
|
||||
|
||||
RETURN_TYPES = ("LATENT",)
|
||||
FUNCTION = "sample"
|
||||
CATEGORY = "selflift-Avatar"
|
||||
|
||||
def sample(self, model, positive, negative, vae, latent_image, sampler, sigmas, seed, cfg,
|
||||
transition_step, lowres_scale, rho, w_min, w_max, upscaler_model, model_hires=None, highres_tiling=False):
|
||||
if rho == 0.0 and upscaler_model == "none":
|
||||
raise ValueError(
|
||||
"SelfLift H3: rho=0 with upscaler_model=none disables both SelfLift-zero correction "
|
||||
"and external latent upscaling; choose rho>0 or select an external H3 upscaler."
|
||||
)
|
||||
lifter = None
|
||||
if upscaler_model != "none":
|
||||
if rho > 0.0 and w_max > 0.0:
|
||||
logging.warning("SelfLift H3: rho > 0 with an external upscaler is a hybrid experiment; select upscaler_model=none to test the paper's SelfLift-zero direct route")
|
||||
lifter = lambda z, hw: h3_upscaler.learned_latent_lift(z, hw, upscaler_model)
|
||||
return (progressive_sample(model, positive, negative, vae, latent_image, sampler, sigmas, seed, cfg,
|
||||
transition_step, lowres_scale, rho, w_min, w_max, "nearest",
|
||||
latent_lifter=lifter, highres_tiling=highres_tiling, model_hires=model_hires),)
|
||||
|
||||
|
||||
class SelfLiftAvatarImageSampler:
|
||||
"""SelfLift-zero for compatible rectified-flow image backbones."""
|
||||
|
||||
@classmethod
|
||||
def INPUT_TYPES(cls):
|
||||
return {"required": {
|
||||
"model": ("MODEL",),
|
||||
"positive": ("CONDITIONING",),
|
||||
"negative": ("CONDITIONING",),
|
||||
"vae": ("VAE", {"tooltip": "VAE used for the pixel re-encode anchor at the resolution transition."}),
|
||||
"latent_image": ("LATENT", {"tooltip": "Target-resolution image latent. Experimental: accepts existing content and BHW/BCHW Tensor masks. 0 keeps content; 1 generates."}),
|
||||
"sampler": ("SAMPLER", {"tooltip": "Standard Euler only; SelfLift reuses its transition-step prediction to keep the original NFE count."}),
|
||||
"sigmas": ("SIGMAS",),
|
||||
"seed": ("INT", {"default": 0, "min": 0, "max": 0xffffffffffffffff, "control_after_generate": True}),
|
||||
"cfg": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 100.0, "step": 0.1, "round": 0.01}),
|
||||
"transition_step": ("INT", {"default": 6, "min": 1, "max": 10000, "tooltip": "Number of low-resolution denoiser evaluations. Paper: 3 of 4 for FLUX.2-Klein, 6 of 8 for Z-Image-Turbo."}),
|
||||
"lowres_scale": ("FLOAT", {"default": 0.5, "min": 0.25, "max": 1.0, "step": 0.05, "tooltip": "Spatial scale of the low-resolution prefix (paper: 0.5)."}),
|
||||
"rho": ("FLOAT", {"default": 0.3, "min": 0.0, "max": 1.0, "step": 0.05, "tooltip": "Fraction of locations corrected toward the pixel-VAE anchor. Paper: 0.4 for FLUX.2-Klein, 0.3 for Z-Image-Turbo."}),
|
||||
"w_min": ("FLOAT", {"default": 0.5, "min": 0.0, "max": 1.0, "step": 0.05}),
|
||||
"w_max": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 1.0, "step": 0.05}),
|
||||
"latent_upsample": (["nearest", "bilinear"], {"default": "nearest", "tooltip": "Interpolation for the direct latent lift (paper: nearest)."}),
|
||||
}, "optional": {
|
||||
"model_hires": ("MODEL", {"tooltip": "Optional: model used for the high-resolution stage instead of `model` (e.g. a different checkpoint or LoRA stack). Must share the same architecture and latent format. The low-resolution prefix always runs on `model`."}),
|
||||
}}
|
||||
|
||||
RETURN_TYPES = ("LATENT",)
|
||||
FUNCTION = "sample"
|
||||
CATEGORY = "selflift-Avatar"
|
||||
|
||||
def sample(self, model, positive, negative, vae, latent_image, sampler, sigmas, seed, cfg,
|
||||
transition_step, lowres_scale, rho, w_min, w_max, latent_upsample, model_hires=None):
|
||||
return (progressive_sample(model, positive, negative, vae, latent_image, sampler, sigmas, seed, cfg,
|
||||
transition_step, lowres_scale, rho, w_min, w_max, latent_upsample,
|
||||
model_hires=model_hires),)
|
||||
|
||||
|
||||
class SelfLiftAvatarH3TST:
|
||||
"""Training-free Temporal State Transport correction (arXiv:2609.08505) for MiniMax H3."""
|
||||
|
||||
@classmethod
|
||||
def INPUT_TYPES(cls):
|
||||
return {"required": {
|
||||
"model": ("MODEL",),
|
||||
"tau": ("FLOAT", {"default": 0.2, "min": 0.0, "max": 1.0, "step": 0.05,
|
||||
"tooltip": "Homeostatic correction strength; 0.2 is the paper setting. 0 disables correction while keeping the diagnostic active."}),
|
||||
"log_diagnostics": ("BOOLEAN", {"default": True, "label_on": "诊断日志:开启", "label_off": "诊断日志:关闭",
|
||||
"tooltip": "Log per-forward Spectral Tension and correction statistics to the console. Note: TST is skipped with a warning when highres_tiling is enabled on the SelfLift sampler."}),
|
||||
}}
|
||||
|
||||
RETURN_TYPES = ("MODEL",)
|
||||
FUNCTION = "patch"
|
||||
CATEGORY = "selflift-Avatar"
|
||||
|
||||
def patch(self, model, tau, log_diagnostics):
|
||||
return (h3_tst.patch_model(model, tau, log_diagnostics),)
|
||||
|
||||
|
||||
NODE_CLASS_MAPPINGS = {
|
||||
"SelfLiftAvatarH3Sampler": SelfLiftAvatarH3Sampler,
|
||||
"SelfLiftAvatarImageSampler": SelfLiftAvatarImageSampler,
|
||||
"SelfLiftAvatarH3TST": SelfLiftAvatarH3TST,
|
||||
}
|
||||
|
||||
NODE_DISPLAY_NAME_MAPPINGS = {
|
||||
"SelfLiftAvatarH3Sampler": "selflift-Avatar Sampler (MiniMax H3)",
|
||||
"SelfLiftAvatarImageSampler": "selflift-Avatar Sampler (Image)",
|
||||
"SelfLiftAvatarH3TST": "selflift-Avatar H3 TST",
|
||||
}
|
||||
@@ -0,0 +1,137 @@
|
||||
"""SelfLift-zero (Artifact-Aware Consistency Lift) for progressive-resolution sampling.
|
||||
|
||||
Implements the training-free transition from the SelfLift paper (arXiv:2609.02036),
|
||||
Algorithm 1 with mode=zero:
|
||||
1. predict the clean endpoint at the transition state (Eq. 3)
|
||||
2. build paired lifts: direct latent upsample vs pixel-VAE re-encode (Eqs. 4-5)
|
||||
3. use their residual as a localized artifact-risk signal and correction direction
|
||||
(Eqs. 6-8), correcting only the top-rho inconsistent locations (Eq. 9)
|
||||
4. re-noise the corrected clean latent at the transition sigma (Eq. 10)
|
||||
"""
|
||||
|
||||
import torch
|
||||
import torch.nn.functional
|
||||
|
||||
import comfy.utils
|
||||
|
||||
|
||||
def paired_lifts(z0_low, vae, out_hw, latent_mode="nearest", latent_lifter=None,
|
||||
need_lat=True, need_pix=True):
|
||||
"""Direct latent lift and pixel-VAE re-encode of the low-res clean endpoint (Eqs. 4-5).
|
||||
|
||||
z0_low: [B, C, T, h, w] video or [B, C, h, w] image clean latent prediction in the
|
||||
VAE's native latent space. latent_lifter: optional learned upsampler callable
|
||||
(z0_low, out_hw) -> latent, used for the direct lift on MiniMax H3.
|
||||
need_lat/need_pix skip branches the correction weights would discard: rho=0 needs
|
||||
no pixel anchor, the pure anchor (rho=w=1) needs no direct lift.
|
||||
Returns (z_lat, z_pix) at the target resolution, None for skipped branches.
|
||||
"""
|
||||
H, W = out_hw
|
||||
if z0_low.ndim == 4: # image latent
|
||||
z_lat = None
|
||||
if need_lat:
|
||||
z_lat = torch.nn.functional.interpolate(z0_low.float(), size=(H, W),
|
||||
mode="nearest" if latent_mode == "nearest" else "bilinear")
|
||||
z_pix = None
|
||||
if need_pix:
|
||||
img = vae.decode(z0_low) # [B, h*ratio, w*ratio, 3]
|
||||
ratio = img.shape[1] // z0_low.shape[-2]
|
||||
up = comfy.utils.common_upscale(img.movedim(-1, 1), W * ratio, H * ratio, "lanczos", "disabled").movedim(1, -1)
|
||||
del img
|
||||
z_pix = vae.encode(up).float()
|
||||
if z_lat is not None:
|
||||
z_lat = z_lat.to(z_pix.device)
|
||||
return z_lat, z_pix
|
||||
|
||||
T = z0_low.shape[2]
|
||||
z_lat = None
|
||||
if need_lat:
|
||||
if latent_lifter is not None:
|
||||
z_lat = latent_lifter(z0_low, (H, W))
|
||||
else:
|
||||
if latent_mode == "bilinear":
|
||||
latent_mode = "trilinear" # same method family, 5D name
|
||||
z_lat = torch.nn.functional.interpolate(z0_low.float(), size=(T, H, W), mode=latent_mode)
|
||||
|
||||
z_pix = None
|
||||
if need_pix:
|
||||
z_pix = _pixel_anchor_video(z0_low, vae, (H, W))
|
||||
if z_lat is not None:
|
||||
z_lat = z_lat.to(z_pix.device)
|
||||
return z_lat, z_pix
|
||||
|
||||
|
||||
def _pixel_anchor_video(z0_low, vae, out_hw):
|
||||
"""Build pixel anchors independently for each video in the latent batch."""
|
||||
if z0_low.shape[0] == 1:
|
||||
return _pixel_anchor_video_single(z0_low, vae, out_hw)
|
||||
return torch.cat([
|
||||
_pixel_anchor_video_single(sample, vae, out_hw)
|
||||
for sample in z0_low.split(1)
|
||||
], dim=0)
|
||||
|
||||
|
||||
def _pixel_anchor_video_single(z0_low, vae, out_hw):
|
||||
"""Pixel-VAE anchor for video: decode low-res, upscale, re-encode (Eq. 5).
|
||||
|
||||
The upscale runs in fp16 GPU frame chunks into a preallocated buffer: a naive
|
||||
whole-video lanczos pass materializes several fp32 [F, H*ratio, W*ratio, 3] copies
|
||||
on the CPU (tens of GB on long clips), which pushes an already full RAM into swap
|
||||
and stalls the transition for minutes.
|
||||
"""
|
||||
H, W = out_hw
|
||||
frames = vae.decode(z0_low)
|
||||
if frames.ndim == 5: # VAEDecode convention: video pixels are frames-as-batch [F, H, W, C]
|
||||
frames = frames.reshape(-1, frames.shape[-3], frames.shape[-2], frames.shape[-1])
|
||||
ratio = frames.shape[1] // z0_low.shape[-2]
|
||||
Hp, Wp = H * ratio, W * ratio
|
||||
work_dtype = vae.vae_dtype if vae.vae_dtype in (torch.float16, torch.bfloat16, torch.float32) else torch.float32
|
||||
if vae.device.type == "cpu":
|
||||
work_dtype = torch.float32
|
||||
n = frames.shape[0]
|
||||
up = torch.empty((n, Hp, Wp, frames.shape[-1]), dtype=work_dtype)
|
||||
for i in range(0, n, 32):
|
||||
chunk = frames[i:i + 32].movedim(-1, 1).to(device=vae.device, dtype=work_dtype)
|
||||
chunk = torch.nn.functional.interpolate(chunk, size=(Hp, Wp), mode="bicubic", antialias=True)
|
||||
up[i:i + 32] = chunk.movedim(1, -1).to(up.device)
|
||||
del chunk
|
||||
del frames
|
||||
return vae.encode(up).float() # the wrapper turns the frame batch back into the time dim
|
||||
|
||||
|
||||
def artifact_aware_consistency_lift(z_lat, z_pix, rho, w_min, w_max, mask=None):
|
||||
"""Selective correction of the direct lift toward the pixel-VAE anchor (Eqs. 6-9).
|
||||
|
||||
mask: optional [B, 1|C, (T,) H, W] generate-region mask (1 = generate). Risk
|
||||
statistics and the correction are restricted to mask > 0; masked-out
|
||||
locations always keep the direct lift.
|
||||
"""
|
||||
if rho <= 0.0 or w_max <= 0.0:
|
||||
return z_lat
|
||||
if rho >= 1.0 and w_min >= 1.0 and w_max >= 1.0:
|
||||
return z_pix
|
||||
delta = z_pix - z_lat
|
||||
if mask is not None:
|
||||
mask = mask.to(delta)
|
||||
s = (delta.abs() * mask).mean(dim=1) # per-location inconsistency, [B, (T,) H, W]
|
||||
region = (mask.amax(dim=1) > 0).expand_as(s)
|
||||
view = (-1,) + (1,) * (s.ndim - 1)
|
||||
thr = torch.stack([
|
||||
torch.quantile(s[b][region[b]], 1.0 - rho) if region[b].any()
|
||||
else torch.full((), float("inf"), device=s.device, dtype=s.dtype)
|
||||
for b in range(s.shape[0])
|
||||
]).view(view)
|
||||
selected = (s >= thr) & region
|
||||
else:
|
||||
s = delta.abs().mean(dim=1)
|
||||
view = (-1,) + (1,) * (s.ndim - 1)
|
||||
flat = s.flatten(1)
|
||||
thr = torch.quantile(flat, 1.0 - rho, dim=1).view(view)
|
||||
selected = s >= thr
|
||||
if not selected.any():
|
||||
return z_lat
|
||||
s_min = s.masked_fill(~selected, float("inf")).flatten(1).amin(dim=1).view(view)
|
||||
s_max = s.masked_fill(~selected, float("-inf")).flatten(1).amax(dim=1).view(view)
|
||||
w = w_min + (w_max - w_min) * (s - s_min) / (s_max - s_min + 1e-8)
|
||||
w = torch.where(selected, w, torch.zeros_like(w)).unsqueeze(1)
|
||||
return z_lat + w * delta
|
||||
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user