Text-to-Image
MLX
comfyui
workflows
custom-nodes
krea-2
z-image
minimax-music-3
qwen3-vl
text-to-music
image-to-text
chat
Instructions to use lvladikov/ComfyUI-Nodes-and-Workflows with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- MLX
How to use lvladikov/ComfyUI-Nodes-and-Workflows with MLX:
# Download the model from the Hub pip install huggingface_hub[hf_xet] hf download lvladikov/ComfyUI-Nodes-and-Workflows --local-dir ComfyUI-Nodes-and-Workflows
- Notebooks
- Google Colab
- Kaggle
- Local Apps Settings
- LM Studio
- Atomic Chat
Upload 90 files
Browse files- LVNodes/ComfyUI-DFlow-MLX/LICENSE +674 -0
- LVNodes/ComfyUI-DFlow-MLX/README.md +30 -0
- LVNodes/ComfyUI-DFlow-MLX/__init__.py +348 -0
- LVNodes/ComfyUI-DFlow-MLX/dflow_mlx/__init__.py +3 -0
- LVNodes/ComfyUI-DFlow-MLX/dflow_mlx/family.py +331 -0
- LVNodes/ComfyUI-DFlow-MLX/dflow_mlx/fp16.py +38 -0
- LVNodes/ComfyUI-DFlow-MLX/dflow_mlx/lora.py +168 -0
- LVNodes/ComfyUI-DFlow-MLX/dflow_mlx/pipeline.py +226 -0
- LVNodes/ComfyUI-DFlow-MLX/dflow_mlx/text.py +314 -0
- LVNodes/ComfyUI-DFlow-MLX/dflow_mlx/transformer.py +441 -0
- LVNodes/ComfyUI-DFlow-MLX/dflow_mlx/vae.py +215 -0
- LVNodes/ComfyUI-DFlow-MLX/dflow_mlx_worker.py +98 -0
- LVNodes/README.md +2 -1
- README.md +4 -4
LVNodes/ComfyUI-DFlow-MLX/LICENSE
ADDED
|
@@ -0,0 +1,674 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
GNU GENERAL PUBLIC LICENSE
|
| 2 |
+
Version 3, 29 June 2007
|
| 3 |
+
|
| 4 |
+
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
| 5 |
+
Everyone is permitted to copy and distribute verbatim copies
|
| 6 |
+
of this license document, but changing it is not allowed.
|
| 7 |
+
|
| 8 |
+
Preamble
|
| 9 |
+
|
| 10 |
+
The GNU General Public License is a free, copyleft license for
|
| 11 |
+
software and other kinds of works.
|
| 12 |
+
|
| 13 |
+
The licenses for most software and other practical works are designed
|
| 14 |
+
to take away your freedom to share and change the works. By contrast,
|
| 15 |
+
the GNU General Public License is intended to guarantee your freedom to
|
| 16 |
+
share and change all versions of a program--to make sure it remains free
|
| 17 |
+
software for all its users. We, the Free Software Foundation, use the
|
| 18 |
+
GNU General Public License for most of our software; it applies also to
|
| 19 |
+
any other work released this way by its authors. You can apply it to
|
| 20 |
+
your programs, too.
|
| 21 |
+
|
| 22 |
+
When we speak of free software, we are referring to freedom, not
|
| 23 |
+
price. Our General Public Licenses are designed to make sure that you
|
| 24 |
+
have the freedom to distribute copies of free software (and charge for
|
| 25 |
+
them if you wish), that you receive source code or can get it if you
|
| 26 |
+
want it, that you can change the software or use pieces of it in new
|
| 27 |
+
free programs, and that you know you can do these things.
|
| 28 |
+
|
| 29 |
+
To protect your rights, we need to prevent others from denying you
|
| 30 |
+
these rights or asking you to surrender the rights. Therefore, you have
|
| 31 |
+
certain responsibilities if you distribute copies of the software, or if
|
| 32 |
+
you modify it: responsibilities to respect the freedom of others.
|
| 33 |
+
|
| 34 |
+
For example, if you distribute copies of such a program, whether
|
| 35 |
+
gratis or for a fee, you must pass on to the recipients the same
|
| 36 |
+
freedoms that you received. You must make sure that they, too, receive
|
| 37 |
+
or can get the source code. And you must show them these terms so they
|
| 38 |
+
know their rights.
|
| 39 |
+
|
| 40 |
+
Developers that use the GNU GPL protect your rights with two steps:
|
| 41 |
+
(1) assert copyright on the software, and (2) offer you this License
|
| 42 |
+
giving you legal permission to copy, distribute and/or modify it.
|
| 43 |
+
|
| 44 |
+
For the developers' and authors' protection, the GPL clearly explains
|
| 45 |
+
that there is no warranty for this free software. For both users' and
|
| 46 |
+
authors' sake, the GPL requires that modified versions be marked as
|
| 47 |
+
changed, so that their problems will not be attributed erroneously to
|
| 48 |
+
authors of previous versions.
|
| 49 |
+
|
| 50 |
+
Some devices are designed to deny users access to install or run
|
| 51 |
+
modified versions of the software inside them, although the manufacturer
|
| 52 |
+
can do so. This is fundamentally incompatible with the aim of
|
| 53 |
+
protecting users' freedom to change the software. The systematic
|
| 54 |
+
pattern of such abuse occurs in the area of products for individuals to
|
| 55 |
+
use, which is precisely where it is most unacceptable. Therefore, we
|
| 56 |
+
have designed this version of the GPL to prohibit the practice for those
|
| 57 |
+
products. If such problems arise substantially in other domains, we
|
| 58 |
+
stand ready to extend this provision to those domains in future versions
|
| 59 |
+
of the GPL, as needed to protect the freedom of users.
|
| 60 |
+
|
| 61 |
+
Finally, every program is threatened constantly by software patents.
|
| 62 |
+
States should not allow patents to restrict development and use of
|
| 63 |
+
software on general-purpose computers, but in those that do, we wish to
|
| 64 |
+
avoid the special danger that patents applied to a free program could
|
| 65 |
+
make it effectively proprietary. To prevent this, the GPL assures that
|
| 66 |
+
patents cannot be used to render the program non-free.
|
| 67 |
+
|
| 68 |
+
The precise terms and conditions for copying, distribution and
|
| 69 |
+
modification follow.
|
| 70 |
+
|
| 71 |
+
TERMS AND CONDITIONS
|
| 72 |
+
|
| 73 |
+
0. Definitions.
|
| 74 |
+
|
| 75 |
+
"This License" refers to version 3 of the GNU General Public License.
|
| 76 |
+
|
| 77 |
+
"Copyright" also means copyright-like laws that apply to other kinds of
|
| 78 |
+
works, such as semiconductor masks.
|
| 79 |
+
|
| 80 |
+
"The Program" refers to any copyrightable work licensed under this
|
| 81 |
+
License. Each licensee is addressed as "you". "Licensees" and
|
| 82 |
+
"recipients" may be individuals or organizations.
|
| 83 |
+
|
| 84 |
+
To "modify" a work means to copy from or adapt all or part of the work
|
| 85 |
+
in a fashion requiring copyright permission, other than the making of an
|
| 86 |
+
exact copy. The resulting work is called a "modified version" of the
|
| 87 |
+
earlier work or a work "based on" the earlier work.
|
| 88 |
+
|
| 89 |
+
A "covered work" means either the unmodified Program or a work based
|
| 90 |
+
on the Program.
|
| 91 |
+
|
| 92 |
+
To "propagate" a work means to do anything with it that, without
|
| 93 |
+
permission, would make you directly or secondarily liable for
|
| 94 |
+
infringement under applicable copyright law, except executing it on a
|
| 95 |
+
computer or modifying a private copy. Propagation includes copying,
|
| 96 |
+
distribution (with or without modification), making available to the
|
| 97 |
+
public, and in some countries other activities as well.
|
| 98 |
+
|
| 99 |
+
To "convey" a work means any kind of propagation that enables other
|
| 100 |
+
parties to make or receive copies. Mere interaction with a user through
|
| 101 |
+
a computer network, with no transfer of a copy, is not conveying.
|
| 102 |
+
|
| 103 |
+
An interactive user interface displays "Appropriate Legal Notices"
|
| 104 |
+
to the extent that it includes a convenient and prominently visible
|
| 105 |
+
feature that (1) displays an appropriate copyright notice, and (2)
|
| 106 |
+
tells the user that there is no warranty for the work (except to the
|
| 107 |
+
extent that warranties are provided), that licensees may convey the
|
| 108 |
+
work under this License, and how to view a copy of this License. If
|
| 109 |
+
the interface presents a list of user commands or options, such as a
|
| 110 |
+
menu, a prominent item in the list meets this criterion.
|
| 111 |
+
|
| 112 |
+
1. Source Code.
|
| 113 |
+
|
| 114 |
+
The "source code" for a work means the preferred form of the work
|
| 115 |
+
for making modifications to it. "Object code" means any non-source
|
| 116 |
+
form of a work.
|
| 117 |
+
|
| 118 |
+
A "Standard Interface" means an interface that either is an official
|
| 119 |
+
standard defined by a recognized standards body, or, in the case of
|
| 120 |
+
interfaces specified for a particular programming language, one that
|
| 121 |
+
is widely used among developers working in that language.
|
| 122 |
+
|
| 123 |
+
The "System Libraries" of an executable work include anything, other
|
| 124 |
+
than the work as a whole, that (a) is included in the normal form of
|
| 125 |
+
packaging a Major Component, but which is not part of that Major
|
| 126 |
+
Component, and (b) serves only to enable use of the work with that
|
| 127 |
+
Major Component, or to implement a Standard Interface for which an
|
| 128 |
+
implementation is available to the public in source code form. A
|
| 129 |
+
"Major Component", in this context, means a major essential component
|
| 130 |
+
(kernel, window system, and so on) of the specific operating system
|
| 131 |
+
(if any) on which the executable work runs, or a compiler used to
|
| 132 |
+
produce the work, or an object code interpreter used to run it.
|
| 133 |
+
|
| 134 |
+
The "Corresponding Source" for a work in object code form means all
|
| 135 |
+
the source code needed to generate, install, and (for an executable
|
| 136 |
+
work) run the object code and to modify the work, including scripts to
|
| 137 |
+
control those activities. However, it does not include the work's
|
| 138 |
+
System Libraries, or general-purpose tools or generally available free
|
| 139 |
+
programs which are used unmodified in performing those activities but
|
| 140 |
+
which are not part of the work. For example, Corresponding Source
|
| 141 |
+
includes interface definition files associated with source files for
|
| 142 |
+
the work, and the source code for shared libraries and dynamically
|
| 143 |
+
linked subprograms that the work is specifically designed to require,
|
| 144 |
+
such as by intimate data communication or control flow between those
|
| 145 |
+
subprograms and other parts of the work.
|
| 146 |
+
|
| 147 |
+
The Corresponding Source need not include anything that users
|
| 148 |
+
can regenerate automatically from other parts of the Corresponding
|
| 149 |
+
Source.
|
| 150 |
+
|
| 151 |
+
The Corresponding Source for a work in source code form is that
|
| 152 |
+
same work.
|
| 153 |
+
|
| 154 |
+
2. Basic Permissions.
|
| 155 |
+
|
| 156 |
+
All rights granted under this License are granted for the term of
|
| 157 |
+
copyright on the Program, and are irrevocable provided the stated
|
| 158 |
+
conditions are met. This License explicitly affirms your unlimited
|
| 159 |
+
permission to run the unmodified Program. The output from running a
|
| 160 |
+
covered work is covered by this License only if the output, given its
|
| 161 |
+
content, constitutes a covered work. This License acknowledges your
|
| 162 |
+
rights of fair use or other equivalent, as provided by copyright law.
|
| 163 |
+
|
| 164 |
+
You may make, run and propagate covered works that you do not
|
| 165 |
+
convey, without conditions so long as your license otherwise remains
|
| 166 |
+
in force. You may convey covered works to others for the sole purpose
|
| 167 |
+
of having them make modifications exclusively for you, or provide you
|
| 168 |
+
with facilities for running those works, provided that you comply with
|
| 169 |
+
the terms of this License in conveying all material for which you do
|
| 170 |
+
not control copyright. Those thus making or running the covered works
|
| 171 |
+
for you must do so exclusively on your behalf, under your direction
|
| 172 |
+
and control, on terms that prohibit them from making any copies of
|
| 173 |
+
your copyrighted material outside their relationship with you.
|
| 174 |
+
|
| 175 |
+
Conveying under any other circumstances is permitted solely under
|
| 176 |
+
the conditions stated below. Sublicensing is not allowed; section 10
|
| 177 |
+
makes it unnecessary.
|
| 178 |
+
|
| 179 |
+
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
| 180 |
+
|
| 181 |
+
No covered work shall be deemed part of an effective technological
|
| 182 |
+
measure under any applicable law fulfilling obligations under article
|
| 183 |
+
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
| 184 |
+
similar laws prohibiting or restricting circumvention of such
|
| 185 |
+
measures.
|
| 186 |
+
|
| 187 |
+
When you convey a covered work, you waive any legal power to forbid
|
| 188 |
+
circumvention of technological measures to the extent such circumvention
|
| 189 |
+
is effected by exercising rights under this License with respect to
|
| 190 |
+
the covered work, and you disclaim any intention to limit operation or
|
| 191 |
+
modification of the work as a means of enforcing, against the work's
|
| 192 |
+
users, your or third parties' legal rights to forbid circumvention of
|
| 193 |
+
technological measures.
|
| 194 |
+
|
| 195 |
+
4. Conveying Verbatim Copies.
|
| 196 |
+
|
| 197 |
+
You may convey verbatim copies of the Program's source code as you
|
| 198 |
+
receive it, in any medium, provided that you conspicuously and
|
| 199 |
+
appropriately publish on each copy an appropriate copyright notice;
|
| 200 |
+
keep intact all notices stating that this License and any
|
| 201 |
+
non-permissive terms added in accord with section 7 apply to the code;
|
| 202 |
+
keep intact all notices of the absence of any warranty; and give all
|
| 203 |
+
recipients a copy of this License along with the Program.
|
| 204 |
+
|
| 205 |
+
You may charge any price or no price for each copy that you convey,
|
| 206 |
+
and you may offer support or warranty protection for a fee.
|
| 207 |
+
|
| 208 |
+
5. Conveying Modified Source Versions.
|
| 209 |
+
|
| 210 |
+
You may convey a work based on the Program, or the modifications to
|
| 211 |
+
produce it from the Program, in the form of source code under the
|
| 212 |
+
terms of section 4, provided that you also meet all of these conditions:
|
| 213 |
+
|
| 214 |
+
a) The work must carry prominent notices stating that you modified
|
| 215 |
+
it, and giving a relevant date.
|
| 216 |
+
|
| 217 |
+
b) The work must carry prominent notices stating that it is
|
| 218 |
+
released under this License and any conditions added under section
|
| 219 |
+
7. This requirement modifies the requirement in section 4 to
|
| 220 |
+
"keep intact all notices".
|
| 221 |
+
|
| 222 |
+
c) You must license the entire work, as a whole, under this
|
| 223 |
+
License to anyone who comes into possession of a copy. This
|
| 224 |
+
License will therefore apply, along with any applicable section 7
|
| 225 |
+
additional terms, to the whole of the work, and all its parts,
|
| 226 |
+
regardless of how they are packaged. This License gives no
|
| 227 |
+
permission to license the work in any other way, but it does not
|
| 228 |
+
invalidate such permission if you have separately received it.
|
| 229 |
+
|
| 230 |
+
d) If the work has interactive user interfaces, each must display
|
| 231 |
+
Appropriate Legal Notices; however, if the Program has interactive
|
| 232 |
+
interfaces that do not display Appropriate Legal Notices, your
|
| 233 |
+
work need not make them do so.
|
| 234 |
+
|
| 235 |
+
A compilation of a covered work with other separate and independent
|
| 236 |
+
works, which are not by their nature extensions of the covered work,
|
| 237 |
+
and which are not combined with it such as to form a larger program,
|
| 238 |
+
in or on a volume of a storage or distribution medium, is called an
|
| 239 |
+
"aggregate" if the compilation and its resulting copyright are not
|
| 240 |
+
used to limit the access or legal rights of the compilation's users
|
| 241 |
+
beyond what the individual works permit. Inclusion of a covered work
|
| 242 |
+
in an aggregate does not cause this License to apply to the other
|
| 243 |
+
parts of the aggregate.
|
| 244 |
+
|
| 245 |
+
6. Conveying Non-Source Forms.
|
| 246 |
+
|
| 247 |
+
You may convey a covered work in object code form under the terms
|
| 248 |
+
of sections 4 and 5, provided that you also convey the
|
| 249 |
+
machine-readable Corresponding Source under the terms of this License,
|
| 250 |
+
in one of these ways:
|
| 251 |
+
|
| 252 |
+
a) Convey the object code in, or embodied in, a physical product
|
| 253 |
+
(including a physical distribution medium), accompanied by the
|
| 254 |
+
Corresponding Source fixed on a durable physical medium
|
| 255 |
+
customarily used for software interchange.
|
| 256 |
+
|
| 257 |
+
b) Convey the object code in, or embodied in, a physical product
|
| 258 |
+
(including a physical distribution medium), accompanied by a
|
| 259 |
+
written offer, valid for at least three years and valid for as
|
| 260 |
+
long as you offer spare parts or customer support for that product
|
| 261 |
+
model, to give anyone who possesses the object code either (1) a
|
| 262 |
+
copy of the Corresponding Source for all the software in the
|
| 263 |
+
product that is covered by this License, on a durable physical
|
| 264 |
+
medium customarily used for software interchange, for a price no
|
| 265 |
+
more than your reasonable cost of physically performing this
|
| 266 |
+
conveying of source, or (2) access to copy the
|
| 267 |
+
Corresponding Source from a network server at no charge.
|
| 268 |
+
|
| 269 |
+
c) Convey individual copies of the object code with a copy of the
|
| 270 |
+
written offer to provide the Corresponding Source. This
|
| 271 |
+
alternative is allowed only occasionally and noncommercially, and
|
| 272 |
+
only if you received the object code with such an offer, in accord
|
| 273 |
+
with subsection 6b.
|
| 274 |
+
|
| 275 |
+
d) Convey the object code by offering access from a designated
|
| 276 |
+
place (gratis or for a charge), and offer equivalent access to the
|
| 277 |
+
Corresponding Source in the same way through the same place at no
|
| 278 |
+
further charge. You need not require recipients to copy the
|
| 279 |
+
Corresponding Source along with the object code. If the place to
|
| 280 |
+
copy the object code is a network server, the Corresponding Source
|
| 281 |
+
may be on a different server (operated by you or a third party)
|
| 282 |
+
that supports equivalent copying facilities, provided you maintain
|
| 283 |
+
clear directions next to the object code saying where to find the
|
| 284 |
+
Corresponding Source. Regardless of what server hosts the
|
| 285 |
+
Corresponding Source, you remain obligated to ensure that it is
|
| 286 |
+
available for as long as needed to satisfy these requirements.
|
| 287 |
+
|
| 288 |
+
e) Convey the object code using peer-to-peer transmission, provided
|
| 289 |
+
you inform other peers where the object code and Corresponding
|
| 290 |
+
Source of the work are being offered to the general public at no
|
| 291 |
+
charge under subsection 6d.
|
| 292 |
+
|
| 293 |
+
A separable portion of the object code, whose source code is excluded
|
| 294 |
+
from the Corresponding Source as a System Library, need not be
|
| 295 |
+
included in conveying the object code work.
|
| 296 |
+
|
| 297 |
+
A "User Product" is either (1) a "consumer product", which means any
|
| 298 |
+
tangible personal property which is normally used for personal, family,
|
| 299 |
+
or household purposes, or (2) anything designed or sold for incorporation
|
| 300 |
+
into a dwelling. In determining whether a product is a consumer product,
|
| 301 |
+
doubtful cases shall be resolved in favor of coverage. For a particular
|
| 302 |
+
product received by a particular user, "normally used" refers to a
|
| 303 |
+
typical or common use of that class of product, regardless of the status
|
| 304 |
+
of the particular user or of the way in which the particular user
|
| 305 |
+
actually uses, or expects or is expected to use, the product. A product
|
| 306 |
+
is a consumer product regardless of whether the product has substantial
|
| 307 |
+
commercial, industrial or non-consumer uses, unless such uses represent
|
| 308 |
+
the only significant mode of use of the product.
|
| 309 |
+
|
| 310 |
+
"Installation Information" for a User Product means any methods,
|
| 311 |
+
procedures, authorization keys, or other information required to install
|
| 312 |
+
and execute modified versions of a covered work in that User Product from
|
| 313 |
+
a modified version of its Corresponding Source. The information must
|
| 314 |
+
suffice to ensure that the continued functioning of the modified object
|
| 315 |
+
code is in no case prevented or interfered with solely because
|
| 316 |
+
modification has been made.
|
| 317 |
+
|
| 318 |
+
If you convey an object code work under this section in, or with, or
|
| 319 |
+
specifically for use in, a User Product, and the conveying occurs as
|
| 320 |
+
part of a transaction in which the right of possession and use of the
|
| 321 |
+
User Product is transferred to the recipient in perpetuity or for a
|
| 322 |
+
fixed term (regardless of how the transaction is characterized), the
|
| 323 |
+
Corresponding Source conveyed under this section must be accompanied
|
| 324 |
+
by the Installation Information. But this requirement does not apply
|
| 325 |
+
if neither you nor any third party retains the ability to install
|
| 326 |
+
modified object code on the User Product (for example, the work has
|
| 327 |
+
been installed in ROM).
|
| 328 |
+
|
| 329 |
+
The requirement to provide Installation Information does not include a
|
| 330 |
+
requirement to continue to provide support service, warranty, or updates
|
| 331 |
+
for a work that has been modified or installed by the recipient, or for
|
| 332 |
+
the User Product in which it has been modified or installed. Access to a
|
| 333 |
+
network may be denied when the modification itself materially and
|
| 334 |
+
adversely affects the operation of the network or violates the rules and
|
| 335 |
+
protocols for communication across the network.
|
| 336 |
+
|
| 337 |
+
Corresponding Source conveyed, and Installation Information provided,
|
| 338 |
+
in accord with this section must be in a format that is publicly
|
| 339 |
+
documented (and with an implementation available to the public in
|
| 340 |
+
source code form), and must require no special password or key for
|
| 341 |
+
unpacking, reading or copying.
|
| 342 |
+
|
| 343 |
+
7. Additional Terms.
|
| 344 |
+
|
| 345 |
+
"Additional permissions" are terms that supplement the terms of this
|
| 346 |
+
License by making exceptions from one or more of its conditions.
|
| 347 |
+
Additional permissions that are applicable to the entire Program shall
|
| 348 |
+
be treated as though they were included in this License, to the extent
|
| 349 |
+
that they are valid under applicable law. If additional permissions
|
| 350 |
+
apply only to part of the Program, that part may be used separately
|
| 351 |
+
under those permissions, but the entire Program remains governed by
|
| 352 |
+
this License without regard to the additional permissions.
|
| 353 |
+
|
| 354 |
+
When you convey a copy of a covered work, you may at your option
|
| 355 |
+
remove any additional permissions from that copy, or from any part of
|
| 356 |
+
it. (Additional permissions may be written to require their own
|
| 357 |
+
removal in certain cases when you modify the work.) You may place
|
| 358 |
+
additional permissions on material, added by you to a covered work,
|
| 359 |
+
for which you have or can give appropriate copyright permission.
|
| 360 |
+
|
| 361 |
+
Notwithstanding any other provision of this License, for material you
|
| 362 |
+
add to a covered work, you may (if authorized by the copyright holders of
|
| 363 |
+
that material) supplement the terms of this License with terms:
|
| 364 |
+
|
| 365 |
+
a) Disclaiming warranty or limiting liability differently from the
|
| 366 |
+
terms of sections 15 and 16 of this License; or
|
| 367 |
+
|
| 368 |
+
b) Requiring preservation of specified reasonable legal notices or
|
| 369 |
+
author attributions in that material or in the Appropriate Legal
|
| 370 |
+
Notices displayed by works containing it; or
|
| 371 |
+
|
| 372 |
+
c) Prohibiting misrepresentation of the origin of that material, or
|
| 373 |
+
requiring that modified versions of such material be marked in
|
| 374 |
+
reasonable ways as different from the original version; or
|
| 375 |
+
|
| 376 |
+
d) Limiting the use for publicity purposes of names of licensors or
|
| 377 |
+
authors of the material; or
|
| 378 |
+
|
| 379 |
+
e) Declining to grant rights under trademark law for use of some
|
| 380 |
+
trade names, trademarks, or service marks; or
|
| 381 |
+
|
| 382 |
+
f) Requiring indemnification of licensors and authors of that
|
| 383 |
+
material by anyone who conveys the material (or modified versions of
|
| 384 |
+
it) with contractual assumptions of liability to the recipient, for
|
| 385 |
+
any liability that these contractual assumptions directly impose on
|
| 386 |
+
those licensors and authors.
|
| 387 |
+
|
| 388 |
+
All other non-permissive additional terms are considered "further
|
| 389 |
+
restrictions" within the meaning of section 10. If the Program as you
|
| 390 |
+
received it, or any part of it, contains a notice stating that it is
|
| 391 |
+
governed by this License along with a term that is a further
|
| 392 |
+
restriction, you may remove that term. If a license document contains
|
| 393 |
+
a further restriction but permits relicensing or conveying under this
|
| 394 |
+
License, you may add to a covered work material governed by the terms
|
| 395 |
+
of that license document, provided that the further restriction does
|
| 396 |
+
not survive such relicensing or conveying.
|
| 397 |
+
|
| 398 |
+
If you add terms to a covered work in accord with this section, you
|
| 399 |
+
must place, in the relevant source files, a statement of the
|
| 400 |
+
additional terms that apply to those files, or a notice indicating
|
| 401 |
+
where to find the applicable terms.
|
| 402 |
+
|
| 403 |
+
Additional terms, permissive or non-permissive, may be stated in the
|
| 404 |
+
form of a separately written license, or stated as exceptions;
|
| 405 |
+
the above requirements apply either way.
|
| 406 |
+
|
| 407 |
+
8. Termination.
|
| 408 |
+
|
| 409 |
+
You may not propagate or modify a covered work except as expressly
|
| 410 |
+
provided under this License. Any attempt otherwise to propagate or
|
| 411 |
+
modify it is void, and will automatically terminate your rights under
|
| 412 |
+
this License (including any patent licenses granted under the third
|
| 413 |
+
paragraph of section 11).
|
| 414 |
+
|
| 415 |
+
However, if you cease all violation of this License, then your
|
| 416 |
+
license from a particular copyright holder is reinstated (a)
|
| 417 |
+
provisionally, unless and until the copyright holder explicitly and
|
| 418 |
+
finally terminates your license, and (b) permanently, if the copyright
|
| 419 |
+
holder fails to notify you of the violation by some reasonable means
|
| 420 |
+
prior to 60 days after the cessation.
|
| 421 |
+
|
| 422 |
+
Moreover, your license from a particular copyright holder is
|
| 423 |
+
reinstated permanently if the copyright holder notifies you of the
|
| 424 |
+
violation by some reasonable means, this is the first time you have
|
| 425 |
+
received notice of violation of this License (for any work) from that
|
| 426 |
+
copyright holder, and you cure the violation prior to 30 days after
|
| 427 |
+
your receipt of the notice.
|
| 428 |
+
|
| 429 |
+
Termination of your rights under this section does not terminate the
|
| 430 |
+
licenses of parties who have received copies or rights from you under
|
| 431 |
+
this License. If your rights have been terminated and not permanently
|
| 432 |
+
reinstated, you do not qualify to receive new licenses for the same
|
| 433 |
+
material under section 10.
|
| 434 |
+
|
| 435 |
+
9. Acceptance Not Required for Having Copies.
|
| 436 |
+
|
| 437 |
+
You are not required to accept this License in order to receive or
|
| 438 |
+
run a copy of the Program. Ancillary propagation of a covered work
|
| 439 |
+
occurring solely as a consequence of using peer-to-peer transmission
|
| 440 |
+
to receive a copy likewise does not require acceptance. However,
|
| 441 |
+
nothing other than this License grants you permission to propagate or
|
| 442 |
+
modify any covered work. These actions infringe copyright if you do
|
| 443 |
+
not accept this License. Therefore, by modifying or propagating a
|
| 444 |
+
covered work, you indicate your acceptance of this License to do so.
|
| 445 |
+
|
| 446 |
+
10. Automatic Licensing of Downstream Recipients.
|
| 447 |
+
|
| 448 |
+
Each time you convey a covered work, the recipient automatically
|
| 449 |
+
receives a license from the original licensors, to run, modify and
|
| 450 |
+
propagate that work, subject to this License. You are not responsible
|
| 451 |
+
for enforcing compliance by third parties with this License.
|
| 452 |
+
|
| 453 |
+
An "entity transaction" is a transaction transferring control of an
|
| 454 |
+
organization, or substantially all assets of one, or subdividing an
|
| 455 |
+
organization, or merging organizations. If propagation of a covered
|
| 456 |
+
work results from an entity transaction, each party to that
|
| 457 |
+
transaction who receives a copy of the work also receives whatever
|
| 458 |
+
licenses to the work the party's predecessor in interest had or could
|
| 459 |
+
give under the previous paragraph, plus a right to possession of the
|
| 460 |
+
Corresponding Source of the work from the predecessor in interest, if
|
| 461 |
+
the predecessor has it or can get it with reasonable efforts.
|
| 462 |
+
|
| 463 |
+
You may not impose any further restrictions on the exercise of the
|
| 464 |
+
rights granted or affirmed under this License. For example, you may
|
| 465 |
+
not impose a license fee, royalty, or other charge for exercise of
|
| 466 |
+
rights granted under this License, and you may not initiate litigation
|
| 467 |
+
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
| 468 |
+
any patent claim is infringed by making, using, selling, offering for
|
| 469 |
+
sale, or importing the Program or any portion of it.
|
| 470 |
+
|
| 471 |
+
11. Patents.
|
| 472 |
+
|
| 473 |
+
A "contributor" is a copyright holder who authorizes use under this
|
| 474 |
+
License of the Program or a work on which the Program is based. The
|
| 475 |
+
work thus licensed is called the contributor's "contributor version".
|
| 476 |
+
|
| 477 |
+
A contributor's "essential patent claims" are all patent claims
|
| 478 |
+
owned or controlled by the contributor, whether already acquired or
|
| 479 |
+
hereafter acquired, that would be infringed by some manner, permitted
|
| 480 |
+
by this License, of making, using, or selling its contributor version,
|
| 481 |
+
but do not include claims that would be infringed only as a
|
| 482 |
+
consequence of further modification of the contributor version. For
|
| 483 |
+
purposes of this definition, "control" includes the right to grant
|
| 484 |
+
patent sublicenses in a manner consistent with the requirements of
|
| 485 |
+
this License.
|
| 486 |
+
|
| 487 |
+
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
| 488 |
+
patent license under the contributor's essential patent claims, to
|
| 489 |
+
make, use, sell, offer for sale, import and otherwise run, modify and
|
| 490 |
+
propagate the contents of its contributor version.
|
| 491 |
+
|
| 492 |
+
In the following three paragraphs, a "patent license" is any express
|
| 493 |
+
agreement or commitment, however denominated, not to enforce a patent
|
| 494 |
+
(such as an express permission to practice a patent or covenant not to
|
| 495 |
+
sue for patent infringement). To "grant" such a patent license to a
|
| 496 |
+
party means to make such an agreement or commitment not to enforce a
|
| 497 |
+
patent against the party.
|
| 498 |
+
|
| 499 |
+
If you convey a covered work, knowingly relying on a patent license,
|
| 500 |
+
and the Corresponding Source of the work is not available for anyone
|
| 501 |
+
to copy, free of charge and under the terms of this License, through a
|
| 502 |
+
publicly available network server or other readily accessible means,
|
| 503 |
+
then you must either (1) cause the Corresponding Source to be so
|
| 504 |
+
available, or (2) arrange to deprive yourself of the benefit of the
|
| 505 |
+
patent license for this particular work, or (3) arrange, in a manner
|
| 506 |
+
consistent with the requirements of this License, to extend the patent
|
| 507 |
+
license to downstream recipients. "Knowingly relying" means you have
|
| 508 |
+
actual knowledge that, but for the patent license, your conveying the
|
| 509 |
+
covered work in a country, or your recipient's use of the covered work
|
| 510 |
+
in a country, would infringe one or more identifiable patents in that
|
| 511 |
+
country that you have reason to believe are valid.
|
| 512 |
+
|
| 513 |
+
If, pursuant to or in connection with a single transaction or
|
| 514 |
+
arrangement, you convey, or propagate by procuring conveyance of, a
|
| 515 |
+
covered work, and grant a patent license to some of the parties
|
| 516 |
+
receiving the covered work authorizing them to use, propagate, modify
|
| 517 |
+
or convey a specific copy of the covered work, then the patent license
|
| 518 |
+
you grant is automatically extended to all recipients of the covered
|
| 519 |
+
work and works based on it.
|
| 520 |
+
|
| 521 |
+
A patent license is "discriminatory" if it does not include within
|
| 522 |
+
the scope of its coverage, prohibits the exercise of, or is
|
| 523 |
+
conditioned on the non-exercise of one or more of the rights that are
|
| 524 |
+
specifically granted under this License. You may not convey a covered
|
| 525 |
+
work if you are a party to an arrangement with a third party that is
|
| 526 |
+
in the business of distributing software, under which you make payment
|
| 527 |
+
to the third party based on the extent of your activity of conveying
|
| 528 |
+
the work, and under which the third party grants, to any of the
|
| 529 |
+
parties who would receive the covered work from you, a discriminatory
|
| 530 |
+
patent license (a) in connection with copies of the covered work
|
| 531 |
+
conveyed by you (or copies made from those copies), or (b) primarily
|
| 532 |
+
for and in connection with specific products or compilations that
|
| 533 |
+
contain the covered work, unless you entered into that arrangement,
|
| 534 |
+
or that patent license was granted, prior to 28 March 2007.
|
| 535 |
+
|
| 536 |
+
Nothing in this License shall be construed as excluding or limiting
|
| 537 |
+
any implied license or other defenses to infringement that may
|
| 538 |
+
otherwise be available to you under applicable patent law.
|
| 539 |
+
|
| 540 |
+
12. No Surrender of Others' Freedom.
|
| 541 |
+
|
| 542 |
+
If conditions are imposed on you (whether by court order, agreement or
|
| 543 |
+
otherwise) that contradict the conditions of this License, they do not
|
| 544 |
+
excuse you from the conditions of this License. If you cannot convey a
|
| 545 |
+
covered work so as to satisfy simultaneously your obligations under this
|
| 546 |
+
License and any other pertinent obligations, then as a consequence you may
|
| 547 |
+
not convey it at all. For example, if you agree to terms that obligate you
|
| 548 |
+
to collect a royalty for further conveying from those to whom you convey
|
| 549 |
+
the Program, the only way you could satisfy both those terms and this
|
| 550 |
+
License would be to refrain entirely from conveying the Program.
|
| 551 |
+
|
| 552 |
+
13. Use with the GNU Affero General Public License.
|
| 553 |
+
|
| 554 |
+
Notwithstanding any other provision of this License, you have
|
| 555 |
+
permission to link or combine any covered work with a work licensed
|
| 556 |
+
under version 3 of the GNU Affero General Public License into a single
|
| 557 |
+
combined work, and to convey the resulting work. The terms of this
|
| 558 |
+
License will continue to apply to the part which is the covered work,
|
| 559 |
+
but the special requirements of the GNU Affero General Public License,
|
| 560 |
+
section 13, concerning interaction through a network will apply to the
|
| 561 |
+
combination as such.
|
| 562 |
+
|
| 563 |
+
14. Revised Versions of this License.
|
| 564 |
+
|
| 565 |
+
The Free Software Foundation may publish revised and/or new versions of
|
| 566 |
+
the GNU General Public License from time to time. Such new versions will
|
| 567 |
+
be similar in spirit to the present version, but may differ in detail to
|
| 568 |
+
address new problems or concerns.
|
| 569 |
+
|
| 570 |
+
Each version is given a distinguishing version number. If the
|
| 571 |
+
Program specifies that a certain numbered version of the GNU General
|
| 572 |
+
Public License "or any later version" applies to it, you have the
|
| 573 |
+
option of following the terms and conditions either of that numbered
|
| 574 |
+
version or of any later version published by the Free Software
|
| 575 |
+
Foundation. If the Program does not specify a version number of the
|
| 576 |
+
GNU General Public License, you may choose any version ever published
|
| 577 |
+
by the Free Software Foundation.
|
| 578 |
+
|
| 579 |
+
If the Program specifies that a proxy can decide which future
|
| 580 |
+
versions of the GNU General Public License can be used, that proxy's
|
| 581 |
+
public statement of acceptance of a version permanently authorizes you
|
| 582 |
+
to choose that version for the Program.
|
| 583 |
+
|
| 584 |
+
Later license versions may give you additional or different
|
| 585 |
+
permissions. However, no additional obligations are imposed on any
|
| 586 |
+
author or copyright holder as a result of your choosing to follow a
|
| 587 |
+
later version.
|
| 588 |
+
|
| 589 |
+
15. Disclaimer of Warranty.
|
| 590 |
+
|
| 591 |
+
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
| 592 |
+
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
| 593 |
+
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
| 594 |
+
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
| 595 |
+
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
| 596 |
+
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
| 597 |
+
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
| 598 |
+
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
| 599 |
+
|
| 600 |
+
16. Limitation of Liability.
|
| 601 |
+
|
| 602 |
+
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
| 603 |
+
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
| 604 |
+
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
| 605 |
+
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
| 606 |
+
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
| 607 |
+
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
| 608 |
+
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
| 609 |
+
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
| 610 |
+
SUCH DAMAGES.
|
| 611 |
+
|
| 612 |
+
17. Interpretation of Sections 15 and 16.
|
| 613 |
+
|
| 614 |
+
If the disclaimer of warranty and limitation of liability provided
|
| 615 |
+
above cannot be given local legal effect according to their terms,
|
| 616 |
+
reviewing courts shall apply local law that most closely approximates
|
| 617 |
+
an absolute waiver of all civil liability in connection with the
|
| 618 |
+
Program, unless a warranty or assumption of liability accompanies a
|
| 619 |
+
copy of the Program in return for a fee.
|
| 620 |
+
|
| 621 |
+
END OF TERMS AND CONDITIONS
|
| 622 |
+
|
| 623 |
+
How to Apply These Terms to Your New Programs
|
| 624 |
+
|
| 625 |
+
If you develop a new program, and you want it to be of the greatest
|
| 626 |
+
possible use to the public, the best way to achieve this is to make it
|
| 627 |
+
free software which everyone can redistribute and change under these terms.
|
| 628 |
+
|
| 629 |
+
To do so, attach the following notices to the program. It is safest
|
| 630 |
+
to attach them to the start of each source file to most effectively
|
| 631 |
+
state the exclusion of warranty; and each file should have at least
|
| 632 |
+
the "copyright" line and a pointer to where the full notice is found.
|
| 633 |
+
|
| 634 |
+
<one line to give the program's name and a brief idea of what it does.>
|
| 635 |
+
Copyright (C) <year> <name of author>
|
| 636 |
+
|
| 637 |
+
This program is free software: you can redistribute it and/or modify
|
| 638 |
+
it under the terms of the GNU General Public License as published by
|
| 639 |
+
the Free Software Foundation, either version 3 of the License, or
|
| 640 |
+
(at your option) any later version.
|
| 641 |
+
|
| 642 |
+
This program is distributed in the hope that it will be useful,
|
| 643 |
+
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
| 644 |
+
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
| 645 |
+
GNU General Public License for more details.
|
| 646 |
+
|
| 647 |
+
You should have received a copy of the GNU General Public License
|
| 648 |
+
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
| 649 |
+
|
| 650 |
+
Also add information on how to contact you by electronic and paper mail.
|
| 651 |
+
|
| 652 |
+
If the program does terminal interaction, make it output a short
|
| 653 |
+
notice like this when it starts in an interactive mode:
|
| 654 |
+
|
| 655 |
+
<program> Copyright (C) <year> <name of author>
|
| 656 |
+
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
| 657 |
+
This is free software, and you are welcome to redistribute it
|
| 658 |
+
under certain conditions; type `show c' for details.
|
| 659 |
+
|
| 660 |
+
The hypothetical commands `show w' and `show c' should show the appropriate
|
| 661 |
+
parts of the General Public License. Of course, your program's commands
|
| 662 |
+
might be different; for a GUI interface, you would use an "about box".
|
| 663 |
+
|
| 664 |
+
You should also get your employer (if you work as a programmer) or school,
|
| 665 |
+
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
| 666 |
+
For more information on this, and how to apply and follow the GNU GPL, see
|
| 667 |
+
<https://www.gnu.org/licenses/>.
|
| 668 |
+
|
| 669 |
+
The GNU General Public License does not permit incorporating your program
|
| 670 |
+
into proprietary programs. If your program is a subroutine library, you
|
| 671 |
+
may consider it more useful to permit linking proprietary applications with
|
| 672 |
+
the library. If this is what you want to do, use the GNU Lesser General
|
| 673 |
+
Public License instead of this License. But first, please read
|
| 674 |
+
<https://www.gnu.org/licenses/why-not-lgpl.html>.
|
LVNodes/ComfyUI-DFlow-MLX/README.md
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# ComfyUI-DFlow-MLX
|
| 2 |
+
|
| 3 |
+
[dflow_2b](https://huggingface.co/data-archetype/dflow_2b) on an Apple Silicon Mac, inside ComfyUI. dflow_2b's own nodes
|
| 4 |
+
run on CUDA only (at the time of writing); these two run it on Apple's MLX, with or without a LoRA such as the
|
| 5 |
+
[DFlow2 4-step LoRA](https://huggingface.co/lvladikov/DFlow2-Distill-4steps-eDMD-LADD-LoRA).
|
| 6 |
+
|
| 7 |
+
| Node | What it does |
|
| 8 |
+
|---|---|
|
| 9 |
+
| **DFlow Model (MLX)** (`LVDFlowMLXModel`) | Which dflow_2b to run: the release folder as its README installs it (`custom_nodes/dflow_2b`), or a copy in `models/dflow`; an optional LoRA from `models/loras`, applied beside the weights rather than merged; float16 compute (default; faster on Apple GPUs) or bfloat16. Nothing loads here. |
|
| 10 |
+
| **DFlow Sampler (MLX)** (`LVDFlowMLXSampler`) | A prompt, or one of dflow's JSON layouts (compiled at the image size); width, height, steps, seed, the path-drop guidance scale and the solver. The release's default is 50 steps, guidance 2.5, er_sde; the DFlow2 4-step LoRA wants 4 steps, guidance 1, euler. The self-attention gain follows the image size (-1 = automatic). Returns an IMAGE. |
|
| 11 |
+
|
| 12 |
+
A seed draws the release's own noise (torch's CPU generator), so it composes the same picture as dflow's PyTorch nodes.
|
| 13 |
+
The render matches the release's arithmetic: its schedule, solvers, guidance and prompt rules (its tokenizer and layout
|
| 14 |
+
code are read from the dflow_2b folder itself).
|
| 15 |
+
|
| 16 |
+
**Needs:**
|
| 17 |
+
- an Apple Silicon Mac;
|
| 18 |
+
- dflow_2b downloaded as its README says: `hf download data-archetype/dflow_2b --local-dir ComfyUI/custom_nodes/dflow_2b`
|
| 19 |
+
(its weights, text encoder and prompt rules are read from there). Its autoencoder, dinac3_96, downloads on the first
|
| 20 |
+
run (about 320 MB);
|
| 21 |
+
- LVNodes' shared MLX environment (`LVNodes/.venv`), which the first run sets up by itself (about 1.3 GB, once).
|
| 22 |
+
ComfyUI's own Python packages are not touched.
|
| 23 |
+
|
| 24 |
+
**Install** with LVNodes (see [LVNodes/README.md](../README.md)): already using LVNodes, copy just this folder into your
|
| 25 |
+
`custom_nodes/LVNodes`, then restart ComfyUI. Add it; don't replace the `LVNodes` folder.
|
| 26 |
+
|
| 27 |
+
The MLX code runs in a helper process (`dflow_mlx_worker.py`); its log is `LVNodes/.cache/dflow-mlx/worker.log`.
|
| 28 |
+
|
| 29 |
+
GPL-3.0 (`LICENSE`): the `dflow_mlx/` package is a port of dflow_2b's GPL-3.0 inference code; the rest of LVNodes is
|
| 30 |
+
Apache-2.0.
|
LVNodes/ComfyUI-DFlow-MLX/__init__.py
ADDED
|
@@ -0,0 +1,348 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""LVNodes/ComfyUI-DFlow-MLX: dflow_2b (Data Archetype) on Apple MLX, inside ComfyUI, with or without a LoRA such as the
|
| 2 |
+
DFlow2 4-step LoRA. dflow_2b's own ComfyUI nodes run on CUDA only; these two run it on an Apple Silicon Mac.
|
| 3 |
+
|
| 4 |
+
Two nodes, like a loader and a sampler. DFlow Model (MLX) says which dflow_2b release folder to run, with an optional
|
| 5 |
+
LoRA; DFlow Sampler (MLX) runs it: a prompt (or one of dflow's JSON layouts, compiled at the image size), size, steps,
|
| 6 |
+
seed, the path-drop guidance scale and the solver, and returns an IMAGE. The MLX code runs in a helper process
|
| 7 |
+
(dflow_mlx_worker.py) inside the shared LVNodes MLX environment (LVNodes/.venv), which the first run sets up with
|
| 8 |
+
LVNodes/install.py. ComfyUI's own Python and packages are never touched, and this file imports no MLX.
|
| 9 |
+
"""
|
| 10 |
+
import atexit
|
| 11 |
+
import gc
|
| 12 |
+
import importlib.util
|
| 13 |
+
import json
|
| 14 |
+
import os
|
| 15 |
+
import queue
|
| 16 |
+
import subprocess
|
| 17 |
+
import sys
|
| 18 |
+
import threading
|
| 19 |
+
|
| 20 |
+
import numpy as np
|
| 21 |
+
import torch
|
| 22 |
+
|
| 23 |
+
import comfy.model_management
|
| 24 |
+
import comfy.utils
|
| 25 |
+
import folder_paths
|
| 26 |
+
|
| 27 |
+
PACK = os.path.dirname(os.path.abspath(__file__))
|
| 28 |
+
LVNODES = os.path.dirname(PACK)
|
| 29 |
+
VENV_PYTHON = os.path.join(LVNODES, ".venv", "bin", "python")
|
| 30 |
+
WORKER_SCRIPT = os.path.join(PACK, "dflow_mlx_worker.py")
|
| 31 |
+
LOG = os.path.join(LVNODES, ".cache", "dflow-mlx", "worker.log")
|
| 32 |
+
FOLDER = "dflow"
|
| 33 |
+
NONE = "None"
|
| 34 |
+
CUSTOM_NODES_COPY = "custom_nodes/dflow_2b"
|
| 35 |
+
SOLVER_CHOICES = ["euler", "er_sde", "dpmpp_2m"]
|
| 36 |
+
|
| 37 |
+
if FOLDER not in folder_paths.folder_names_and_paths:
|
| 38 |
+
folder_paths.add_model_folder_path(FOLDER, os.path.join(folder_paths.models_dir, FOLDER))
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def _is_release(path):
|
| 42 |
+
return all(os.path.exists(os.path.join(path, n)) for n in ("model.safetensors", "config.json",
|
| 43 |
+
os.path.join("dflow", "__init__.py")))
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def _custom_nodes_copy():
|
| 47 |
+
"""dflow_2b downloaded as its README says (the repository is a custom-node folder): its weights are read from there."""
|
| 48 |
+
for base in folder_paths.get_folder_paths("custom_nodes"):
|
| 49 |
+
path = os.path.join(base, "dflow_2b")
|
| 50 |
+
if _is_release(path):
|
| 51 |
+
return path
|
| 52 |
+
return None
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def _model_folders():
|
| 56 |
+
names = [CUSTOM_NODES_COPY] if _custom_nodes_copy() else []
|
| 57 |
+
for base in folder_paths.get_folder_paths(FOLDER):
|
| 58 |
+
if os.path.isdir(base):
|
| 59 |
+
for name in sorted(os.listdir(base)):
|
| 60 |
+
if _is_release(os.path.join(base, name)) and name not in names:
|
| 61 |
+
names.append(name)
|
| 62 |
+
return names or [CUSTOM_NODES_COPY]
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def _model_dir(name, override):
|
| 66 |
+
if override and override.strip():
|
| 67 |
+
path = os.path.expanduser(override.strip())
|
| 68 |
+
if not _is_release(path):
|
| 69 |
+
raise FileNotFoundError(f"DFlow MLX: {path} is not a dflow_2b release folder (model.safetensors, config.json, "
|
| 70 |
+
"text_encoder/, dflow/).")
|
| 71 |
+
return path
|
| 72 |
+
if name == CUSTOM_NODES_COPY:
|
| 73 |
+
path = _custom_nodes_copy()
|
| 74 |
+
if path:
|
| 75 |
+
return path
|
| 76 |
+
for base in folder_paths.get_folder_paths(FOLDER):
|
| 77 |
+
path = os.path.join(base, name)
|
| 78 |
+
if _is_release(path):
|
| 79 |
+
return path
|
| 80 |
+
raise FileNotFoundError("DFlow MLX: no dflow_2b release folder found. Download it as its README says "
|
| 81 |
+
"(hf download data-archetype/dflow_2b --local-dir ComfyUI/custom_nodes/dflow_2b), put a copy "
|
| 82 |
+
f"in ComfyUI/models/{FOLDER}/, or set model_path.")
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
def _lora_file(name):
|
| 86 |
+
path = folder_paths.get_full_path("loras", name) if name and name != NONE else None
|
| 87 |
+
if path is None:
|
| 88 |
+
raise FileNotFoundError(f"DFlow MLX: the LoRA '{name}' isn't in models/loras.")
|
| 89 |
+
return path
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def _ensure_environment(node_id):
|
| 93 |
+
"""Set up the shared LVNodes MLX environment with LVNodes/install.py when it is missing, unfinished or out of date
|
| 94 |
+
(the first time: about 1.3 GB, a few minutes)."""
|
| 95 |
+
spec = importlib.util.spec_from_file_location("LVNodes_install", os.path.join(LVNODES, "install.py"))
|
| 96 |
+
installer = importlib.util.module_from_spec(spec)
|
| 97 |
+
spec.loader.exec_module(installer)
|
| 98 |
+
state = installer.setup_state()
|
| 99 |
+
if state == "ready":
|
| 100 |
+
return
|
| 101 |
+
if not installer.is_apple_silicon():
|
| 102 |
+
raise RuntimeError("DFlow MLX needs an Apple Silicon Mac.")
|
| 103 |
+
text = ("installing the MLX environment (first run only, about 1.3 GB)" if state == "missing"
|
| 104 |
+
else "updating the MLX environment")
|
| 105 |
+
_progress_text(text, node_id)
|
| 106 |
+
print(f"[DFlow MLX] {text}")
|
| 107 |
+
try:
|
| 108 |
+
installer.ensure_environment(log=print)
|
| 109 |
+
except Exception as e:
|
| 110 |
+
raise RuntimeError(f"DFlow MLX: setting up the MLX environment failed ({e}). Check the internet connection "
|
| 111 |
+
f"and run again; the details are in the ComfyUI log.") from e
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
def _progress_text(text, node_id):
|
| 115 |
+
try:
|
| 116 |
+
from server import PromptServer
|
| 117 |
+
PromptServer.instance.send_progress_text(text, node_id)
|
| 118 |
+
except Exception:
|
| 119 |
+
pass
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
def _next_run_uses_mlx():
|
| 123 |
+
"""True when the next run waiting in ComfyUI's queue also uses this sampler, e.g. the rest of a "Number of runs" batch:
|
| 124 |
+
the helper then keeps the model for it instead of loading it again."""
|
| 125 |
+
try:
|
| 126 |
+
from server import PromptServer
|
| 127 |
+
q = PromptServer.instance.prompt_queue
|
| 128 |
+
_, pending = (q.get_current_queue_volatile() if hasattr(q, "get_current_queue_volatile")
|
| 129 |
+
else q.get_current_queue())
|
| 130 |
+
if not pending:
|
| 131 |
+
return False
|
| 132 |
+
upcoming = min(pending, key=lambda item: item[0]) # queue items: (number, prompt_id, prompt, ...)
|
| 133 |
+
return any(isinstance(n, dict) and n.get("class_type") == "LVDFlowMLXSampler" for n in upcoming[2].values())
|
| 134 |
+
except Exception:
|
| 135 |
+
return False
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
class _Worker:
|
| 139 |
+
"""The MLX helper process: started on first use, reused across runs, stopped on interrupt or exit."""
|
| 140 |
+
|
| 141 |
+
def __init__(self):
|
| 142 |
+
self.proc = None
|
| 143 |
+
self.lines = None
|
| 144 |
+
self.lock = threading.Lock()
|
| 145 |
+
|
| 146 |
+
def _start(self, node_id=None):
|
| 147 |
+
_ensure_environment(node_id)
|
| 148 |
+
os.makedirs(os.path.dirname(LOG), exist_ok=True)
|
| 149 |
+
log = open(LOG, "a", buffering=1)
|
| 150 |
+
env = {k: v for k, v in os.environ.items() if k not in ("PYTHONPATH", "PYTHONHOME", "VIRTUAL_ENV")}
|
| 151 |
+
self.proc = subprocess.Popen([VENV_PYTHON, "-u", WORKER_SCRIPT], stdin=subprocess.PIPE, stdout=subprocess.PIPE,
|
| 152 |
+
stderr=log, cwd=PACK, env=env, text=True, bufsize=1)
|
| 153 |
+
self.lines = queue.Queue()
|
| 154 |
+
|
| 155 |
+
def pump(stream, q):
|
| 156 |
+
for line in stream:
|
| 157 |
+
q.put(line)
|
| 158 |
+
q.put(None)
|
| 159 |
+
|
| 160 |
+
threading.Thread(target=pump, args=(self.proc.stdout, self.lines), daemon=True).start()
|
| 161 |
+
msg = self._next(timeout=180)
|
| 162 |
+
if not msg or msg.get("event") != "ready":
|
| 163 |
+
self.stop()
|
| 164 |
+
raise RuntimeError(f"DFlow MLX: the helper didn't start; see {LOG}")
|
| 165 |
+
print(f"[DFlow MLX] helper ready (mlx {msg.get('mlx')})")
|
| 166 |
+
|
| 167 |
+
def _next(self, timeout):
|
| 168 |
+
try:
|
| 169 |
+
line = self.lines.get(timeout=timeout)
|
| 170 |
+
except queue.Empty:
|
| 171 |
+
return {}
|
| 172 |
+
return None if line is None else json.loads(line)
|
| 173 |
+
|
| 174 |
+
def stop(self):
|
| 175 |
+
if self.proc is not None and self.proc.poll() is None:
|
| 176 |
+
self.proc.kill()
|
| 177 |
+
try:
|
| 178 |
+
self.proc.wait(timeout=10)
|
| 179 |
+
except Exception:
|
| 180 |
+
pass
|
| 181 |
+
self.proc = None
|
| 182 |
+
|
| 183 |
+
def run(self, request, node_id=None):
|
| 184 |
+
with self.lock:
|
| 185 |
+
if self.proc is None or self.proc.poll() is not None:
|
| 186 |
+
self._start(node_id)
|
| 187 |
+
self.proc.stdin.write(json.dumps(request) + "\n")
|
| 188 |
+
self.proc.stdin.flush()
|
| 189 |
+
bar = None
|
| 190 |
+
while True:
|
| 191 |
+
if comfy.model_management.processing_interrupted():
|
| 192 |
+
self.stop() # ends the run immediately and frees all of its memory
|
| 193 |
+
comfy.model_management.throw_exception_if_processing_interrupted()
|
| 194 |
+
msg = self._next(timeout=0.25)
|
| 195 |
+
if msg == {}:
|
| 196 |
+
continue
|
| 197 |
+
if msg is None:
|
| 198 |
+
self.proc = None
|
| 199 |
+
raise RuntimeError(f"DFlow MLX: the helper stopped unexpectedly; see {LOG}")
|
| 200 |
+
event = msg.get("event")
|
| 201 |
+
if event == "progress":
|
| 202 |
+
if bar is None:
|
| 203 |
+
bar = comfy.utils.ProgressBar(msg["total"], node_id=node_id)
|
| 204 |
+
bar.update_absolute(msg["step"], msg["total"])
|
| 205 |
+
elif event == "phase":
|
| 206 |
+
_progress_text(msg.get("text", ""), node_id)
|
| 207 |
+
elif event == "done":
|
| 208 |
+
return msg
|
| 209 |
+
elif event == "error":
|
| 210 |
+
raise RuntimeError(f"DFlow MLX: {msg.get('message')} (details in {LOG})")
|
| 211 |
+
|
| 212 |
+
def unload(self, wait=60):
|
| 213 |
+
"""Free the model the helper keeps (keep_loaded), leaving the helper itself running."""
|
| 214 |
+
with self.lock:
|
| 215 |
+
if self.proc is None or self.proc.poll() is not None:
|
| 216 |
+
return
|
| 217 |
+
self.proc.stdin.write(json.dumps({"cmd": "unload"}) + "\n")
|
| 218 |
+
self.proc.stdin.flush()
|
| 219 |
+
for _ in range(int(wait / 0.25)):
|
| 220 |
+
msg = self._next(timeout=0.25)
|
| 221 |
+
if msg is None:
|
| 222 |
+
self.proc = None
|
| 223 |
+
return
|
| 224 |
+
if msg and msg.get("event") in ("done", "error"):
|
| 225 |
+
return
|
| 226 |
+
|
| 227 |
+
|
| 228 |
+
WORKER = _Worker()
|
| 229 |
+
atexit.register(WORKER.stop)
|
| 230 |
+
# LVNodes' "free models now" (POST /lvnodes/free, the App Mode toggle) also empties the helper
|
| 231 |
+
_keep = sys.modules.get("LVNodes_ComfyUI_Keep_Loaded")
|
| 232 |
+
if _keep is not None:
|
| 233 |
+
_keep.RELEASE_HOOKS.append(WORKER.unload)
|
| 234 |
+
|
| 235 |
+
DFLOW_MLX = "DFLOW_MLX"
|
| 236 |
+
|
| 237 |
+
|
| 238 |
+
class LVDFlowMLXModel:
|
| 239 |
+
CATEGORY = "sampling/DFlow MLX"
|
| 240 |
+
RETURN_TYPES = (DFLOW_MLX,)
|
| 241 |
+
RETURN_NAMES = ("model",)
|
| 242 |
+
FUNCTION = "pick"
|
| 243 |
+
DESCRIPTION = ("Which dflow_2b the MLX sampler runs: the release folder (as downloaded into custom_nodes/dflow_2b, or "
|
| 244 |
+
"a copy in models/dflow), with an optional LoRA (e.g. the DFlow2 4-step LoRA) and the precision. "
|
| 245 |
+
"Nothing loads here; DFlow Sampler (MLX) loads it when it runs.")
|
| 246 |
+
|
| 247 |
+
@classmethod
|
| 248 |
+
def INPUT_TYPES(cls):
|
| 249 |
+
return {
|
| 250 |
+
"required": {
|
| 251 |
+
"model": (_model_folders(), {"tooltip": f"{CUSTOM_NODES_COPY}: the release as its README installs it (its "
|
| 252 |
+
f"own nodes run on CUDA only, but its weights and prompt rules are read from there). Or a "
|
| 253 |
+
f"release folder copied into ComfyUI/models/{FOLDER}."}),
|
| 254 |
+
"lora_name": ([NONE] + folder_paths.get_filename_list("loras"), {"default": NONE, "tooltip":
|
| 255 |
+
"A LoRA for dflow_2b in models/loras, applied beside the weights (not merged). For the "
|
| 256 |
+
"DFlow2 4-step LoRA: 4 steps, guidance 1, euler."}),
|
| 257 |
+
"lora_strength": ("FLOAT", {"default": 1.0, "min": -2.0, "max": 3.0, "step": 0.05,
|
| 258 |
+
"tooltip": "1.0 = as trained; 0 = off."}),
|
| 259 |
+
"precision": (["float16", "bfloat16"], {"default": "float16", "tooltip": "float16: the attention and MLP "
|
| 260 |
+
"layers compute in float16 (faster on Apple GPUs; the weights stay bfloat16). bfloat16: "
|
| 261 |
+
"the release's own precision throughout."}),
|
| 262 |
+
},
|
| 263 |
+
"optional": {
|
| 264 |
+
"keep_loaded": ("BOOLEAN", {"default": False, "tooltip": "Keep the model in memory after the last run "
|
| 265 |
+
"too, so the next run you start skips loading. Off still keeps it between the runs of a "
|
| 266 |
+
"batch and frees it after the last one."}),
|
| 267 |
+
"model_path": ("STRING", {"default": "", "tooltip": "An absolute dflow_2b release folder; overrides "
|
| 268 |
+
"model."}),
|
| 269 |
+
},
|
| 270 |
+
}
|
| 271 |
+
|
| 272 |
+
@classmethod
|
| 273 |
+
def VALIDATE_INPUTS(cls, model=None, lora_name=None):
|
| 274 |
+
return True # the sampler checks the files a run uses
|
| 275 |
+
|
| 276 |
+
def pick(self, model, lora_name=NONE, lora_strength=1.0, precision="float16", keep_loaded=False, model_path=""):
|
| 277 |
+
return ({"model": model, "model_path": model_path or "", "lora_name": lora_name,
|
| 278 |
+
"lora_strength": float(lora_strength), "precision": precision, "keep_loaded": bool(keep_loaded)},)
|
| 279 |
+
|
| 280 |
+
|
| 281 |
+
class LVDFlowMLXSampler:
|
| 282 |
+
CATEGORY = "sampling/DFlow MLX"
|
| 283 |
+
RETURN_TYPES = ("IMAGE",)
|
| 284 |
+
FUNCTION = "sample"
|
| 285 |
+
DESCRIPTION = ("dflow_2b on Apple MLX: the model from DFlow Model (MLX), a prompt or one of dflow's JSON layouts, size, "
|
| 286 |
+
"steps, seed, path-drop guidance and solver, sampled as the release does. The release's default: 50 "
|
| 287 |
+
"steps, guidance 2.5, er_sde. With the DFlow2 4-step LoRA: 4 steps, guidance 1, euler.")
|
| 288 |
+
|
| 289 |
+
@classmethod
|
| 290 |
+
def INPUT_TYPES(cls):
|
| 291 |
+
return {
|
| 292 |
+
"required": {
|
| 293 |
+
"model": (DFLOW_MLX, {"tooltip": "From DFlow Model (MLX)."}),
|
| 294 |
+
"prompt": ("STRING", {"multiline": True, "default": "", "tooltip": "A prompt, or one of dflow's JSON "
|
| 295 |
+
"layouts (summary and items with box_2d), compiled at the image size. (phrase:weight) marks "
|
| 296 |
+
"emphasis."}),
|
| 297 |
+
"width": ("INT", {"default": 832, "min": 256, "max": 4096, "step": 16}),
|
| 298 |
+
"height": ("INT", {"default": 1216, "min": 256, "max": 4096, "step": 16}),
|
| 299 |
+
"steps": ("INT", {"default": 4, "min": 1, "max": 200, "tooltip": "4 with the DFlow2 4-step LoRA; the "
|
| 300 |
+
"release's default is 50."}),
|
| 301 |
+
"seed": ("INT", {"default": 0, "min": 0, "max": 0xffffffffffffffff, "control_after_generate": True,
|
| 302 |
+
"tooltip": "The release's own noise for the seed (torch's CPU generator), so a seed "
|
| 303 |
+
"composes the same picture as dflow's PyTorch nodes."}),
|
| 304 |
+
"guidance": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.1, "round": 0.01, "tooltip":
|
| 305 |
+
"Path-drop guidance scale. 1 = off (one model pass a step): the DFlow2 4-step LoRA. 2.5 = "
|
| 306 |
+
"the release's default (two passes a step)."}),
|
| 307 |
+
"solver": (SOLVER_CHOICES, {"default": "euler", "tooltip": "euler: the DFlow2 4-step LoRA's. er_sde: "
|
| 308 |
+
"the release's default. dpmpp_2m: deterministic."}),
|
| 309 |
+
},
|
| 310 |
+
"optional": {
|
| 311 |
+
"self_attention_gain": ("FLOAT", {"default": -1.0, "min": -1.0, "max": 0.1, "step": 0.001, "tooltip":
|
| 312 |
+
"-1 = automatic: the release manual's gain for the image size (-0.03 up to about "
|
| 313 |
+
"1 MP, toward 0 above; the 4-step LoRA was trained with it). Or a fixed gain."}),
|
| 314 |
+
},
|
| 315 |
+
"hidden": {"unique_id": "UNIQUE_ID"},
|
| 316 |
+
}
|
| 317 |
+
|
| 318 |
+
def sample(self, model, prompt, width, height, steps, seed, guidance=1.0, solver="euler", self_attention_gain=-1.0,
|
| 319 |
+
unique_id=None):
|
| 320 |
+
m = model
|
| 321 |
+
loras = []
|
| 322 |
+
if m["lora_name"] not in (None, "", NONE) and m["lora_strength"]:
|
| 323 |
+
loras.append([_lora_file(m["lora_name"]), m["lora_strength"]])
|
| 324 |
+
request = {
|
| 325 |
+
"cmd": "generate", "model_dir": _model_dir(m["model"], m["model_path"]), "loras": loras,
|
| 326 |
+
"precision": m["precision"], "prompt": prompt or "", "width": int(width) // 16 * 16,
|
| 327 |
+
"height": int(height) // 16 * 16, "steps": int(steps), "seed": int(seed), "guidance": float(guidance),
|
| 328 |
+
"solver": solver, "gain": None if self_attention_gain is None or self_attention_gain <= -1.0
|
| 329 |
+
else float(self_attention_gain),
|
| 330 |
+
# kept for the next run of a batch (same settings reuse it), freed after the last one unless keep_loaded
|
| 331 |
+
"keep_loaded": m["keep_loaded"] or _next_run_uses_mlx(),
|
| 332 |
+
}
|
| 333 |
+
# ComfyUI's own models are not needed: the helper encodes the prompt itself. Free them before it loads dflow_2b,
|
| 334 |
+
# so only one stage is in memory at a time.
|
| 335 |
+
comfy.model_management.unload_all_models()
|
| 336 |
+
comfy.model_management.soft_empty_cache()
|
| 337 |
+
gc.collect()
|
| 338 |
+
msg = WORKER.run(request, node_id=unique_id)
|
| 339 |
+
image = np.load(msg["path"])
|
| 340 |
+
try:
|
| 341 |
+
os.remove(msg["path"])
|
| 342 |
+
except OSError:
|
| 343 |
+
pass
|
| 344 |
+
return (torch.from_numpy(image.astype(np.float32) / 255.0).unsqueeze(0),)
|
| 345 |
+
|
| 346 |
+
|
| 347 |
+
NODE_CLASS_MAPPINGS = {"LVDFlowMLXModel": LVDFlowMLXModel, "LVDFlowMLXSampler": LVDFlowMLXSampler}
|
| 348 |
+
NODE_DISPLAY_NAME_MAPPINGS = {"LVDFlowMLXModel": "DFlow Model (MLX)", "LVDFlowMLXSampler": "DFlow Sampler (MLX)"}
|
LVNodes/ComfyUI-DFlow-MLX/dflow_mlx/__init__.py
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""dflow_2b (Data Archetype) on Apple MLX: the denoiser (transformer.py), the text path (text.py), dinac3_96's decoder
|
| 2 |
+
(vae.py), unmerged LoRAs (lora.py), float16 compute (fp16.py), the schedule and solvers (family.py) and one render
|
| 3 |
+
(pipeline.py). It reads the release folder (https://huggingface.co/data-archetype/dflow_2b) as it is: no conversion."""
|
LVNodes/ComfyUI-DFlow-MLX/dflow_mlx/family.py
ADDED
|
@@ -0,0 +1,331 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""dflow_2b (Data Archetype) on MLX: the constants, the sampler's schedule and the solvers' arithmetic, in float32 numpy,
|
| 2 |
+
operation for operation as the release's own package (dflow/schedules.py, solvers.py, guidance.py).
|
| 3 |
+
|
| 4 |
+
The model folder (https://huggingface.co/data-archetype/dflow_2b) ships the authors' package, dflow/ (GPL-3.0-only, CUDA
|
| 5 |
+
only). Its torch-free modules (tokenization, layout, prompt_emphasis) are imported from the folder at run time under a
|
| 6 |
+
private name (reference_module), so the prompt rules are the release's own. The autoencoder is data-archetype/dinac3_96 at
|
| 7 |
+
the commit the package pins (VAE_REVISION): a dinac3_96 folder inside the model folder, or the Hugging Face cache
|
| 8 |
+
(downloaded on first use, as the release's own loader does).
|
| 9 |
+
|
| 10 |
+
Conventions (dflow/modeling.py): x_t = (1 - t) x0 + t eps with t = 1 pure noise; the model returns v = eps - x0, so
|
| 11 |
+
x0 = x_t - t v.
|
| 12 |
+
"""
|
| 13 |
+
from __future__ import annotations
|
| 14 |
+
|
| 15 |
+
import importlib
|
| 16 |
+
import importlib.util
|
| 17 |
+
import math
|
| 18 |
+
import os
|
| 19 |
+
import sys
|
| 20 |
+
import threading
|
| 21 |
+
|
| 22 |
+
import numpy as np
|
| 23 |
+
|
| 24 |
+
VAE_REPOSITORY = "data-archetype/dinac3_96"
|
| 25 |
+
VAE_REVISION = "d0ca36daa3e429a510ba465a5f7f8139c66d2f82"
|
| 26 |
+
VAE_FOLDER_NAME = "dinac3_96"
|
| 27 |
+
LATENT_CHANNELS = 96
|
| 28 |
+
LATENT_STRIDE = 16
|
| 29 |
+
#: the release's default preset (dflow/inference.py, guidance.py, schedules.py, solvers.py)
|
| 30 |
+
DEFAULT_WIDTH, DEFAULT_HEIGHT = 832, 1216
|
| 31 |
+
DEFAULT_STEPS = 50
|
| 32 |
+
DEFAULT_PDG_SCALE = 2.5
|
| 33 |
+
DEFAULT_SUFFIX_CAPTION_BIAS = -4.0
|
| 34 |
+
DEFAULT_SELF_ATTENTION_GAIN = -0.03
|
| 35 |
+
TRAINING_BASE_LOG_SNR_SHIFT = -0.25
|
| 36 |
+
RESOLUTION_SHIFT_REFERENCE = 256
|
| 37 |
+
FINITE_NOISY_ENDPOINT_EPSILON = 1.0e-4
|
| 38 |
+
BETA_1_25_SHAPE = 1.25
|
| 39 |
+
DEFAULT_NOISE_SCALE = 1.0
|
| 40 |
+
#: a PDG scale this close to 1 skips the path-drop forward (guidance.py _NEUTRAL_SCALE_TOLERANCE)
|
| 41 |
+
NEUTRAL_SCALE_TOLERANCE = 1.0e-6
|
| 42 |
+
#: the learned tokens after every prompt (types.SUFFIX_TOKEN_COUNT); the longest prompt trained (tokenization.py)
|
| 43 |
+
SUFFIX_TOKEN_COUNT = 3
|
| 44 |
+
MAX_PROMPT_TOKENS = 6144
|
| 45 |
+
#: the RoPE capacity (config.json rope_axes_lens): text positions below 8192, a token grid of at most 512 x 512
|
| 46 |
+
ROPE_AXES_LENS = (8192, 512, 512)
|
| 47 |
+
#: the manual's self-attention-gain table: -0.03 up to ~1.05 MP, then linear in log(area) to 0 at ~2.5 MP
|
| 48 |
+
GAIN_FULL_AREA = 1.05e6
|
| 49 |
+
GAIN_ZERO_AREA = 2.5e6
|
| 50 |
+
EMPTY_PROMPT_ERROR = "dflow: please enter a prompt (the release turns empty prompts off: config.json inference.allow_empty_prompt)"
|
| 51 |
+
SOLVERS = ("er_sde", "euler", "dpmpp_2m")
|
| 52 |
+
|
| 53 |
+
_REF_PACKAGE = "_dflow_reference"
|
| 54 |
+
_REF_LOCK = threading.Lock()
|
| 55 |
+
#: the reference modules that import without torch (the rest of the package needs torch and CUDA)
|
| 56 |
+
_TORCH_FREE = ("tokenization", "layout", "prompt_emphasis", "version")
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def vae_folder(model_path: str) -> str:
|
| 60 |
+
"""dinac3_96: a folder of that name inside the model folder, else the Hugging Face cache at the pinned revision
|
| 61 |
+
(downloaded on first use, about 320 MB)."""
|
| 62 |
+
folder = os.path.join(os.path.abspath(str(model_path)), VAE_FOLDER_NAME)
|
| 63 |
+
if all(os.path.isfile(os.path.join(folder, n)) for n in ("config.json", "model.safetensors")):
|
| 64 |
+
return folder
|
| 65 |
+
from huggingface_hub import snapshot_download
|
| 66 |
+
return snapshot_download(VAE_REPOSITORY, revision=VAE_REVISION, allow_patterns=["config.json", "model.safetensors",
|
| 67 |
+
"LICENSE*", "README*"])
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def reference_module(model_path: str, name: str):
|
| 71 |
+
"""A torch-free module of the authors' dflow package in the model folder (tokenization, layout, prompt_emphasis,
|
| 72 |
+
version), imported under a private package name so it never clashes with anything installed. Relative imports
|
| 73 |
+
inside the package resolve against the same private name."""
|
| 74 |
+
if name not in _TORCH_FREE:
|
| 75 |
+
raise ValueError(f"dflow reference module {name!r} needs torch and CUDA; only {_TORCH_FREE} are read")
|
| 76 |
+
package_dir = os.path.join(os.path.abspath(str(model_path)), "dflow")
|
| 77 |
+
init = os.path.join(package_dir, "__init__.py")
|
| 78 |
+
if not os.path.isfile(init):
|
| 79 |
+
raise FileNotFoundError(f"dflow: no dflow/ package in {model_path}: the release folder ships it (tokenizer rules, "
|
| 80 |
+
"layouts, prompt emphasis)")
|
| 81 |
+
with _REF_LOCK:
|
| 82 |
+
module = sys.modules.get(_REF_PACKAGE)
|
| 83 |
+
if module is None or os.path.realpath(module.__file__ or "") != os.path.realpath(init):
|
| 84 |
+
for key in [k for k in sys.modules if k == _REF_PACKAGE or k.startswith(_REF_PACKAGE + ".")]:
|
| 85 |
+
del sys.modules[key]
|
| 86 |
+
spec = importlib.util.spec_from_file_location(_REF_PACKAGE, init, submodule_search_locations=[package_dir])
|
| 87 |
+
module = importlib.util.module_from_spec(spec)
|
| 88 |
+
sys.modules[_REF_PACKAGE] = module
|
| 89 |
+
spec.loader.exec_module(module)
|
| 90 |
+
return importlib.import_module(f"{_REF_PACKAGE}.{name}")
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
def check_size(width: int, height: int) -> None:
|
| 94 |
+
"""Multiples of 16 within the RoPE grid (512 tokens a side = 8192 px)."""
|
| 95 |
+
for name, value in (("width", width), ("height", height)):
|
| 96 |
+
if value <= 0 or value % LATENT_STRIDE:
|
| 97 |
+
raise ValueError(f"dflow: {name} {value}: width and height must be positive multiples of {LATENT_STRIDE}")
|
| 98 |
+
if width // LATENT_STRIDE > ROPE_AXES_LENS[2] or height // LATENT_STRIDE > ROPE_AXES_LENS[1]:
|
| 99 |
+
raise ValueError(f"dflow: {width}x{height} is past the RoPE grid ({ROPE_AXES_LENS[2] * LATENT_STRIDE} px a side)")
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
def auto_self_attention_gain(width: int, height: int) -> float:
|
| 103 |
+
"""The main pass's self-attention gain for an image size, from the manual's table: -0.03 (the release default) up
|
| 104 |
+
to ~1.05 MP, then linear in log(area) to 0 at ~2.5 MP (1824x1024 -> -0.0101)."""
|
| 105 |
+
area = float(width) * float(height)
|
| 106 |
+
if area <= GAIN_FULL_AREA:
|
| 107 |
+
return DEFAULT_SELF_ATTENTION_GAIN
|
| 108 |
+
frac = math.log(area / GAIN_FULL_AREA) / math.log(GAIN_ZERO_AREA / GAIN_FULL_AREA)
|
| 109 |
+
return DEFAULT_SELF_ATTENTION_GAIN * max(0.0, 1.0 - frac)
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
# ββ the schedule (dflow/schedules.py, float32) ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 113 |
+
|
| 114 |
+
def resolution_log_snr_shift(width: int, height: int, base: float = TRAINING_BASE_LOG_SNR_SHIFT) -> float:
|
| 115 |
+
"""min(0, base - ln(W H / 256^2)): the shift the model was trained with at a size (-2.99 at 832 x 1216)."""
|
| 116 |
+
term = -math.log((width * height) / float(RESOLUTION_SHIFT_REFERENCE * RESOLUTION_SHIFT_REFERENCE))
|
| 117 |
+
return min(0.0, float(base) + term)
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
def _linspace01_f32(points: int) -> np.ndarray:
|
| 121 |
+
"""torch.linspace(0, 1, points, dtype=float32) by its CPU kernel's formula: start + step * i below the halfway
|
| 122 |
+
point, end - step * (points - 1 - i) from it, in float32."""
|
| 123 |
+
if points == 1:
|
| 124 |
+
return np.zeros(1, np.float32)
|
| 125 |
+
step = np.float32(1.0) / np.float32(points - 1)
|
| 126 |
+
idx = np.arange(points)
|
| 127 |
+
half = points // 2
|
| 128 |
+
out = np.empty(points, np.float32)
|
| 129 |
+
lo = idx < half
|
| 130 |
+
out[lo] = np.float32(0.0) + step * idx[lo].astype(np.float32)
|
| 131 |
+
out[~lo] = np.float32(1.0) - step * (points - 1 - idx[~lo]).astype(np.float32)
|
| 132 |
+
return out
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
def _betainc(a: float, b: float, x: float) -> float:
|
| 136 |
+
"""The regularized incomplete beta function I_x(a, b) (a continued fraction, Lentz's method), float64."""
|
| 137 |
+
if x <= 0.0:
|
| 138 |
+
return 0.0
|
| 139 |
+
if x >= 1.0:
|
| 140 |
+
return 1.0
|
| 141 |
+
ln_front = math.lgamma(a + b) - math.lgamma(a) - math.lgamma(b) + a * math.log(x) + b * math.log1p(-x)
|
| 142 |
+
if x > (a + 1.0) / (a + b + 2.0):
|
| 143 |
+
return 1.0 - _betainc(b, a, 1.0 - x)
|
| 144 |
+
tiny = 1.0e-300
|
| 145 |
+
c, d = 1.0, 1.0 - (a + b) * x / (a + 1.0)
|
| 146 |
+
d = 1.0 / (d if abs(d) > tiny else tiny)
|
| 147 |
+
f = d
|
| 148 |
+
for m in range(1, 400):
|
| 149 |
+
m2 = 2 * m
|
| 150 |
+
num = m * (b - m) * x / ((a + m2 - 1.0) * (a + m2))
|
| 151 |
+
d = 1.0 + num * d
|
| 152 |
+
d = 1.0 / (d if abs(d) > tiny else tiny)
|
| 153 |
+
c = 1.0 + num / c
|
| 154 |
+
c = c if abs(c) > tiny else tiny
|
| 155 |
+
f *= d * c
|
| 156 |
+
num = -(a + m) * (a + b + m) * x / ((a + m2) * (a + m2 + 1.0))
|
| 157 |
+
d = 1.0 + num * d
|
| 158 |
+
d = 1.0 / (d if abs(d) > tiny else tiny)
|
| 159 |
+
c = 1.0 + num / c
|
| 160 |
+
c = c if abs(c) > tiny else tiny
|
| 161 |
+
delta = d * c
|
| 162 |
+
f *= delta
|
| 163 |
+
if abs(delta - 1.0) < 1.0e-15:
|
| 164 |
+
break
|
| 165 |
+
return math.exp(ln_front) * f / a
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
def _beta_ppf(q: float, a: float, b: float) -> float:
|
| 169 |
+
"""The Beta(a, b) quantile by bisection on _betainc (float64, to ~1e-15), for environments without scipy."""
|
| 170 |
+
if q <= 0.0:
|
| 171 |
+
return 0.0
|
| 172 |
+
if q >= 1.0:
|
| 173 |
+
return 1.0
|
| 174 |
+
lo, hi = 0.0, 1.0
|
| 175 |
+
for _ in range(200):
|
| 176 |
+
mid = 0.5 * (lo + hi)
|
| 177 |
+
if _betainc(a, b, mid) < q:
|
| 178 |
+
lo = mid
|
| 179 |
+
else:
|
| 180 |
+
hi = mid
|
| 181 |
+
if hi - lo < 1.0e-16:
|
| 182 |
+
break
|
| 183 |
+
return 0.5 * (lo + hi)
|
| 184 |
+
|
| 185 |
+
|
| 186 |
+
def _ascending_base(steps: int) -> np.ndarray:
|
| 187 |
+
"""The unshifted ascending float32 grid of steps + 1 points: Beta(1.25, 1.25) quantiles of an even grid."""
|
| 188 |
+
grid = _linspace01_f32(steps + 1)
|
| 189 |
+
try:
|
| 190 |
+
from scipy import stats
|
| 191 |
+
values = stats.beta.ppf(grid.astype(np.float64), BETA_1_25_SHAPE, BETA_1_25_SHAPE)
|
| 192 |
+
except ImportError:
|
| 193 |
+
values = [_beta_ppf(float(q), BETA_1_25_SHAPE, BETA_1_25_SHAPE) for q in grid.astype(np.float64)]
|
| 194 |
+
values = np.asarray(values, dtype=np.float32)
|
| 195 |
+
if not np.isfinite(values).all():
|
| 196 |
+
raise RuntimeError("Beta(1.25, 1.25) quantiles are not finite")
|
| 197 |
+
return values
|
| 198 |
+
|
| 199 |
+
|
| 200 |
+
def apply_log_snr_shift(times: np.ndarray, shift: float) -> np.ndarray:
|
| 201 |
+
"""sigmoid(logit(t) - shift / 2) on the interior points in float32; exact 0 and 1 kept."""
|
| 202 |
+
t = np.asarray(times, np.float32)
|
| 203 |
+
if abs(shift) <= 1.0e-9:
|
| 204 |
+
return t
|
| 205 |
+
eps = np.finfo(np.float32).eps
|
| 206 |
+
clamped = np.clip(t, np.float32(max(float(np.finfo(np.float32).tiny), 1.0e-12)), np.float32(1.0 - float(eps)))
|
| 207 |
+
with np.errstate(divide="ignore", over="ignore"):
|
| 208 |
+
logit = np.log(clamped / (np.float32(1.0) - clamped)).astype(np.float32)
|
| 209 |
+
shifted = (np.float32(1.0) / (np.float32(1.0) + np.exp(-(logit - np.float32(0.5 * shift))))).astype(np.float32)
|
| 210 |
+
shifted = np.where(t == 0.0, np.float32(0.0), shifted)
|
| 211 |
+
return np.where(t == 1.0, np.float32(1.0), shifted).astype(np.float32)
|
| 212 |
+
|
| 213 |
+
|
| 214 |
+
def cap_noisy_endpoint(descending: np.ndarray) -> np.ndarray:
|
| 215 |
+
"""An exact t = 1 start becomes 1 - 1e-4 (or the next float above its neighbour when that is closer to 1): the
|
| 216 |
+
log-SNR solvers need a finite start."""
|
| 217 |
+
d = np.asarray(descending, np.float32).copy()
|
| 218 |
+
if float(d[0]) != 1.0:
|
| 219 |
+
return d
|
| 220 |
+
candidate = np.float32(1.0 - FINITE_NOISY_ENDPOINT_EPSILON)
|
| 221 |
+
if len(d) > 1 and float(d[1]) >= float(candidate):
|
| 222 |
+
candidate = np.nextafter(d[1], np.float32(1.0), dtype=np.float32)
|
| 223 |
+
if float(candidate) >= 1.0:
|
| 224 |
+
raise ValueError("dflow: no finite noisy endpoint fits below t = 1: lower the steps or the shift")
|
| 225 |
+
d[0] = candidate
|
| 226 |
+
return d
|
| 227 |
+
|
| 228 |
+
|
| 229 |
+
def build_timesteps(steps: int, log_snr_shift: float, finite_noisy_endpoint: bool = True) -> np.ndarray:
|
| 230 |
+
"""The descending float32 schedule of steps + 1 times ending at 0 (build_timesteps: grid, shift, flip, cap)."""
|
| 231 |
+
if int(steps) < 1:
|
| 232 |
+
raise ValueError(f"dflow: {steps} steps: at least 1")
|
| 233 |
+
desc = apply_log_snr_shift(_ascending_base(int(steps)), log_snr_shift)[::-1].copy()
|
| 234 |
+
return cap_noisy_endpoint(desc) if finite_noisy_endpoint else desc
|
| 235 |
+
|
| 236 |
+
|
| 237 |
+
# ββ the solvers' coefficients (dflow/solvers.py, the same float32 operations) ββββββββββββββββββββββββββββββββββββββββ
|
| 238 |
+
|
| 239 |
+
def _f32(x) -> np.float32:
|
| 240 |
+
return np.float32(x)
|
| 241 |
+
|
| 242 |
+
|
| 243 |
+
def _er_scaler(lam: np.float32) -> np.float32:
|
| 244 |
+
"""l (exp(l^0.3) + 10): ER-SDE's noise-scaling function."""
|
| 245 |
+
return _f32(lam * _f32(np.exp(_f32(np.power(lam, _f32(0.3)))) + _f32(10.0)))
|
| 246 |
+
|
| 247 |
+
|
| 248 |
+
def er_sde_plan(times: np.ndarray, noise_scale: float = DEFAULT_NOISE_SCALE) -> list:
|
| 249 |
+
"""Per update i of the third-stage ER-SDE, the float32 scalars of
|
| 250 |
+
x' = c_state x + c_den x0 [+ c_d1 d1 [+ c_d2 d2]] + c_noise z,
|
| 251 |
+
d1 = (x0 - x0_prev) / d1_div, d2 = (d1 - d1_prev) / d2_div,
|
| 252 |
+
or None for a last update that lands on t = 0 (x' = x0). Mirrors _er_sde_step's tensor arithmetic in float32."""
|
| 253 |
+
t = np.asarray(times, np.float32)
|
| 254 |
+
with np.errstate(divide="ignore"):
|
| 255 |
+
half_log_snr = (np.log1p(-t).astype(np.float32) - np.log(t).astype(np.float32)).astype(np.float32)
|
| 256 |
+
lam = np.exp(-half_log_snr).astype(np.float32)
|
| 257 |
+
nodes64, weights64 = np.polynomial.legendre.leggauss(16)
|
| 258 |
+
nodes, weights = nodes64.astype(np.float32), weights64.astype(np.float32)
|
| 259 |
+
plan = []
|
| 260 |
+
has_derivative = False
|
| 261 |
+
for i in range(len(t) - 1):
|
| 262 |
+
if float(t[i + 1]) == 0.0:
|
| 263 |
+
plan.append(None)
|
| 264 |
+
continue
|
| 265 |
+
ls, lt = lam[i], lam[i + 1]
|
| 266 |
+
alpha_s = _f32(t[i] / ls)
|
| 267 |
+
alpha_t = _f32(t[i + 1] / lt)
|
| 268 |
+
noise_t = _er_scaler(lt)
|
| 269 |
+
ratio = _f32(noise_t / _er_scaler(ls))
|
| 270 |
+
step = {"c_state": float(_f32(_f32(alpha_t / alpha_s) * ratio)),
|
| 271 |
+
"c_den": float(_f32(alpha_t * _f32(_f32(1.0) - ratio))),
|
| 272 |
+
"c_d1": None, "d1_div": None, "c_d2": None, "d2_div": None, "c_noise": 0.0}
|
| 273 |
+
stage = min(3, i + 1)
|
| 274 |
+
if stage >= 2:
|
| 275 |
+
midpoint = _f32(_f32(ls + lt) / _f32(2.0))
|
| 276 |
+
half_span = _f32(_f32(ls - lt) / _f32(2.0))
|
| 277 |
+
positions = (midpoint + half_span * nodes).astype(np.float32)
|
| 278 |
+
scaled = (positions * (np.exp(np.power(positions, np.float32(0.3))).astype(np.float32)
|
| 279 |
+
+ np.float32(10.0))).astype(np.float32)
|
| 280 |
+
second = _f32(half_span * _f32(np.sum((weights / scaled).astype(np.float32), dtype=np.float32)))
|
| 281 |
+
third = _f32(half_span * _f32(np.sum((weights * (positions - ls) / scaled).astype(np.float32),
|
| 282 |
+
dtype=np.float32)))
|
| 283 |
+
delta = _f32(lt - ls)
|
| 284 |
+
step["d1_div"] = float(_f32(ls - lam[i - 1]))
|
| 285 |
+
step["c_d1"] = float(_f32(alpha_t * _f32(delta + _f32(second * noise_t))))
|
| 286 |
+
if stage >= 3 and has_derivative:
|
| 287 |
+
step["d2_div"] = float(_f32(_f32(ls - lam[i - 2]) / _f32(2.0)))
|
| 288 |
+
step["c_d2"] = float(_f32(alpha_t * _f32(_f32(_f32(delta * delta) / _f32(2.0))
|
| 289 |
+
+ _f32(third * noise_t))))
|
| 290 |
+
if noise_scale > 0.0:
|
| 291 |
+
variance = _f32(_f32(lt * lt) - _f32(_f32(ls * ls) * _f32(ratio * ratio)))
|
| 292 |
+
stochastic = _f32(alpha_t * _f32(np.sqrt(max(variance, _f32(0.0)))))
|
| 293 |
+
step["c_noise"] = float(_f32(_f32(noise_scale) * stochastic))
|
| 294 |
+
has_derivative = step["c_d1"] is not None
|
| 295 |
+
plan.append(step)
|
| 296 |
+
return plan
|
| 297 |
+
|
| 298 |
+
|
| 299 |
+
def dpmpp_2m_plan(times: np.ndarray) -> list:
|
| 300 |
+
"""Per update i of DPM++ 2M in half-log-SNR: (sigma_ratio, coefficient, extrapolation weights a, b with
|
| 301 |
+
x0_ext = a x0 - b x0_prev or None on the first update), float32 scalars from the float64 lambdas as
|
| 302 |
+
_dpmpp_2m_update computes them; None for a last update that lands on t = 0."""
|
| 303 |
+
t32 = np.asarray(times, np.float32)
|
| 304 |
+
t64 = np.maximum(t32, np.finfo(np.float32).tiny).astype(np.float64)
|
| 305 |
+
lam = np.log1p(-t64) - np.log(t64)
|
| 306 |
+
for i in range(len(lam) - 1):
|
| 307 |
+
if float(t32[i + 1]) != 0.0 and lam[i + 1] - lam[i] <= 0.0:
|
| 308 |
+
raise ValueError("dflow dpmpp_2m: the schedule must raise half-log-SNR over every step")
|
| 309 |
+
|
| 310 |
+
def logsigmoid(x):
|
| 311 |
+
return -np.logaddexp(0.0, -x)
|
| 312 |
+
plan = []
|
| 313 |
+
for i in range(len(lam) - 1):
|
| 314 |
+
if float(t32[i + 1]) == 0.0:
|
| 315 |
+
plan.append(None)
|
| 316 |
+
continue
|
| 317 |
+
step = lam[i + 1] - lam[i]
|
| 318 |
+
ext = None
|
| 319 |
+
if i > 0:
|
| 320 |
+
ratio = (lam[i] - lam[i - 1]) / step
|
| 321 |
+
ext = (float(np.float32(1.0 + 1.0 / (2.0 * ratio))), float(np.float32(1.0 / (2.0 * ratio))))
|
| 322 |
+
sigma_ratio = float(np.float32(np.exp(logsigmoid(-lam[i + 1]) - logsigmoid(-lam[i]))))
|
| 323 |
+
alpha_next = np.float32(1.0 / (1.0 + np.exp(-lam[i + 1])))
|
| 324 |
+
coefficient = float(np.float32(np.float64(alpha_next) * (-np.expm1(-step))))
|
| 325 |
+
plan.append({"sigma_ratio": sigma_ratio, "coefficient": coefficient, "ext": ext})
|
| 326 |
+
return plan
|
| 327 |
+
|
| 328 |
+
|
| 329 |
+
def pdg_active(scale: float) -> bool:
|
| 330 |
+
"""Whether a PDG scale runs the path-drop reference forward (a scale within 1e-6 of 1 does not)."""
|
| 331 |
+
return not math.isclose(float(scale), 1.0, rel_tol=0.0, abs_tol=NEUTRAL_SCALE_TOLERANCE)
|
LVNodes/ComfyUI-DFlow-MLX/dflow_mlx/fp16.py
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""float16 compute for the dflow denoiser (the technique of mflux's ComputePrecision, #820): only the inside of the
|
| 2 |
+
attention and MLP modules runs in float16; the residual stream, the modulation, the norms between modules and the
|
| 3 |
+
embedders keep bfloat16, and a module's output is clipped to float16's range on its way back into the stream, so an
|
| 4 |
+
overflow stays local. Apple M1 / M2 GPUs compute float16 faster than bfloat16.
|
| 5 |
+
"""
|
| 6 |
+
from __future__ import annotations
|
| 7 |
+
|
| 8 |
+
import mlx.core as mx
|
| 9 |
+
|
| 10 |
+
#: float16's largest finite value
|
| 11 |
+
FP16_MAX = 65504.0
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def to_fp16(value):
|
| 15 |
+
"""A floating mx.array in float16; anything else unchanged."""
|
| 16 |
+
if isinstance(value, mx.array) and mx.issubdtype(value.dtype, mx.floating) and value.dtype != mx.float16:
|
| 17 |
+
return value.astype(mx.float16)
|
| 18 |
+
return value
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def cast_mask(mask):
|
| 22 |
+
"""An additive attention mask in float16: the usual -1e9 fill is past float16, so it is clamped to its lowest value."""
|
| 23 |
+
if mask is None or not isinstance(mask, mx.array) or mask.dtype in (mx.float16, mx.bool_):
|
| 24 |
+
return mask
|
| 25 |
+
return mx.maximum(mask, -FP16_MAX).astype(mx.float16)
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def to_stream(out, dtype):
|
| 29 |
+
"""A module's float16 output back to the residual stream's dtype, clipped to float16's range."""
|
| 30 |
+
return mx.clip(out, -FP16_MAX, FP16_MAX).astype(dtype)
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def cast_module(module) -> None:
|
| 34 |
+
"""A module's floating parameters (its LoRA adapters' down / up lists included) to float16 in place, evaluated before
|
| 35 |
+
returning, so the old weights are freed module by module."""
|
| 36 |
+
from mlx.utils import tree_map
|
| 37 |
+
module.update(tree_map(to_fp16, module.parameters()))
|
| 38 |
+
mx.eval(module.parameters())
|
LVNodes/ComfyUI-DFlow-MLX/dflow_mlx/lora.py
ADDED
|
@@ -0,0 +1,168 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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adapter in the run's
|
| 3 |
+
compute dtype (bfloat16; float32 in a float32 build).
|
| 4 |
+
|
| 5 |
+
The file layout (the same names as the release's model.safetensors): for a targeted nn.Linear
|
| 6 |
+
whose base weight key is "<K>.weight",
|
| 7 |
+
<K>.lora_down.weight [r, in] <K>.lora_up.weight [out, r] <K>.alpha (scalar) float32
|
| 8 |
+
with delta W = (alpha / r) up @ down. K is "denoiser.<module path>"; the bare path, ComfyUI's "diffusion_model." prefix
|
| 9 |
+
and PEFT's lora_A / lora_B names read the same way, and alpha defaults to the rank.
|
| 10 |
+
|
| 11 |
+
Every key must place: a module that is not a linear layer of the denoiser, a shape that does not match, a key of another
|
| 12 |
+
form or an adapter without its other half stops the run naming them (a LoRA trained for this model places fully; a part
|
| 13 |
+
of one applied would render neither the base nor the LoRA). The velocity head, which the final layer reads through its
|
| 14 |
+
weight instead of calling it, takes its delta merged in float32 (its stored dtype). The counts are logged at each load.
|
| 15 |
+
"""
|
| 16 |
+
from __future__ import annotations
|
| 17 |
+
|
| 18 |
+
import os
|
| 19 |
+
import re
|
| 20 |
+
|
| 21 |
+
import mlx.core as mx
|
| 22 |
+
import mlx.nn as nn
|
| 23 |
+
|
| 24 |
+
#: the key prefixes read as the denoiser's own module paths (the release file's, ComfyUI's)
|
| 25 |
+
PREFIXES = ("denoiser.", "model.diffusion_model.", "diffusion_model.")
|
| 26 |
+
_PART = re.compile(r"\.(lora_down|lora_up|lora_A|lora_B)\.weight$|\.(alpha)$")
|
| 27 |
+
_ROLE = {"lora_down": "down", "lora_A": "down", "lora_up": "up", "lora_B": "up", "alpha": "alpha"}
|
| 28 |
+
#: linear layers read through .weight / .bias by their caller (DFlowDenoiser._final), never called: merged
|
| 29 |
+
MERGED = ("velocity_head",)
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
class LoRALinear(nn.Module):
|
| 33 |
+
"""A release nn.Linear plus unmerged adapters: base(x) + sum_i s_i (x down_i^T) up_i^T, each adapter in its own dtype
|
| 34 |
+
(the run's compute dtype), rounded once to the output's."""
|
| 35 |
+
|
| 36 |
+
def __init__(self, base: nn.Linear, down: mx.array, up: mx.array, scale: float):
|
| 37 |
+
super().__init__()
|
| 38 |
+
self.base_layer = base
|
| 39 |
+
self.downs, self.ups, self.scales = [], [], []
|
| 40 |
+
self.add(down, up, scale)
|
| 41 |
+
|
| 42 |
+
def add(self, down: mx.array, up: mx.array, scale: float):
|
| 43 |
+
self.downs.append(down)
|
| 44 |
+
self.ups.append(up)
|
| 45 |
+
self.scales.append(float(scale))
|
| 46 |
+
|
| 47 |
+
@property
|
| 48 |
+
def weight(self):
|
| 49 |
+
return self.base_layer.weight
|
| 50 |
+
|
| 51 |
+
def __call__(self, x):
|
| 52 |
+
y = self.base_layer(x)
|
| 53 |
+
for down, up, scale in zip(self.downs, self.ups, self.scales):
|
| 54 |
+
delta = (x.astype(down.dtype) @ down.T) @ up.T
|
| 55 |
+
y = y + (delta * scale).astype(y.dtype)
|
| 56 |
+
return y
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def _child(obj, name: str):
|
| 60 |
+
if isinstance(obj, (list, tuple)):
|
| 61 |
+
return obj[int(name)] if name.isdigit() and int(name) < len(obj) else None
|
| 62 |
+
if isinstance(obj, dict): # an nn.Module is a dict as well
|
| 63 |
+
return obj.get(name)
|
| 64 |
+
return None
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def nav(root, path: str):
|
| 68 |
+
"""(parent, last, target) for a dotted path through modules and lists; (None, None, None) when absent."""
|
| 69 |
+
parts = path.split(".")
|
| 70 |
+
obj = root
|
| 71 |
+
for p in parts[:-1]:
|
| 72 |
+
obj = _child(obj, p)
|
| 73 |
+
if obj is None:
|
| 74 |
+
return None, None, None
|
| 75 |
+
target = _child(obj, parts[-1])
|
| 76 |
+
return (obj, parts[-1], target) if target is not None else (None, None, None)
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
def _put(parent, last: str, value):
|
| 80 |
+
if isinstance(parent, list):
|
| 81 |
+
parent[int(last)] = value
|
| 82 |
+
else:
|
| 83 |
+
parent[last] = value
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
def module_path(key_base: str) -> str:
|
| 87 |
+
"""A key without its role suffix -> the denoiser's module path ("denoiser.prefix_layers.0.attn.qkv" ->
|
| 88 |
+
"prefix_layers.0.attn.qkv")."""
|
| 89 |
+
for prefix in PREFIXES:
|
| 90 |
+
if key_base.startswith(prefix):
|
| 91 |
+
return key_base[len(prefix):]
|
| 92 |
+
return key_base
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
def group_keys(keys) -> tuple[dict, list]:
|
| 96 |
+
"""-> ({module path: {"down": key, "up": key[, "alpha": key]}}, the keys of another form)."""
|
| 97 |
+
groups, other = {}, []
|
| 98 |
+
for k in keys:
|
| 99 |
+
m = _PART.search(k)
|
| 100 |
+
if m is None:
|
| 101 |
+
other.append(k)
|
| 102 |
+
continue
|
| 103 |
+
role = _ROLE[m.group(1) or m.group(2)]
|
| 104 |
+
groups.setdefault(module_path(k[:m.start()]), {})[role] = k
|
| 105 |
+
return groups, other
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
def apply_lora_file(denoiser, path: str, weight: float = 1.0, dtype=mx.bfloat16, log=print) -> dict:
|
| 109 |
+
"""One LoRA file onto a DFlowDenoiser in place (a second LoRA on a layer stacks as another adapter) -> the counts.
|
| 110 |
+
Any key that does not place stops the run (an error naming it), before anything is applied."""
|
| 111 |
+
name = os.path.basename(str(path))
|
| 112 |
+
if not os.path.isfile(str(path)):
|
| 113 |
+
raise ValueError(f"dflow: LoRA file not found: {path}")
|
| 114 |
+
arrays = mx.load(str(path))
|
| 115 |
+
groups, other = group_keys(arrays)
|
| 116 |
+
unplaced, misshaped, half, plan = [], [], [], []
|
| 117 |
+
for p, parts in sorted(groups.items()):
|
| 118 |
+
if "down" not in parts or "up" not in parts:
|
| 119 |
+
half.append(p)
|
| 120 |
+
continue
|
| 121 |
+
parent, last, target = nav(denoiser, p)
|
| 122 |
+
base = target.base_layer if isinstance(target, LoRALinear) else target
|
| 123 |
+
if not isinstance(base, nn.Linear):
|
| 124 |
+
unplaced.append(p)
|
| 125 |
+
continue
|
| 126 |
+
down, up = arrays[parts["down"]], arrays[parts["up"]]
|
| 127 |
+
out_f, in_f = (int(s) for s in base.weight.shape)
|
| 128 |
+
rank = int(down.shape[0]) if down.ndim == 2 else 0
|
| 129 |
+
if (down.ndim != 2 or up.ndim != 2 or rank == 0 or int(down.shape[1]) != in_f
|
| 130 |
+
or tuple(int(s) for s in up.shape) != (out_f, rank)):
|
| 131 |
+
misshaped.append(f"{p}: down {tuple(down.shape)}, up {tuple(up.shape)} vs the weight {(out_f, in_f)}")
|
| 132 |
+
continue
|
| 133 |
+
alpha = float(arrays[parts["alpha"]].item()) if "alpha" in parts else float(rank)
|
| 134 |
+
plan.append((p, parent, last, target, base, down, up, rank, float(weight) * alpha / rank))
|
| 135 |
+
if other or unplaced or misshaped or half:
|
| 136 |
+
raise ValueError(
|
| 137 |
+
f"dflow: LoRA {name} does not fit dflow_2b's denoiser β nothing applied:"
|
| 138 |
+
+ (f"\n not a linear layer of the denoiser ({len(unplaced)}): {unplaced[:4]}" if unplaced else "")
|
| 139 |
+
+ (f"\n shape mismatch ({len(misshaped)}): {misshaped[:3]}" if misshaped else "")
|
| 140 |
+
+ (f"\n down without up or up without down ({len(half)}): {half[:4]}" if half else "")
|
| 141 |
+
+ (f"\n keys of another form ({len(other)}): {other[:4]}" if other else ""))
|
| 142 |
+
if not plan:
|
| 143 |
+
raise ValueError(f"dflow: LoRA {name} holds no adapters")
|
| 144 |
+
merged = 0
|
| 145 |
+
for p, parent, last, target, base, down, up, rank, scale in plan:
|
| 146 |
+
if p in MERGED:
|
| 147 |
+
w = base.weight
|
| 148 |
+
base.weight = (w.astype(mx.float32) + scale * (up.astype(mx.float32) @ down.astype(mx.float32))).astype(w.dtype)
|
| 149 |
+
merged += 1
|
| 150 |
+
elif isinstance(target, LoRALinear):
|
| 151 |
+
target.add(down.astype(dtype), up.astype(dtype), scale)
|
| 152 |
+
else:
|
| 153 |
+
_put(parent, last, LoRALinear(target, down.astype(dtype), up.astype(dtype), scale))
|
| 154 |
+
ranks = sorted({r for *_, r, _s in plan})
|
| 155 |
+
log(f" β
dflow LoRA {name}: {len(plan) - merged} adapters unmerged"
|
| 156 |
+
f"{f' + {merged} merged (velocity head)' if merged else ''}, rank {'/'.join(map(str, ranks))}, "
|
| 157 |
+
f"weight {float(weight):g}")
|
| 158 |
+
return {"adapters": len(plan) - merged, "merged": merged, "ranks": ranks}
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
def apply_loras(denoiser, specs, dtype=mx.bfloat16, log=print) -> list:
|
| 162 |
+
"""specs: [(path, weight), ...] in order."""
|
| 163 |
+
return [apply_lora_file(denoiser, p, w, dtype=dtype, log=log) for p, w in specs]
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
def missing_files(specs) -> list:
|
| 167 |
+
"""The LoRA files of specs that do not exist (checked at the model's load, before any weights)."""
|
| 168 |
+
return [str(p) for p, _w in specs if not os.path.isfile(str(p))]
|
LVNodes/ComfyUI-DFlow-MLX/dflow_mlx/pipeline.py
ADDED
|
@@ -0,0 +1,226 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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iled at the image size) through the text path, the seed's noise (torch's CPU generator, as the release draws it, so a
|
| 3 |
+
seed composes the same picture), the solver over Beta(1.25, 1.25) quantiles under the resolution log-SNR shift, path-drop
|
| 4 |
+
guidance when its scale is not 1 (the reference forward skips the 18 middle layers and reads the prompt with a -4 logit
|
| 5 |
+
bias in its suffix layers; v = v_ref + scale (v_full - v_ref)), the main forward's self-attention gain by image size (the
|
| 6 |
+
manual's table), then dinac3_96's decoder. Memory is staged: text encoder -> freed -> denoiser -> freed -> decoder, unless
|
| 7 |
+
keep_loaded keeps them for the next render.
|
| 8 |
+
|
| 9 |
+
The release's default: 50 steps of the third-stage ER-SDE at PDG 2.5. The DFlow2 4-step LoRA: 4 Euler steps, PDG off.
|
| 10 |
+
"""
|
| 11 |
+
from __future__ import annotations
|
| 12 |
+
|
| 13 |
+
import gc
|
| 14 |
+
import json
|
| 15 |
+
import os
|
| 16 |
+
import time
|
| 17 |
+
|
| 18 |
+
import mlx.core as mx
|
| 19 |
+
import numpy as np
|
| 20 |
+
|
| 21 |
+
from . import family as F
|
| 22 |
+
|
| 23 |
+
DTYPES = {"bfloat16": mx.bfloat16, "float16": mx.bfloat16, "float32": mx.float32}
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def seed_noise(shape, seed: int) -> mx.array:
|
| 27 |
+
"""The starting noise dflow draws for `seed`: torch.randn on a CPU generator, float32 (inference._initial_noise)."""
|
| 28 |
+
import torch
|
| 29 |
+
gen = torch.Generator("cpu").manual_seed(int(seed))
|
| 30 |
+
return mx.array(torch.randn(tuple(shape), generator=gen, dtype=torch.float32).numpy())
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
class _SolverNoise:
|
| 34 |
+
"""The stochastic solver's noise: Tensor.normal_ on a second CPU generator seeded alike (brownian_noise)."""
|
| 35 |
+
|
| 36 |
+
def __init__(self, seed: int):
|
| 37 |
+
import torch
|
| 38 |
+
self.torch = torch
|
| 39 |
+
self.gen = torch.Generator("cpu").manual_seed(int(seed))
|
| 40 |
+
|
| 41 |
+
def draw(self, shape) -> mx.array:
|
| 42 |
+
host = self.torch.empty(tuple(shape), dtype=self.torch.float32)
|
| 43 |
+
host.normal_(generator=self.gen)
|
| 44 |
+
return mx.array(host.numpy())
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def to_uint8(rgb: mx.array) -> np.ndarray:
|
| 48 |
+
"""[1, 3, H, W] float32 about [-1, 1] -> [H, W, 3] uint8, as dflow/preview.preview_images: clamp, (x + 1) 127.5, round."""
|
| 49 |
+
x = np.clip(np.array(rgb[0].astype(mx.float32)), -1.0, 1.0)
|
| 50 |
+
return np.ascontiguousarray(np.clip(np.round((x + 1.0) * 127.5), 0, 255).astype(np.uint8).transpose(1, 2, 0))
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def sample(tr, x: mx.array, times: np.ndarray, text: dict, *, scale: float, gain: float, solver: str = "er_sde",
|
| 54 |
+
noise_scale: float = F.DEFAULT_NOISE_SCALE, seed: int = 0, caption_bias: float = F.DEFAULT_SUFFIX_CAPTION_BIAS,
|
| 55 |
+
on_step=None) -> mx.array:
|
| 56 |
+
"""The guided solver loop (inference.DFlowEngine.sample, solvers.py's loops): x_t [1, 96, h, w] float32 from times[0]
|
| 57 |
+
down to times[-1] = 0."""
|
| 58 |
+
from .transformer import FULL, PATH_DROP
|
| 59 |
+
guided = F.pdg_active(scale)
|
| 60 |
+
n = len(times) - 1
|
| 61 |
+
noise = None
|
| 62 |
+
if solver == "er_sde":
|
| 63 |
+
plan = F.er_sde_plan(times, noise_scale)
|
| 64 |
+
if noise_scale > 0:
|
| 65 |
+
noise = _SolverNoise(seed)
|
| 66 |
+
elif solver == "dpmpp_2m":
|
| 67 |
+
plan = F.dpmpp_2m_plan(times)
|
| 68 |
+
elif solver == "euler":
|
| 69 |
+
plan = None
|
| 70 |
+
else:
|
| 71 |
+
raise ValueError(f"dflow: solver {solver!r}: er_sde, euler or dpmpp_2m")
|
| 72 |
+
prev_den = prev_d1 = None
|
| 73 |
+
for i in range(n):
|
| 74 |
+
t = np.full((x.shape[0],), times[i], np.float32)
|
| 75 |
+
v = tr(x, t, text, FULL, gain, 0.0)
|
| 76 |
+
if guided:
|
| 77 |
+
r = tr(x, t, text, PATH_DROP, 0.0, caption_bias)
|
| 78 |
+
v = r + scale * (v - r)
|
| 79 |
+
if solver == "euler":
|
| 80 |
+
x = x + float(np.float32(times[i + 1]) - np.float32(times[i])) * v
|
| 81 |
+
else:
|
| 82 |
+
den = x - float(times[i]) * v
|
| 83 |
+
step = plan[i]
|
| 84 |
+
if step is None:
|
| 85 |
+
x = den
|
| 86 |
+
elif solver == "dpmpp_2m":
|
| 87 |
+
ext = den if step["ext"] is None else step["ext"][0] * den - step["ext"][1] * prev_den
|
| 88 |
+
x = step["sigma_ratio"] * x + step["coefficient"] * ext
|
| 89 |
+
else:
|
| 90 |
+
nxt = step["c_state"] * x
|
| 91 |
+
nxt = nxt + step["c_den"] * den
|
| 92 |
+
d1 = None
|
| 93 |
+
if step["c_d1"] is not None:
|
| 94 |
+
d1 = (den - prev_den) / step["d1_div"]
|
| 95 |
+
nxt = nxt + step["c_d1"] * d1
|
| 96 |
+
if step["c_d2"] is not None:
|
| 97 |
+
nxt = nxt + step["c_d2"] * ((d1 - prev_d1) / step["d2_div"])
|
| 98 |
+
if step["c_noise"]:
|
| 99 |
+
nxt = nxt + step["c_noise"] * noise.draw(x.shape)
|
| 100 |
+
x = nxt
|
| 101 |
+
prev_d1 = d1
|
| 102 |
+
prev_den = den
|
| 103 |
+
mx.eval(x)
|
| 104 |
+
if on_step is not None:
|
| 105 |
+
on_step(i + 1, n)
|
| 106 |
+
return x
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
class DFlowPipeline:
|
| 110 |
+
"""dflow_2b from its release folder, with LoRAs [(path, strength)] applied unmerged at every denoiser load."""
|
| 111 |
+
|
| 112 |
+
def __init__(self, model_path: str, loras=(), precision: str = "float16", log=print):
|
| 113 |
+
self.model_path = os.path.abspath(str(model_path))
|
| 114 |
+
for need in ("model.safetensors", "config.json", os.path.join("text_encoder", "model.safetensors"),
|
| 115 |
+
os.path.join("dflow", "__init__.py")):
|
| 116 |
+
if not os.path.exists(os.path.join(self.model_path, need)):
|
| 117 |
+
raise FileNotFoundError(f"dflow: {self.model_path} is not a dflow_2b release folder (no {need})")
|
| 118 |
+
self.loras = [(str(p), float(w)) for p, w in loras]
|
| 119 |
+
for p, _ in self.loras:
|
| 120 |
+
if not os.path.isfile(p):
|
| 121 |
+
raise FileNotFoundError(f"dflow: LoRA file not found: {p}")
|
| 122 |
+
self.precision = str(precision or "float16").lower()
|
| 123 |
+
if self.precision not in DTYPES:
|
| 124 |
+
raise ValueError(f"dflow: precision {precision!r}: float16, bfloat16 or float32")
|
| 125 |
+
self.dtype = DTYPES[self.precision]
|
| 126 |
+
self.log = log
|
| 127 |
+
with open(os.path.join(self.model_path, "config.json"), encoding="utf-8") as f:
|
| 128 |
+
self.allow_empty_prompt = bool((json.load(f).get("inference") or {}).get("allow_empty_prompt", False))
|
| 129 |
+
self.transformer = self.text = self.vae = None
|
| 130 |
+
self._adapter = None
|
| 131 |
+
|
| 132 |
+
def key(self):
|
| 133 |
+
"""What a loaded pipeline is: the next render reuses it only for the same key."""
|
| 134 |
+
return (self.model_path, tuple(self.loras), self.precision)
|
| 135 |
+
|
| 136 |
+
def _adapter_tensors(self) -> dict:
|
| 137 |
+
if self._adapter is None:
|
| 138 |
+
raw = mx.load(os.path.join(self.model_path, "model.safetensors"))
|
| 139 |
+
self._adapter = {k[len("text_adapter."):]: v for k, v in raw.items() if k.startswith("text_adapter.")}
|
| 140 |
+
mx.eval(list(self._adapter.values()))
|
| 141 |
+
del raw
|
| 142 |
+
return self._adapter
|
| 143 |
+
|
| 144 |
+
def _load_text(self):
|
| 145 |
+
if self.text is None:
|
| 146 |
+
from .text import DFlowTextEncoder
|
| 147 |
+
self.text = DFlowTextEncoder(self.model_path, self._adapter_tensors(), self.dtype)
|
| 148 |
+
return self.text
|
| 149 |
+
|
| 150 |
+
def _load_transformer(self):
|
| 151 |
+
if self.transformer is None:
|
| 152 |
+
from .transformer import enable_fp16_compute, load_denoiser
|
| 153 |
+
t0 = time.perf_counter()
|
| 154 |
+
self.transformer, adapter = load_denoiser(self.model_path, self.dtype)
|
| 155 |
+
self._adapter = self._adapter or adapter
|
| 156 |
+
if self.loras:
|
| 157 |
+
from .lora import apply_loras
|
| 158 |
+
apply_loras(self.transformer, self.loras, dtype=self.dtype, log=self.log)
|
| 159 |
+
mx.eval(self.transformer.parameters())
|
| 160 |
+
if self.precision == "float16": # after the LoRAs: their adapters go to float16 with their modules
|
| 161 |
+
n = enable_fp16_compute(self.transformer)
|
| 162 |
+
gc.collect()
|
| 163 |
+
mx.clear_cache()
|
| 164 |
+
self.log(f"float16 compute in {n} attention / MLP modules")
|
| 165 |
+
self.log(f"denoiser ready in {time.perf_counter() - t0:.1f} s")
|
| 166 |
+
return self.transformer
|
| 167 |
+
|
| 168 |
+
def _load_vae(self):
|
| 169 |
+
if self.vae is None:
|
| 170 |
+
from .vae import Dinac3Decoder
|
| 171 |
+
self.vae = Dinac3Decoder(F.vae_folder(self.model_path), self.dtype)
|
| 172 |
+
return self.vae
|
| 173 |
+
|
| 174 |
+
def free(self, text=True, transformer=True, vae=True):
|
| 175 |
+
if text:
|
| 176 |
+
self.text = None
|
| 177 |
+
if transformer:
|
| 178 |
+
self.transformer = None
|
| 179 |
+
if vae:
|
| 180 |
+
self.vae = None
|
| 181 |
+
gc.collect()
|
| 182 |
+
mx.clear_cache()
|
| 183 |
+
|
| 184 |
+
def render(self, prompt: str, width: int, height: int, steps: int, seed: int, guidance: float = 1.0,
|
| 185 |
+
solver: str = "euler", noise_scale: float = F.DEFAULT_NOISE_SCALE, gain=None, keep_loaded: bool = False,
|
| 186 |
+
on_phase=None, on_step=None) -> np.ndarray:
|
| 187 |
+
"""-> [H, W, 3] uint8. guidance: the path-drop guidance scale (1 = off: one forward a step); gain: None = the
|
| 188 |
+
manual's gain for the size."""
|
| 189 |
+
phase = on_phase or (lambda _t: None)
|
| 190 |
+
W, H = int(width), int(height)
|
| 191 |
+
F.check_size(W, H)
|
| 192 |
+
if solver not in F.SOLVERS:
|
| 193 |
+
raise ValueError(f"dflow: solver {solver!r}: er_sde, euler or dpmpp_2m")
|
| 194 |
+
scale = float(guidance)
|
| 195 |
+
if not (np.isfinite(scale) and scale >= 0.0):
|
| 196 |
+
raise ValueError(f"dflow: guidance {guidance}: finite and >= 0 (1 = off)")
|
| 197 |
+
prompt = prompt or ""
|
| 198 |
+
if not prompt.strip() and not self.allow_empty_prompt:
|
| 199 |
+
raise ValueError(F.EMPTY_PROMPT_ERROR)
|
| 200 |
+
g = F.auto_self_attention_gain(W, H) if gain is None else float(gain)
|
| 201 |
+
times = F.build_timesteps(int(steps), F.resolution_log_snr_shift(W, H), finite_noisy_endpoint=solver != "euler")
|
| 202 |
+
layout = F.reference_module(self.model_path, "layout")
|
| 203 |
+
resolved = layout.compile_layout(prompt, W, H) if layout.is_compiled_layout(prompt) else prompt
|
| 204 |
+
phase("encoding the prompt")
|
| 205 |
+
cond = self._load_text().encode(resolved)
|
| 206 |
+
mx.eval([c for c in cond if c is not None])
|
| 207 |
+
if not keep_loaded:
|
| 208 |
+
self.free(transformer=False, vae=False)
|
| 209 |
+
phase("loading the model")
|
| 210 |
+
tr = self._load_transformer()
|
| 211 |
+
text = tr.prepare_text(*cond)
|
| 212 |
+
mx.eval(text["tokens"])
|
| 213 |
+
phase("generating")
|
| 214 |
+
x = seed_noise((1, F.LATENT_CHANNELS, H // F.LATENT_STRIDE, W // F.LATENT_STRIDE), int(seed))
|
| 215 |
+
x = sample(tr, x, times, text, scale=scale, gain=g, solver=solver, noise_scale=noise_scale, seed=int(seed),
|
| 216 |
+
on_step=on_step)
|
| 217 |
+
del tr, text
|
| 218 |
+
if not keep_loaded:
|
| 219 |
+
self.free(text=False, vae=False)
|
| 220 |
+
phase("decoding")
|
| 221 |
+
rgb = self._load_vae().decode(x)
|
| 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
| 1 |
+
"""dflow_2b's text path on MLX: prompts -> the denoiser's text tokens, as the release's dflow/text_conditioning.py.
|
| 2 |
+
|
| 3 |
+
tokenizer the authors' PromptTokenizer (dflow/tokenization.py, imported from the model folder: the <bos> frame,
|
| 4 |
+
quoted lettering one character per token, JSON layout rules, the 6,144-token limit)
|
| 5 |
+
encoder the bundled T5Gemma2-270M encoder subset (text_encoder/model.safetensors: the embeddings and layers 1-12,
|
| 6 |
+
Gemma 3 blocks with bidirectional attention, sliding window 512 except layers 6 and 12), hidden states
|
| 7 |
+
tapped after layers 2, 6 and 12 β dflow/text_encoder.py module for module, its names loaded strictly
|
| 8 |
+
adapter each tap standardized per channel (fixed statistics), projected 640 -> 2304, the three summed in float32,
|
| 9 |
+
then the 3 learned suffix tokens ("text_adapter." in the model's model.safetensors)
|
| 10 |
+
emphasis (phrase:weight) markup (dflow/prompt_emphasis.py, on by default: linear mapping, strength 1, inside the
|
| 11 |
+
encoder too) -> a key bias / value scale per token
|
| 12 |
+
|
| 13 |
+
Precision as the reference under bfloat16 autocast: a float32 residual stream (Gemma's massive-activation channels),
|
| 14 |
+
matrix multiplies and attention in bfloat16, Gemma RMSNorm (1 + w) in float32, the taps float32.
|
| 15 |
+
"""
|
| 16 |
+
from __future__ import annotations
|
| 17 |
+
|
| 18 |
+
import json
|
| 19 |
+
import math
|
| 20 |
+
import os
|
| 21 |
+
import time
|
| 22 |
+
|
| 23 |
+
import mlx.core as mx
|
| 24 |
+
import mlx.nn as nn
|
| 25 |
+
import numpy as np
|
| 26 |
+
from mlx.utils import tree_flatten, tree_unflatten
|
| 27 |
+
|
| 28 |
+
from . import family as F
|
| 29 |
+
|
| 30 |
+
#: text_encoder/config.json of the release (dflow/text_encoder.py ENCODER_CONFIG), checked at load
|
| 31 |
+
ENCODER = {"vocab_size": 262144, "hidden_size": 640, "intermediate_size": 2048, "num_attention_heads": 4,
|
| 32 |
+
"num_key_value_heads": 1, "head_dim": 256, "query_pre_attn_scalar": 256.0, "rms_norm_eps": 1e-06,
|
| 33 |
+
"sliding_window": 512, "embed_scale": 640 ** 0.5, "eoi_token_index": 256000, "tap_layers": [2, 6, 12]}
|
| 34 |
+
LAYER_TYPES = ("sliding",) * 5 + ("full",) + ("sliding",) * 5 + ("full",)
|
| 35 |
+
ROPE = {"sliding": (10000.0, 1.0), "full": (1000000.0, 8.0)} # (theta, linear factor)
|
| 36 |
+
TEXT_WIDTH = 2304
|
| 37 |
+
F32 = mx.float32
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
class GemmaRMSNorm(nn.Module):
|
| 41 |
+
"""x rsqrt(mean(x^2) + eps) (1 + w) in float32, the input's dtype back."""
|
| 42 |
+
|
| 43 |
+
def __init__(self, dims: int):
|
| 44 |
+
super().__init__()
|
| 45 |
+
self.weight = mx.zeros((dims,), dtype=F32)
|
| 46 |
+
|
| 47 |
+
def __call__(self, x):
|
| 48 |
+
return mx.fast.rms_norm(x.astype(F32), 1.0 + self.weight.astype(F32), ENCODER["rms_norm_eps"]).astype(x.dtype)
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def _rotate_half(x):
|
| 52 |
+
half = x.shape[-1] // 2
|
| 53 |
+
return mx.concatenate([-x[..., half:], x[..., :half]], axis=-1)
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
class EncoderAttention(nn.Module):
|
| 57 |
+
def __init__(self):
|
| 58 |
+
super().__init__()
|
| 59 |
+
w, heads, kv, hd = (ENCODER[k] for k in ("hidden_size", "num_attention_heads", "num_key_value_heads", "head_dim"))
|
| 60 |
+
self.q_proj = nn.Linear(w, heads * hd, bias=False)
|
| 61 |
+
self.k_proj = nn.Linear(w, kv * hd, bias=False)
|
| 62 |
+
self.v_proj = nn.Linear(w, kv * hd, bias=False)
|
| 63 |
+
self.o_proj = nn.Linear(heads * hd, w, bias=False)
|
| 64 |
+
self.q_norm = GemmaRMSNorm(hd)
|
| 65 |
+
self.k_norm = GemmaRMSNorm(hd)
|
| 66 |
+
|
| 67 |
+
def __call__(self, x, cos, sin, bias, value_scale, cd):
|
| 68 |
+
"""x: the normalized float32 layer input [B, L, 640]; cos / sin [L, 1, 256] float32 (used in the compute dtype,
|
| 69 |
+
as the reference); bias [B or 1, 1, L, L] or None; value_scale [B, L, 1, 1] or None."""
|
| 70 |
+
b, length, _ = x.shape
|
| 71 |
+
hd = ENCODER["head_dim"]
|
| 72 |
+
xc = x.astype(cd)
|
| 73 |
+
q = self.q_norm(self.q_proj(xc).reshape(b, length, ENCODER["num_attention_heads"], hd))
|
| 74 |
+
k = self.k_norm(self.k_proj(xc).reshape(b, length, ENCODER["num_key_value_heads"], hd))
|
| 75 |
+
v = self.v_proj(xc).reshape(b, length, ENCODER["num_key_value_heads"], hd)
|
| 76 |
+
if value_scale is not None:
|
| 77 |
+
v = v * value_scale.astype(v.dtype)
|
| 78 |
+
cq, sq = cos.astype(q.dtype), sin.astype(q.dtype)
|
| 79 |
+
q = q * cq + _rotate_half(q) * sq
|
| 80 |
+
k = k * cq + _rotate_half(k) * sq
|
| 81 |
+
out = mx.fast.scaled_dot_product_attention(q.transpose(0, 2, 1, 3), k.transpose(0, 2, 1, 3),
|
| 82 |
+
v.transpose(0, 2, 1, 3),
|
| 83 |
+
scale=ENCODER["query_pre_attn_scalar"] ** -0.5, mask=bias)
|
| 84 |
+
return self.o_proj(out.transpose(0, 2, 1, 3).reshape(b, length, -1))
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
class EncoderMLP(nn.Module):
|
| 88 |
+
def __init__(self):
|
| 89 |
+
super().__init__()
|
| 90 |
+
w, h = ENCODER["hidden_size"], ENCODER["intermediate_size"]
|
| 91 |
+
self.gate_proj = nn.Linear(w, h, bias=False)
|
| 92 |
+
self.up_proj = nn.Linear(w, h, bias=False)
|
| 93 |
+
self.down_proj = nn.Linear(h, w, bias=False)
|
| 94 |
+
|
| 95 |
+
def __call__(self, x, cd):
|
| 96 |
+
xc = x.astype(cd)
|
| 97 |
+
gate = self.gate_proj(xc)
|
| 98 |
+
gate = nn.gelu_approx(gate.astype(F32)).astype(gate.dtype) # tanh GELU, float32 inside, rounded once
|
| 99 |
+
return self.down_proj(gate * self.up_proj(xc))
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
class EncoderLayer(nn.Module):
|
| 103 |
+
def __init__(self, kind: str):
|
| 104 |
+
super().__init__()
|
| 105 |
+
self.pre_self_attn_layernorm = GemmaRMSNorm(ENCODER["hidden_size"])
|
| 106 |
+
self.self_attn = EncoderAttention()
|
| 107 |
+
self.post_self_attn_layernorm = GemmaRMSNorm(ENCODER["hidden_size"])
|
| 108 |
+
self.pre_feedforward_layernorm = GemmaRMSNorm(ENCODER["hidden_size"])
|
| 109 |
+
self.mlp = EncoderMLP()
|
| 110 |
+
self.post_feedforward_layernorm = GemmaRMSNorm(ENCODER["hidden_size"])
|
| 111 |
+
self.kind = kind
|
| 112 |
+
|
| 113 |
+
def __call__(self, x, cos, sin, bias, value_scale, cd):
|
| 114 |
+
attn = self.self_attn(self.pre_self_attn_layernorm(x), cos, sin, bias, value_scale, cd)
|
| 115 |
+
x = x + self.post_self_attn_layernorm(attn)
|
| 116 |
+
return x + self.post_feedforward_layernorm(self.mlp(self.pre_feedforward_layernorm(x), cd))
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
class ScaledEmbedding(nn.Module):
|
| 120 |
+
def __init__(self):
|
| 121 |
+
super().__init__()
|
| 122 |
+
self.weight = mx.zeros((ENCODER["vocab_size"], ENCODER["hidden_size"]))
|
| 123 |
+
self.eoi_embedding = mx.zeros((ENCODER["hidden_size"],))
|
| 124 |
+
|
| 125 |
+
def __call__(self, ids: mx.array):
|
| 126 |
+
"""Float32 rows of the stored (bfloat16) table x sqrt(640); the end-of-image id takes its own vector."""
|
| 127 |
+
values = self.weight[ids].astype(F32) * ENCODER["embed_scale"]
|
| 128 |
+
is_eoi = (ids == ENCODER["eoi_token_index"])[..., None]
|
| 129 |
+
return mx.where(is_eoi, self.eoi_embedding.astype(F32), values)
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
def _inv_freq(kind: str) -> np.ndarray:
|
| 133 |
+
theta, factor = ROPE[kind]
|
| 134 |
+
hd = ENCODER["head_dim"]
|
| 135 |
+
exps = np.arange(0, hd, 2, dtype=np.int64).astype(np.float32)
|
| 136 |
+
inv = (np.float32(1.0) / np.power(np.float32(theta), exps / np.float32(hd))).astype(np.float32)
|
| 137 |
+
return (inv / np.float32(factor)).astype(np.float32) if factor != 1.0 else inv
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
def rope_tables(length: int) -> dict:
|
| 141 |
+
"""Each layer kind's float32 (cos, sin) [L, 1, 256] (half-split layout)."""
|
| 142 |
+
positions = np.arange(length, dtype=np.int64).astype(np.float32)[:, None]
|
| 143 |
+
out = {}
|
| 144 |
+
for kind in ("sliding", "full"):
|
| 145 |
+
freqs = (positions * _inv_freq(kind)[None, :]).astype(np.float32)
|
| 146 |
+
emb = np.concatenate([freqs, freqs], axis=-1)
|
| 147 |
+
out[kind] = (mx.array(np.cos(emb).astype(np.float32))[:, None, :],
|
| 148 |
+
mx.array(np.sin(emb).astype(np.float32))[:, None, :])
|
| 149 |
+
return out
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
def attention_biases(length: int, key_bias, cd) -> dict:
|
| 153 |
+
"""The sliding layers mask keys outside the window when the prompt is longer than half of it (-inf), as
|
| 154 |
+
_attention_biases; the emphasis key bias [B, L] is added for both kinds."""
|
| 155 |
+
key = None if key_bias is None else key_bias.astype(cd)[:, None, None, :]
|
| 156 |
+
window = ENCODER["sliding_window"]
|
| 157 |
+
left, right = (window + 1) // 2 - 1, window // 2
|
| 158 |
+
sliding = key
|
| 159 |
+
if length - 1 > min(left, right):
|
| 160 |
+
steps = np.arange(length)
|
| 161 |
+
delta = steps[:, None] - steps[None, :]
|
| 162 |
+
outside = (delta > left) | (-delta > right)
|
| 163 |
+
mask = mx.array(np.where(outside, -np.inf, 0.0).astype(np.float32)).astype(cd)[None, None]
|
| 164 |
+
sliding = mask if key is None else mask + key
|
| 165 |
+
return {"sliding": sliding, "full": key}
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
class T5Gemma2Encoder(nn.Module):
|
| 169 |
+
"""Embeddings and the first 12 T5Gemma2 encoder layers; __call__ -> the float32 taps after layers 2, 6, 12."""
|
| 170 |
+
|
| 171 |
+
def __init__(self, compute_dtype=mx.bfloat16):
|
| 172 |
+
super().__init__()
|
| 173 |
+
self.embed_tokens = ScaledEmbedding()
|
| 174 |
+
self.layers = [EncoderLayer(kind) for kind in LAYER_TYPES]
|
| 175 |
+
self._cd = compute_dtype
|
| 176 |
+
|
| 177 |
+
def __call__(self, ids: mx.array, key_bias=None, value_scale=None):
|
| 178 |
+
length = ids.shape[1]
|
| 179 |
+
biases = attention_biases(length, key_bias, self._cd)
|
| 180 |
+
ropes = rope_tables(length)
|
| 181 |
+
vs = None if value_scale is None else value_scale[:, :, None, None]
|
| 182 |
+
x = self.embed_tokens(ids)
|
| 183 |
+
taps = {}
|
| 184 |
+
for index, layer in enumerate(self.layers, start=1):
|
| 185 |
+
cos, sin = ropes[layer.kind]
|
| 186 |
+
x = layer(x, cos, sin, biases[layer.kind], vs, self._cd)
|
| 187 |
+
if index in ENCODER["tap_layers"]:
|
| 188 |
+
taps[index] = x
|
| 189 |
+
return [taps[i] for i in ENCODER["tap_layers"]]
|
| 190 |
+
|
| 191 |
+
|
| 192 |
+
class TextAdapter:
|
| 193 |
+
"""The tap standardization, the three projections (bfloat16) and the learned tokens (float32)."""
|
| 194 |
+
|
| 195 |
+
KEYS = {"proj_lo.weight": (TEXT_WIDTH, 640), "proj_mid.weight": (TEXT_WIDTH, 640),
|
| 196 |
+
"proj_hi.weight": (TEXT_WIDTH, 640), "tap_mean": (3, 640), "tap_std": (3, 640),
|
| 197 |
+
"uncond_token": (1, TEXT_WIDTH), "suffix_tokens": (3, TEXT_WIDTH)}
|
| 198 |
+
|
| 199 |
+
def __init__(self, tensors: dict, compute_dtype=mx.bfloat16):
|
| 200 |
+
missing = sorted(set(self.KEYS) - set(tensors))
|
| 201 |
+
unexpected = sorted(set(tensors) - set(self.KEYS))
|
| 202 |
+
shapes = sorted(k for k in set(self.KEYS) & set(tensors) if tuple(tensors[k].shape) != self.KEYS[k])
|
| 203 |
+
if missing or unexpected or shapes:
|
| 204 |
+
raise ValueError(f"dflow: the text adapter does not match: missing {missing}, unexpected {unexpected}, "
|
| 205 |
+
f"misshaped {shapes}")
|
| 206 |
+
self.cd = compute_dtype
|
| 207 |
+
self.proj = [tensors[f"proj_{n}.weight"].astype(compute_dtype) for n in ("lo", "mid", "hi")]
|
| 208 |
+
self.mean = tensors["tap_mean"].astype(F32)
|
| 209 |
+
self.std = tensors["tap_std"].astype(F32)
|
| 210 |
+
self.uncond = tensors["uncond_token"].astype(F32)
|
| 211 |
+
self.suffix = tensors["suffix_tokens"].astype(F32)
|
| 212 |
+
|
| 213 |
+
def conditioning(self, taps) -> mx.array:
|
| 214 |
+
"""[B, L + 3, 2304] float32: the summed projected taps, then the suffix."""
|
| 215 |
+
total = None
|
| 216 |
+
for slot, (weight, tap) in enumerate(zip(self.proj, taps)):
|
| 217 |
+
normalized = (tap.astype(F32) - self.mean[slot]) / self.std[slot]
|
| 218 |
+
projected = (normalized.astype(self.cd) @ weight.T).astype(F32)
|
| 219 |
+
total = projected if total is None else total + projected
|
| 220 |
+
suffix = mx.broadcast_to(self.suffix[None], (total.shape[0], *self.suffix.shape))
|
| 221 |
+
return mx.concatenate([total, suffix], axis=1)
|
| 222 |
+
|
| 223 |
+
def unconditional(self) -> mx.array:
|
| 224 |
+
"""The null text [1, 4, 2304] float32: the learned unconditional token, then the suffix."""
|
| 225 |
+
return mx.concatenate([self.uncond, self.suffix], axis=0)[None]
|
| 226 |
+
|
| 227 |
+
|
| 228 |
+
def load_encoder(folder: str, dtype=mx.bfloat16) -> T5Gemma2Encoder:
|
| 229 |
+
"""text_encoder/: config.json checked against the architecture, model.safetensors loaded strictly (bfloat16 as
|
| 230 |
+
stored; the embeddings and norms used in float32 as the reference's copies, the linears in the compute dtype)."""
|
| 231 |
+
with open(os.path.join(folder, "config.json"), encoding="utf-8") as f:
|
| 232 |
+
cfg = json.load(f)
|
| 233 |
+
bad = [k for k, v in ENCODER.items() if k != "embed_scale" and cfg.get(k) != v]
|
| 234 |
+
kinds = tuple("full" if k == "full_attention" else "sliding" for k in cfg.get("layer_types") or [])
|
| 235 |
+
if bad or kinds != LAYER_TYPES or not math.isclose(float(cfg.get("embed_scale", 0)), ENCODER["embed_scale"]):
|
| 236 |
+
raise ValueError(f"dflow: {folder}/config.json is not the bundled T5Gemma2 encoder subset (keys {bad})")
|
| 237 |
+
for kind, key in (("sliding", "sliding_rope"), ("full", "full_rope")):
|
| 238 |
+
rope = cfg.get(key) or {}
|
| 239 |
+
if (float(rope.get("theta", 0)), float(rope.get("factor", 0))) != ROPE[kind]:
|
| 240 |
+
raise ValueError(f"dflow: {folder}/config.json {key} is not the encoder's RoPE")
|
| 241 |
+
tensors = mx.load(os.path.join(folder, "model.safetensors"))
|
| 242 |
+
enc = T5Gemma2Encoder(compute_dtype=mx.float32 if dtype == mx.float32 else mx.bfloat16)
|
| 243 |
+
expected = dict(tree_flatten(enc.parameters()))
|
| 244 |
+
missing = sorted(set(expected) - set(tensors))
|
| 245 |
+
unexpected = sorted(set(tensors) - set(expected))
|
| 246 |
+
shapes = sorted(k for k in set(expected) & set(tensors) if tuple(expected[k].shape) != tuple(tensors[k].shape))
|
| 247 |
+
if missing or unexpected or shapes:
|
| 248 |
+
raise ValueError(f"dflow: {folder}/model.safetensors does not match the encoder: missing {missing[:4]}, "
|
| 249 |
+
f"unexpected {unexpected[:4]}, misshaped {shapes[:4]}")
|
| 250 |
+
if dtype == mx.float32:
|
| 251 |
+
tensors = {k: v.astype(mx.float32) for k, v in tensors.items()}
|
| 252 |
+
enc.update(tree_unflatten(list(tensors.items())))
|
| 253 |
+
mx.eval(enc.parameters())
|
| 254 |
+
return enc
|
| 255 |
+
|
| 256 |
+
|
| 257 |
+
class DFlowTextEncoder:
|
| 258 |
+
"""Prompt -> (tokens [1, L, 2304] float32, key_bias [1, L] or None, value_scale [1, L] or None) β the denoiser's
|
| 259 |
+
TextConditioning for one prompt."""
|
| 260 |
+
|
| 261 |
+
def __init__(self, model_path: str, adapter_tensors: dict, dtype=mx.bfloat16, emphasis=True):
|
| 262 |
+
t0 = time.perf_counter()
|
| 263 |
+
self.model_path = str(model_path)
|
| 264 |
+
folder = os.path.join(self.model_path, "text_encoder")
|
| 265 |
+
self.tokenizer = F.reference_module(self.model_path, "tokenization").PromptTokenizer.from_directory(folder)
|
| 266 |
+
self.layout = F.reference_module(self.model_path, "layout")
|
| 267 |
+
self.emph = F.reference_module(self.model_path, "prompt_emphasis")
|
| 268 |
+
self.settings = self.emph.EmphasisSettings() if emphasis else None
|
| 269 |
+
self.encoder = load_encoder(folder, dtype)
|
| 270 |
+
self.adapter = TextAdapter(adapter_tensors, mx.float32 if dtype == mx.float32 else mx.bfloat16)
|
| 271 |
+
self.load_s = time.perf_counter() - t0
|
| 272 |
+
|
| 273 |
+
def resolve(self, prompt: str, width: int, height: int) -> str:
|
| 274 |
+
"""A stored layout compiled to the size (the pixel boxes the model was trained on); other prompts unchanged."""
|
| 275 |
+
if self.layout.is_compiled_layout(prompt):
|
| 276 |
+
return self.layout.compile_layout(prompt, width, height)
|
| 277 |
+
return prompt
|
| 278 |
+
|
| 279 |
+
def token_count(self, prompt: str) -> int:
|
| 280 |
+
return len(self.tokenizer.tokenize(prompt).ids)
|
| 281 |
+
|
| 282 |
+
def encode(self, prompt: str):
|
| 283 |
+
"""One resolved prompt -> (tokens, key_bias, value_scale), as DFlowTextEncoder._prepare / _encode_prepared."""
|
| 284 |
+
if not prompt.strip():
|
| 285 |
+
return self.adapter.unconditional(), None, None
|
| 286 |
+
emphasis = None
|
| 287 |
+
if self.layout.is_compiled_layout(prompt):
|
| 288 |
+
# v0.215 renamed the check (is_uncompiled_layout: a stored layout or a MOSS draft); v0.21 has is_stored_layout
|
| 289 |
+
uncompiled = getattr(self.layout, "is_uncompiled_layout", None) or self.layout.is_stored_layout
|
| 290 |
+
if uncompiled(prompt):
|
| 291 |
+
raise ValueError("dflow: a stored layout must be compiled at the image size first (resolve)")
|
| 292 |
+
ids = self.tokenizer.tokenize(prompt).ids
|
| 293 |
+
elif self.settings is None:
|
| 294 |
+
ids = self.tokenizer.tokenize(prompt).ids
|
| 295 |
+
else:
|
| 296 |
+
parsed = self.emph.parse_prompt_weights(prompt)
|
| 297 |
+
tokenized = self.tokenizer.tokenize(parsed.clean_text)
|
| 298 |
+
ids = tokenized.ids
|
| 299 |
+
emphasis = self.emph.token_emphasis(parsed, tokenized.offsets, self.settings)
|
| 300 |
+
kb_enc = vs_enc = kb = vs = None
|
| 301 |
+
if emphasis is not None:
|
| 302 |
+
if emphasis.has_key_bias():
|
| 303 |
+
kb_enc = mx.array(np.asarray([emphasis.key_bias], np.float32))
|
| 304 |
+
kb = mx.array(np.asarray([list(emphasis.key_bias) + [0.0] * F.SUFFIX_TOKEN_COUNT], np.float32))
|
| 305 |
+
if emphasis.has_value_scale():
|
| 306 |
+
vs_enc = mx.array(np.asarray([emphasis.value_scale], np.float32))
|
| 307 |
+
vs = mx.array(np.asarray([list(emphasis.value_scale) + [1.0] * F.SUFFIX_TOKEN_COUNT], np.float32))
|
| 308 |
+
use_enc = self.settings is not None and self.settings.encoder
|
| 309 |
+
taps = self.encoder(mx.array(np.asarray([ids], np.int32)), kb_enc if use_enc else None,
|
| 310 |
+
vs_enc if use_enc else None)
|
| 311 |
+
return self.adapter.conditioning(taps), kb, vs
|
| 312 |
+
|
| 313 |
+
def free(self):
|
| 314 |
+
self.encoder = None
|
LVNodes/ComfyUI-DFlow-MLX/dflow_mlx/transformer.py
ADDED
|
@@ -0,0 +1,441 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""dflow_2b's denoiser on MLX: the authors' DFlowModel (the release's dflow/modeling.py, blocks.py, rope3d.py) module for
|
| 2 |
+
module, with their parameter names, so the release's model.safetensors loads as it is (the "denoiser." tensors strictly;
|
| 3 |
+
the "text_adapter." ones go to text.py).
|
| 4 |
+
|
| 5 |
+
A single-stream text-image flow transformer, width 2304, 18 heads of 128: two unmodulated text-refiner blocks, then 6
|
| 6 |
+
prefix, 18 middle and 6 suffix image blocks (scale-and-gate AdaLN from the timestep, sandwich RMSNorms, fused QKV, QK
|
| 7 |
+
RMSNorm, 3-axis adjacent-pair RoPE, exact-GELU MLP), a tail join of the prefix and middle streams, a final modulated
|
| 8 |
+
norm and the velocity head. Each sample is one sequence [image tokens, text tokens].
|
| 9 |
+
|
| 10 |
+
Precision follows the reference under CUDA bfloat16 autocast: matrix multiplies and attention in bfloat16; norms,
|
| 11 |
+
RoPE, the AdaLN scales and gates and the returned velocity in float32 (each rounded back once, where the reference
|
| 12 |
+
rounds); the text refiner keeps a float32 residual stream, the joint stream is bfloat16. A float32 build runs everything
|
| 13 |
+
in float32 (the weights upcast at load).
|
| 14 |
+
|
| 15 |
+
float16 compute (as mflux's #820; fp16.py): enable_fp16_compute() casts every attention and MLP module (the 2 refiner and 30 image blocks; their
|
| 16 |
+
weights, q / k norms and LoRA adapters) to float16 and runs their inside in float16, each output clipped to float16's range on
|
| 17 |
+
its way back into the stream; the residual streams, the norms between the modules, the AdaLN modulation, the time embedding,
|
| 18 |
+
the patch embedding, the tail join and the velocity head stay as in bfloat16. RANGE (None, or a dict a measuring script
|
| 19 |
+
sets) records the largest magnitude inside those modules per site.
|
| 20 |
+
"""
|
| 21 |
+
from __future__ import annotations
|
| 22 |
+
|
| 23 |
+
import json
|
| 24 |
+
import math
|
| 25 |
+
import os
|
| 26 |
+
from functools import lru_cache
|
| 27 |
+
|
| 28 |
+
import mlx.core as mx
|
| 29 |
+
import mlx.nn as nn
|
| 30 |
+
import numpy as np
|
| 31 |
+
from mlx.utils import tree_flatten, tree_unflatten
|
| 32 |
+
|
| 33 |
+
from .fp16 import cast_mask, cast_module, to_stream
|
| 34 |
+
|
| 35 |
+
#: config.json "denoiser" of the release, checked key for key at load (dflow/configuration.py DFLOW_2B_CONFIG)
|
| 36 |
+
CONFIG = {"heads": 18, "latent_channels": 96, "middle_depth": 18, "mlp_ratio": 4, "norm_eps": 1e-06, "patch_size": 1,
|
| 37 |
+
"prefix_depth": 6, "rope_axes_dims": [32, 48, 48], "rope_axes_lens": [8192, 512, 512], "rope_theta": 10000.0,
|
| 38 |
+
"suffix_depth": 6, "text_refiner_depth": 2, "time_embed_width": 256, "time_frequency_width": 256,
|
| 39 |
+
"time_hidden_width": 1024, "time_max_period": 10000.0, "time_scale": 1000.0, "width": 2304}
|
| 40 |
+
WIDTH = CONFIG["width"]
|
| 41 |
+
HEADS = CONFIG["heads"]
|
| 42 |
+
HEAD_WIDTH = WIDTH // HEADS
|
| 43 |
+
LATENT = CONFIG["latent_channels"]
|
| 44 |
+
EPS = CONFIG["norm_eps"]
|
| 45 |
+
ROPE_DIMS = tuple(CONFIG["rope_axes_dims"])
|
| 46 |
+
ROPE_THETA = CONFIG["rope_theta"]
|
| 47 |
+
SUFFIX_TOKENS = 3
|
| 48 |
+
DENOISER_PREFIX = "denoiser."
|
| 49 |
+
ADAPTER_PREFIX = "text_adapter."
|
| 50 |
+
FULL, PATH_DROP = "full", "path_drop"
|
| 51 |
+
#: supported self-attention logit gains, inclusive (modeling.SELF_ATTENTION_GAIN_RANGE)
|
| 52 |
+
SELF_ATTENTION_GAIN_RANGE = (-0.5, 0.1)
|
| 53 |
+
F32 = mx.float32
|
| 54 |
+
#: a range probe: None, or {site: largest |value| seen} for the tensors float16 compute
|
| 55 |
+
#: holds (attn.qkv, attn.sdpa, attn.proj_out, mlp.up, mlp.gelu, mlp.down); recording evaluates them, so only for probing
|
| 56 |
+
RANGE = None
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def _seen(site: str, t: mx.array) -> mx.array:
|
| 60 |
+
if RANGE is not None:
|
| 61 |
+
RANGE[site] = max(RANGE.get(site, 0.0), float(mx.max(mx.abs(t.astype(F32)))))
|
| 62 |
+
return t
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def rms(x: mx.array, weight: mx.array, eps: float = EPS) -> mx.array:
|
| 66 |
+
"""F.rms_norm under autocast: float32 arithmetic with the weight in the input's dtype, one rounding to it."""
|
| 67 |
+
w = weight.astype(x.dtype).astype(F32)
|
| 68 |
+
return mx.fast.rms_norm(x.astype(F32), w, eps).astype(x.dtype)
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def _rotate_pairs(x: mx.array) -> mx.array:
|
| 72 |
+
"""(x0, x1) -> (-x1, x0) over adjacent channel pairs of the last axis."""
|
| 73 |
+
pairs = x.reshape(*x.shape[:-1], x.shape[-1] // 2, 2)
|
| 74 |
+
return mx.stack([-pairs[..., 1], pairs[..., 0]], axis=-1).reshape(x.shape)
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def apply_rope(x: mx.array, sin: mx.array, cos: mx.array) -> mx.array:
|
| 78 |
+
"""Rotate [B, S, H, D] by float32 sin / cos [B, S, 1, D] in float32; x's dtype back."""
|
| 79 |
+
xf = x.astype(F32)
|
| 80 |
+
return (xf * cos + _rotate_pairs(xf) * sin).astype(x.dtype)
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def _gelu_f32(h: mx.array) -> mx.array:
|
| 84 |
+
"""The exact (erf) GELU in float32, rounded once to h's dtype (CUDA's bfloat16 GELU computes in float32)."""
|
| 85 |
+
return nn.gelu(h.astype(F32)).astype(h.dtype)
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
def _silu_f32(h: mx.array) -> mx.array:
|
| 89 |
+
return nn.silu(h.astype(F32)).astype(h.dtype)
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
class RMSNorm(nn.Module):
|
| 93 |
+
def __init__(self, dims: int):
|
| 94 |
+
super().__init__()
|
| 95 |
+
self.weight = mx.ones((dims,), dtype=F32)
|
| 96 |
+
|
| 97 |
+
def __call__(self, x):
|
| 98 |
+
return rms(x, self.weight)
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
class JointSelfAttention(nn.Module):
|
| 102 |
+
def __init__(self):
|
| 103 |
+
super().__init__()
|
| 104 |
+
self.qkv = nn.Linear(WIDTH, 3 * WIDTH, bias=False)
|
| 105 |
+
self.q_norm = RMSNorm(HEAD_WIDTH)
|
| 106 |
+
self.k_norm = RMSNorm(HEAD_WIDTH)
|
| 107 |
+
self.proj_out = nn.Linear(WIDTH, WIDTH, bias=False)
|
| 108 |
+
self.fp16 = False # float16 compute inside (enable_fp16_compute, -p float16)
|
| 109 |
+
|
| 110 |
+
def __call__(self, x, sin, cos, query_scale, key_bias, value_scale):
|
| 111 |
+
"""x [B, S, width] in the compute dtype; query_scale a float32 Python number or None; key_bias [B, 1, 1, S] and
|
| 112 |
+
value_scale [B, 1, S, 1] in the compute dtype, or None. Under float16 compute the inside runs in float16 and the
|
| 113 |
+
output comes back in x's dtype, clipped to float16's range."""
|
| 114 |
+
if not self.fp16:
|
| 115 |
+
return self._attend(x, sin, cos, query_scale, key_bias, value_scale)
|
| 116 |
+
out = self._attend(x.astype(mx.float16), sin, cos, query_scale, cast_mask(key_bias),
|
| 117 |
+
None if value_scale is None else value_scale.astype(mx.float16))
|
| 118 |
+
return to_stream(out, x.dtype)
|
| 119 |
+
|
| 120 |
+
def _attend(self, x, sin, cos, query_scale, key_bias, value_scale):
|
| 121 |
+
b, s, _ = x.shape
|
| 122 |
+
qkv = _seen("attn.qkv", self.qkv(x)).reshape(b, s, 3, HEADS, HEAD_WIDTH)
|
| 123 |
+
q, k, v = qkv[:, :, 0], qkv[:, :, 1], qkv[:, :, 2]
|
| 124 |
+
q = apply_rope(self.q_norm(q), sin, cos)
|
| 125 |
+
k = apply_rope(self.k_norm(k), sin, cos)
|
| 126 |
+
if query_scale is not None:
|
| 127 |
+
q = (q.astype(F32) * query_scale).astype(k.dtype)
|
| 128 |
+
q, k, v = (t.transpose(0, 2, 1, 3) for t in (q, k, v))
|
| 129 |
+
if value_scale is not None:
|
| 130 |
+
v = v * value_scale
|
| 131 |
+
out = _seen("attn.sdpa", mx.fast.scaled_dot_product_attention(q, k, v, scale=HEAD_WIDTH ** -0.5, mask=key_bias))
|
| 132 |
+
return _seen("attn.proj_out", self.proj_out(out.transpose(0, 2, 1, 3).reshape(b, s, WIDTH)))
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
class GeluMlp(nn.Module):
|
| 136 |
+
def __init__(self):
|
| 137 |
+
super().__init__()
|
| 138 |
+
self.up = nn.Linear(WIDTH, CONFIG["mlp_ratio"] * WIDTH)
|
| 139 |
+
self.down = nn.Linear(CONFIG["mlp_ratio"] * WIDTH, WIDTH)
|
| 140 |
+
self.fp16 = False # float16 compute inside (enable_fp16_compute, -p float16)
|
| 141 |
+
|
| 142 |
+
def __call__(self, x):
|
| 143 |
+
if not self.fp16:
|
| 144 |
+
return self._mlp(x)
|
| 145 |
+
return to_stream(self._mlp(x.astype(mx.float16)), x.dtype)
|
| 146 |
+
|
| 147 |
+
def _mlp(self, x):
|
| 148 |
+
h = _seen("mlp.gelu", _gelu_f32(_seen("mlp.up", self.up(x))))
|
| 149 |
+
return _seen("mlp.down", self.down(h))
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
def enable_fp16_compute(model) -> int:
|
| 153 |
+
"""mflux's float16 compute (#820) on the dflow port (see the module docstring): every attention and MLP
|
| 154 |
+
module (2 refiner + 30 image blocks: 64) gets its weights, q / k norms and LoRA adapters cast to float16 in place and
|
| 155 |
+
runs its inside in float16. Call it once the denoiser is final (after LoRAs). Returns the number of modules switched."""
|
| 156 |
+
n = 0
|
| 157 |
+
for m in model.modules():
|
| 158 |
+
if isinstance(m, (JointSelfAttention, GeluMlp)) and not m.fp16:
|
| 159 |
+
cast_module(m)
|
| 160 |
+
m.fp16 = True
|
| 161 |
+
n += 1
|
| 162 |
+
return n
|
| 163 |
+
|
| 164 |
+
|
| 165 |
+
def _modulate(normed, scale):
|
| 166 |
+
return (normed.astype(F32) * (1.0 + scale[:, None, :])).astype(normed.dtype)
|
| 167 |
+
|
| 168 |
+
|
| 169 |
+
def _gate(gate, values):
|
| 170 |
+
return (mx.tanh(gate)[:, None, :] * values.astype(F32)).astype(values.dtype)
|
| 171 |
+
|
| 172 |
+
|
| 173 |
+
class DFlowBlock(nn.Module):
|
| 174 |
+
"""h = norm2(attn(modulate(norm1(x), s_a))); x += tanh(g_a) h; the same with the MLP. The refiner (modulation
|
| 175 |
+
None) adds h directly and keeps its float32 residual; the linears see the compute dtype, as under autocast."""
|
| 176 |
+
|
| 177 |
+
def __init__(self):
|
| 178 |
+
super().__init__()
|
| 179 |
+
self.attn_norm1 = RMSNorm(WIDTH)
|
| 180 |
+
self.attn_norm2 = RMSNorm(WIDTH)
|
| 181 |
+
self.mlp_norm1 = RMSNorm(WIDTH)
|
| 182 |
+
self.mlp_norm2 = RMSNorm(WIDTH)
|
| 183 |
+
self.attn = JointSelfAttention()
|
| 184 |
+
self.mlp = GeluMlp()
|
| 185 |
+
|
| 186 |
+
def __call__(self, x, sin, cos, modulation, query_scale, key_bias, value_scale, cd):
|
| 187 |
+
if modulation is None:
|
| 188 |
+
h = self.attn(self.attn_norm1(x).astype(cd), sin, cos, query_scale, key_bias, value_scale)
|
| 189 |
+
x = x + self.attn_norm2(h)
|
| 190 |
+
return x + self.mlp_norm2(self.mlp(self.mlp_norm1(x).astype(cd)))
|
| 191 |
+
scale_a, gate_a, scale_m, gate_m = mx.split(modulation, 4, axis=-1)
|
| 192 |
+
h = self.attn(_modulate(self.attn_norm1(x), scale_a).astype(cd), sin, cos, query_scale, key_bias, value_scale)
|
| 193 |
+
x = x + _gate(gate_a, self.attn_norm2(h))
|
| 194 |
+
h = self.mlp(_modulate(self.mlp_norm1(x), scale_m).astype(cd))
|
| 195 |
+
return x + _gate(gate_m, self.mlp_norm2(h))
|
| 196 |
+
|
| 197 |
+
|
| 198 |
+
class TimeEmbedding(nn.Module):
|
| 199 |
+
def __init__(self):
|
| 200 |
+
super().__init__()
|
| 201 |
+
self.proj_in = nn.Linear(CONFIG["time_frequency_width"], CONFIG["time_hidden_width"])
|
| 202 |
+
self.proj_out = nn.Linear(CONFIG["time_hidden_width"], CONFIG["time_embed_width"])
|
| 203 |
+
|
| 204 |
+
def __call__(self, t: np.ndarray, cd):
|
| 205 |
+
"""t: float32 [B] on the host. The sinusoidal features in float32 numpy (sin / cos of 1000 t f_k, f_k from 1
|
| 206 |
+
to 1/10000), then the SiLU MLP in the compute dtype."""
|
| 207 |
+
half = CONFIG["time_frequency_width"] // 2
|
| 208 |
+
freqs = np.exp(np.float32(-math.log(CONFIG["time_max_period"])) * np.arange(half, dtype=np.float32)
|
| 209 |
+
/ np.float32(max(float(half - 1), 1.0))).astype(np.float32)
|
| 210 |
+
angles = (np.asarray(t, np.float32) * np.float32(CONFIG["time_scale"]))[:, None] * freqs[None]
|
| 211 |
+
feats = np.concatenate([np.sin(angles), np.cos(angles)], axis=-1).astype(np.float32)
|
| 212 |
+
hidden = _silu_f32(self.proj_in(mx.array(feats).astype(cd)))
|
| 213 |
+
return self.proj_out(hidden)
|
| 214 |
+
|
| 215 |
+
|
| 216 |
+
class TailJoin(nn.Module):
|
| 217 |
+
"""W [g_p p ; g_m m] + b with g = 1 + s(t), plus dropped_skip_proj(g_p p) where the middle did not run."""
|
| 218 |
+
|
| 219 |
+
def __init__(self):
|
| 220 |
+
super().__init__()
|
| 221 |
+
self.mask_token = mx.zeros((1, WIDTH))
|
| 222 |
+
self.adascale = nn.Linear(CONFIG["time_embed_width"], 2 * WIDTH)
|
| 223 |
+
self.proj = nn.Linear(2 * WIDTH, WIDTH)
|
| 224 |
+
self.dropped_skip_proj = nn.Linear(WIDTH, WIDTH, bias=False)
|
| 225 |
+
|
| 226 |
+
def __call__(self, prefix, middle, dropped: bool, time_act):
|
| 227 |
+
concat = mx.concatenate([prefix, middle], axis=-1)
|
| 228 |
+
scale = self.adascale(time_act).astype(F32)
|
| 229 |
+
scaled = (concat.astype(F32) * (1.0 + scale[:, None, :])).astype(concat.dtype)
|
| 230 |
+
fused = self.proj(scaled)
|
| 231 |
+
if dropped:
|
| 232 |
+
fused = fused + self.dropped_skip_proj(scaled[..., :WIDTH])
|
| 233 |
+
return fused
|
| 234 |
+
|
| 235 |
+
|
| 236 |
+
class PatchEmbed(nn.Module):
|
| 237 |
+
"""The 1x1 Conv2d(96, 2304) as a channel matmul (weight kept in the release's [2304, 96, 1, 1])."""
|
| 238 |
+
|
| 239 |
+
def __init__(self):
|
| 240 |
+
super().__init__()
|
| 241 |
+
self.weight = mx.zeros((WIDTH, LATENT, 1, 1))
|
| 242 |
+
self.bias = mx.zeros((WIDTH,))
|
| 243 |
+
|
| 244 |
+
def __call__(self, tokens):
|
| 245 |
+
return mx.addmm(self.bias.astype(tokens.dtype), tokens, self.weight.reshape(WIDTH, LATENT).astype(tokens.dtype).T)
|
| 246 |
+
|
| 247 |
+
|
| 248 |
+
# ββ RoPE rows (rope3d.py: float64 angles rounded to float32, sine and cosine in float32) ββββββββββββββββββββββββββββ
|
| 249 |
+
|
| 250 |
+
def _axis_freqs(dim: int) -> np.ndarray:
|
| 251 |
+
return 1.0 / (ROPE_THETA ** (np.arange(0, dim, 2, dtype=np.float64) / float(dim)))
|
| 252 |
+
|
| 253 |
+
|
| 254 |
+
def rope_rows(positions: np.ndarray):
|
| 255 |
+
"""[N, 3] real positions -> (sin, cos) [N, 128] float32, adjacent-pair layout, one block of channels per axis."""
|
| 256 |
+
sins, coses = [], []
|
| 257 |
+
for axis, dim in enumerate(ROPE_DIMS):
|
| 258 |
+
angles = np.outer(positions[:, axis].astype(np.float64), _axis_freqs(dim)).astype(np.float32)
|
| 259 |
+
sins.append(np.repeat(np.sin(angles), 2, axis=-1))
|
| 260 |
+
coses.append(np.repeat(np.cos(angles), 2, axis=-1))
|
| 261 |
+
return np.concatenate(sins, -1).astype(np.float32), np.concatenate(coses, -1).astype(np.float32)
|
| 262 |
+
|
| 263 |
+
|
| 264 |
+
def text_positions(length: int) -> np.ndarray:
|
| 265 |
+
"""(1..L, 0, 0): text token i of an L-token prompt."""
|
| 266 |
+
pos = np.zeros((length, 3), np.float64)
|
| 267 |
+
pos[:, 0] = np.arange(1, length + 1)
|
| 268 |
+
return pos
|
| 269 |
+
|
| 270 |
+
|
| 271 |
+
def image_positions(text_length: int, grid_h: int, grid_w: int) -> np.ndarray:
|
| 272 |
+
"""(L + 1, row - (H - 1) / 2, col - (W - 1) / 2) over the row-major token grid, centred on the text."""
|
| 273 |
+
rows, cols = np.divmod(np.arange(grid_h * grid_w), grid_w)
|
| 274 |
+
pos = np.empty((grid_h * grid_w, 3), np.float64)
|
| 275 |
+
pos[:, 0] = text_length + 1
|
| 276 |
+
pos[:, 1] = rows - (grid_h - 1) / 2
|
| 277 |
+
pos[:, 2] = cols - (grid_w - 1) / 2
|
| 278 |
+
return pos
|
| 279 |
+
|
| 280 |
+
|
| 281 |
+
@lru_cache(maxsize=8)
|
| 282 |
+
def _joint_rope(text_length: int, grid_h: int, grid_w: int):
|
| 283 |
+
sin, cos = rope_rows(np.concatenate([image_positions(text_length, grid_h, grid_w), text_positions(text_length)]))
|
| 284 |
+
return mx.array(sin)[None, :, None, :], mx.array(cos)[None, :, None, :]
|
| 285 |
+
|
| 286 |
+
|
| 287 |
+
@lru_cache(maxsize=8)
|
| 288 |
+
def _text_rope(length: int):
|
| 289 |
+
sin, cos = rope_rows(text_positions(length))
|
| 290 |
+
return mx.array(sin)[None, :, None, :], mx.array(cos)[None, :, None, :]
|
| 291 |
+
|
| 292 |
+
|
| 293 |
+
def check_rope_capacity(text_length: int, grid_h: int, grid_w: int):
|
| 294 |
+
lens = CONFIG["rope_axes_lens"]
|
| 295 |
+
if text_length + 1 >= lens[0]:
|
| 296 |
+
raise ValueError(f"dflow: a {text_length}-token prompt exceeds the RoPE text capacity ({lens[0] - 1})")
|
| 297 |
+
if grid_h > lens[1] or grid_w > lens[2]:
|
| 298 |
+
raise ValueError(f"dflow: token grid {grid_h}x{grid_w} exceeds the RoPE grid {lens[1]}x{lens[2]}")
|
| 299 |
+
|
| 300 |
+
|
| 301 |
+
class DFlowDenoiser(nn.Module):
|
| 302 |
+
"""dflow_2b's denoiser. prepare_text(...) once per prompt, then __call__(latents, t, prepared, ...) -> velocity."""
|
| 303 |
+
|
| 304 |
+
def __init__(self, compute_dtype=mx.bfloat16):
|
| 305 |
+
super().__init__()
|
| 306 |
+
self.patch_embed = PatchEmbed()
|
| 307 |
+
self.time_embed = TimeEmbedding()
|
| 308 |
+
self.text_refiner_layers = [DFlowBlock() for _ in range(CONFIG["text_refiner_depth"])]
|
| 309 |
+
self.prefix_layers = [DFlowBlock() for _ in range(CONFIG["prefix_depth"])]
|
| 310 |
+
self.middle_layers = [DFlowBlock() for _ in range(CONFIG["middle_depth"])]
|
| 311 |
+
self.suffix_layers = [DFlowBlock() for _ in range(CONFIG["suffix_depth"])]
|
| 312 |
+
te = CONFIG["time_embed_width"]
|
| 313 |
+
self.prefix_adaln = [nn.Linear(te, 4 * WIDTH) for _ in range(CONFIG["prefix_depth"])]
|
| 314 |
+
self.middle_adaln = [nn.Linear(te, 4 * WIDTH) for _ in range(CONFIG["middle_depth"])]
|
| 315 |
+
self.suffix_adaln = [nn.Linear(te, 4 * WIDTH) for _ in range(CONFIG["suffix_depth"])]
|
| 316 |
+
self.tail_join = TailJoin()
|
| 317 |
+
self.final_norm = RMSNorm(WIDTH)
|
| 318 |
+
self.final_modulation = nn.Linear(te, 2 * WIDTH)
|
| 319 |
+
self.velocity_head = nn.Linear(WIDTH, LATENT)
|
| 320 |
+
self._cd = compute_dtype
|
| 321 |
+
|
| 322 |
+
# ββ the text refiner (once per prompt) ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 323 |
+
def prepare_text(self, tokens: mx.array, key_bias=None, value_scale=None) -> dict:
|
| 324 |
+
"""tokens [B, L, 2304] float32 (text.py); key_bias / value_scale [B, L] float32 or None (prompt
|
| 325 |
+
emphasis). -> {"tokens": refined float32 [B, L, 2304], "key_bias", "value_scale"}, reused at every step."""
|
| 326 |
+
cd = self._cd
|
| 327 |
+
b, length, _ = tokens.shape
|
| 328 |
+
check_rope_capacity(length, 1, 1)
|
| 329 |
+
sin, cos = _text_rope(length)
|
| 330 |
+
kb = None if key_bias is None else key_bias.astype(cd)[:, None, None, :]
|
| 331 |
+
vs = None if value_scale is None else value_scale.astype(cd)[:, None, :, None]
|
| 332 |
+
x = tokens.astype(F32)
|
| 333 |
+
for block in self.text_refiner_layers:
|
| 334 |
+
x = block(x, sin, cos, None, None, kb, vs, cd)
|
| 335 |
+
return {"tokens": x, "key_bias": key_bias, "value_scale": value_scale}
|
| 336 |
+
|
| 337 |
+
# ββ one forward βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 338 |
+
def __call__(self, latents: mx.array, t: np.ndarray, prepared: dict, path: str = FULL, gain: float = 0.0,
|
| 339 |
+
caption_bias: float = 0.0) -> mx.array:
|
| 340 |
+
"""latents x_t [B, 96, H, W] float32, t float32 [B] (host), the prepared text; path "full" or "path_drop";
|
| 341 |
+
gain: the image layers' self-attention logit gain (queries x exp(gain)); caption_bias: an additive logit bias
|
| 342 |
+
on the prompt's keys (not the 3 learned suffix tokens) in the six suffix layers. -> float32 velocity
|
| 343 |
+
eps - x0, [B, 96, H, W]."""
|
| 344 |
+
cd = self._cd
|
| 345 |
+
b, c, h, w = latents.shape
|
| 346 |
+
text = prepared["tokens"]
|
| 347 |
+
length = text.shape[1]
|
| 348 |
+
check_rope_capacity(length, h, w)
|
| 349 |
+
n = h * w
|
| 350 |
+
image = self.patch_embed(latents.reshape(b, c, n).transpose(0, 2, 1).astype(cd))
|
| 351 |
+
x = mx.concatenate([image, text.astype(cd)], axis=1)
|
| 352 |
+
sin, cos = _joint_rope(length, h, w)
|
| 353 |
+
time_act = _silu_f32(self.time_embed(t, cd))
|
| 354 |
+
lo, hi = SELF_ATTENTION_GAIN_RANGE
|
| 355 |
+
if not (math.isfinite(gain) and lo <= gain <= hi):
|
| 356 |
+
raise ValueError(f"dflow: self-attention gain {gain} outside [{lo}, {hi}]")
|
| 357 |
+
query_scale = float(np.float32(math.exp(gain))) if gain != 0.0 else None
|
| 358 |
+
key_bias = _padded(prepared.get("key_bias"), n, 0.0, cd, "key")
|
| 359 |
+
value_scale = _padded(prepared.get("value_scale"), n, 1.0, cd, "value")
|
| 360 |
+
stream = (sin, cos, query_scale, key_bias, value_scale)
|
| 361 |
+
x = self._run(x, self.prefix_layers, self.prefix_adaln, stream, time_act)
|
| 362 |
+
if path == FULL:
|
| 363 |
+
middle = self._run(x, self.middle_layers, self.middle_adaln, stream, time_act)
|
| 364 |
+
x = self.tail_join(x, middle, False, time_act)
|
| 365 |
+
elif path == PATH_DROP:
|
| 366 |
+
mask = mx.broadcast_to(self.tail_join.mask_token.astype(x.dtype), x.shape)
|
| 367 |
+
x = self.tail_join(x, mask, True, time_act)
|
| 368 |
+
else:
|
| 369 |
+
raise ValueError(f"dflow: path {path!r} (full or path_drop)")
|
| 370 |
+
if caption_bias != 0.0:
|
| 371 |
+
caption = np.zeros((b, n + length), np.float32)
|
| 372 |
+
caption[:, n:n + length - SUFFIX_TOKENS] = caption_bias
|
| 373 |
+
added = mx.array(caption).astype(cd)[:, None, None, :]
|
| 374 |
+
stream = (sin, cos, query_scale, added if key_bias is None else key_bias + added, value_scale)
|
| 375 |
+
x = self._run(x, self.suffix_layers, self.suffix_adaln, stream, time_act)
|
| 376 |
+
return self._final(x[:, :n], time_act, h, w)
|
| 377 |
+
|
| 378 |
+
def _run(self, x, layers, adaln, stream, time_act):
|
| 379 |
+
sin, cos, query_scale, key_bias, value_scale = stream
|
| 380 |
+
for block, projection in zip(layers, adaln):
|
| 381 |
+
x = block(x, sin, cos, projection(time_act).astype(F32), query_scale, key_bias, value_scale, self._cd)
|
| 382 |
+
return x
|
| 383 |
+
|
| 384 |
+
def _final(self, image, time_act, h, w):
|
| 385 |
+
normed = self.final_norm(image)
|
| 386 |
+
shift, scale = mx.split(self.final_modulation(time_act).astype(F32), 2, axis=-1)
|
| 387 |
+
out = (normed.astype(F32) * (1.0 + scale[:, None, :]) + shift[:, None, :]).astype(normed.dtype)
|
| 388 |
+
head = self.velocity_head
|
| 389 |
+
v = mx.addmm(head.bias.astype(out.dtype), out, head.weight.astype(out.dtype).T).astype(F32)
|
| 390 |
+
b = v.shape[0]
|
| 391 |
+
return v.transpose(0, 2, 1).reshape(b, LATENT, h, w)
|
| 392 |
+
|
| 393 |
+
|
| 394 |
+
def _padded(values, image_count: int, fill: float, cd, kind: str):
|
| 395 |
+
"""[B, L] text emphasis prefixed by `fill` for the image rows, as the SDPA mask [B, 1, 1, S] (key) or the value
|
| 396 |
+
multiplier [B, 1, S, 1] (value), in the compute dtype; None stays None."""
|
| 397 |
+
if values is None:
|
| 398 |
+
return None
|
| 399 |
+
pad = mx.full((values.shape[0], image_count), fill, dtype=F32)
|
| 400 |
+
row = mx.concatenate([pad, values.astype(F32)], axis=1).astype(cd)
|
| 401 |
+
return row[:, None, None, :] if kind == "key" else row[:, None, :, None]
|
| 402 |
+
|
| 403 |
+
|
| 404 |
+
# ββ loading βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 405 |
+
|
| 406 |
+
def check_config(model_path: str) -> None:
|
| 407 |
+
"""config.json's "denoiser" must be the architecture above, key for key."""
|
| 408 |
+
path = os.path.join(str(model_path), "config.json")
|
| 409 |
+
with open(path, encoding="utf-8") as f:
|
| 410 |
+
raw = json.load(f)
|
| 411 |
+
got = raw.get("denoiser") or {}
|
| 412 |
+
bad = sorted(k for k in set(CONFIG) | set(got) if got.get(k) != CONFIG.get(k))
|
| 413 |
+
if bad:
|
| 414 |
+
raise ValueError(f"dflow: {path} is not dflow_2b's architecture (keys {bad}) β this port reads the v0.21 release")
|
| 415 |
+
|
| 416 |
+
|
| 417 |
+
def load_denoiser(model_path: str, dtype=mx.bfloat16):
|
| 418 |
+
"""The release's model.safetensors -> (DFlowDenoiser, the text adapter's tensors). Every "denoiser." tensor must
|
| 419 |
+
match the module tree by name and shape (none missing, none extra); stored bfloat16 with float32 norms and
|
| 420 |
+
velocity head, kept as stored for -p bfloat16, upcast for -p float32."""
|
| 421 |
+
check_config(model_path)
|
| 422 |
+
path = os.path.join(str(model_path), "model.safetensors")
|
| 423 |
+
if not os.path.isfile(path):
|
| 424 |
+
raise ValueError(f"dflow: no model.safetensors in {model_path}")
|
| 425 |
+
tensors = mx.load(path)
|
| 426 |
+
den = {k[len(DENOISER_PREFIX):]: v for k, v in tensors.items() if k.startswith(DENOISER_PREFIX)}
|
| 427 |
+
adapter = {k[len(ADAPTER_PREFIX):]: v for k, v in tensors.items() if k.startswith(ADAPTER_PREFIX)}
|
| 428 |
+
other = sorted(k for k in tensors if not k.startswith((DENOISER_PREFIX, ADAPTER_PREFIX)))
|
| 429 |
+
model = DFlowDenoiser(compute_dtype=mx.float32 if dtype == mx.float32 else mx.bfloat16)
|
| 430 |
+
expected = dict(tree_flatten(model.parameters()))
|
| 431 |
+
missing = sorted(set(expected) - set(den))
|
| 432 |
+
unexpected = sorted(set(den) - set(expected))
|
| 433 |
+
shapes = sorted(k for k in set(expected) & set(den) if tuple(expected[k].shape) != tuple(den[k].shape))
|
| 434 |
+
if missing or unexpected or shapes or other:
|
| 435 |
+
raise ValueError(f"dflow: {path} does not match the denoiser: missing {missing[:4]}, unexpected "
|
| 436 |
+
f"{(unexpected + other)[:4]}, misshaped {shapes[:4]}")
|
| 437 |
+
if dtype == mx.float32:
|
| 438 |
+
den = {k: v.astype(mx.float32) for k, v in den.items()}
|
| 439 |
+
model.update(tree_unflatten(list(den.items())))
|
| 440 |
+
mx.eval(model.parameters())
|
| 441 |
+
return model, adapter
|
LVNodes/ComfyUI-DFlow-MLX/dflow_mlx/vae.py
ADDED
|
@@ -0,0 +1,215 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""dinac3_96's decoder on MLX (data-archetype/dinac3_96 at the commit dflow pins): whitened dflow latents
|
| 2 |
+
[B, 96, h, w] -> RGB [B, 3, 16h, 16w] about [-1, 1], one deterministic pass, as the repository's own dinac3/decoder.py,
|
| 3 |
+
trunk.py, conv_up_head.py and layers.py under bfloat16 autocast.
|
| 4 |
+
|
| 5 |
+
dewhiten x = z sqrt(var + 1e-4) + mean (the latent statistics, float32)
|
| 6 |
+
latent_up 1x1 conv 96 -> 1152
|
| 7 |
+
trunk 4 ViT blocks (width 1152, 18 heads of 64, RMS sandwich norms, QK RMSNorm, axial 2-D RoPE, GELU MLP)
|
| 8 |
+
conv up handoff (channel RMSNorm, 1x1 to 512, upsample to /8), four levels of three residual blocks
|
| 9 |
+
(256, 256, 128, 128 channels) with an upsample between levels, readout (RMSNorm, SiLU, 3x3 to RGB).
|
| 10 |
+
Every upsample is nearest x2 then a 3x3 conv, run as the stride-2 transposed conv whose 4x4 kernel
|
| 11 |
+
folds the float32 3x3 weights (UpsampleConv.fold_kernel)
|
| 12 |
+
|
| 13 |
+
Feature maps run channels-last (MLX's convolution layout); the weights keep the release's names and are laid out for
|
| 14 |
+
MLX at load, in memory. The encoder (img2img) is not ported.
|
| 15 |
+
"""
|
| 16 |
+
from __future__ import annotations
|
| 17 |
+
|
| 18 |
+
import json
|
| 19 |
+
import os
|
| 20 |
+
|
| 21 |
+
import mlx.core as mx
|
| 22 |
+
import mlx.nn as nn
|
| 23 |
+
import numpy as np
|
| 24 |
+
|
| 25 |
+
F32 = mx.float32
|
| 26 |
+
EPS = 1e-6
|
| 27 |
+
ROPE_BASE = 10000.0
|
| 28 |
+
NEAREST_CONV_FOLD = np.array([[0.0, 0.0, 1.0], [0.0, 1.0, 1.0], [1.0, 1.0, 0.0], [1.0, 0.0, 0.0]], np.float32)
|
| 29 |
+
CONFIG = {"latent_channels": 96, "decoder_width": 1152, "decoder_depth": 4, "decoder_head_dim": 64,
|
| 30 |
+
"decoder_mlp_ratio": 4.0, "conv_up_handoff_channels": 512, "conv_up_channels": [256, 256, 128, 128],
|
| 31 |
+
"conv_up_blocks_per_level": 3, "latent_stats_eps": 0.0001}
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def _rms(x, weight):
|
| 35 |
+
"""layers.RMSNorm: F.rms_norm with the gain in the input's dtype, float32 inside, rounded once."""
|
| 36 |
+
w = weight.astype(x.dtype).astype(F32)
|
| 37 |
+
return mx.fast.rms_norm(x.astype(F32), w, EPS).astype(x.dtype)
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def _channel_rms(x, weight=None, bias=None):
|
| 41 |
+
"""layers.ChannelRMSNorm on channels-last x: the squares in x's dtype, their mean in float32, rsqrt rounded to x's
|
| 42 |
+
dtype and applied there; the gain and bias in x's dtype."""
|
| 43 |
+
mean_square = mx.mean(mx.square(x).astype(F32), axis=-1, keepdims=True)
|
| 44 |
+
y = x * mx.rsqrt(mean_square + EPS).astype(x.dtype)
|
| 45 |
+
if weight is not None:
|
| 46 |
+
y = y * weight.astype(x.dtype)
|
| 47 |
+
y = y + bias.astype(x.dtype)
|
| 48 |
+
return y
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def _silu(x):
|
| 52 |
+
return nn.silu(x.astype(F32)).astype(x.dtype)
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def _conv3(x, weight, bias):
|
| 56 |
+
"""same_conv: a stride-1 3x3 conv (bias added in the activation dtype); weight [O, 3, 3, I] channels-last."""
|
| 57 |
+
return mx.conv2d(x, weight, padding=1) + bias
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def _pointwise(x, weight, bias):
|
| 61 |
+
"""pointwise_conv: a channel matmul, then the bias (two roundings, as the einsum + add)."""
|
| 62 |
+
return (x @ weight.T) + bias
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def rope_tables(h: int, w: int, head_dim: int):
|
| 66 |
+
"""trunk.rope_tables: float32 (sin, cos) [h*w, head_dim] of axial 2-D RoPE on (row, column), adjacent pairs."""
|
| 67 |
+
exps = (np.float32(2.0) * np.arange(head_dim // 4, dtype=np.float32) / np.float32(head_dim // 2)).astype(np.float32)
|
| 68 |
+
periods = np.power(np.float32(ROPE_BASE), exps).astype(np.float32)
|
| 69 |
+
rows, cols = np.meshgrid(np.arange(h, dtype=np.float32), np.arange(w, dtype=np.float32), indexing="ij")
|
| 70 |
+
coords = np.stack([rows, cols], axis=-1).reshape(-1, 2)
|
| 71 |
+
angles = (np.float32(1.0) * coords[:, :, None] / periods[None, None, :]).astype(np.float32)
|
| 72 |
+
angles = np.repeat(angles, 2, axis=-1).reshape(h * w, head_dim)
|
| 73 |
+
return mx.array(np.sin(angles).astype(np.float32)), mx.array(np.cos(angles).astype(np.float32))
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
def _rotate_pairs(x):
|
| 77 |
+
pairs = x.reshape(*x.shape[:-1], x.shape[-1] // 2, 2)
|
| 78 |
+
return mx.stack([-pairs[..., 1], pairs[..., 0]], axis=-1).reshape(x.shape)
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
class _TrunkBlock:
|
| 82 |
+
def __init__(self, p: dict, width: int, head_dim: int):
|
| 83 |
+
self.p, self.width, self.head_dim = p, width, head_dim
|
| 84 |
+
self.heads = width // head_dim
|
| 85 |
+
|
| 86 |
+
def __call__(self, x, sin, cos):
|
| 87 |
+
p = self.p
|
| 88 |
+
b, n, w = x.shape
|
| 89 |
+
h = _rms(x, p["attn_norm1.weight"])
|
| 90 |
+
q, k, v = mx.split(h @ p["attn.qkv.weight"].T, 3, axis=-1)
|
| 91 |
+
q, k, v = (t.reshape(b, n, self.heads, self.head_dim).transpose(0, 2, 1, 3) for t in (q, k, v))
|
| 92 |
+
q = self._rope(_rms(q, p["attn.q_norm.weight"]), sin, cos)
|
| 93 |
+
k = self._rope(_rms(k, p["attn.k_norm.weight"]), sin, cos)
|
| 94 |
+
out = mx.fast.scaled_dot_product_attention(q, k, v, scale=self.head_dim ** -0.5)
|
| 95 |
+
out = out.transpose(0, 2, 1, 3).reshape(b, n, w) @ p["attn.proj_out.weight"].T
|
| 96 |
+
x = x + _rms(out, p["attn_norm2.weight"])
|
| 97 |
+
h = mx.addmm(p["mlp.up.bias"], _rms(x, p["mlp_norm1.weight"]), p["mlp.up.weight"].T)
|
| 98 |
+
h = nn.gelu(h.astype(F32)).astype(h.dtype)
|
| 99 |
+
h = mx.addmm(p["mlp.down.bias"], h, p["mlp.down.weight"].T)
|
| 100 |
+
return x + _rms(h, p["mlp_norm2.weight"])
|
| 101 |
+
|
| 102 |
+
@staticmethod
|
| 103 |
+
def _rope(x, sin, cos):
|
| 104 |
+
xf = x.astype(F32)
|
| 105 |
+
return (xf * cos + _rotate_pairs(xf) * sin).astype(x.dtype)
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
class Dinac3Decoder:
|
| 109 |
+
"""The decoder with the release's tensors (names as in model.safetensors, minus "decoder.")."""
|
| 110 |
+
|
| 111 |
+
def __init__(self, folder: str, dtype=mx.bfloat16):
|
| 112 |
+
with open(os.path.join(folder, "config.json"), encoding="utf-8") as f:
|
| 113 |
+
cfg = json.load(f)
|
| 114 |
+
bad = [k for k, v in CONFIG.items() if cfg.get(k) != v]
|
| 115 |
+
if bad:
|
| 116 |
+
raise ValueError(f"dflow: {folder}/config.json is not dinac3_96's decoder (keys {bad})")
|
| 117 |
+
raw = mx.load(os.path.join(folder, "model.safetensors"))
|
| 118 |
+
self.dtype = dtype
|
| 119 |
+
self.mean = raw["latent_mean"].astype(F32).reshape(1, -1, 1, 1)
|
| 120 |
+
self.std = mx.sqrt(raw["latent_var"].astype(F32).reshape(1, -1, 1, 1) + CONFIG["latent_stats_eps"])
|
| 121 |
+
dec = {k[len("decoder."):]: v for k, v in raw.items() if k.startswith("decoder.")}
|
| 122 |
+
expected = self._expected_keys()
|
| 123 |
+
missing, unexpected = sorted(expected - set(dec)), sorted(set(dec) - expected)
|
| 124 |
+
if missing or unexpected:
|
| 125 |
+
raise ValueError(f"dflow: {folder}/model.safetensors does not match dinac3_96's decoder: missing "
|
| 126 |
+
f"{missing[:4]}, unexpected {unexpected[:4]}")
|
| 127 |
+
cast = (lambda a: a.astype(F32)) if dtype == F32 else (lambda a: a)
|
| 128 |
+
self.p = {}
|
| 129 |
+
for name, value in dec.items():
|
| 130 |
+
if name.endswith(".fold"):
|
| 131 |
+
if not np.array_equal(np.array(value.astype(F32)), NEAREST_CONV_FOLD):
|
| 132 |
+
raise ValueError(f"dflow: {name} is not the nearest x2 fold matrix")
|
| 133 |
+
continue
|
| 134 |
+
if value.ndim == 4 and not name.endswith("upsample.conv.weight") and ".upsamples." not in name:
|
| 135 |
+
if value.shape[-1] == 1 and value.shape[-2] == 1:
|
| 136 |
+
value = value.reshape(value.shape[0], value.shape[1]) # 1x1 conv -> matrix [O, I]
|
| 137 |
+
else:
|
| 138 |
+
value = value.transpose(0, 2, 3, 1) # [O, I, kh, kw] -> [O, kh, kw, I]
|
| 139 |
+
self.p[name] = cast(value)
|
| 140 |
+
#: the upsamplers' 4x4 transposed kernels, folded once from the float32 3x3 weights in float32, then held in the
|
| 141 |
+
#: activation dtype (autocast casts the kernel to bfloat16 at use)
|
| 142 |
+
for prefix in ["conv_up_head.handoff_upsample"] + [f"conv_up_head.upsamples.{i}" for i in range(3)]:
|
| 143 |
+
w3 = np.array(dec[f"{prefix}.conv.weight"].astype(F32)) # [O, I, 3, 3]
|
| 144 |
+
kernel = np.einsum("ka,ocab,lb->ockl", NEAREST_CONV_FOLD, w3, NEAREST_CONV_FOLD) # [O, I, 4, 4]
|
| 145 |
+
self.p[f"{prefix}.kernel"] = mx.array(np.ascontiguousarray(kernel.transpose(0, 2, 3, 1))).astype(
|
| 146 |
+
F32 if dtype == F32 else mx.bfloat16) # [O, 4, 4, I]
|
| 147 |
+
self.p[f"{prefix}.conv.bias"] = cast(dec[f"{prefix}.conv.bias"])
|
| 148 |
+
del self.p[f"{prefix}.conv.weight"]
|
| 149 |
+
mx.eval(list(self.p.values()) + [self.mean, self.std])
|
| 150 |
+
hd = CONFIG["decoder_head_dim"]
|
| 151 |
+
self.trunk = [_TrunkBlock({k[len(f"trunk.{i}."):]: v for k, v in self.p.items() if k.startswith(f"trunk.{i}.")},
|
| 152 |
+
CONFIG["decoder_width"], hd) for i in range(CONFIG["decoder_depth"])]
|
| 153 |
+
|
| 154 |
+
@staticmethod
|
| 155 |
+
def _expected_keys() -> set:
|
| 156 |
+
keys = {"latent_up.weight", "latent_up.bias", "conv_up_head.handoff_proj.weight",
|
| 157 |
+
"conv_up_head.handoff_proj.bias", "conv_up_head.out_norm.weight", "conv_up_head.out_norm.bias",
|
| 158 |
+
"conv_up_head.out_proj.weight", "conv_up_head.out_proj.bias"}
|
| 159 |
+
for i in range(CONFIG["decoder_depth"]):
|
| 160 |
+
for n in ("attn_norm1.weight", "attn_norm2.weight", "mlp_norm1.weight", "mlp_norm2.weight",
|
| 161 |
+
"attn.qkv.weight", "attn.proj_out.weight", "attn.q_norm.weight", "attn.k_norm.weight",
|
| 162 |
+
"mlp.up.weight", "mlp.up.bias", "mlp.down.weight", "mlp.down.bias"):
|
| 163 |
+
keys.add(f"trunk.{i}.{n}")
|
| 164 |
+
for prefix in ["conv_up_head.handoff_upsample"] + [f"conv_up_head.upsamples.{i}" for i in range(3)]:
|
| 165 |
+
keys |= {f"{prefix}.conv.weight", f"{prefix}.conv.bias", f"{prefix}.fold"}
|
| 166 |
+
width, idx = CONFIG["conv_up_handoff_channels"], 0
|
| 167 |
+
for channels in CONFIG["conv_up_channels"]:
|
| 168 |
+
for _ in range(CONFIG["conv_up_blocks_per_level"]):
|
| 169 |
+
b = f"conv_up_head.blocks.{idx}"
|
| 170 |
+
keys |= {f"{b}.{n}" for n in ("norm1.weight", "norm1.bias", "conv1.weight", "conv1.bias",
|
| 171 |
+
"norm2.weight", "norm2.bias", "conv2.weight", "conv2.bias")}
|
| 172 |
+
if width != channels:
|
| 173 |
+
keys |= {f"{b}.shortcut.weight", f"{b}.shortcut.bias"}
|
| 174 |
+
width, idx = channels, idx + 1
|
| 175 |
+
return keys
|
| 176 |
+
|
| 177 |
+
def _upsample(self, x, prefix):
|
| 178 |
+
p = self.p
|
| 179 |
+
return mx.conv_transpose2d(x, p[f"{prefix}.kernel"], stride=2, padding=1) + p[f"{prefix}.conv.bias"]
|
| 180 |
+
|
| 181 |
+
def _block(self, x, idx):
|
| 182 |
+
p, b = self.p, f"conv_up_head.blocks.{idx}"
|
| 183 |
+
h = _conv3(_silu(_channel_rms(x, p[f"{b}.norm1.weight"], p[f"{b}.norm1.bias"])), p[f"{b}.conv1.weight"],
|
| 184 |
+
p[f"{b}.conv1.bias"])
|
| 185 |
+
h = _conv3(_silu(_channel_rms(h, p[f"{b}.norm2.weight"], p[f"{b}.norm2.bias"])), p[f"{b}.conv2.weight"],
|
| 186 |
+
p[f"{b}.conv2.bias"])
|
| 187 |
+
skip = x if f"{b}.shortcut.weight" not in p else _pointwise(x, p[f"{b}.shortcut.weight"], p[f"{b}.shortcut.bias"])
|
| 188 |
+
return skip + h
|
| 189 |
+
|
| 190 |
+
def decode(self, latents: mx.array) -> mx.array:
|
| 191 |
+
"""Whitened float32 latents [B, 96, h, w] -> float32 RGB [B, 3, 16h, 16w], unclamped (about [-1, 1])."""
|
| 192 |
+
p = self.p
|
| 193 |
+
cd = F32 if self.dtype == F32 else mx.bfloat16
|
| 194 |
+
raw = latents.astype(F32) * self.std + self.mean
|
| 195 |
+
b, c, h, w = raw.shape
|
| 196 |
+
x = raw.transpose(0, 2, 3, 1).astype(cd) # [B, h, w, 96]
|
| 197 |
+
x = mx.addmm(p["latent_up.bias"], x.reshape(b * h * w, c), p["latent_up.weight"].T)
|
| 198 |
+
tokens = x.reshape(b, h * w, -1)
|
| 199 |
+
sin, cos = rope_tables(h, w, CONFIG["decoder_head_dim"])
|
| 200 |
+
for block in self.trunk:
|
| 201 |
+
tokens = block(tokens, sin, cos)
|
| 202 |
+
feats = tokens.reshape(b, h, w, -1)
|
| 203 |
+
x = _pointwise(_channel_rms(feats), p["conv_up_head.handoff_proj.weight"], p["conv_up_head.handoff_proj.bias"])
|
| 204 |
+
x = self._upsample(x, "conv_up_head.handoff_upsample")
|
| 205 |
+
per = CONFIG["conv_up_blocks_per_level"]
|
| 206 |
+
levels = len(CONFIG["conv_up_channels"])
|
| 207 |
+
for idx in range(per * levels):
|
| 208 |
+
x = self._block(x, idx)
|
| 209 |
+
level, position = divmod(idx, per)
|
| 210 |
+
if position == per - 1 and level < levels - 1:
|
| 211 |
+
x = self._upsample(x, f"conv_up_head.upsamples.{level}")
|
| 212 |
+
mx.eval(x)
|
| 213 |
+
x = _silu(_channel_rms(x, p["conv_up_head.out_norm.weight"], p["conv_up_head.out_norm.bias"]))
|
| 214 |
+
x = _conv3(x, p["conv_up_head.out_proj.weight"], p["conv_up_head.out_proj.bias"])
|
| 215 |
+
return x.astype(F32).transpose(0, 3, 1, 2)
|
LVNodes/ComfyUI-DFlow-MLX/dflow_mlx_worker.py
ADDED
|
@@ -0,0 +1,98 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Helper process for ComfyUI-DFlow-MLX.
|
| 2 |
+
|
| 3 |
+
Runs inside the shared LVNodes MLX environment (LVNodes/.venv), never inside ComfyUI's, and renders dflow_2b pictures on
|
| 4 |
+
Apple MLX (the dflow_mlx package beside this file). ComfyUI talks to it over stdin/stdout, one JSON object per line:
|
| 5 |
+
|
| 6 |
+
request {"cmd": "generate", "model_dir", "loras": [[path, strength]], "precision", "prompt", "width", "height",
|
| 7 |
+
"steps", "seed", "guidance", "solver", "gain" (null = by size), "keep_loaded"}
|
| 8 |
+
{"cmd": "unload"} {"cmd": "quit"}
|
| 9 |
+
replies {"event": "ready", "mlx": ...} {"event": "phase", "text": ...} {"event": "progress", "step": i, "total": n}
|
| 10 |
+
{"event": "done", "path": ".../image.npy", "seconds": s} {"event": "error", "message": ...}
|
| 11 |
+
|
| 12 |
+
The model is the dflow_2b release folder as downloaded (model.safetensors, text_encoder/, the dflow/ package whose
|
| 13 |
+
torch-free tokenizer and layout modules are read); dinac3_96 comes from a folder of that name inside it, else the Hugging
|
| 14 |
+
Face cache (downloaded on first use, as the release itself does).
|
| 15 |
+
"""
|
| 16 |
+
import json
|
| 17 |
+
import os
|
| 18 |
+
import sys
|
| 19 |
+
import time
|
| 20 |
+
import traceback
|
| 21 |
+
import uuid
|
| 22 |
+
|
| 23 |
+
os.environ.setdefault("TOKENIZERS_PARALLELISM", "false")
|
| 24 |
+
PACK = os.path.dirname(os.path.abspath(__file__))
|
| 25 |
+
CACHE = os.path.join(os.path.dirname(PACK), ".cache", "dflow-mlx")
|
| 26 |
+
sys.path.insert(0, PACK)
|
| 27 |
+
|
| 28 |
+
PIPE = None
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def emit(**message):
|
| 32 |
+
sys.stdout.write(json.dumps(message) + "\n")
|
| 33 |
+
sys.stdout.flush()
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def log(text):
|
| 37 |
+
print(f"[DFlow MLX] {text}", file=sys.stderr, flush=True)
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def generate(req):
|
| 41 |
+
global PIPE
|
| 42 |
+
import numpy as np
|
| 43 |
+
from dflow_mlx.pipeline import DFlowPipeline
|
| 44 |
+
loras = [(str(p), float(w)) for p, w in (req.get("loras") or []) if float(w) != 0.0]
|
| 45 |
+
precision = req.get("precision") or "float16"
|
| 46 |
+
key = (os.path.abspath(req["model_dir"]), tuple(loras), precision)
|
| 47 |
+
if PIPE is not None and PIPE.key() != key:
|
| 48 |
+
PIPE.free()
|
| 49 |
+
PIPE = None
|
| 50 |
+
if PIPE is None:
|
| 51 |
+
PIPE = DFlowPipeline(req["model_dir"], loras, precision, log=log)
|
| 52 |
+
t0 = time.time()
|
| 53 |
+
gain = req.get("gain")
|
| 54 |
+
image = PIPE.render(req.get("prompt") or "", int(req["width"]), int(req["height"]), int(req["steps"]),
|
| 55 |
+
int(req["seed"]), guidance=float(req.get("guidance", 1.0)), solver=req.get("solver") or "euler",
|
| 56 |
+
gain=None if gain is None else float(gain), keep_loaded=bool(req.get("keep_loaded")),
|
| 57 |
+
on_phase=lambda text: emit(event="phase", text=text),
|
| 58 |
+
on_step=lambda i, n: emit(event="progress", step=i, total=n))
|
| 59 |
+
os.makedirs(CACHE, exist_ok=True)
|
| 60 |
+
path = os.path.join(CACHE, f"image-{uuid.uuid4().hex}.npy")
|
| 61 |
+
np.save(path, image)
|
| 62 |
+
seconds = time.time() - t0
|
| 63 |
+
log(f"{image.shape[1]}x{image.shape[0]}, {req['steps']} steps, {req.get('solver')}, guidance {req.get('guidance')}: "
|
| 64 |
+
f"{seconds:.1f} s")
|
| 65 |
+
emit(event="done", path=path, seconds=round(seconds, 2))
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def main():
|
| 69 |
+
import mlx.core as mx
|
| 70 |
+
emit(event="ready", mlx=mx.__version__)
|
| 71 |
+
global PIPE
|
| 72 |
+
for line in sys.stdin:
|
| 73 |
+
line = line.strip()
|
| 74 |
+
if not line:
|
| 75 |
+
continue
|
| 76 |
+
try:
|
| 77 |
+
req = json.loads(line)
|
| 78 |
+
cmd = req.get("cmd")
|
| 79 |
+
if cmd == "generate":
|
| 80 |
+
generate(req)
|
| 81 |
+
elif cmd == "unload":
|
| 82 |
+
if PIPE is not None:
|
| 83 |
+
PIPE.free()
|
| 84 |
+
PIPE = None
|
| 85 |
+
emit(event="done")
|
| 86 |
+
elif cmd == "ping":
|
| 87 |
+
emit(event="pong")
|
| 88 |
+
elif cmd == "quit":
|
| 89 |
+
break
|
| 90 |
+
else:
|
| 91 |
+
emit(event="error", message=f"unknown command {cmd!r}")
|
| 92 |
+
except Exception as e: # noqa: BLE001 - every failure goes back to the node as a message
|
| 93 |
+
traceback.print_exc(file=sys.stderr)
|
| 94 |
+
emit(event="error", message=f"{type(e).__name__}: {e}")
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
if __name__ == "__main__":
|
| 98 |
+
main()
|
LVNodes/README.md
CHANGED
|
@@ -12,7 +12,8 @@ A collection of ComfyUI node sets, one folder each, loaded as **one** custom nod
|
|
| 12 |
| `ComfyUI-SeedVR2-1.4B/` | Lets ComfyUI load **SeedVR2 1.4B** ([lvladikov/SeedVR2-1.4B](https://huggingface.co/lvladikov/SeedVR2-1.4B)), a 6-block distill of SeedVR2 7B sharp that ComfyUI's own model detection doesn't recognise. It adds no nodes and only answers when ComfyUI's detection finds nothing | nothing |
|
| 13 |
| `ComfyUI-Skip-Blocks/` | **Skip Blocks (DiT)** (`LVSkipBlocks`): skips chosen transformer blocks of a diffusion model for a run (experimental, training-free depth pruning), through ComfyUI's block hook (MiniMax-H3, LTX, Wan, Flux, Qwen-Image, ...) or by swapping the block for the run (Krea 2, Z-Image, SD / SDXL's transformer layers); presets measured for MiniMax-H3-Image and LTX-2.5's two stages | nothing |
|
| 14 |
| `ComfyUI-Native-Upscalers/` | **Upscale Image (native)** (`LVNativeUpscale`): enlarging without a model, Lanczos with 3, 8 or 16 lobes and the edge-directed DCCI, NEDI and ICBI, which double per pass and finish with Lanczos to the exact size | nothing (PyTorch, which ComfyUI has) |
|
| 15 |
-
| `ComfyUI-DFlow-LoRA/` | **DFlow LoRA (unmerged)** and **DFlow Size and Gain (from latent)** (`LVDFlowLoRALoader`, `LVDFlowSizeFromLatent`): a LoRA for [dflow_2b](https://huggingface.co/data-archetype/dflow_2b)'s own nodes, which have no LoRA support, applied beside the weights rather than merged into them; and the settings that depend on the image size (the guider's self-attention gain, the layout's width and height) read from DFlow Empty Latent, so the size is set in one place. Made for the [DFlow2 4-step LoRA](https://huggingface.co/lvladikov/DFlow2-Distill-4steps-eDMD-LADD-LoRA), whose workflows use both. GPL-3.0 (its own `LICENSE`), as dflow_2b's nodes are | dflow_2b's own nodes, installed as its README says (their loader also needs `timm`) |
|
|
|
|
| 16 |
| `ComfyUI-Krea2-MLX/` | Krea 2 (Turbo and Raw) on Apple MLX: **Krea 2 Model (MLX)** (`LVKrea2MLXModel`) and **Krea 2 Sampler (MLX)** (`LVKrea2MLXSampler`), with CFG and a negative prompt, and float16 compute inside the model's layers (on by default; about a quarter faster on M1 / M2 Macs) | an Apple Silicon Mac; its MLX environment (`.venv`) sets itself up, see below |
|
| 17 |
| `ComfyUI-Z-Image-MLX/` | Z-Image (Turbo and Base) on Apple MLX: **Z-Image Model (MLX)** (`LVZImageMLXModel`) and **Z-Image Sampler (MLX)** (`LVZImageMLXSampler`), sampled as ComfyUI does (res_multistep, ComfyUI's CFG with a negative prompt, Tongyi's shift: 3 for Turbo, 6 for Base), with float16 compute for Turbo (on by default) | an Apple Silicon Mac; the same MLX environment |
|
| 18 |
| `ComfyUI-MiniMax-Music3-MLX/` | MiniMax Music 3 on Apple MLX: **MiniMax Music 3 Model (MLX)** (`LVMiniMaxMusic3MLXModel`) and **MiniMax Music 3 Sampler (MLX)** (`LVMiniMaxMusic3MLXSampler`), songs from a caption and lyrics, from ComfyUI's own bf16, fp16 or int8 files, with an int8 LLM by default | an Apple Silicon Mac; the same MLX environment |
|
|
|
|
| 12 |
| `ComfyUI-SeedVR2-1.4B/` | Lets ComfyUI load **SeedVR2 1.4B** ([lvladikov/SeedVR2-1.4B](https://huggingface.co/lvladikov/SeedVR2-1.4B)), a 6-block distill of SeedVR2 7B sharp that ComfyUI's own model detection doesn't recognise. It adds no nodes and only answers when ComfyUI's detection finds nothing | nothing |
|
| 13 |
| `ComfyUI-Skip-Blocks/` | **Skip Blocks (DiT)** (`LVSkipBlocks`): skips chosen transformer blocks of a diffusion model for a run (experimental, training-free depth pruning), through ComfyUI's block hook (MiniMax-H3, LTX, Wan, Flux, Qwen-Image, ...) or by swapping the block for the run (Krea 2, Z-Image, SD / SDXL's transformer layers); presets measured for MiniMax-H3-Image and LTX-2.5's two stages | nothing |
|
| 14 |
| `ComfyUI-Native-Upscalers/` | **Upscale Image (native)** (`LVNativeUpscale`): enlarging without a model, Lanczos with 3, 8 or 16 lobes and the edge-directed DCCI, NEDI and ICBI, which double per pass and finish with Lanczos to the exact size | nothing (PyTorch, which ComfyUI has) |
|
| 15 |
+
| `ComfyUI-DFlow-LoRA/` | **DFlow LoRA (unmerged)** and **DFlow Size and Gain (from latent)** (`LVDFlowLoRALoader`, `LVDFlowSizeFromLatent`): a LoRA for [dflow_2b](https://huggingface.co/data-archetype/dflow_2b)'s own nodes, which have no LoRA support, applied beside the weights rather than merged into them; and the settings that depend on the image size (the guider's self-attention gain, the layout's width and height) read from DFlow Empty Latent, so the size is set in one place. Made for the [DFlow2 4-step LoRA](https://huggingface.co/lvladikov/DFlow2-Distill-4steps-eDMD-LADD-LoRA), whose workflows use both. GPL-3.0 (its own `LICENSE`), as dflow_2b's nodes are | dflow_2b's own nodes, installed as its README says (their loader also needs `timm`); an NVIDIA GPU, since they run on CUDA only |
|
| 16 |
+
| `ComfyUI-DFlow-MLX/` | dflow_2b on Apple MLX: **DFlow Model (MLX)** (`LVDFlowMLXModel`: the dflow_2b folder, an optional LoRA applied unmerged, float16 compute) and **DFlow Sampler (MLX)** (`LVDFlowMLXSampler`: a prompt or one of dflow's JSON layouts, size, steps, seed, path-drop guidance and solver), sampled as the release does, a seed drawing the release's own noise; for the [DFlow2 4-step LoRA](https://huggingface.co/lvladikov/DFlow2-Distill-4steps-eDMD-LADD-LoRA): 4 steps, guidance 1, euler. GPL-3.0 (its own `LICENSE`: a port of dflow_2b's inference code) | an Apple Silicon Mac; dflow_2b downloaded into `custom_nodes/dflow_2b` (its weights and prompt rules are read from there; its autoencoder downloads on the first run); the same MLX environment |
|
| 17 |
| `ComfyUI-Krea2-MLX/` | Krea 2 (Turbo and Raw) on Apple MLX: **Krea 2 Model (MLX)** (`LVKrea2MLXModel`) and **Krea 2 Sampler (MLX)** (`LVKrea2MLXSampler`), with CFG and a negative prompt, and float16 compute inside the model's layers (on by default; about a quarter faster on M1 / M2 Macs) | an Apple Silicon Mac; its MLX environment (`.venv`) sets itself up, see below |
|
| 18 |
| `ComfyUI-Z-Image-MLX/` | Z-Image (Turbo and Base) on Apple MLX: **Z-Image Model (MLX)** (`LVZImageMLXModel`) and **Z-Image Sampler (MLX)** (`LVZImageMLXSampler`), sampled as ComfyUI does (res_multistep, ComfyUI's CFG with a negative prompt, Tongyi's shift: 3 for Turbo, 6 for Base), with float16 compute for Turbo (on by default) | an Apple Silicon Mac; the same MLX environment |
|
| 19 |
| `ComfyUI-MiniMax-Music3-MLX/` | MiniMax Music 3 on Apple MLX: **MiniMax Music 3 Model (MLX)** (`LVMiniMaxMusic3MLXModel`) and **MiniMax Music 3 Sampler (MLX)** (`LVMiniMaxMusic3MLXSampler`), songs from a caption and lyrics, from ComfyUI's own bf16, fp16 or int8 files, with an int8 LLM by default | an Apple Silicon Mac; the same MLX environment |
|
README.md
CHANGED
|
@@ -23,7 +23,7 @@ A collection of ComfyUI workflows and nodes: apps for image, music and language
|
|
| 23 |
|
| 24 |
| Date | What's new |
|
| 25 |
|---|---|
|
| 26 |
-
| 21 Nov 2026 | A LoRA for [dflow_2b](https://huggingface.co/data-archetype/dflow_2b) in ComfyUI: LVNodes' [DFlow LoRA](LVNodes/ComfyUI-DFlow-LoRA/README.md) nodes, made for the [DFlow2 4-step LoRA](https://huggingface.co/lvladikov/DFlow2-Distill-4steps-eDMD-LADD-LoRA) (4 model passes a picture instead of 100), whose repository has the workflows |
|
| 27 |
| 19 Oct 2026 | Upscalers that need no model, for Krea 2 and Z-Image: pure computation, so nothing to download and much faster than SeedVR2. The star is [**ICBI**](LVNodes/ComfyUI-Native-Upscalers/README.md): sharp, clean edges on generated photos in seconds (local; Cloud gets Lanczos) |
|
| 28 |
| 11 Oct 2026 | The [SeedVR2 1.4B distill](https://huggingface.co/lvladikov/SeedVR2-1.4B) upscaler in the local Krea 2 and Z-Image workflows: near-7B detail, faster and far lighter |
|
| 29 |
| 10 Oct 2026 | Krea 2 Turbo's [2-step LoRA](https://huggingface.co/lvladikov/Krea2-Turbo-Distill-2step-LoRA): final version under the same file name, so get it again |
|
|
@@ -52,10 +52,10 @@ A collection of ComfyUI workflows and nodes: apps for image, music and language
|
|
| 52 |
- π£οΈ **Prompt enhancement with any LLM** β by default the same file as the model's text encoder (Qwen3-VL 4B for Krea 2, Qwen3 4B for Z-Image), so nothing extra to download; falls back to your own prompt if the LLM refuses or returns nothing
|
| 53 |
- π¨ **Extra LoRAs and upscaling** β style LoRAs on top, with their own strength and trigger words; SeedVR2 7B (locally also its 1.4B distill), classic upscalers, or ones without a model (Lanczos; locally also Lanczos-8 / -16, DCCI, NEDI and ICBI) at any factor (a 3.5 MP image at 4Γ comes out at 8864Γ6624)
|
| 54 |
- π§ **Memory on demand (local)** β models load stage by stage, and **Keep models loaded** holds them between runs only when you want, whatever ComfyUI's startup flags
|
| 55 |
-
- π§© **[LVNodes](LVNodes/README.md), one light pack** β the MLX nodes for all three models and for language models, LLM Chat and its chat view, loaders that need only the files a run uses, keep-loaded loaders, seeded random prompts, live dataset rows, Wait For gates, block skipping for faster diffusion steps, a LoRA loader for dflow_2b's own nodes, and in the app the status line, the keep checkbox, settings that follow the model and a fresh first seed. It needs nothing beyond Python's standard library (LLM Chat also uses Jinja2 and regex, which ComfyUI already has), except the MLX nodes: on their first run they make a one-off install of mflux, MLX, mlx-lm, mlx-vlm and transformers 5 (about 1.3 GB, a few minutes, automatic) into LVNodes' own environment, so ComfyUI's packages stay untouched. Besides LVNodes, the local workflows need only KJNodes (for the Set/Get pills); Comfy Cloud needs nothing
|
| 56 |
- π§Ή **No spaghetti** β every workflow starts from a Fields β Set column and wires its groups with Set/Get pills, aligned with even gaps
|
| 57 |
- π₯ **Models download themselves** β every file carries its link for ComfyUI's missing-models dialog
|
| 58 |
-
- π **Apache-2.0** β workflows, nodes and docs (
|
| 59 |
|
| 60 |
| Model | Folder | Versions |
|
| 61 |
|---|---|---|
|
|
@@ -190,4 +190,4 @@ Each model's README adds its own Mac tips, such as which model files suit a Mac.
|
|
| 190 |
|
| 191 |
## Licences
|
| 192 |
|
| 193 |
-
Everything in this project, the workflows, LVNodes and these READMEs, is under the [Apache License 2.0](LICENSE), except the three JavaScript libraries LLM Chat's view uses (marked and Mermaid, MIT; DOMPurify, Apache-2.0 or MPL-2.0), which keep their own licences: see [LVNodes/web/lib/LICENSES.md](LVNodes/web/lib/LICENSES.md); and LVNodes' `ComfyUI-DFlow-LoRA` node
|
|
|
|
| 23 |
|
| 24 |
| Date | What's new |
|
| 25 |
|---|---|
|
| 26 |
+
| 21 Nov 2026 | A LoRA for [dflow_2b](https://huggingface.co/data-archetype/dflow_2b) in ComfyUI: LVNodes' [DFlow LoRA](LVNodes/ComfyUI-DFlow-LoRA/README.md) nodes (NVIDIA), and [DFlow MLX](LVNodes/ComfyUI-DFlow-MLX/README.md), dflow_2b on an Apple Silicon Mac, whose own nodes run on CUDA only; made for the [DFlow2 4-step LoRA](https://huggingface.co/lvladikov/DFlow2-Distill-4steps-eDMD-LADD-LoRA) (4 model passes a picture instead of 100), whose repository has the workflows |
|
| 27 |
| 19 Oct 2026 | Upscalers that need no model, for Krea 2 and Z-Image: pure computation, so nothing to download and much faster than SeedVR2. The star is [**ICBI**](LVNodes/ComfyUI-Native-Upscalers/README.md): sharp, clean edges on generated photos in seconds (local; Cloud gets Lanczos) |
|
| 28 |
| 11 Oct 2026 | The [SeedVR2 1.4B distill](https://huggingface.co/lvladikov/SeedVR2-1.4B) upscaler in the local Krea 2 and Z-Image workflows: near-7B detail, faster and far lighter |
|
| 29 |
| 10 Oct 2026 | Krea 2 Turbo's [2-step LoRA](https://huggingface.co/lvladikov/Krea2-Turbo-Distill-2step-LoRA): final version under the same file name, so get it again |
|
|
|
|
| 52 |
- π£οΈ **Prompt enhancement with any LLM** β by default the same file as the model's text encoder (Qwen3-VL 4B for Krea 2, Qwen3 4B for Z-Image), so nothing extra to download; falls back to your own prompt if the LLM refuses or returns nothing
|
| 53 |
- π¨ **Extra LoRAs and upscaling** β style LoRAs on top, with their own strength and trigger words; SeedVR2 7B (locally also its 1.4B distill), classic upscalers, or ones without a model (Lanczos; locally also Lanczos-8 / -16, DCCI, NEDI and ICBI) at any factor (a 3.5 MP image at 4Γ comes out at 8864Γ6624)
|
| 54 |
- π§ **Memory on demand (local)** β models load stage by stage, and **Keep models loaded** holds them between runs only when you want, whatever ComfyUI's startup flags
|
| 55 |
+
- π§© **[LVNodes](LVNodes/README.md), one light pack** β the MLX nodes for all three models and for language models, LLM Chat and its chat view, loaders that need only the files a run uses, keep-loaded loaders, seeded random prompts, live dataset rows, Wait For gates, block skipping for faster diffusion steps, a LoRA loader for dflow_2b's own nodes and dflow_2b on MLX, and in the app the status line, the keep checkbox, settings that follow the model and a fresh first seed. It needs nothing beyond Python's standard library (LLM Chat also uses Jinja2 and regex, which ComfyUI already has), except the MLX nodes: on their first run they make a one-off install of mflux, MLX, mlx-lm, mlx-vlm and transformers 5 (about 1.3 GB, a few minutes, automatic) into LVNodes' own environment, so ComfyUI's packages stay untouched. Besides LVNodes, the local workflows need only KJNodes (for the Set/Get pills); Comfy Cloud needs nothing
|
| 56 |
- π§Ή **No spaghetti** β every workflow starts from a Fields β Set column and wires its groups with Set/Get pills, aligned with even gaps
|
| 57 |
- π₯ **Models download themselves** β every file carries its link for ComfyUI's missing-models dialog
|
| 58 |
+
- π **Apache-2.0** β workflows, nodes and docs (two node sets, ComfyUI-DFlow-LoRA and ComfyUI-DFlow-MLX, are GPL-3.0, as dflow_2b's own code is)
|
| 59 |
|
| 60 |
| Model | Folder | Versions |
|
| 61 |
|---|---|---|
|
|
|
|
| 190 |
|
| 191 |
## Licences
|
| 192 |
|
| 193 |
+
Everything in this project, the workflows, LVNodes and these READMEs, is under the [Apache License 2.0](LICENSE), except the three JavaScript libraries LLM Chat's view uses (marked and Mermaid, MIT; DOMPurify, Apache-2.0 or MPL-2.0), which keep their own licences: see [LVNodes/web/lib/LICENSES.md](LVNodes/web/lib/LICENSES.md); and LVNodes' `ComfyUI-DFlow-LoRA` and `ComfyUI-DFlow-MLX` node sets, which are GPL-3.0 ([LICENSE](LVNodes/ComfyUI-DFlow-LoRA/LICENSE), [LICENSE](LVNodes/ComfyUI-DFlow-MLX/LICENSE)), as dflow_2b's own code is (ComfyUI-DFlow-MLX ports its inference code to MLX). The models are not part of it: each workflow downloads them from their own repositories, under their own licences, which the model's folder names. For Krea 2 that is the Krea 2 Community License ([Krea-2/LICENSE.pdf](Krea-2/LICENSE.pdf)), which covers the Krea model files and the 2-step and 4-step LoRAs. Z-Image (Base), Z-Image Turbo, the step LoRAs and UltraFlux are Apache-2.0, and TAEF1 is MIT. MiniMax Music 3 is under the MiniMax-Music3 Community License ([Minimax-Music3/LICENSE](Minimax-Music3/LICENSE)). Image2Text's and LLM Chat's default model, Qwen3-VL, is Apache-2.0; the other language models are under their own licences, which their model cards state. `LVNodes/ComfyUI-MLX-LLM/gemma4_configs.json` holds settings from Google's Gemma 4 model cards.
|