Emmanuel Durand commited on
Commit
8749e18
·
1 Parent(s): a2f1ee5

Add the whole ComfyUI sources

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. CODEOWNERS +24 -0
  2. CONTRIBUTING.md +41 -0
  3. LICENSE +674 -0
  4. api_server/__init__.py +0 -0
  5. api_server/routes/__init__.py +0 -0
  6. api_server/routes/internal/README.md +3 -0
  7. api_server/routes/internal/__init__.py +0 -0
  8. api_server/routes/internal/internal_routes.py +73 -0
  9. api_server/services/__init__.py +0 -0
  10. api_server/services/terminal_service.py +60 -0
  11. api_server/utils/file_operations.py +42 -0
  12. app/__init__.py +0 -0
  13. app/app_settings.py +65 -0
  14. app/custom_node_manager.py +145 -0
  15. app/frontend_management.py +322 -0
  16. app/logger.py +98 -0
  17. app/model_manager.py +184 -0
  18. app/user_manager.py +436 -0
  19. comfy/checkpoint_pickle.py +13 -0
  20. comfy/cldm/cldm.py +433 -0
  21. comfy/cldm/control_types.py +10 -0
  22. comfy/cldm/dit_embedder.py +120 -0
  23. comfy/cldm/mmdit.py +81 -0
  24. comfy/cli_args.py +229 -0
  25. comfy/clip_config_bigg.json +23 -0
  26. comfy/clip_model.py +244 -0
  27. comfy/clip_vision.py +148 -0
  28. comfy/clip_vision_config_g.json +18 -0
  29. comfy/clip_vision_config_h.json +18 -0
  30. comfy/clip_vision_config_vitl.json +18 -0
  31. comfy/clip_vision_config_vitl_336.json +18 -0
  32. comfy/clip_vision_config_vitl_336_llava.json +19 -0
  33. comfy/clip_vision_siglip_384.json +13 -0
  34. comfy/clip_vision_siglip_512.json +13 -0
  35. comfy/comfy_types/README.md +43 -0
  36. comfy/comfy_types/__init__.py +46 -0
  37. comfy/comfy_types/examples/example_nodes.py +28 -0
  38. comfy/comfy_types/examples/input_options.png +0 -0
  39. comfy/comfy_types/examples/input_types.png +0 -0
  40. comfy/comfy_types/examples/required_hint.png +0 -0
  41. comfy/comfy_types/node_typing.py +348 -0
  42. comfy/conds.py +130 -0
  43. comfy/controlnet.py +857 -0
  44. comfy/diffusers_convert.py +189 -0
  45. comfy/diffusers_load.py +36 -0
  46. comfy/extra_samplers/uni_pc.py +873 -0
  47. comfy/float.py +67 -0
  48. comfy/gligen.py +344 -0
  49. comfy/hooks.py +785 -0
  50. comfy/image_encoders/dino2.py +141 -0
CODEOWNERS ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Admins
2
+ * @comfyanonymous
3
+
4
+ # Note: Github teams syntax cannot be used here as the repo is not owned by Comfy-Org.
5
+ # Inlined the team members for now.
6
+
7
+ # Maintainers
8
+ *.md @yoland68 @robinjhuang @webfiltered @pythongosssss @ltdrdata @Kosinkadink @christian-byrne
9
+ /tests/ @yoland68 @robinjhuang @webfiltered @pythongosssss @ltdrdata @Kosinkadink @christian-byrne
10
+ /tests-unit/ @yoland68 @robinjhuang @webfiltered @pythongosssss @ltdrdata @Kosinkadink @christian-byrne
11
+ /notebooks/ @yoland68 @robinjhuang @webfiltered @pythongosssss @ltdrdata @Kosinkadink @christian-byrne
12
+ /script_examples/ @yoland68 @robinjhuang @webfiltered @pythongosssss @ltdrdata @Kosinkadink @christian-byrne
13
+ /.github/ @yoland68 @robinjhuang @webfiltered @pythongosssss @ltdrdata @Kosinkadink @christian-byrne
14
+ /requirements.txt @yoland68 @robinjhuang @webfiltered @pythongosssss @ltdrdata @Kosinkadink @christian-byrne
15
+ /pyproject.toml @yoland68 @robinjhuang @webfiltered @pythongosssss @ltdrdata @Kosinkadink @christian-byrne
16
+
17
+ # Python web server
18
+ /api_server/ @yoland68 @robinjhuang @webfiltered @pythongosssss @ltdrdata @christian-byrne
19
+ /app/ @yoland68 @robinjhuang @webfiltered @pythongosssss @ltdrdata @christian-byrne
20
+ /utils/ @yoland68 @robinjhuang @webfiltered @pythongosssss @ltdrdata @christian-byrne
21
+
22
+ # Node developers
23
+ /comfy_extras/ @yoland68 @robinjhuang @pythongosssss @ltdrdata @Kosinkadink @webfiltered @christian-byrne
24
+ /comfy/comfy_types/ @yoland68 @robinjhuang @pythongosssss @ltdrdata @Kosinkadink @webfiltered @christian-byrne
CONTRIBUTING.md ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Contributing to ComfyUI
2
+
3
+ Welcome, and thank you for your interest in contributing to ComfyUI!
4
+
5
+ There are several ways in which you can contribute, beyond writing code. The goal of this document is to provide a high-level overview of how you can get involved.
6
+
7
+ ## Asking Questions
8
+
9
+ Have a question? Instead of opening an issue, please ask on [Discord](https://comfy.org/discord) or [Matrix](https://app.element.io/#/room/%23comfyui_space%3Amatrix.org) channels. Our team and the community will help you.
10
+
11
+ ## Providing Feedback
12
+
13
+ Your comments and feedback are welcome, and the development team is available via a handful of different channels.
14
+
15
+ See the `#bug-report`, `#feature-request` and `#feedback` channels on Discord.
16
+
17
+ ## Reporting Issues
18
+
19
+ Have you identified a reproducible problem in ComfyUI? Do you have a feature request? We want to hear about it! Here's how you can report your issue as effectively as possible.
20
+
21
+
22
+ ### Look For an Existing Issue
23
+
24
+ Before you create a new issue, please do a search in [open issues](https://github.com/comfyanonymous/ComfyUI/issues) to see if the issue or feature request has already been filed.
25
+
26
+ If you find your issue already exists, make relevant comments and add your [reaction](https://github.com/blog/2119-add-reactions-to-pull-requests-issues-and-comments). Use a reaction in place of a "+1" comment:
27
+
28
+ * 👍 - upvote
29
+ * 👎 - downvote
30
+
31
+ If you cannot find an existing issue that describes your bug or feature, create a new issue. We have an issue template in place to organize new issues.
32
+
33
+
34
+ ### Creating Pull Requests
35
+
36
+ * Please refer to the article on [creating pull requests](https://github.com/comfyanonymous/ComfyUI/wiki/How-to-Contribute-Code) and contributing to this project.
37
+
38
+
39
+ ## Thank You
40
+
41
+ Your contributions to open source, large or small, make great projects like this possible. Thank you for taking the time to contribute.
LICENSE ADDED
@@ -0,0 +1,674 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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>.
api_server/__init__.py ADDED
File without changes
api_server/routes/__init__.py ADDED
File without changes
api_server/routes/internal/README.md ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ # ComfyUI Internal Routes
2
+
3
+ All routes under the `/internal` path are designated for **internal use by ComfyUI only**. These routes are not intended for use by external applications may change at any time without notice.
api_server/routes/internal/__init__.py ADDED
File without changes
api_server/routes/internal/internal_routes.py ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from aiohttp import web
2
+ from typing import Optional
3
+ from folder_paths import folder_names_and_paths, get_directory_by_type
4
+ from api_server.services.terminal_service import TerminalService
5
+ import app.logger
6
+ import os
7
+
8
+ class InternalRoutes:
9
+ '''
10
+ The top level web router for internal routes: /internal/*
11
+ The endpoints here should NOT be depended upon. It is for ComfyUI frontend use only.
12
+ Check README.md for more information.
13
+ '''
14
+
15
+ def __init__(self, prompt_server):
16
+ self.routes: web.RouteTableDef = web.RouteTableDef()
17
+ self._app: Optional[web.Application] = None
18
+ self.prompt_server = prompt_server
19
+ self.terminal_service = TerminalService(prompt_server)
20
+
21
+ def setup_routes(self):
22
+ @self.routes.get('/logs')
23
+ async def get_logs(request):
24
+ return web.json_response("".join([(l["t"] + " - " + l["m"]) for l in app.logger.get_logs()]))
25
+
26
+ @self.routes.get('/logs/raw')
27
+ async def get_raw_logs(request):
28
+ self.terminal_service.update_size()
29
+ return web.json_response({
30
+ "entries": list(app.logger.get_logs()),
31
+ "size": {"cols": self.terminal_service.cols, "rows": self.terminal_service.rows}
32
+ })
33
+
34
+ @self.routes.patch('/logs/subscribe')
35
+ async def subscribe_logs(request):
36
+ json_data = await request.json()
37
+ client_id = json_data["clientId"]
38
+ enabled = json_data["enabled"]
39
+ if enabled:
40
+ self.terminal_service.subscribe(client_id)
41
+ else:
42
+ self.terminal_service.unsubscribe(client_id)
43
+
44
+ return web.Response(status=200)
45
+
46
+
47
+ @self.routes.get('/folder_paths')
48
+ async def get_folder_paths(request):
49
+ response = {}
50
+ for key in folder_names_and_paths:
51
+ response[key] = folder_names_and_paths[key][0]
52
+ return web.json_response(response)
53
+
54
+ @self.routes.get('/files/{directory_type}')
55
+ async def get_files(request: web.Request) -> web.Response:
56
+ directory_type = request.match_info['directory_type']
57
+ if directory_type not in ("output", "input", "temp"):
58
+ return web.json_response({"error": "Invalid directory type"}, status=400)
59
+
60
+ directory = get_directory_by_type(directory_type)
61
+ sorted_files = sorted(
62
+ (entry for entry in os.scandir(directory) if entry.is_file()),
63
+ key=lambda entry: -entry.stat().st_mtime
64
+ )
65
+ return web.json_response([entry.name for entry in sorted_files], status=200)
66
+
67
+
68
+ def get_app(self):
69
+ if self._app is None:
70
+ self._app = web.Application()
71
+ self.setup_routes()
72
+ self._app.add_routes(self.routes)
73
+ return self._app
api_server/services/__init__.py ADDED
File without changes
api_server/services/terminal_service.py ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from app.logger import on_flush
2
+ import os
3
+ import shutil
4
+
5
+
6
+ class TerminalService:
7
+ def __init__(self, server):
8
+ self.server = server
9
+ self.cols = None
10
+ self.rows = None
11
+ self.subscriptions = set()
12
+ on_flush(self.send_messages)
13
+
14
+ def get_terminal_size(self):
15
+ try:
16
+ size = os.get_terminal_size()
17
+ return (size.columns, size.lines)
18
+ except OSError:
19
+ try:
20
+ size = shutil.get_terminal_size()
21
+ return (size.columns, size.lines)
22
+ except OSError:
23
+ return (80, 24) # fallback to 80x24
24
+
25
+ def update_size(self):
26
+ columns, lines = self.get_terminal_size()
27
+ changed = False
28
+
29
+ if columns != self.cols:
30
+ self.cols = columns
31
+ changed = True
32
+
33
+ if lines != self.rows:
34
+ self.rows = lines
35
+ changed = True
36
+
37
+ if changed:
38
+ return {"cols": self.cols, "rows": self.rows}
39
+
40
+ return None
41
+
42
+ def subscribe(self, client_id):
43
+ self.subscriptions.add(client_id)
44
+
45
+ def unsubscribe(self, client_id):
46
+ self.subscriptions.discard(client_id)
47
+
48
+ def send_messages(self, entries):
49
+ if not len(entries) or not len(self.subscriptions):
50
+ return
51
+
52
+ new_size = self.update_size()
53
+
54
+ for client_id in self.subscriptions.copy(): # prevent: Set changed size during iteration
55
+ if client_id not in self.server.sockets:
56
+ # Automatically unsub if the socket has disconnected
57
+ self.unsubscribe(client_id)
58
+ continue
59
+
60
+ self.server.send_sync("logs", {"entries": entries, "size": new_size}, client_id)
api_server/utils/file_operations.py ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from typing import List, Union, TypedDict, Literal
3
+ from typing_extensions import TypeGuard
4
+ class FileInfo(TypedDict):
5
+ name: str
6
+ path: str
7
+ type: Literal["file"]
8
+ size: int
9
+
10
+ class DirectoryInfo(TypedDict):
11
+ name: str
12
+ path: str
13
+ type: Literal["directory"]
14
+
15
+ FileSystemItem = Union[FileInfo, DirectoryInfo]
16
+
17
+ def is_file_info(item: FileSystemItem) -> TypeGuard[FileInfo]:
18
+ return item["type"] == "file"
19
+
20
+ class FileSystemOperations:
21
+ @staticmethod
22
+ def walk_directory(directory: str) -> List[FileSystemItem]:
23
+ file_list: List[FileSystemItem] = []
24
+ for root, dirs, files in os.walk(directory):
25
+ for name in files:
26
+ file_path = os.path.join(root, name)
27
+ relative_path = os.path.relpath(file_path, directory)
28
+ file_list.append({
29
+ "name": name,
30
+ "path": relative_path,
31
+ "type": "file",
32
+ "size": os.path.getsize(file_path)
33
+ })
34
+ for name in dirs:
35
+ dir_path = os.path.join(root, name)
36
+ relative_path = os.path.relpath(dir_path, directory)
37
+ file_list.append({
38
+ "name": name,
39
+ "path": relative_path,
40
+ "type": "directory"
41
+ })
42
+ return file_list
app/__init__.py ADDED
File without changes
app/app_settings.py ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import json
3
+ from aiohttp import web
4
+ import logging
5
+
6
+
7
+ class AppSettings():
8
+ def __init__(self, user_manager):
9
+ self.user_manager = user_manager
10
+
11
+ def get_settings(self, request):
12
+ try:
13
+ file = self.user_manager.get_request_user_filepath(
14
+ request,
15
+ "comfy.settings.json"
16
+ )
17
+ except KeyError as e:
18
+ logging.error("User settings not found.")
19
+ raise web.HTTPUnauthorized() from e
20
+ if os.path.isfile(file):
21
+ try:
22
+ with open(file) as f:
23
+ return json.load(f)
24
+ except:
25
+ logging.error(f"The user settings file is corrupted: {file}")
26
+ return {}
27
+ else:
28
+ return {}
29
+
30
+ def save_settings(self, request, settings):
31
+ file = self.user_manager.get_request_user_filepath(
32
+ request, "comfy.settings.json")
33
+ with open(file, "w") as f:
34
+ f.write(json.dumps(settings, indent=4))
35
+
36
+ def add_routes(self, routes):
37
+ @routes.get("/settings")
38
+ async def get_settings(request):
39
+ return web.json_response(self.get_settings(request))
40
+
41
+ @routes.get("/settings/{id}")
42
+ async def get_setting(request):
43
+ value = None
44
+ settings = self.get_settings(request)
45
+ setting_id = request.match_info.get("id", None)
46
+ if setting_id and setting_id in settings:
47
+ value = settings[setting_id]
48
+ return web.json_response(value)
49
+
50
+ @routes.post("/settings")
51
+ async def post_settings(request):
52
+ settings = self.get_settings(request)
53
+ new_settings = await request.json()
54
+ self.save_settings(request, {**settings, **new_settings})
55
+ return web.Response(status=200)
56
+
57
+ @routes.post("/settings/{id}")
58
+ async def post_setting(request):
59
+ setting_id = request.match_info.get("id", None)
60
+ if not setting_id:
61
+ return web.Response(status=400)
62
+ settings = self.get_settings(request)
63
+ settings[setting_id] = await request.json()
64
+ self.save_settings(request, settings)
65
+ return web.Response(status=200)
app/custom_node_manager.py ADDED
@@ -0,0 +1,145 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import os
4
+ import folder_paths
5
+ import glob
6
+ from aiohttp import web
7
+ import json
8
+ import logging
9
+ from functools import lru_cache
10
+
11
+ from utils.json_util import merge_json_recursive
12
+
13
+
14
+ # Extra locale files to load into main.json
15
+ EXTRA_LOCALE_FILES = [
16
+ "nodeDefs.json",
17
+ "commands.json",
18
+ "settings.json",
19
+ ]
20
+
21
+
22
+ def safe_load_json_file(file_path: str) -> dict:
23
+ if not os.path.exists(file_path):
24
+ return {}
25
+
26
+ try:
27
+ with open(file_path, "r", encoding="utf-8") as f:
28
+ return json.load(f)
29
+ except json.JSONDecodeError:
30
+ logging.error(f"Error loading {file_path}")
31
+ return {}
32
+
33
+
34
+ class CustomNodeManager:
35
+ @lru_cache(maxsize=1)
36
+ def build_translations(self):
37
+ """Load all custom nodes translations during initialization. Translations are
38
+ expected to be loaded from `locales/` folder.
39
+
40
+ The folder structure is expected to be the following:
41
+ - custom_nodes/
42
+ - custom_node_1/
43
+ - locales/
44
+ - en/
45
+ - main.json
46
+ - commands.json
47
+ - settings.json
48
+
49
+ returned translations are expected to be in the following format:
50
+ {
51
+ "en": {
52
+ "nodeDefs": {...},
53
+ "commands": {...},
54
+ "settings": {...},
55
+ ...{other main.json keys}
56
+ }
57
+ }
58
+ """
59
+
60
+ translations = {}
61
+
62
+ for folder in folder_paths.get_folder_paths("custom_nodes"):
63
+ # Sort glob results for deterministic ordering
64
+ for custom_node_dir in sorted(glob.glob(os.path.join(folder, "*/"))):
65
+ locales_dir = os.path.join(custom_node_dir, "locales")
66
+ if not os.path.exists(locales_dir):
67
+ continue
68
+
69
+ for lang_dir in glob.glob(os.path.join(locales_dir, "*/")):
70
+ lang_code = os.path.basename(os.path.dirname(lang_dir))
71
+
72
+ if lang_code not in translations:
73
+ translations[lang_code] = {}
74
+
75
+ # Load main.json
76
+ main_file = os.path.join(lang_dir, "main.json")
77
+ node_translations = safe_load_json_file(main_file)
78
+
79
+ # Load extra locale files
80
+ for extra_file in EXTRA_LOCALE_FILES:
81
+ extra_file_path = os.path.join(lang_dir, extra_file)
82
+ key = extra_file.split(".")[0]
83
+ json_data = safe_load_json_file(extra_file_path)
84
+ if json_data:
85
+ node_translations[key] = json_data
86
+
87
+ if node_translations:
88
+ translations[lang_code] = merge_json_recursive(
89
+ translations[lang_code], node_translations
90
+ )
91
+
92
+ return translations
93
+
94
+ def add_routes(self, routes, webapp, loadedModules):
95
+
96
+ example_workflow_folder_names = ["example_workflows", "example", "examples", "workflow", "workflows"]
97
+
98
+ @routes.get("/workflow_templates")
99
+ async def get_workflow_templates(request):
100
+ """Returns a web response that contains the map of custom_nodes names and their associated workflow templates. The ones without templates are omitted."""
101
+
102
+ files = []
103
+
104
+ for folder in folder_paths.get_folder_paths("custom_nodes"):
105
+ for folder_name in example_workflow_folder_names:
106
+ pattern = os.path.join(folder, f"*/{folder_name}/*.json")
107
+ matched_files = glob.glob(pattern)
108
+ files.extend(matched_files)
109
+
110
+ workflow_templates_dict = (
111
+ {}
112
+ ) # custom_nodes folder name -> example workflow names
113
+ for file in files:
114
+ custom_nodes_name = os.path.basename(
115
+ os.path.dirname(os.path.dirname(file))
116
+ )
117
+ workflow_name = os.path.splitext(os.path.basename(file))[0]
118
+ workflow_templates_dict.setdefault(custom_nodes_name, []).append(
119
+ workflow_name
120
+ )
121
+ return web.json_response(workflow_templates_dict)
122
+
123
+ # Serve workflow templates from custom nodes.
124
+ for module_name, module_dir in loadedModules:
125
+ for folder_name in example_workflow_folder_names:
126
+ workflows_dir = os.path.join(module_dir, folder_name)
127
+
128
+ if os.path.exists(workflows_dir):
129
+ if folder_name != "example_workflows":
130
+ logging.debug(
131
+ "Found example workflow folder '%s' for custom node '%s', consider renaming it to 'example_workflows'",
132
+ folder_name, module_name)
133
+
134
+ webapp.add_routes(
135
+ [
136
+ web.static(
137
+ "/api/workflow_templates/" + module_name, workflows_dir
138
+ )
139
+ ]
140
+ )
141
+
142
+ @routes.get("/i18n")
143
+ async def get_i18n(request):
144
+ """Returns translations from all custom nodes' locales folders."""
145
+ return web.json_response(self.build_translations())
app/frontend_management.py ADDED
@@ -0,0 +1,322 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+ import argparse
3
+ import logging
4
+ import os
5
+ import re
6
+ import sys
7
+ import tempfile
8
+ import zipfile
9
+ import importlib
10
+ from dataclasses import dataclass
11
+ from functools import cached_property
12
+ from pathlib import Path
13
+ from typing import TypedDict, Optional
14
+ from importlib.metadata import version
15
+
16
+ import requests
17
+ from typing_extensions import NotRequired
18
+
19
+ from comfy.cli_args import DEFAULT_VERSION_STRING
20
+ import app.logger
21
+
22
+ # The path to the requirements.txt file
23
+ req_path = Path(__file__).parents[1] / "requirements.txt"
24
+
25
+
26
+ def frontend_install_warning_message():
27
+ """The warning message to display when the frontend version is not up to date."""
28
+
29
+ extra = ""
30
+ if sys.flags.no_user_site:
31
+ extra = "-s "
32
+ return f"""
33
+ Please install the updated requirements.txt file by running:
34
+ {sys.executable} {extra}-m pip install -r {req_path}
35
+
36
+ This error is happening because the ComfyUI frontend is no longer shipped as part of the main repo but as a pip package instead.
37
+
38
+ If you are on the portable package you can run: update\\update_comfyui.bat to solve this problem
39
+ """.strip()
40
+
41
+
42
+ def check_frontend_version():
43
+ """Check if the frontend version is up to date."""
44
+
45
+ def parse_version(version: str) -> tuple[int, int, int]:
46
+ return tuple(map(int, version.split(".")))
47
+
48
+ try:
49
+ frontend_version_str = version("comfyui-frontend-package")
50
+ frontend_version = parse_version(frontend_version_str)
51
+ with open(req_path, "r", encoding="utf-8") as f:
52
+ required_frontend = parse_version(f.readline().split("=")[-1])
53
+ if frontend_version < required_frontend:
54
+ app.logger.log_startup_warning(
55
+ f"""
56
+ ________________________________________________________________________
57
+ WARNING WARNING WARNING WARNING WARNING
58
+
59
+ Installed frontend version {".".join(map(str, frontend_version))} is lower than the recommended version {".".join(map(str, required_frontend))}.
60
+
61
+ {frontend_install_warning_message()}
62
+ ________________________________________________________________________
63
+ """.strip()
64
+ )
65
+ else:
66
+ logging.info("ComfyUI frontend version: {}".format(frontend_version_str))
67
+ except Exception as e:
68
+ logging.error(f"Failed to check frontend version: {e}")
69
+
70
+
71
+ REQUEST_TIMEOUT = 10 # seconds
72
+
73
+
74
+ class Asset(TypedDict):
75
+ url: str
76
+
77
+
78
+ class Release(TypedDict):
79
+ id: int
80
+ tag_name: str
81
+ name: str
82
+ prerelease: bool
83
+ created_at: str
84
+ published_at: str
85
+ body: str
86
+ assets: NotRequired[list[Asset]]
87
+
88
+
89
+ @dataclass
90
+ class FrontEndProvider:
91
+ owner: str
92
+ repo: str
93
+
94
+ @property
95
+ def folder_name(self) -> str:
96
+ return f"{self.owner}_{self.repo}"
97
+
98
+ @property
99
+ def release_url(self) -> str:
100
+ return f"https://api.github.com/repos/{self.owner}/{self.repo}/releases"
101
+
102
+ @cached_property
103
+ def all_releases(self) -> list[Release]:
104
+ releases = []
105
+ api_url = self.release_url
106
+ while api_url:
107
+ response = requests.get(api_url, timeout=REQUEST_TIMEOUT)
108
+ response.raise_for_status() # Raises an HTTPError if the response was an error
109
+ releases.extend(response.json())
110
+ # GitHub uses the Link header to provide pagination links. Check if it exists and update api_url accordingly.
111
+ if "next" in response.links:
112
+ api_url = response.links["next"]["url"]
113
+ else:
114
+ api_url = None
115
+ return releases
116
+
117
+ @cached_property
118
+ def latest_release(self) -> Release:
119
+ latest_release_url = f"{self.release_url}/latest"
120
+ response = requests.get(latest_release_url, timeout=REQUEST_TIMEOUT)
121
+ response.raise_for_status() # Raises an HTTPError if the response was an error
122
+ return response.json()
123
+
124
+ def get_release(self, version: str) -> Release:
125
+ if version == "latest":
126
+ return self.latest_release
127
+ else:
128
+ for release in self.all_releases:
129
+ if release["tag_name"] in [version, f"v{version}"]:
130
+ return release
131
+ raise ValueError(f"Version {version} not found in releases")
132
+
133
+
134
+ def download_release_asset_zip(release: Release, destination_path: str) -> None:
135
+ """Download dist.zip from github release."""
136
+ asset_url = None
137
+ for asset in release.get("assets", []):
138
+ if asset["name"] == "dist.zip":
139
+ asset_url = asset["url"]
140
+ break
141
+
142
+ if not asset_url:
143
+ raise ValueError("dist.zip not found in the release assets")
144
+
145
+ # Use a temporary file to download the zip content
146
+ with tempfile.TemporaryFile() as tmp_file:
147
+ headers = {"Accept": "application/octet-stream"}
148
+ response = requests.get(
149
+ asset_url, headers=headers, allow_redirects=True, timeout=REQUEST_TIMEOUT
150
+ )
151
+ response.raise_for_status() # Ensure we got a successful response
152
+
153
+ # Write the content to the temporary file
154
+ tmp_file.write(response.content)
155
+
156
+ # Go back to the beginning of the temporary file
157
+ tmp_file.seek(0)
158
+
159
+ # Extract the zip file content to the destination path
160
+ with zipfile.ZipFile(tmp_file, "r") as zip_ref:
161
+ zip_ref.extractall(destination_path)
162
+
163
+
164
+ class FrontendManager:
165
+ CUSTOM_FRONTENDS_ROOT = str(Path(__file__).parents[1] / "web_custom_versions")
166
+
167
+ @classmethod
168
+ def default_frontend_path(cls) -> str:
169
+ try:
170
+ import comfyui_frontend_package
171
+
172
+ return str(importlib.resources.files(comfyui_frontend_package) / "static")
173
+ except ImportError:
174
+ logging.error(
175
+ f"""
176
+ ********** ERROR ***********
177
+
178
+ comfyui-frontend-package is not installed.
179
+
180
+ {frontend_install_warning_message()}
181
+
182
+ ********** ERROR ***********
183
+ """.strip()
184
+ )
185
+ sys.exit(-1)
186
+
187
+ @classmethod
188
+ def templates_path(cls) -> str:
189
+ try:
190
+ import comfyui_workflow_templates
191
+
192
+ return str(
193
+ importlib.resources.files(comfyui_workflow_templates) / "templates"
194
+ )
195
+ except ImportError:
196
+ logging.error(
197
+ f"""
198
+ ********** ERROR ***********
199
+
200
+ comfyui-workflow-templates is not installed.
201
+
202
+ {frontend_install_warning_message()}
203
+
204
+ ********** ERROR ***********
205
+ """.strip()
206
+ )
207
+
208
+ @classmethod
209
+ def embedded_docs_path(cls) -> str:
210
+ """Get the path to embedded documentation"""
211
+ try:
212
+ import comfyui_embedded_docs
213
+
214
+ return str(
215
+ importlib.resources.files(comfyui_embedded_docs) / "docs"
216
+ )
217
+ except ImportError:
218
+ logging.info("comfyui-embedded-docs package not found")
219
+ return None
220
+
221
+ @classmethod
222
+ def parse_version_string(cls, value: str) -> tuple[str, str, str]:
223
+ """
224
+ Args:
225
+ value (str): The version string to parse.
226
+
227
+ Returns:
228
+ tuple[str, str]: A tuple containing provider name and version.
229
+
230
+ Raises:
231
+ argparse.ArgumentTypeError: If the version string is invalid.
232
+ """
233
+ VERSION_PATTERN = r"^([a-zA-Z0-9][a-zA-Z0-9-]{0,38})/([a-zA-Z0-9_.-]+)@(v?\d+\.\d+\.\d+|latest)$"
234
+ match_result = re.match(VERSION_PATTERN, value)
235
+ if match_result is None:
236
+ raise argparse.ArgumentTypeError(f"Invalid version string: {value}")
237
+
238
+ return match_result.group(1), match_result.group(2), match_result.group(3)
239
+
240
+ @classmethod
241
+ def init_frontend_unsafe(
242
+ cls, version_string: str, provider: Optional[FrontEndProvider] = None
243
+ ) -> str:
244
+ """
245
+ Initializes the frontend for the specified version.
246
+
247
+ Args:
248
+ version_string (str): The version string.
249
+ provider (FrontEndProvider, optional): The provider to use. Defaults to None.
250
+
251
+ Returns:
252
+ str: The path to the initialized frontend.
253
+
254
+ Raises:
255
+ Exception: If there is an error during the initialization process.
256
+ main error source might be request timeout or invalid URL.
257
+ """
258
+ if version_string == DEFAULT_VERSION_STRING:
259
+ check_frontend_version()
260
+ return cls.default_frontend_path()
261
+
262
+ repo_owner, repo_name, version = cls.parse_version_string(version_string)
263
+
264
+ if version.startswith("v"):
265
+ expected_path = str(
266
+ Path(cls.CUSTOM_FRONTENDS_ROOT)
267
+ / f"{repo_owner}_{repo_name}"
268
+ / version.lstrip("v")
269
+ )
270
+ if os.path.exists(expected_path):
271
+ logging.info(
272
+ f"Using existing copy of specific frontend version tag: {repo_owner}/{repo_name}@{version}"
273
+ )
274
+ return expected_path
275
+
276
+ logging.info(
277
+ f"Initializing frontend: {repo_owner}/{repo_name}@{version}, requesting version details from GitHub..."
278
+ )
279
+
280
+ provider = provider or FrontEndProvider(repo_owner, repo_name)
281
+ release = provider.get_release(version)
282
+
283
+ semantic_version = release["tag_name"].lstrip("v")
284
+ web_root = str(
285
+ Path(cls.CUSTOM_FRONTENDS_ROOT) / provider.folder_name / semantic_version
286
+ )
287
+ if not os.path.exists(web_root):
288
+ try:
289
+ os.makedirs(web_root, exist_ok=True)
290
+ logging.info(
291
+ "Downloading frontend(%s) version(%s) to (%s)",
292
+ provider.folder_name,
293
+ semantic_version,
294
+ web_root,
295
+ )
296
+ logging.debug(release)
297
+ download_release_asset_zip(release, destination_path=web_root)
298
+ finally:
299
+ # Clean up the directory if it is empty, i.e. the download failed
300
+ if not os.listdir(web_root):
301
+ os.rmdir(web_root)
302
+
303
+ return web_root
304
+
305
+ @classmethod
306
+ def init_frontend(cls, version_string: str) -> str:
307
+ """
308
+ Initializes the frontend with the specified version string.
309
+
310
+ Args:
311
+ version_string (str): The version string to initialize the frontend with.
312
+
313
+ Returns:
314
+ str: The path of the initialized frontend.
315
+ """
316
+ try:
317
+ return cls.init_frontend_unsafe(version_string)
318
+ except Exception as e:
319
+ logging.error("Failed to initialize frontend: %s", e)
320
+ logging.info("Falling back to the default frontend.")
321
+ check_frontend_version()
322
+ return cls.default_frontend_path()
app/logger.py ADDED
@@ -0,0 +1,98 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from collections import deque
2
+ from datetime import datetime
3
+ import io
4
+ import logging
5
+ import sys
6
+ import threading
7
+
8
+ logs = None
9
+ stdout_interceptor = None
10
+ stderr_interceptor = None
11
+
12
+
13
+ class LogInterceptor(io.TextIOWrapper):
14
+ def __init__(self, stream, *args, **kwargs):
15
+ buffer = stream.buffer
16
+ encoding = stream.encoding
17
+ super().__init__(buffer, *args, **kwargs, encoding=encoding, line_buffering=stream.line_buffering)
18
+ self._lock = threading.Lock()
19
+ self._flush_callbacks = []
20
+ self._logs_since_flush = []
21
+
22
+ def write(self, data):
23
+ entry = {"t": datetime.now().isoformat(), "m": data}
24
+ with self._lock:
25
+ self._logs_since_flush.append(entry)
26
+
27
+ # Simple handling for cr to overwrite the last output if it isnt a full line
28
+ # else logs just get full of progress messages
29
+ if isinstance(data, str) and data.startswith("\r") and not logs[-1]["m"].endswith("\n"):
30
+ logs.pop()
31
+ logs.append(entry)
32
+ super().write(data)
33
+
34
+ def flush(self):
35
+ super().flush()
36
+ for cb in self._flush_callbacks:
37
+ cb(self._logs_since_flush)
38
+ self._logs_since_flush = []
39
+
40
+ def on_flush(self, callback):
41
+ self._flush_callbacks.append(callback)
42
+
43
+
44
+ def get_logs():
45
+ return logs
46
+
47
+
48
+ def on_flush(callback):
49
+ if stdout_interceptor is not None:
50
+ stdout_interceptor.on_flush(callback)
51
+ if stderr_interceptor is not None:
52
+ stderr_interceptor.on_flush(callback)
53
+
54
+ def setup_logger(log_level: str = 'INFO', capacity: int = 300, use_stdout: bool = False):
55
+ global logs
56
+ if logs:
57
+ return
58
+
59
+ # Override output streams and log to buffer
60
+ logs = deque(maxlen=capacity)
61
+
62
+ global stdout_interceptor
63
+ global stderr_interceptor
64
+ stdout_interceptor = sys.stdout = LogInterceptor(sys.stdout)
65
+ stderr_interceptor = sys.stderr = LogInterceptor(sys.stderr)
66
+
67
+ # Setup default global logger
68
+ logger = logging.getLogger()
69
+ logger.setLevel(log_level)
70
+
71
+ stream_handler = logging.StreamHandler()
72
+ stream_handler.setFormatter(logging.Formatter("%(message)s"))
73
+
74
+ if use_stdout:
75
+ # Only errors and critical to stderr
76
+ stream_handler.addFilter(lambda record: not record.levelno < logging.ERROR)
77
+
78
+ # Lesser to stdout
79
+ stdout_handler = logging.StreamHandler(sys.stdout)
80
+ stdout_handler.setFormatter(logging.Formatter("%(message)s"))
81
+ stdout_handler.addFilter(lambda record: record.levelno < logging.ERROR)
82
+ logger.addHandler(stdout_handler)
83
+
84
+ logger.addHandler(stream_handler)
85
+
86
+
87
+ STARTUP_WARNINGS = []
88
+
89
+
90
+ def log_startup_warning(msg):
91
+ logging.warning(msg)
92
+ STARTUP_WARNINGS.append(msg)
93
+
94
+
95
+ def print_startup_warnings():
96
+ for s in STARTUP_WARNINGS:
97
+ logging.warning(s)
98
+ STARTUP_WARNINGS.clear()
app/model_manager.py ADDED
@@ -0,0 +1,184 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import os
4
+ import base64
5
+ import json
6
+ import time
7
+ import logging
8
+ import folder_paths
9
+ import glob
10
+ import comfy.utils
11
+ from aiohttp import web
12
+ from PIL import Image
13
+ from io import BytesIO
14
+ from folder_paths import map_legacy, filter_files_extensions, filter_files_content_types
15
+
16
+
17
+ class ModelFileManager:
18
+ def __init__(self) -> None:
19
+ self.cache: dict[str, tuple[list[dict], dict[str, float], float]] = {}
20
+
21
+ def get_cache(self, key: str, default=None) -> tuple[list[dict], dict[str, float], float] | None:
22
+ return self.cache.get(key, default)
23
+
24
+ def set_cache(self, key: str, value: tuple[list[dict], dict[str, float], float]):
25
+ self.cache[key] = value
26
+
27
+ def clear_cache(self):
28
+ self.cache.clear()
29
+
30
+ def add_routes(self, routes):
31
+ # NOTE: This is an experiment to replace `/models`
32
+ @routes.get("/experiment/models")
33
+ async def get_model_folders(request):
34
+ model_types = list(folder_paths.folder_names_and_paths.keys())
35
+ folder_black_list = ["configs", "custom_nodes"]
36
+ output_folders: list[dict] = []
37
+ for folder in model_types:
38
+ if folder in folder_black_list:
39
+ continue
40
+ output_folders.append({"name": folder, "folders": folder_paths.get_folder_paths(folder)})
41
+ return web.json_response(output_folders)
42
+
43
+ # NOTE: This is an experiment to replace `/models/{folder}`
44
+ @routes.get("/experiment/models/{folder}")
45
+ async def get_all_models(request):
46
+ folder = request.match_info.get("folder", None)
47
+ if not folder in folder_paths.folder_names_and_paths:
48
+ return web.Response(status=404)
49
+ files = self.get_model_file_list(folder)
50
+ return web.json_response(files)
51
+
52
+ @routes.get("/experiment/models/preview/{folder}/{path_index}/{filename:.*}")
53
+ async def get_model_preview(request):
54
+ folder_name = request.match_info.get("folder", None)
55
+ path_index = int(request.match_info.get("path_index", None))
56
+ filename = request.match_info.get("filename", None)
57
+
58
+ if not folder_name in folder_paths.folder_names_and_paths:
59
+ return web.Response(status=404)
60
+
61
+ folders = folder_paths.folder_names_and_paths[folder_name]
62
+ folder = folders[0][path_index]
63
+ full_filename = os.path.join(folder, filename)
64
+
65
+ previews = self.get_model_previews(full_filename)
66
+ default_preview = previews[0] if len(previews) > 0 else None
67
+ if default_preview is None or (isinstance(default_preview, str) and not os.path.isfile(default_preview)):
68
+ return web.Response(status=404)
69
+
70
+ try:
71
+ with Image.open(default_preview) as img:
72
+ img_bytes = BytesIO()
73
+ img.save(img_bytes, format="WEBP")
74
+ img_bytes.seek(0)
75
+ return web.Response(body=img_bytes.getvalue(), content_type="image/webp")
76
+ except:
77
+ return web.Response(status=404)
78
+
79
+ def get_model_file_list(self, folder_name: str):
80
+ folder_name = map_legacy(folder_name)
81
+ folders = folder_paths.folder_names_and_paths[folder_name]
82
+ output_list: list[dict] = []
83
+
84
+ for index, folder in enumerate(folders[0]):
85
+ if not os.path.isdir(folder):
86
+ continue
87
+ out = self.cache_model_file_list_(folder)
88
+ if out is None:
89
+ out = self.recursive_search_models_(folder, index)
90
+ self.set_cache(folder, out)
91
+ output_list.extend(out[0])
92
+
93
+ return output_list
94
+
95
+ def cache_model_file_list_(self, folder: str):
96
+ model_file_list_cache = self.get_cache(folder)
97
+
98
+ if model_file_list_cache is None:
99
+ return None
100
+ if not os.path.isdir(folder):
101
+ return None
102
+ if os.path.getmtime(folder) != model_file_list_cache[1]:
103
+ return None
104
+ for x in model_file_list_cache[1]:
105
+ time_modified = model_file_list_cache[1][x]
106
+ folder = x
107
+ if os.path.getmtime(folder) != time_modified:
108
+ return None
109
+
110
+ return model_file_list_cache
111
+
112
+ def recursive_search_models_(self, directory: str, pathIndex: int) -> tuple[list[str], dict[str, float], float]:
113
+ if not os.path.isdir(directory):
114
+ return [], {}, time.perf_counter()
115
+
116
+ excluded_dir_names = [".git"]
117
+ # TODO use settings
118
+ include_hidden_files = False
119
+
120
+ result: list[str] = []
121
+ dirs: dict[str, float] = {}
122
+
123
+ for dirpath, subdirs, filenames in os.walk(directory, followlinks=True, topdown=True):
124
+ subdirs[:] = [d for d in subdirs if d not in excluded_dir_names]
125
+ if not include_hidden_files:
126
+ subdirs[:] = [d for d in subdirs if not d.startswith(".")]
127
+ filenames = [f for f in filenames if not f.startswith(".")]
128
+
129
+ filenames = filter_files_extensions(filenames, folder_paths.supported_pt_extensions)
130
+
131
+ for file_name in filenames:
132
+ try:
133
+ relative_path = os.path.relpath(os.path.join(dirpath, file_name), directory)
134
+ result.append(relative_path)
135
+ except:
136
+ logging.warning(f"Warning: Unable to access {file_name}. Skipping this file.")
137
+ continue
138
+
139
+ for d in subdirs:
140
+ path: str = os.path.join(dirpath, d)
141
+ try:
142
+ dirs[path] = os.path.getmtime(path)
143
+ except FileNotFoundError:
144
+ logging.warning(f"Warning: Unable to access {path}. Skipping this path.")
145
+ continue
146
+
147
+ return [{"name": f, "pathIndex": pathIndex} for f in result], dirs, time.perf_counter()
148
+
149
+ def get_model_previews(self, filepath: str) -> list[str | BytesIO]:
150
+ dirname = os.path.dirname(filepath)
151
+
152
+ if not os.path.exists(dirname):
153
+ return []
154
+
155
+ basename = os.path.splitext(filepath)[0]
156
+ match_files = glob.glob(f"{basename}.*", recursive=False)
157
+ image_files = filter_files_content_types(match_files, "image")
158
+ safetensors_file = next(filter(lambda x: x.endswith(".safetensors"), match_files), None)
159
+ safetensors_metadata = {}
160
+
161
+ result: list[str | BytesIO] = []
162
+
163
+ for filename in image_files:
164
+ _basename = os.path.splitext(filename)[0]
165
+ if _basename == basename:
166
+ result.append(filename)
167
+ if _basename == f"{basename}.preview":
168
+ result.append(filename)
169
+
170
+ if safetensors_file:
171
+ safetensors_filepath = os.path.join(dirname, safetensors_file)
172
+ header = comfy.utils.safetensors_header(safetensors_filepath, max_size=8*1024*1024)
173
+ if header:
174
+ safetensors_metadata = json.loads(header)
175
+ safetensors_images = safetensors_metadata.get("__metadata__", {}).get("ssmd_cover_images", None)
176
+ if safetensors_images:
177
+ safetensors_images = json.loads(safetensors_images)
178
+ for image in safetensors_images:
179
+ result.append(BytesIO(base64.b64decode(image)))
180
+
181
+ return result
182
+
183
+ def __exit__(self, exc_type, exc_value, traceback):
184
+ self.clear_cache()
app/user_manager.py ADDED
@@ -0,0 +1,436 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+ import json
3
+ import os
4
+ import re
5
+ import uuid
6
+ import glob
7
+ import shutil
8
+ import logging
9
+ from aiohttp import web
10
+ from urllib import parse
11
+ from comfy.cli_args import args
12
+ import folder_paths
13
+ from .app_settings import AppSettings
14
+ from typing import TypedDict
15
+
16
+ default_user = "default"
17
+
18
+
19
+ class FileInfo(TypedDict):
20
+ path: str
21
+ size: int
22
+ modified: int
23
+
24
+
25
+ def get_file_info(path: str, relative_to: str) -> FileInfo:
26
+ return {
27
+ "path": os.path.relpath(path, relative_to).replace(os.sep, '/'),
28
+ "size": os.path.getsize(path),
29
+ "modified": os.path.getmtime(path)
30
+ }
31
+
32
+
33
+ class UserManager():
34
+ def __init__(self):
35
+ user_directory = folder_paths.get_user_directory()
36
+
37
+ self.settings = AppSettings(self)
38
+ if not os.path.exists(user_directory):
39
+ os.makedirs(user_directory, exist_ok=True)
40
+ if not args.multi_user:
41
+ logging.warning("****** User settings have been changed to be stored on the server instead of browser storage. ******")
42
+ logging.warning("****** For multi-user setups add the --multi-user CLI argument to enable multiple user profiles. ******")
43
+
44
+ if args.multi_user:
45
+ if os.path.isfile(self.get_users_file()):
46
+ with open(self.get_users_file()) as f:
47
+ self.users = json.load(f)
48
+ else:
49
+ self.users = {}
50
+ else:
51
+ self.users = {"default": "default"}
52
+
53
+ def get_users_file(self):
54
+ return os.path.join(folder_paths.get_user_directory(), "users.json")
55
+
56
+ def get_request_user_id(self, request):
57
+ user = "default"
58
+ if args.multi_user and "comfy-user" in request.headers:
59
+ user = request.headers["comfy-user"]
60
+
61
+ if user not in self.users:
62
+ raise KeyError("Unknown user: " + user)
63
+
64
+ return user
65
+
66
+ def get_request_user_filepath(self, request, file, type="userdata", create_dir=True):
67
+ user_directory = folder_paths.get_user_directory()
68
+
69
+ if type == "userdata":
70
+ root_dir = user_directory
71
+ else:
72
+ raise KeyError("Unknown filepath type:" + type)
73
+
74
+ user = self.get_request_user_id(request)
75
+ path = user_root = os.path.abspath(os.path.join(root_dir, user))
76
+
77
+ # prevent leaving /{type}
78
+ if os.path.commonpath((root_dir, user_root)) != root_dir:
79
+ return None
80
+
81
+ if file is not None:
82
+ # Check if filename is url encoded
83
+ if "%" in file:
84
+ file = parse.unquote(file)
85
+
86
+ # prevent leaving /{type}/{user}
87
+ path = os.path.abspath(os.path.join(user_root, file))
88
+ if os.path.commonpath((user_root, path)) != user_root:
89
+ return None
90
+
91
+ parent = os.path.split(path)[0]
92
+
93
+ if create_dir and not os.path.exists(parent):
94
+ os.makedirs(parent, exist_ok=True)
95
+
96
+ return path
97
+
98
+ def add_user(self, name):
99
+ name = name.strip()
100
+ if not name:
101
+ raise ValueError("username not provided")
102
+ user_id = re.sub("[^a-zA-Z0-9-_]+", '-', name)
103
+ user_id = user_id + "_" + str(uuid.uuid4())
104
+
105
+ self.users[user_id] = name
106
+
107
+ with open(self.get_users_file(), "w") as f:
108
+ json.dump(self.users, f)
109
+
110
+ return user_id
111
+
112
+ def add_routes(self, routes):
113
+ self.settings.add_routes(routes)
114
+
115
+ @routes.get("/users")
116
+ async def get_users(request):
117
+ if args.multi_user:
118
+ return web.json_response({"storage": "server", "users": self.users})
119
+ else:
120
+ user_dir = self.get_request_user_filepath(request, None, create_dir=False)
121
+ return web.json_response({
122
+ "storage": "server",
123
+ "migrated": os.path.exists(user_dir)
124
+ })
125
+
126
+ @routes.post("/users")
127
+ async def post_users(request):
128
+ body = await request.json()
129
+ username = body["username"]
130
+ if username in self.users.values():
131
+ return web.json_response({"error": "Duplicate username."}, status=400)
132
+
133
+ user_id = self.add_user(username)
134
+ return web.json_response(user_id)
135
+
136
+ @routes.get("/userdata")
137
+ async def listuserdata(request):
138
+ """
139
+ List user data files in a specified directory.
140
+
141
+ This endpoint allows listing files in a user's data directory, with options for recursion,
142
+ full file information, and path splitting.
143
+
144
+ Query Parameters:
145
+ - dir (required): The directory to list files from.
146
+ - recurse (optional): If "true", recursively list files in subdirectories.
147
+ - full_info (optional): If "true", return detailed file information (path, size, modified time).
148
+ - split (optional): If "true", split file paths into components (only applies when full_info is false).
149
+
150
+ Returns:
151
+ - 400: If 'dir' parameter is missing.
152
+ - 403: If the requested path is not allowed.
153
+ - 404: If the requested directory does not exist.
154
+ - 200: JSON response with the list of files or file information.
155
+
156
+ The response format depends on the query parameters:
157
+ - Default: List of relative file paths.
158
+ - full_info=true: List of dictionaries with file details.
159
+ - split=true (and full_info=false): List of lists, each containing path components.
160
+ """
161
+ directory = request.rel_url.query.get('dir', '')
162
+ if not directory:
163
+ return web.Response(status=400, text="Directory not provided")
164
+
165
+ path = self.get_request_user_filepath(request, directory)
166
+ if not path:
167
+ return web.Response(status=403, text="Invalid directory")
168
+
169
+ if not os.path.exists(path):
170
+ return web.Response(status=404, text="Directory not found")
171
+
172
+ recurse = request.rel_url.query.get('recurse', '').lower() == "true"
173
+ full_info = request.rel_url.query.get('full_info', '').lower() == "true"
174
+ split_path = request.rel_url.query.get('split', '').lower() == "true"
175
+
176
+ # Use different patterns based on whether we're recursing or not
177
+ if recurse:
178
+ pattern = os.path.join(glob.escape(path), '**', '*')
179
+ else:
180
+ pattern = os.path.join(glob.escape(path), '*')
181
+
182
+ def process_full_path(full_path: str) -> FileInfo | str | list[str]:
183
+ if full_info:
184
+ return get_file_info(full_path, path)
185
+
186
+ rel_path = os.path.relpath(full_path, path).replace(os.sep, '/')
187
+ if split_path:
188
+ return [rel_path] + rel_path.split('/')
189
+
190
+ return rel_path
191
+
192
+ results = [
193
+ process_full_path(full_path)
194
+ for full_path in glob.glob(pattern, recursive=recurse)
195
+ if os.path.isfile(full_path)
196
+ ]
197
+
198
+ return web.json_response(results)
199
+
200
+ @routes.get("/v2/userdata")
201
+ async def list_userdata_v2(request):
202
+ """
203
+ List files and directories in a user's data directory.
204
+
205
+ This endpoint provides a structured listing of contents within a specified
206
+ subdirectory of the user's data storage.
207
+
208
+ Query Parameters:
209
+ - path (optional): The relative path within the user's data directory
210
+ to list. Defaults to the root ('').
211
+
212
+ Returns:
213
+ - 400: If the requested path is invalid, outside the user's data directory, or is not a directory.
214
+ - 404: If the requested path does not exist.
215
+ - 403: If the user is invalid.
216
+ - 500: If there is an error reading the directory contents.
217
+ - 200: JSON response containing a list of file and directory objects.
218
+ Each object includes:
219
+ - name: The name of the file or directory.
220
+ - type: 'file' or 'directory'.
221
+ - path: The relative path from the user's data root.
222
+ - size (for files): The size in bytes.
223
+ - modified (for files): The last modified timestamp (Unix epoch).
224
+ """
225
+ requested_rel_path = request.rel_url.query.get('path', '')
226
+
227
+ # URL-decode the path parameter
228
+ try:
229
+ requested_rel_path = parse.unquote(requested_rel_path)
230
+ except Exception as e:
231
+ logging.warning(f"Failed to decode path parameter: {requested_rel_path}, Error: {e}")
232
+ return web.Response(status=400, text="Invalid characters in path parameter")
233
+
234
+
235
+ # Check user validity and get the absolute path for the requested directory
236
+ try:
237
+ base_user_path = self.get_request_user_filepath(request, None, create_dir=False)
238
+
239
+ if requested_rel_path:
240
+ target_abs_path = self.get_request_user_filepath(request, requested_rel_path, create_dir=False)
241
+ else:
242
+ target_abs_path = base_user_path
243
+
244
+ except KeyError as e:
245
+ # Invalid user detected by get_request_user_id inside get_request_user_filepath
246
+ logging.warning(f"Access denied for user: {e}")
247
+ return web.Response(status=403, text="Invalid user specified in request")
248
+
249
+
250
+ if not target_abs_path:
251
+ # Path traversal or other issue detected by get_request_user_filepath
252
+ return web.Response(status=400, text="Invalid path requested")
253
+
254
+ # Handle cases where the user directory or target path doesn't exist
255
+ if not os.path.exists(target_abs_path):
256
+ # Check if it's the base user directory that's missing (new user case)
257
+ if target_abs_path == base_user_path:
258
+ # It's okay if the base user directory doesn't exist yet, return empty list
259
+ return web.json_response([])
260
+ else:
261
+ # A specific subdirectory was requested but doesn't exist
262
+ return web.Response(status=404, text="Requested path not found")
263
+
264
+ if not os.path.isdir(target_abs_path):
265
+ return web.Response(status=400, text="Requested path is not a directory")
266
+
267
+ results = []
268
+ try:
269
+ for root, dirs, files in os.walk(target_abs_path, topdown=True):
270
+ # Process directories
271
+ for dir_name in dirs:
272
+ dir_path = os.path.join(root, dir_name)
273
+ rel_path = os.path.relpath(dir_path, base_user_path).replace(os.sep, '/')
274
+ results.append({
275
+ "name": dir_name,
276
+ "path": rel_path,
277
+ "type": "directory"
278
+ })
279
+
280
+ # Process files
281
+ for file_name in files:
282
+ file_path = os.path.join(root, file_name)
283
+ rel_path = os.path.relpath(file_path, base_user_path).replace(os.sep, '/')
284
+ entry_info = {
285
+ "name": file_name,
286
+ "path": rel_path,
287
+ "type": "file"
288
+ }
289
+ try:
290
+ stats = os.stat(file_path) # Use os.stat for potentially better performance with os.walk
291
+ entry_info["size"] = stats.st_size
292
+ entry_info["modified"] = stats.st_mtime
293
+ except OSError as stat_error:
294
+ logging.warning(f"Could not stat file {file_path}: {stat_error}")
295
+ pass # Include file with available info
296
+ results.append(entry_info)
297
+ except OSError as e:
298
+ logging.error(f"Error listing directory {target_abs_path}: {e}")
299
+ return web.Response(status=500, text="Error reading directory contents")
300
+
301
+ # Sort results alphabetically, directories first then files
302
+ results.sort(key=lambda x: (x['type'] != 'directory', x['name'].lower()))
303
+
304
+ return web.json_response(results)
305
+
306
+ def get_user_data_path(request, check_exists = False, param = "file"):
307
+ file = request.match_info.get(param, None)
308
+ if not file:
309
+ return web.Response(status=400)
310
+
311
+ path = self.get_request_user_filepath(request, file)
312
+ if not path:
313
+ return web.Response(status=403)
314
+
315
+ if check_exists and not os.path.exists(path):
316
+ return web.Response(status=404)
317
+
318
+ return path
319
+
320
+ @routes.get("/userdata/{file}")
321
+ async def getuserdata(request):
322
+ path = get_user_data_path(request, check_exists=True)
323
+ if not isinstance(path, str):
324
+ return path
325
+
326
+ return web.FileResponse(path)
327
+
328
+ @routes.post("/userdata/{file}")
329
+ async def post_userdata(request):
330
+ """
331
+ Upload or update a user data file.
332
+
333
+ This endpoint handles file uploads to a user's data directory, with options for
334
+ controlling overwrite behavior and response format.
335
+
336
+ Query Parameters:
337
+ - overwrite (optional): If "false", prevents overwriting existing files. Defaults to "true".
338
+ - full_info (optional): If "true", returns detailed file information (path, size, modified time).
339
+ If "false", returns only the relative file path.
340
+
341
+ Path Parameters:
342
+ - file: The target file path (URL encoded if necessary).
343
+
344
+ Returns:
345
+ - 400: If 'file' parameter is missing.
346
+ - 403: If the requested path is not allowed.
347
+ - 409: If overwrite=false and the file already exists.
348
+ - 200: JSON response with either:
349
+ - Full file information (if full_info=true)
350
+ - Relative file path (if full_info=false)
351
+
352
+ The request body should contain the raw file content to be written.
353
+ """
354
+ path = get_user_data_path(request)
355
+ if not isinstance(path, str):
356
+ return path
357
+
358
+ overwrite = request.query.get("overwrite", 'true') != "false"
359
+ full_info = request.query.get('full_info', 'false').lower() == "true"
360
+
361
+ if not overwrite and os.path.exists(path):
362
+ return web.Response(status=409, text="File already exists")
363
+
364
+ body = await request.read()
365
+
366
+ with open(path, "wb") as f:
367
+ f.write(body)
368
+
369
+ user_path = self.get_request_user_filepath(request, None)
370
+ if full_info:
371
+ resp = get_file_info(path, user_path)
372
+ else:
373
+ resp = os.path.relpath(path, user_path)
374
+
375
+ return web.json_response(resp)
376
+
377
+ @routes.delete("/userdata/{file}")
378
+ async def delete_userdata(request):
379
+ path = get_user_data_path(request, check_exists=True)
380
+ if not isinstance(path, str):
381
+ return path
382
+
383
+ os.remove(path)
384
+
385
+ return web.Response(status=204)
386
+
387
+ @routes.post("/userdata/{file}/move/{dest}")
388
+ async def move_userdata(request):
389
+ """
390
+ Move or rename a user data file.
391
+
392
+ This endpoint handles moving or renaming files within a user's data directory, with options for
393
+ controlling overwrite behavior and response format.
394
+
395
+ Path Parameters:
396
+ - file: The source file path (URL encoded if necessary)
397
+ - dest: The destination file path (URL encoded if necessary)
398
+
399
+ Query Parameters:
400
+ - overwrite (optional): If "false", prevents overwriting existing files. Defaults to "true".
401
+ - full_info (optional): If "true", returns detailed file information (path, size, modified time).
402
+ If "false", returns only the relative file path.
403
+
404
+ Returns:
405
+ - 400: If either 'file' or 'dest' parameter is missing
406
+ - 403: If either requested path is not allowed
407
+ - 404: If the source file does not exist
408
+ - 409: If overwrite=false and the destination file already exists
409
+ - 200: JSON response with either:
410
+ - Full file information (if full_info=true)
411
+ - Relative file path (if full_info=false)
412
+ """
413
+ source = get_user_data_path(request, check_exists=True)
414
+ if not isinstance(source, str):
415
+ return source
416
+
417
+ dest = get_user_data_path(request, check_exists=False, param="dest")
418
+ if not isinstance(source, str):
419
+ return dest
420
+
421
+ overwrite = request.query.get("overwrite", 'true') != "false"
422
+ full_info = request.query.get('full_info', 'false').lower() == "true"
423
+
424
+ if not overwrite and os.path.exists(dest):
425
+ return web.Response(status=409, text="File already exists")
426
+
427
+ logging.info(f"moving '{source}' -> '{dest}'")
428
+ shutil.move(source, dest)
429
+
430
+ user_path = self.get_request_user_filepath(request, None)
431
+ if full_info:
432
+ resp = get_file_info(dest, user_path)
433
+ else:
434
+ resp = os.path.relpath(dest, user_path)
435
+
436
+ return web.json_response(resp)
comfy/checkpoint_pickle.py ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pickle
2
+
3
+ load = pickle.load
4
+
5
+ class Empty:
6
+ pass
7
+
8
+ class Unpickler(pickle.Unpickler):
9
+ def find_class(self, module, name):
10
+ #TODO: safe unpickle
11
+ if module.startswith("pytorch_lightning"):
12
+ return Empty
13
+ return super().find_class(module, name)
comfy/cldm/cldm.py ADDED
@@ -0,0 +1,433 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #taken from: https://github.com/lllyasviel/ControlNet
2
+ #and modified
3
+
4
+ import torch
5
+ import torch.nn as nn
6
+
7
+ from ..ldm.modules.diffusionmodules.util import (
8
+ timestep_embedding,
9
+ )
10
+
11
+ from ..ldm.modules.attention import SpatialTransformer
12
+ from ..ldm.modules.diffusionmodules.openaimodel import UNetModel, TimestepEmbedSequential, ResBlock, Downsample
13
+ from ..ldm.util import exists
14
+ from .control_types import UNION_CONTROLNET_TYPES
15
+ from collections import OrderedDict
16
+ import comfy.ops
17
+ from comfy.ldm.modules.attention import optimized_attention
18
+
19
+ class OptimizedAttention(nn.Module):
20
+ def __init__(self, c, nhead, dropout=0.0, dtype=None, device=None, operations=None):
21
+ super().__init__()
22
+ self.heads = nhead
23
+ self.c = c
24
+
25
+ self.in_proj = operations.Linear(c, c * 3, bias=True, dtype=dtype, device=device)
26
+ self.out_proj = operations.Linear(c, c, bias=True, dtype=dtype, device=device)
27
+
28
+ def forward(self, x):
29
+ x = self.in_proj(x)
30
+ q, k, v = x.split(self.c, dim=2)
31
+ out = optimized_attention(q, k, v, self.heads)
32
+ return self.out_proj(out)
33
+
34
+ class QuickGELU(nn.Module):
35
+ def forward(self, x: torch.Tensor):
36
+ return x * torch.sigmoid(1.702 * x)
37
+
38
+ class ResBlockUnionControlnet(nn.Module):
39
+ def __init__(self, dim, nhead, dtype=None, device=None, operations=None):
40
+ super().__init__()
41
+ self.attn = OptimizedAttention(dim, nhead, dtype=dtype, device=device, operations=operations)
42
+ self.ln_1 = operations.LayerNorm(dim, dtype=dtype, device=device)
43
+ self.mlp = nn.Sequential(
44
+ OrderedDict([("c_fc", operations.Linear(dim, dim * 4, dtype=dtype, device=device)), ("gelu", QuickGELU()),
45
+ ("c_proj", operations.Linear(dim * 4, dim, dtype=dtype, device=device))]))
46
+ self.ln_2 = operations.LayerNorm(dim, dtype=dtype, device=device)
47
+
48
+ def attention(self, x: torch.Tensor):
49
+ return self.attn(x)
50
+
51
+ def forward(self, x: torch.Tensor):
52
+ x = x + self.attention(self.ln_1(x))
53
+ x = x + self.mlp(self.ln_2(x))
54
+ return x
55
+
56
+ class ControlledUnetModel(UNetModel):
57
+ #implemented in the ldm unet
58
+ pass
59
+
60
+ class ControlNet(nn.Module):
61
+ def __init__(
62
+ self,
63
+ image_size,
64
+ in_channels,
65
+ model_channels,
66
+ hint_channels,
67
+ num_res_blocks,
68
+ dropout=0,
69
+ channel_mult=(1, 2, 4, 8),
70
+ conv_resample=True,
71
+ dims=2,
72
+ num_classes=None,
73
+ use_checkpoint=False,
74
+ dtype=torch.float32,
75
+ num_heads=-1,
76
+ num_head_channels=-1,
77
+ num_heads_upsample=-1,
78
+ use_scale_shift_norm=False,
79
+ resblock_updown=False,
80
+ use_new_attention_order=False,
81
+ use_spatial_transformer=False, # custom transformer support
82
+ transformer_depth=1, # custom transformer support
83
+ context_dim=None, # custom transformer support
84
+ n_embed=None, # custom support for prediction of discrete ids into codebook of first stage vq model
85
+ legacy=True,
86
+ disable_self_attentions=None,
87
+ num_attention_blocks=None,
88
+ disable_middle_self_attn=False,
89
+ use_linear_in_transformer=False,
90
+ adm_in_channels=None,
91
+ transformer_depth_middle=None,
92
+ transformer_depth_output=None,
93
+ attn_precision=None,
94
+ union_controlnet_num_control_type=None,
95
+ device=None,
96
+ operations=comfy.ops.disable_weight_init,
97
+ **kwargs,
98
+ ):
99
+ super().__init__()
100
+ assert use_spatial_transformer == True, "use_spatial_transformer has to be true"
101
+ if use_spatial_transformer:
102
+ assert context_dim is not None, 'Fool!! You forgot to include the dimension of your cross-attention conditioning...'
103
+
104
+ if context_dim is not None:
105
+ assert use_spatial_transformer, 'Fool!! You forgot to use the spatial transformer for your cross-attention conditioning...'
106
+ # from omegaconf.listconfig import ListConfig
107
+ # if type(context_dim) == ListConfig:
108
+ # context_dim = list(context_dim)
109
+
110
+ if num_heads_upsample == -1:
111
+ num_heads_upsample = num_heads
112
+
113
+ if num_heads == -1:
114
+ assert num_head_channels != -1, 'Either num_heads or num_head_channels has to be set'
115
+
116
+ if num_head_channels == -1:
117
+ assert num_heads != -1, 'Either num_heads or num_head_channels has to be set'
118
+
119
+ self.dims = dims
120
+ self.image_size = image_size
121
+ self.in_channels = in_channels
122
+ self.model_channels = model_channels
123
+
124
+ if isinstance(num_res_blocks, int):
125
+ self.num_res_blocks = len(channel_mult) * [num_res_blocks]
126
+ else:
127
+ if len(num_res_blocks) != len(channel_mult):
128
+ raise ValueError("provide num_res_blocks either as an int (globally constant) or "
129
+ "as a list/tuple (per-level) with the same length as channel_mult")
130
+ self.num_res_blocks = num_res_blocks
131
+
132
+ if disable_self_attentions is not None:
133
+ # should be a list of booleans, indicating whether to disable self-attention in TransformerBlocks or not
134
+ assert len(disable_self_attentions) == len(channel_mult)
135
+ if num_attention_blocks is not None:
136
+ assert len(num_attention_blocks) == len(self.num_res_blocks)
137
+ assert all(map(lambda i: self.num_res_blocks[i] >= num_attention_blocks[i], range(len(num_attention_blocks))))
138
+
139
+ transformer_depth = transformer_depth[:]
140
+
141
+ self.dropout = dropout
142
+ self.channel_mult = channel_mult
143
+ self.conv_resample = conv_resample
144
+ self.num_classes = num_classes
145
+ self.use_checkpoint = use_checkpoint
146
+ self.dtype = dtype
147
+ self.num_heads = num_heads
148
+ self.num_head_channels = num_head_channels
149
+ self.num_heads_upsample = num_heads_upsample
150
+ self.predict_codebook_ids = n_embed is not None
151
+
152
+ time_embed_dim = model_channels * 4
153
+ self.time_embed = nn.Sequential(
154
+ operations.Linear(model_channels, time_embed_dim, dtype=self.dtype, device=device),
155
+ nn.SiLU(),
156
+ operations.Linear(time_embed_dim, time_embed_dim, dtype=self.dtype, device=device),
157
+ )
158
+
159
+ if self.num_classes is not None:
160
+ if isinstance(self.num_classes, int):
161
+ self.label_emb = nn.Embedding(num_classes, time_embed_dim)
162
+ elif self.num_classes == "continuous":
163
+ self.label_emb = nn.Linear(1, time_embed_dim)
164
+ elif self.num_classes == "sequential":
165
+ assert adm_in_channels is not None
166
+ self.label_emb = nn.Sequential(
167
+ nn.Sequential(
168
+ operations.Linear(adm_in_channels, time_embed_dim, dtype=self.dtype, device=device),
169
+ nn.SiLU(),
170
+ operations.Linear(time_embed_dim, time_embed_dim, dtype=self.dtype, device=device),
171
+ )
172
+ )
173
+ else:
174
+ raise ValueError()
175
+
176
+ self.input_blocks = nn.ModuleList(
177
+ [
178
+ TimestepEmbedSequential(
179
+ operations.conv_nd(dims, in_channels, model_channels, 3, padding=1, dtype=self.dtype, device=device)
180
+ )
181
+ ]
182
+ )
183
+ self.zero_convs = nn.ModuleList([self.make_zero_conv(model_channels, operations=operations, dtype=self.dtype, device=device)])
184
+
185
+ self.input_hint_block = TimestepEmbedSequential(
186
+ operations.conv_nd(dims, hint_channels, 16, 3, padding=1, dtype=self.dtype, device=device),
187
+ nn.SiLU(),
188
+ operations.conv_nd(dims, 16, 16, 3, padding=1, dtype=self.dtype, device=device),
189
+ nn.SiLU(),
190
+ operations.conv_nd(dims, 16, 32, 3, padding=1, stride=2, dtype=self.dtype, device=device),
191
+ nn.SiLU(),
192
+ operations.conv_nd(dims, 32, 32, 3, padding=1, dtype=self.dtype, device=device),
193
+ nn.SiLU(),
194
+ operations.conv_nd(dims, 32, 96, 3, padding=1, stride=2, dtype=self.dtype, device=device),
195
+ nn.SiLU(),
196
+ operations.conv_nd(dims, 96, 96, 3, padding=1, dtype=self.dtype, device=device),
197
+ nn.SiLU(),
198
+ operations.conv_nd(dims, 96, 256, 3, padding=1, stride=2, dtype=self.dtype, device=device),
199
+ nn.SiLU(),
200
+ operations.conv_nd(dims, 256, model_channels, 3, padding=1, dtype=self.dtype, device=device)
201
+ )
202
+
203
+ self._feature_size = model_channels
204
+ input_block_chans = [model_channels]
205
+ ch = model_channels
206
+ ds = 1
207
+ for level, mult in enumerate(channel_mult):
208
+ for nr in range(self.num_res_blocks[level]):
209
+ layers = [
210
+ ResBlock(
211
+ ch,
212
+ time_embed_dim,
213
+ dropout,
214
+ out_channels=mult * model_channels,
215
+ dims=dims,
216
+ use_checkpoint=use_checkpoint,
217
+ use_scale_shift_norm=use_scale_shift_norm,
218
+ dtype=self.dtype,
219
+ device=device,
220
+ operations=operations,
221
+ )
222
+ ]
223
+ ch = mult * model_channels
224
+ num_transformers = transformer_depth.pop(0)
225
+ if num_transformers > 0:
226
+ if num_head_channels == -1:
227
+ dim_head = ch // num_heads
228
+ else:
229
+ num_heads = ch // num_head_channels
230
+ dim_head = num_head_channels
231
+ if legacy:
232
+ #num_heads = 1
233
+ dim_head = ch // num_heads if use_spatial_transformer else num_head_channels
234
+ if exists(disable_self_attentions):
235
+ disabled_sa = disable_self_attentions[level]
236
+ else:
237
+ disabled_sa = False
238
+
239
+ if not exists(num_attention_blocks) or nr < num_attention_blocks[level]:
240
+ layers.append(
241
+ SpatialTransformer(
242
+ ch, num_heads, dim_head, depth=num_transformers, context_dim=context_dim,
243
+ disable_self_attn=disabled_sa, use_linear=use_linear_in_transformer,
244
+ use_checkpoint=use_checkpoint, attn_precision=attn_precision, dtype=self.dtype, device=device, operations=operations
245
+ )
246
+ )
247
+ self.input_blocks.append(TimestepEmbedSequential(*layers))
248
+ self.zero_convs.append(self.make_zero_conv(ch, operations=operations, dtype=self.dtype, device=device))
249
+ self._feature_size += ch
250
+ input_block_chans.append(ch)
251
+ if level != len(channel_mult) - 1:
252
+ out_ch = ch
253
+ self.input_blocks.append(
254
+ TimestepEmbedSequential(
255
+ ResBlock(
256
+ ch,
257
+ time_embed_dim,
258
+ dropout,
259
+ out_channels=out_ch,
260
+ dims=dims,
261
+ use_checkpoint=use_checkpoint,
262
+ use_scale_shift_norm=use_scale_shift_norm,
263
+ down=True,
264
+ dtype=self.dtype,
265
+ device=device,
266
+ operations=operations
267
+ )
268
+ if resblock_updown
269
+ else Downsample(
270
+ ch, conv_resample, dims=dims, out_channels=out_ch, dtype=self.dtype, device=device, operations=operations
271
+ )
272
+ )
273
+ )
274
+ ch = out_ch
275
+ input_block_chans.append(ch)
276
+ self.zero_convs.append(self.make_zero_conv(ch, operations=operations, dtype=self.dtype, device=device))
277
+ ds *= 2
278
+ self._feature_size += ch
279
+
280
+ if num_head_channels == -1:
281
+ dim_head = ch // num_heads
282
+ else:
283
+ num_heads = ch // num_head_channels
284
+ dim_head = num_head_channels
285
+ if legacy:
286
+ #num_heads = 1
287
+ dim_head = ch // num_heads if use_spatial_transformer else num_head_channels
288
+ mid_block = [
289
+ ResBlock(
290
+ ch,
291
+ time_embed_dim,
292
+ dropout,
293
+ dims=dims,
294
+ use_checkpoint=use_checkpoint,
295
+ use_scale_shift_norm=use_scale_shift_norm,
296
+ dtype=self.dtype,
297
+ device=device,
298
+ operations=operations
299
+ )]
300
+ if transformer_depth_middle >= 0:
301
+ mid_block += [SpatialTransformer( # always uses a self-attn
302
+ ch, num_heads, dim_head, depth=transformer_depth_middle, context_dim=context_dim,
303
+ disable_self_attn=disable_middle_self_attn, use_linear=use_linear_in_transformer,
304
+ use_checkpoint=use_checkpoint, attn_precision=attn_precision, dtype=self.dtype, device=device, operations=operations
305
+ ),
306
+ ResBlock(
307
+ ch,
308
+ time_embed_dim,
309
+ dropout,
310
+ dims=dims,
311
+ use_checkpoint=use_checkpoint,
312
+ use_scale_shift_norm=use_scale_shift_norm,
313
+ dtype=self.dtype,
314
+ device=device,
315
+ operations=operations
316
+ )]
317
+ self.middle_block = TimestepEmbedSequential(*mid_block)
318
+ self.middle_block_out = self.make_zero_conv(ch, operations=operations, dtype=self.dtype, device=device)
319
+ self._feature_size += ch
320
+
321
+ if union_controlnet_num_control_type is not None:
322
+ self.num_control_type = union_controlnet_num_control_type
323
+ num_trans_channel = 320
324
+ num_trans_head = 8
325
+ num_trans_layer = 1
326
+ num_proj_channel = 320
327
+ # task_scale_factor = num_trans_channel ** 0.5
328
+ self.task_embedding = nn.Parameter(torch.empty(self.num_control_type, num_trans_channel, dtype=self.dtype, device=device))
329
+
330
+ self.transformer_layes = nn.Sequential(*[ResBlockUnionControlnet(num_trans_channel, num_trans_head, dtype=self.dtype, device=device, operations=operations) for _ in range(num_trans_layer)])
331
+ self.spatial_ch_projs = operations.Linear(num_trans_channel, num_proj_channel, dtype=self.dtype, device=device)
332
+ #-----------------------------------------------------------------------------------------------------
333
+
334
+ control_add_embed_dim = 256
335
+ class ControlAddEmbedding(nn.Module):
336
+ def __init__(self, in_dim, out_dim, num_control_type, dtype=None, device=None, operations=None):
337
+ super().__init__()
338
+ self.num_control_type = num_control_type
339
+ self.in_dim = in_dim
340
+ self.linear_1 = operations.Linear(in_dim * num_control_type, out_dim, dtype=dtype, device=device)
341
+ self.linear_2 = operations.Linear(out_dim, out_dim, dtype=dtype, device=device)
342
+ def forward(self, control_type, dtype, device):
343
+ c_type = torch.zeros((self.num_control_type,), device=device)
344
+ c_type[control_type] = 1.0
345
+ c_type = timestep_embedding(c_type.flatten(), self.in_dim, repeat_only=False).to(dtype).reshape((-1, self.num_control_type * self.in_dim))
346
+ return self.linear_2(torch.nn.functional.silu(self.linear_1(c_type)))
347
+
348
+ self.control_add_embedding = ControlAddEmbedding(control_add_embed_dim, time_embed_dim, self.num_control_type, dtype=self.dtype, device=device, operations=operations)
349
+ else:
350
+ self.task_embedding = None
351
+ self.control_add_embedding = None
352
+
353
+ def union_controlnet_merge(self, hint, control_type, emb, context):
354
+ # Equivalent to: https://github.com/xinsir6/ControlNetPlus/tree/main
355
+ inputs = []
356
+ condition_list = []
357
+
358
+ for idx in range(min(1, len(control_type))):
359
+ controlnet_cond = self.input_hint_block(hint[idx], emb, context)
360
+ feat_seq = torch.mean(controlnet_cond, dim=(2, 3))
361
+ if idx < len(control_type):
362
+ feat_seq += self.task_embedding[control_type[idx]].to(dtype=feat_seq.dtype, device=feat_seq.device)
363
+
364
+ inputs.append(feat_seq.unsqueeze(1))
365
+ condition_list.append(controlnet_cond)
366
+
367
+ x = torch.cat(inputs, dim=1)
368
+ x = self.transformer_layes(x)
369
+ controlnet_cond_fuser = None
370
+ for idx in range(len(control_type)):
371
+ alpha = self.spatial_ch_projs(x[:, idx])
372
+ alpha = alpha.unsqueeze(-1).unsqueeze(-1)
373
+ o = condition_list[idx] + alpha
374
+ if controlnet_cond_fuser is None:
375
+ controlnet_cond_fuser = o
376
+ else:
377
+ controlnet_cond_fuser += o
378
+ return controlnet_cond_fuser
379
+
380
+ def make_zero_conv(self, channels, operations=None, dtype=None, device=None):
381
+ return TimestepEmbedSequential(operations.conv_nd(self.dims, channels, channels, 1, padding=0, dtype=dtype, device=device))
382
+
383
+ def forward(self, x, hint, timesteps, context, y=None, **kwargs):
384
+ t_emb = timestep_embedding(timesteps, self.model_channels, repeat_only=False).to(x.dtype)
385
+ emb = self.time_embed(t_emb)
386
+
387
+ guided_hint = None
388
+ if self.control_add_embedding is not None: #Union Controlnet
389
+ control_type = kwargs.get("control_type", [])
390
+
391
+ if any([c >= self.num_control_type for c in control_type]):
392
+ max_type = max(control_type)
393
+ max_type_name = {
394
+ v: k for k, v in UNION_CONTROLNET_TYPES.items()
395
+ }[max_type]
396
+ raise ValueError(
397
+ f"Control type {max_type_name}({max_type}) is out of range for the number of control types" +
398
+ f"({self.num_control_type}) supported.\n" +
399
+ "Please consider using the ProMax ControlNet Union model.\n" +
400
+ "https://huggingface.co/xinsir/controlnet-union-sdxl-1.0/tree/main"
401
+ )
402
+
403
+ emb += self.control_add_embedding(control_type, emb.dtype, emb.device)
404
+ if len(control_type) > 0:
405
+ if len(hint.shape) < 5:
406
+ hint = hint.unsqueeze(dim=0)
407
+ guided_hint = self.union_controlnet_merge(hint, control_type, emb, context)
408
+
409
+ if guided_hint is None:
410
+ guided_hint = self.input_hint_block(hint, emb, context)
411
+
412
+ out_output = []
413
+ out_middle = []
414
+
415
+ if self.num_classes is not None:
416
+ assert y.shape[0] == x.shape[0]
417
+ emb = emb + self.label_emb(y)
418
+
419
+ h = x
420
+ for module, zero_conv in zip(self.input_blocks, self.zero_convs):
421
+ if guided_hint is not None:
422
+ h = module(h, emb, context)
423
+ h += guided_hint
424
+ guided_hint = None
425
+ else:
426
+ h = module(h, emb, context)
427
+ out_output.append(zero_conv(h, emb, context))
428
+
429
+ h = self.middle_block(h, emb, context)
430
+ out_middle.append(self.middle_block_out(h, emb, context))
431
+
432
+ return {"middle": out_middle, "output": out_output}
433
+
comfy/cldm/control_types.py ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ UNION_CONTROLNET_TYPES = {
2
+ "openpose": 0,
3
+ "depth": 1,
4
+ "hed/pidi/scribble/ted": 2,
5
+ "canny/lineart/anime_lineart/mlsd": 3,
6
+ "normal": 4,
7
+ "segment": 5,
8
+ "tile": 6,
9
+ "repaint": 7,
10
+ }
comfy/cldm/dit_embedder.py ADDED
@@ -0,0 +1,120 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ from typing import List, Optional, Tuple
3
+
4
+ import torch
5
+ import torch.nn as nn
6
+ from torch import Tensor
7
+
8
+ from comfy.ldm.modules.diffusionmodules.mmdit import DismantledBlock, PatchEmbed, VectorEmbedder, TimestepEmbedder, get_2d_sincos_pos_embed_torch
9
+
10
+
11
+ class ControlNetEmbedder(nn.Module):
12
+
13
+ def __init__(
14
+ self,
15
+ img_size: int,
16
+ patch_size: int,
17
+ in_chans: int,
18
+ attention_head_dim: int,
19
+ num_attention_heads: int,
20
+ adm_in_channels: int,
21
+ num_layers: int,
22
+ main_model_double: int,
23
+ double_y_emb: bool,
24
+ device: torch.device,
25
+ dtype: torch.dtype,
26
+ pos_embed_max_size: Optional[int] = None,
27
+ operations = None,
28
+ ):
29
+ super().__init__()
30
+ self.main_model_double = main_model_double
31
+ self.dtype = dtype
32
+ self.hidden_size = num_attention_heads * attention_head_dim
33
+ self.patch_size = patch_size
34
+ self.x_embedder = PatchEmbed(
35
+ img_size=img_size,
36
+ patch_size=patch_size,
37
+ in_chans=in_chans,
38
+ embed_dim=self.hidden_size,
39
+ strict_img_size=pos_embed_max_size is None,
40
+ device=device,
41
+ dtype=dtype,
42
+ operations=operations,
43
+ )
44
+
45
+ self.t_embedder = TimestepEmbedder(self.hidden_size, dtype=dtype, device=device, operations=operations)
46
+
47
+ self.double_y_emb = double_y_emb
48
+ if self.double_y_emb:
49
+ self.orig_y_embedder = VectorEmbedder(
50
+ adm_in_channels, self.hidden_size, dtype, device, operations=operations
51
+ )
52
+ self.y_embedder = VectorEmbedder(
53
+ self.hidden_size, self.hidden_size, dtype, device, operations=operations
54
+ )
55
+ else:
56
+ self.y_embedder = VectorEmbedder(
57
+ adm_in_channels, self.hidden_size, dtype, device, operations=operations
58
+ )
59
+
60
+ self.transformer_blocks = nn.ModuleList(
61
+ DismantledBlock(
62
+ hidden_size=self.hidden_size, num_heads=num_attention_heads, qkv_bias=True,
63
+ dtype=dtype, device=device, operations=operations
64
+ )
65
+ for _ in range(num_layers)
66
+ )
67
+
68
+ # self.use_y_embedder = pooled_projection_dim != self.time_text_embed.text_embedder.linear_1.in_features
69
+ # TODO double check this logic when 8b
70
+ self.use_y_embedder = True
71
+
72
+ self.controlnet_blocks = nn.ModuleList([])
73
+ for _ in range(len(self.transformer_blocks)):
74
+ controlnet_block = operations.Linear(self.hidden_size, self.hidden_size, dtype=dtype, device=device)
75
+ self.controlnet_blocks.append(controlnet_block)
76
+
77
+ self.pos_embed_input = PatchEmbed(
78
+ img_size=img_size,
79
+ patch_size=patch_size,
80
+ in_chans=in_chans,
81
+ embed_dim=self.hidden_size,
82
+ strict_img_size=False,
83
+ device=device,
84
+ dtype=dtype,
85
+ operations=operations,
86
+ )
87
+
88
+ def forward(
89
+ self,
90
+ x: torch.Tensor,
91
+ timesteps: torch.Tensor,
92
+ y: Optional[torch.Tensor] = None,
93
+ context: Optional[torch.Tensor] = None,
94
+ hint = None,
95
+ ) -> Tuple[Tensor, List[Tensor]]:
96
+ x_shape = list(x.shape)
97
+ x = self.x_embedder(x)
98
+ if not self.double_y_emb:
99
+ h = (x_shape[-2] + 1) // self.patch_size
100
+ w = (x_shape[-1] + 1) // self.patch_size
101
+ x += get_2d_sincos_pos_embed_torch(self.hidden_size, w, h, device=x.device)
102
+ c = self.t_embedder(timesteps, dtype=x.dtype)
103
+ if y is not None and self.y_embedder is not None:
104
+ if self.double_y_emb:
105
+ y = self.orig_y_embedder(y)
106
+ y = self.y_embedder(y)
107
+ c = c + y
108
+
109
+ x = x + self.pos_embed_input(hint)
110
+
111
+ block_out = ()
112
+
113
+ repeat = math.ceil(self.main_model_double / len(self.transformer_blocks))
114
+ for i in range(len(self.transformer_blocks)):
115
+ out = self.transformer_blocks[i](x, c)
116
+ if not self.double_y_emb:
117
+ x = out
118
+ block_out += (self.controlnet_blocks[i](out),) * repeat
119
+
120
+ return {"output": block_out}
comfy/cldm/mmdit.py ADDED
@@ -0,0 +1,81 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from typing import Optional
3
+ import comfy.ldm.modules.diffusionmodules.mmdit
4
+
5
+ class ControlNet(comfy.ldm.modules.diffusionmodules.mmdit.MMDiT):
6
+ def __init__(
7
+ self,
8
+ num_blocks = None,
9
+ control_latent_channels = None,
10
+ dtype = None,
11
+ device = None,
12
+ operations = None,
13
+ **kwargs,
14
+ ):
15
+ super().__init__(dtype=dtype, device=device, operations=operations, final_layer=False, num_blocks=num_blocks, **kwargs)
16
+ # controlnet_blocks
17
+ self.controlnet_blocks = torch.nn.ModuleList([])
18
+ for _ in range(len(self.joint_blocks)):
19
+ self.controlnet_blocks.append(operations.Linear(self.hidden_size, self.hidden_size, device=device, dtype=dtype))
20
+
21
+ if control_latent_channels is None:
22
+ control_latent_channels = self.in_channels
23
+
24
+ self.pos_embed_input = comfy.ldm.modules.diffusionmodules.mmdit.PatchEmbed(
25
+ None,
26
+ self.patch_size,
27
+ control_latent_channels,
28
+ self.hidden_size,
29
+ bias=True,
30
+ strict_img_size=False,
31
+ dtype=dtype,
32
+ device=device,
33
+ operations=operations
34
+ )
35
+
36
+ def forward(
37
+ self,
38
+ x: torch.Tensor,
39
+ timesteps: torch.Tensor,
40
+ y: Optional[torch.Tensor] = None,
41
+ context: Optional[torch.Tensor] = None,
42
+ hint = None,
43
+ ) -> torch.Tensor:
44
+
45
+ #weird sd3 controlnet specific stuff
46
+ y = torch.zeros_like(y)
47
+
48
+ if self.context_processor is not None:
49
+ context = self.context_processor(context)
50
+
51
+ hw = x.shape[-2:]
52
+ x = self.x_embedder(x) + self.cropped_pos_embed(hw, device=x.device).to(dtype=x.dtype, device=x.device)
53
+ x += self.pos_embed_input(hint)
54
+
55
+ c = self.t_embedder(timesteps, dtype=x.dtype)
56
+ if y is not None and self.y_embedder is not None:
57
+ y = self.y_embedder(y)
58
+ c = c + y
59
+
60
+ if context is not None:
61
+ context = self.context_embedder(context)
62
+
63
+ output = []
64
+
65
+ blocks = len(self.joint_blocks)
66
+ for i in range(blocks):
67
+ context, x = self.joint_blocks[i](
68
+ context,
69
+ x,
70
+ c=c,
71
+ use_checkpoint=self.use_checkpoint,
72
+ )
73
+
74
+ out = self.controlnet_blocks[i](x)
75
+ count = self.depth // blocks
76
+ if i == blocks - 1:
77
+ count -= 1
78
+ for j in range(count):
79
+ output.append(out)
80
+
81
+ return {"output": output}
comfy/cli_args.py ADDED
@@ -0,0 +1,229 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import enum
3
+ import os
4
+ import comfy.options
5
+
6
+
7
+ class EnumAction(argparse.Action):
8
+ """
9
+ Argparse action for handling Enums
10
+ """
11
+ def __init__(self, **kwargs):
12
+ # Pop off the type value
13
+ enum_type = kwargs.pop("type", None)
14
+
15
+ # Ensure an Enum subclass is provided
16
+ if enum_type is None:
17
+ raise ValueError("type must be assigned an Enum when using EnumAction")
18
+ if not issubclass(enum_type, enum.Enum):
19
+ raise TypeError("type must be an Enum when using EnumAction")
20
+
21
+ # Generate choices from the Enum
22
+ choices = tuple(e.value for e in enum_type)
23
+ kwargs.setdefault("choices", choices)
24
+ kwargs.setdefault("metavar", f"[{','.join(list(choices))}]")
25
+
26
+ super(EnumAction, self).__init__(**kwargs)
27
+
28
+ self._enum = enum_type
29
+
30
+ def __call__(self, parser, namespace, values, option_string=None):
31
+ # Convert value back into an Enum
32
+ value = self._enum(values)
33
+ setattr(namespace, self.dest, value)
34
+
35
+
36
+ parser = argparse.ArgumentParser()
37
+
38
+ parser.add_argument("--listen", type=str, default="127.0.0.1", metavar="IP", nargs="?", const="0.0.0.0,::", help="Specify the IP address to listen on (default: 127.0.0.1). You can give a list of ip addresses by separating them with a comma like: 127.2.2.2,127.3.3.3 If --listen is provided without an argument, it defaults to 0.0.0.0,:: (listens on all ipv4 and ipv6)")
39
+ parser.add_argument("--port", type=int, default=8188, help="Set the listen port.")
40
+ parser.add_argument("--tls-keyfile", type=str, help="Path to TLS (SSL) key file. Enables TLS, makes app accessible at https://... requires --tls-certfile to function")
41
+ parser.add_argument("--tls-certfile", type=str, help="Path to TLS (SSL) certificate file. Enables TLS, makes app accessible at https://... requires --tls-keyfile to function")
42
+ parser.add_argument("--enable-cors-header", type=str, default=None, metavar="ORIGIN", nargs="?", const="*", help="Enable CORS (Cross-Origin Resource Sharing) with optional origin or allow all with default '*'.")
43
+ parser.add_argument("--max-upload-size", type=float, default=100, help="Set the maximum upload size in MB.")
44
+
45
+ parser.add_argument("--base-directory", type=str, default=None, help="Set the ComfyUI base directory for models, custom_nodes, input, output, temp, and user directories.")
46
+ parser.add_argument("--extra-model-paths-config", type=str, default=None, metavar="PATH", nargs='+', action='append', help="Load one or more extra_model_paths.yaml files.")
47
+ parser.add_argument("--output-directory", type=str, default=None, help="Set the ComfyUI output directory. Overrides --base-directory.")
48
+ parser.add_argument("--temp-directory", type=str, default=None, help="Set the ComfyUI temp directory (default is in the ComfyUI directory). Overrides --base-directory.")
49
+ parser.add_argument("--input-directory", type=str, default=None, help="Set the ComfyUI input directory. Overrides --base-directory.")
50
+ parser.add_argument("--auto-launch", action="store_true", help="Automatically launch ComfyUI in the default browser.")
51
+ parser.add_argument("--disable-auto-launch", action="store_true", help="Disable auto launching the browser.")
52
+ parser.add_argument("--cuda-device", type=int, default=None, metavar="DEVICE_ID", help="Set the id of the cuda device this instance will use.")
53
+ cm_group = parser.add_mutually_exclusive_group()
54
+ cm_group.add_argument("--cuda-malloc", action="store_true", help="Enable cudaMallocAsync (enabled by default for torch 2.0 and up).")
55
+ cm_group.add_argument("--disable-cuda-malloc", action="store_true", help="Disable cudaMallocAsync.")
56
+
57
+
58
+ fp_group = parser.add_mutually_exclusive_group()
59
+ fp_group.add_argument("--force-fp32", action="store_true", help="Force fp32 (If this makes your GPU work better please report it).")
60
+ fp_group.add_argument("--force-fp16", action="store_true", help="Force fp16.")
61
+
62
+ fpunet_group = parser.add_mutually_exclusive_group()
63
+ fpunet_group.add_argument("--fp32-unet", action="store_true", help="Run the diffusion model in fp32.")
64
+ fpunet_group.add_argument("--fp64-unet", action="store_true", help="Run the diffusion model in fp64.")
65
+ fpunet_group.add_argument("--bf16-unet", action="store_true", help="Run the diffusion model in bf16.")
66
+ fpunet_group.add_argument("--fp16-unet", action="store_true", help="Run the diffusion model in fp16")
67
+ fpunet_group.add_argument("--fp8_e4m3fn-unet", action="store_true", help="Store unet weights in fp8_e4m3fn.")
68
+ fpunet_group.add_argument("--fp8_e5m2-unet", action="store_true", help="Store unet weights in fp8_e5m2.")
69
+ fpunet_group.add_argument("--fp8_e8m0fnu-unet", action="store_true", help="Store unet weights in fp8_e8m0fnu.")
70
+
71
+ fpvae_group = parser.add_mutually_exclusive_group()
72
+ fpvae_group.add_argument("--fp16-vae", action="store_true", help="Run the VAE in fp16, might cause black images.")
73
+ fpvae_group.add_argument("--fp32-vae", action="store_true", help="Run the VAE in full precision fp32.")
74
+ fpvae_group.add_argument("--bf16-vae", action="store_true", help="Run the VAE in bf16.")
75
+
76
+ parser.add_argument("--cpu-vae", action="store_true", help="Run the VAE on the CPU.")
77
+
78
+ fpte_group = parser.add_mutually_exclusive_group()
79
+ fpte_group.add_argument("--fp8_e4m3fn-text-enc", action="store_true", help="Store text encoder weights in fp8 (e4m3fn variant).")
80
+ fpte_group.add_argument("--fp8_e5m2-text-enc", action="store_true", help="Store text encoder weights in fp8 (e5m2 variant).")
81
+ fpte_group.add_argument("--fp16-text-enc", action="store_true", help="Store text encoder weights in fp16.")
82
+ fpte_group.add_argument("--fp32-text-enc", action="store_true", help="Store text encoder weights in fp32.")
83
+ fpte_group.add_argument("--bf16-text-enc", action="store_true", help="Store text encoder weights in bf16.")
84
+
85
+ parser.add_argument("--force-channels-last", action="store_true", help="Force channels last format when inferencing the models.")
86
+
87
+ parser.add_argument("--directml", type=int, nargs="?", metavar="DIRECTML_DEVICE", const=-1, help="Use torch-directml.")
88
+
89
+ parser.add_argument("--oneapi-device-selector", type=str, default=None, metavar="SELECTOR_STRING", help="Sets the oneAPI device(s) this instance will use.")
90
+ parser.add_argument("--disable-ipex-optimize", action="store_true", help="Disables ipex.optimize default when loading models with Intel's Extension for Pytorch.")
91
+ parser.add_argument("--supports-fp8-compute", action="store_true", help="ComfyUI will act like if the device supports fp8 compute.")
92
+
93
+ class LatentPreviewMethod(enum.Enum):
94
+ NoPreviews = "none"
95
+ Auto = "auto"
96
+ Latent2RGB = "latent2rgb"
97
+ TAESD = "taesd"
98
+
99
+ parser.add_argument("--preview-method", type=LatentPreviewMethod, default=LatentPreviewMethod.NoPreviews, help="Default preview method for sampler nodes.", action=EnumAction)
100
+
101
+ parser.add_argument("--preview-size", type=int, default=512, help="Sets the maximum preview size for sampler nodes.")
102
+
103
+ cache_group = parser.add_mutually_exclusive_group()
104
+ cache_group.add_argument("--cache-classic", action="store_true", help="Use the old style (aggressive) caching.")
105
+ cache_group.add_argument("--cache-lru", type=int, default=0, help="Use LRU caching with a maximum of N node results cached. May use more RAM/VRAM.")
106
+ cache_group.add_argument("--cache-none", action="store_true", help="Reduced RAM/VRAM usage at the expense of executing every node for each run.")
107
+
108
+ attn_group = parser.add_mutually_exclusive_group()
109
+ attn_group.add_argument("--use-split-cross-attention", action="store_true", help="Use the split cross attention optimization. Ignored when xformers is used.")
110
+ attn_group.add_argument("--use-quad-cross-attention", action="store_true", help="Use the sub-quadratic cross attention optimization . Ignored when xformers is used.")
111
+ attn_group.add_argument("--use-pytorch-cross-attention", action="store_true", help="Use the new pytorch 2.0 cross attention function.")
112
+ attn_group.add_argument("--use-sage-attention", action="store_true", help="Use sage attention.")
113
+ attn_group.add_argument("--use-flash-attention", action="store_true", help="Use FlashAttention.")
114
+
115
+ parser.add_argument("--disable-xformers", action="store_true", help="Disable xformers.")
116
+
117
+ upcast = parser.add_mutually_exclusive_group()
118
+ upcast.add_argument("--force-upcast-attention", action="store_true", help="Force enable attention upcasting, please report if it fixes black images.")
119
+ upcast.add_argument("--dont-upcast-attention", action="store_true", help="Disable all upcasting of attention. Should be unnecessary except for debugging.")
120
+
121
+
122
+ vram_group = parser.add_mutually_exclusive_group()
123
+ vram_group.add_argument("--gpu-only", action="store_true", help="Store and run everything (text encoders/CLIP models, etc... on the GPU).")
124
+ vram_group.add_argument("--highvram", action="store_true", help="By default models will be unloaded to CPU memory after being used. This option keeps them in GPU memory.")
125
+ vram_group.add_argument("--normalvram", action="store_true", help="Used to force normal vram use if lowvram gets automatically enabled.")
126
+ vram_group.add_argument("--lowvram", action="store_true", help="Split the unet in parts to use less vram.")
127
+ vram_group.add_argument("--novram", action="store_true", help="When lowvram isn't enough.")
128
+ vram_group.add_argument("--cpu", action="store_true", help="To use the CPU for everything (slow).")
129
+
130
+ parser.add_argument("--reserve-vram", type=float, default=None, help="Set the amount of vram in GB you want to reserve for use by your OS/other software. By default some amount is reserved depending on your OS.")
131
+
132
+ parser.add_argument("--async-offload", action="store_true", help="Use async weight offloading.")
133
+
134
+ parser.add_argument("--default-hashing-function", type=str, choices=['md5', 'sha1', 'sha256', 'sha512'], default='sha256', help="Allows you to choose the hash function to use for duplicate filename / contents comparison. Default is sha256.")
135
+
136
+ parser.add_argument("--disable-smart-memory", action="store_true", help="Force ComfyUI to agressively offload to regular ram instead of keeping models in vram when it can.")
137
+ parser.add_argument("--deterministic", action="store_true", help="Make pytorch use slower deterministic algorithms when it can. Note that this might not make images deterministic in all cases.")
138
+
139
+ class PerformanceFeature(enum.Enum):
140
+ Fp16Accumulation = "fp16_accumulation"
141
+ Fp8MatrixMultiplication = "fp8_matrix_mult"
142
+ CublasOps = "cublas_ops"
143
+
144
+ parser.add_argument("--fast", nargs="*", type=PerformanceFeature, help="Enable some untested and potentially quality deteriorating optimizations. --fast with no arguments enables everything. You can pass a list specific optimizations if you only want to enable specific ones. Current valid optimizations: fp16_accumulation fp8_matrix_mult cublas_ops")
145
+
146
+ parser.add_argument("--mmap-torch-files", action="store_true", help="Use mmap when loading ckpt/pt files.")
147
+
148
+ parser.add_argument("--dont-print-server", action="store_true", help="Don't print server output.")
149
+ parser.add_argument("--quick-test-for-ci", action="store_true", help="Quick test for CI.")
150
+ parser.add_argument("--windows-standalone-build", action="store_true", help="Windows standalone build: Enable convenient things that most people using the standalone windows build will probably enjoy (like auto opening the page on startup).")
151
+
152
+ parser.add_argument("--disable-metadata", action="store_true", help="Disable saving prompt metadata in files.")
153
+ parser.add_argument("--disable-all-custom-nodes", action="store_true", help="Disable loading all custom nodes.")
154
+ parser.add_argument("--disable-api-nodes", action="store_true", help="Disable loading all api nodes.")
155
+
156
+ parser.add_argument("--multi-user", action="store_true", help="Enables per-user storage.")
157
+
158
+ parser.add_argument("--verbose", default='INFO', const='DEBUG', nargs="?", choices=['DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL'], help='Set the logging level')
159
+ parser.add_argument("--log-stdout", action="store_true", help="Send normal process output to stdout instead of stderr (default).")
160
+
161
+ # The default built-in provider hosted under web/
162
+ DEFAULT_VERSION_STRING = "comfyanonymous/ComfyUI@latest"
163
+
164
+ parser.add_argument(
165
+ "--front-end-version",
166
+ type=str,
167
+ default=DEFAULT_VERSION_STRING,
168
+ help="""
169
+ Specifies the version of the frontend to be used. This command needs internet connectivity to query and
170
+ download available frontend implementations from GitHub releases.
171
+
172
+ The version string should be in the format of:
173
+ [repoOwner]/[repoName]@[version]
174
+ where version is one of: "latest" or a valid version number (e.g. "1.0.0")
175
+ """,
176
+ )
177
+
178
+ def is_valid_directory(path: str) -> str:
179
+ """Validate if the given path is a directory, and check permissions."""
180
+ if not os.path.exists(path):
181
+ raise argparse.ArgumentTypeError(f"The path '{path}' does not exist.")
182
+ if not os.path.isdir(path):
183
+ raise argparse.ArgumentTypeError(f"'{path}' is not a directory.")
184
+ if not os.access(path, os.R_OK):
185
+ raise argparse.ArgumentTypeError(f"You do not have read permissions for '{path}'.")
186
+ return path
187
+
188
+ parser.add_argument(
189
+ "--front-end-root",
190
+ type=is_valid_directory,
191
+ default=None,
192
+ help="The local filesystem path to the directory where the frontend is located. Overrides --front-end-version.",
193
+ )
194
+
195
+ parser.add_argument("--user-directory", type=is_valid_directory, default=None, help="Set the ComfyUI user directory with an absolute path. Overrides --base-directory.")
196
+
197
+ parser.add_argument("--enable-compress-response-body", action="store_true", help="Enable compressing response body.")
198
+
199
+ parser.add_argument(
200
+ "--comfy-api-base",
201
+ type=str,
202
+ default="https://api.comfy.org",
203
+ help="Set the base URL for the ComfyUI API. (default: https://api.comfy.org)",
204
+ )
205
+
206
+ if comfy.options.args_parsing:
207
+ args = parser.parse_args()
208
+ else:
209
+ args = parser.parse_args([])
210
+
211
+ if args.windows_standalone_build:
212
+ args.auto_launch = True
213
+
214
+ if args.disable_auto_launch:
215
+ args.auto_launch = False
216
+
217
+ if args.force_fp16:
218
+ args.fp16_unet = True
219
+
220
+
221
+ # '--fast' is not provided, use an empty set
222
+ if args.fast is None:
223
+ args.fast = set()
224
+ # '--fast' is provided with an empty list, enable all optimizations
225
+ elif args.fast == []:
226
+ args.fast = set(PerformanceFeature)
227
+ # '--fast' is provided with a list of performance features, use that list
228
+ else:
229
+ args.fast = set(args.fast)
comfy/clip_config_bigg.json ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "CLIPTextModel"
4
+ ],
5
+ "attention_dropout": 0.0,
6
+ "bos_token_id": 0,
7
+ "dropout": 0.0,
8
+ "eos_token_id": 49407,
9
+ "hidden_act": "gelu",
10
+ "hidden_size": 1280,
11
+ "initializer_factor": 1.0,
12
+ "initializer_range": 0.02,
13
+ "intermediate_size": 5120,
14
+ "layer_norm_eps": 1e-05,
15
+ "max_position_embeddings": 77,
16
+ "model_type": "clip_text_model",
17
+ "num_attention_heads": 20,
18
+ "num_hidden_layers": 32,
19
+ "pad_token_id": 1,
20
+ "projection_dim": 1280,
21
+ "torch_dtype": "float32",
22
+ "vocab_size": 49408
23
+ }
comfy/clip_model.py ADDED
@@ -0,0 +1,244 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from comfy.ldm.modules.attention import optimized_attention_for_device
3
+ import comfy.ops
4
+
5
+ class CLIPAttention(torch.nn.Module):
6
+ def __init__(self, embed_dim, heads, dtype, device, operations):
7
+ super().__init__()
8
+
9
+ self.heads = heads
10
+ self.q_proj = operations.Linear(embed_dim, embed_dim, bias=True, dtype=dtype, device=device)
11
+ self.k_proj = operations.Linear(embed_dim, embed_dim, bias=True, dtype=dtype, device=device)
12
+ self.v_proj = operations.Linear(embed_dim, embed_dim, bias=True, dtype=dtype, device=device)
13
+
14
+ self.out_proj = operations.Linear(embed_dim, embed_dim, bias=True, dtype=dtype, device=device)
15
+
16
+ def forward(self, x, mask=None, optimized_attention=None):
17
+ q = self.q_proj(x)
18
+ k = self.k_proj(x)
19
+ v = self.v_proj(x)
20
+
21
+ out = optimized_attention(q, k, v, self.heads, mask)
22
+ return self.out_proj(out)
23
+
24
+ ACTIVATIONS = {"quick_gelu": lambda a: a * torch.sigmoid(1.702 * a),
25
+ "gelu": torch.nn.functional.gelu,
26
+ "gelu_pytorch_tanh": lambda a: torch.nn.functional.gelu(a, approximate="tanh"),
27
+ }
28
+
29
+ class CLIPMLP(torch.nn.Module):
30
+ def __init__(self, embed_dim, intermediate_size, activation, dtype, device, operations):
31
+ super().__init__()
32
+ self.fc1 = operations.Linear(embed_dim, intermediate_size, bias=True, dtype=dtype, device=device)
33
+ self.activation = ACTIVATIONS[activation]
34
+ self.fc2 = operations.Linear(intermediate_size, embed_dim, bias=True, dtype=dtype, device=device)
35
+
36
+ def forward(self, x):
37
+ x = self.fc1(x)
38
+ x = self.activation(x)
39
+ x = self.fc2(x)
40
+ return x
41
+
42
+ class CLIPLayer(torch.nn.Module):
43
+ def __init__(self, embed_dim, heads, intermediate_size, intermediate_activation, dtype, device, operations):
44
+ super().__init__()
45
+ self.layer_norm1 = operations.LayerNorm(embed_dim, dtype=dtype, device=device)
46
+ self.self_attn = CLIPAttention(embed_dim, heads, dtype, device, operations)
47
+ self.layer_norm2 = operations.LayerNorm(embed_dim, dtype=dtype, device=device)
48
+ self.mlp = CLIPMLP(embed_dim, intermediate_size, intermediate_activation, dtype, device, operations)
49
+
50
+ def forward(self, x, mask=None, optimized_attention=None):
51
+ x += self.self_attn(self.layer_norm1(x), mask, optimized_attention)
52
+ x += self.mlp(self.layer_norm2(x))
53
+ return x
54
+
55
+
56
+ class CLIPEncoder(torch.nn.Module):
57
+ def __init__(self, num_layers, embed_dim, heads, intermediate_size, intermediate_activation, dtype, device, operations):
58
+ super().__init__()
59
+ self.layers = torch.nn.ModuleList([CLIPLayer(embed_dim, heads, intermediate_size, intermediate_activation, dtype, device, operations) for i in range(num_layers)])
60
+
61
+ def forward(self, x, mask=None, intermediate_output=None):
62
+ optimized_attention = optimized_attention_for_device(x.device, mask=mask is not None, small_input=True)
63
+
64
+ if intermediate_output is not None:
65
+ if intermediate_output < 0:
66
+ intermediate_output = len(self.layers) + intermediate_output
67
+
68
+ intermediate = None
69
+ for i, l in enumerate(self.layers):
70
+ x = l(x, mask, optimized_attention)
71
+ if i == intermediate_output:
72
+ intermediate = x.clone()
73
+ return x, intermediate
74
+
75
+ class CLIPEmbeddings(torch.nn.Module):
76
+ def __init__(self, embed_dim, vocab_size=49408, num_positions=77, dtype=None, device=None, operations=None):
77
+ super().__init__()
78
+ self.token_embedding = operations.Embedding(vocab_size, embed_dim, dtype=dtype, device=device)
79
+ self.position_embedding = operations.Embedding(num_positions, embed_dim, dtype=dtype, device=device)
80
+
81
+ def forward(self, input_tokens, dtype=torch.float32):
82
+ return self.token_embedding(input_tokens, out_dtype=dtype) + comfy.ops.cast_to(self.position_embedding.weight, dtype=dtype, device=input_tokens.device)
83
+
84
+
85
+ class CLIPTextModel_(torch.nn.Module):
86
+ def __init__(self, config_dict, dtype, device, operations):
87
+ num_layers = config_dict["num_hidden_layers"]
88
+ embed_dim = config_dict["hidden_size"]
89
+ heads = config_dict["num_attention_heads"]
90
+ intermediate_size = config_dict["intermediate_size"]
91
+ intermediate_activation = config_dict["hidden_act"]
92
+ num_positions = config_dict["max_position_embeddings"]
93
+ self.eos_token_id = config_dict["eos_token_id"]
94
+
95
+ super().__init__()
96
+ self.embeddings = CLIPEmbeddings(embed_dim, num_positions=num_positions, dtype=dtype, device=device, operations=operations)
97
+ self.encoder = CLIPEncoder(num_layers, embed_dim, heads, intermediate_size, intermediate_activation, dtype, device, operations)
98
+ self.final_layer_norm = operations.LayerNorm(embed_dim, dtype=dtype, device=device)
99
+
100
+ def forward(self, input_tokens=None, attention_mask=None, embeds=None, num_tokens=None, intermediate_output=None, final_layer_norm_intermediate=True, dtype=torch.float32):
101
+ if embeds is not None:
102
+ x = embeds + comfy.ops.cast_to(self.embeddings.position_embedding.weight, dtype=dtype, device=embeds.device)
103
+ else:
104
+ x = self.embeddings(input_tokens, dtype=dtype)
105
+
106
+ mask = None
107
+ if attention_mask is not None:
108
+ mask = 1.0 - attention_mask.to(x.dtype).reshape((attention_mask.shape[0], 1, -1, attention_mask.shape[-1])).expand(attention_mask.shape[0], 1, attention_mask.shape[-1], attention_mask.shape[-1])
109
+ mask = mask.masked_fill(mask.to(torch.bool), -torch.finfo(x.dtype).max)
110
+
111
+ causal_mask = torch.full((x.shape[1], x.shape[1]), -torch.finfo(x.dtype).max, dtype=x.dtype, device=x.device).triu_(1)
112
+
113
+ if mask is not None:
114
+ mask += causal_mask
115
+ else:
116
+ mask = causal_mask
117
+
118
+ x, i = self.encoder(x, mask=mask, intermediate_output=intermediate_output)
119
+ x = self.final_layer_norm(x)
120
+ if i is not None and final_layer_norm_intermediate:
121
+ i = self.final_layer_norm(i)
122
+
123
+ if num_tokens is not None:
124
+ pooled_output = x[list(range(x.shape[0])), list(map(lambda a: a - 1, num_tokens))]
125
+ else:
126
+ pooled_output = x[torch.arange(x.shape[0], device=x.device), (torch.round(input_tokens).to(dtype=torch.int, device=x.device) == self.eos_token_id).int().argmax(dim=-1),]
127
+ return x, i, pooled_output
128
+
129
+ class CLIPTextModel(torch.nn.Module):
130
+ def __init__(self, config_dict, dtype, device, operations):
131
+ super().__init__()
132
+ self.num_layers = config_dict["num_hidden_layers"]
133
+ self.text_model = CLIPTextModel_(config_dict, dtype, device, operations)
134
+ embed_dim = config_dict["hidden_size"]
135
+ self.text_projection = operations.Linear(embed_dim, embed_dim, bias=False, dtype=dtype, device=device)
136
+ self.dtype = dtype
137
+
138
+ def get_input_embeddings(self):
139
+ return self.text_model.embeddings.token_embedding
140
+
141
+ def set_input_embeddings(self, embeddings):
142
+ self.text_model.embeddings.token_embedding = embeddings
143
+
144
+ def forward(self, *args, **kwargs):
145
+ x = self.text_model(*args, **kwargs)
146
+ out = self.text_projection(x[2])
147
+ return (x[0], x[1], out, x[2])
148
+
149
+
150
+ class CLIPVisionEmbeddings(torch.nn.Module):
151
+ def __init__(self, embed_dim, num_channels=3, patch_size=14, image_size=224, model_type="", dtype=None, device=None, operations=None):
152
+ super().__init__()
153
+
154
+ num_patches = (image_size // patch_size) ** 2
155
+ if model_type == "siglip_vision_model":
156
+ self.class_embedding = None
157
+ patch_bias = True
158
+ else:
159
+ num_patches = num_patches + 1
160
+ self.class_embedding = torch.nn.Parameter(torch.empty(embed_dim, dtype=dtype, device=device))
161
+ patch_bias = False
162
+
163
+ self.patch_embedding = operations.Conv2d(
164
+ in_channels=num_channels,
165
+ out_channels=embed_dim,
166
+ kernel_size=patch_size,
167
+ stride=patch_size,
168
+ bias=patch_bias,
169
+ dtype=dtype,
170
+ device=device
171
+ )
172
+
173
+ self.position_embedding = operations.Embedding(num_patches, embed_dim, dtype=dtype, device=device)
174
+
175
+ def forward(self, pixel_values):
176
+ embeds = self.patch_embedding(pixel_values).flatten(2).transpose(1, 2)
177
+ if self.class_embedding is not None:
178
+ embeds = torch.cat([comfy.ops.cast_to_input(self.class_embedding, embeds).expand(pixel_values.shape[0], 1, -1), embeds], dim=1)
179
+ return embeds + comfy.ops.cast_to_input(self.position_embedding.weight, embeds)
180
+
181
+
182
+ class CLIPVision(torch.nn.Module):
183
+ def __init__(self, config_dict, dtype, device, operations):
184
+ super().__init__()
185
+ num_layers = config_dict["num_hidden_layers"]
186
+ embed_dim = config_dict["hidden_size"]
187
+ heads = config_dict["num_attention_heads"]
188
+ intermediate_size = config_dict["intermediate_size"]
189
+ intermediate_activation = config_dict["hidden_act"]
190
+ model_type = config_dict["model_type"]
191
+
192
+ self.embeddings = CLIPVisionEmbeddings(embed_dim, config_dict["num_channels"], config_dict["patch_size"], config_dict["image_size"], model_type=model_type, dtype=dtype, device=device, operations=operations)
193
+ if model_type == "siglip_vision_model":
194
+ self.pre_layrnorm = lambda a: a
195
+ self.output_layernorm = True
196
+ else:
197
+ self.pre_layrnorm = operations.LayerNorm(embed_dim)
198
+ self.output_layernorm = False
199
+ self.encoder = CLIPEncoder(num_layers, embed_dim, heads, intermediate_size, intermediate_activation, dtype, device, operations)
200
+ self.post_layernorm = operations.LayerNorm(embed_dim)
201
+
202
+ def forward(self, pixel_values, attention_mask=None, intermediate_output=None):
203
+ x = self.embeddings(pixel_values)
204
+ x = self.pre_layrnorm(x)
205
+ #TODO: attention_mask?
206
+ x, i = self.encoder(x, mask=None, intermediate_output=intermediate_output)
207
+ if self.output_layernorm:
208
+ x = self.post_layernorm(x)
209
+ pooled_output = x
210
+ else:
211
+ pooled_output = self.post_layernorm(x[:, 0, :])
212
+ return x, i, pooled_output
213
+
214
+ class LlavaProjector(torch.nn.Module):
215
+ def __init__(self, in_dim, out_dim, dtype, device, operations):
216
+ super().__init__()
217
+ self.linear_1 = operations.Linear(in_dim, out_dim, bias=True, device=device, dtype=dtype)
218
+ self.linear_2 = operations.Linear(out_dim, out_dim, bias=True, device=device, dtype=dtype)
219
+
220
+ def forward(self, x):
221
+ return self.linear_2(torch.nn.functional.gelu(self.linear_1(x[:, 1:])))
222
+
223
+ class CLIPVisionModelProjection(torch.nn.Module):
224
+ def __init__(self, config_dict, dtype, device, operations):
225
+ super().__init__()
226
+ self.vision_model = CLIPVision(config_dict, dtype, device, operations)
227
+ if "projection_dim" in config_dict:
228
+ self.visual_projection = operations.Linear(config_dict["hidden_size"], config_dict["projection_dim"], bias=False)
229
+ else:
230
+ self.visual_projection = lambda a: a
231
+
232
+ if "llava3" == config_dict.get("projector_type", None):
233
+ self.multi_modal_projector = LlavaProjector(config_dict["hidden_size"], 4096, dtype, device, operations)
234
+ else:
235
+ self.multi_modal_projector = None
236
+
237
+ def forward(self, *args, **kwargs):
238
+ x = self.vision_model(*args, **kwargs)
239
+ out = self.visual_projection(x[2])
240
+ projected = None
241
+ if self.multi_modal_projector is not None:
242
+ projected = self.multi_modal_projector(x[1])
243
+
244
+ return (x[0], x[1], out, projected)
comfy/clip_vision.py ADDED
@@ -0,0 +1,148 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from .utils import load_torch_file, transformers_convert, state_dict_prefix_replace
2
+ import os
3
+ import torch
4
+ import json
5
+ import logging
6
+
7
+ import comfy.ops
8
+ import comfy.model_patcher
9
+ import comfy.model_management
10
+ import comfy.utils
11
+ import comfy.clip_model
12
+ import comfy.image_encoders.dino2
13
+
14
+ class Output:
15
+ def __getitem__(self, key):
16
+ return getattr(self, key)
17
+ def __setitem__(self, key, item):
18
+ setattr(self, key, item)
19
+
20
+ def clip_preprocess(image, size=224, mean=[0.48145466, 0.4578275, 0.40821073], std=[0.26862954, 0.26130258, 0.27577711], crop=True):
21
+ image = image[:, :, :, :3] if image.shape[3] > 3 else image
22
+ mean = torch.tensor(mean, device=image.device, dtype=image.dtype)
23
+ std = torch.tensor(std, device=image.device, dtype=image.dtype)
24
+ image = image.movedim(-1, 1)
25
+ if not (image.shape[2] == size and image.shape[3] == size):
26
+ if crop:
27
+ scale = (size / min(image.shape[2], image.shape[3]))
28
+ scale_size = (round(scale * image.shape[2]), round(scale * image.shape[3]))
29
+ else:
30
+ scale_size = (size, size)
31
+
32
+ image = torch.nn.functional.interpolate(image, size=scale_size, mode="bicubic", antialias=True)
33
+ h = (image.shape[2] - size)//2
34
+ w = (image.shape[3] - size)//2
35
+ image = image[:,:,h:h+size,w:w+size]
36
+ image = torch.clip((255. * image), 0, 255).round() / 255.0
37
+ return (image - mean.view([3,1,1])) / std.view([3,1,1])
38
+
39
+ IMAGE_ENCODERS = {
40
+ "clip_vision_model": comfy.clip_model.CLIPVisionModelProjection,
41
+ "siglip_vision_model": comfy.clip_model.CLIPVisionModelProjection,
42
+ "dinov2": comfy.image_encoders.dino2.Dinov2Model,
43
+ }
44
+
45
+ class ClipVisionModel():
46
+ def __init__(self, json_config):
47
+ with open(json_config) as f:
48
+ config = json.load(f)
49
+
50
+ self.image_size = config.get("image_size", 224)
51
+ self.image_mean = config.get("image_mean", [0.48145466, 0.4578275, 0.40821073])
52
+ self.image_std = config.get("image_std", [0.26862954, 0.26130258, 0.27577711])
53
+ model_class = IMAGE_ENCODERS.get(config.get("model_type", "clip_vision_model"))
54
+ self.load_device = comfy.model_management.text_encoder_device()
55
+ offload_device = comfy.model_management.text_encoder_offload_device()
56
+ self.dtype = comfy.model_management.text_encoder_dtype(self.load_device)
57
+ self.model = model_class(config, self.dtype, offload_device, comfy.ops.manual_cast)
58
+ self.model.eval()
59
+
60
+ self.patcher = comfy.model_patcher.ModelPatcher(self.model, load_device=self.load_device, offload_device=offload_device)
61
+
62
+ def load_sd(self, sd):
63
+ return self.model.load_state_dict(sd, strict=False)
64
+
65
+ def get_sd(self):
66
+ return self.model.state_dict()
67
+
68
+ def encode_image(self, image, crop=True):
69
+ comfy.model_management.load_model_gpu(self.patcher)
70
+ pixel_values = clip_preprocess(image.to(self.load_device), size=self.image_size, mean=self.image_mean, std=self.image_std, crop=crop).float()
71
+ out = self.model(pixel_values=pixel_values, intermediate_output=-2)
72
+
73
+ outputs = Output()
74
+ outputs["last_hidden_state"] = out[0].to(comfy.model_management.intermediate_device())
75
+ outputs["image_embeds"] = out[2].to(comfy.model_management.intermediate_device())
76
+ outputs["penultimate_hidden_states"] = out[1].to(comfy.model_management.intermediate_device())
77
+ outputs["mm_projected"] = out[3]
78
+ return outputs
79
+
80
+ def convert_to_transformers(sd, prefix):
81
+ sd_k = sd.keys()
82
+ if "{}transformer.resblocks.0.attn.in_proj_weight".format(prefix) in sd_k:
83
+ keys_to_replace = {
84
+ "{}class_embedding".format(prefix): "vision_model.embeddings.class_embedding",
85
+ "{}conv1.weight".format(prefix): "vision_model.embeddings.patch_embedding.weight",
86
+ "{}positional_embedding".format(prefix): "vision_model.embeddings.position_embedding.weight",
87
+ "{}ln_post.bias".format(prefix): "vision_model.post_layernorm.bias",
88
+ "{}ln_post.weight".format(prefix): "vision_model.post_layernorm.weight",
89
+ "{}ln_pre.bias".format(prefix): "vision_model.pre_layrnorm.bias",
90
+ "{}ln_pre.weight".format(prefix): "vision_model.pre_layrnorm.weight",
91
+ }
92
+
93
+ for x in keys_to_replace:
94
+ if x in sd_k:
95
+ sd[keys_to_replace[x]] = sd.pop(x)
96
+
97
+ if "{}proj".format(prefix) in sd_k:
98
+ sd['visual_projection.weight'] = sd.pop("{}proj".format(prefix)).transpose(0, 1)
99
+
100
+ sd = transformers_convert(sd, prefix, "vision_model.", 48)
101
+ else:
102
+ replace_prefix = {prefix: ""}
103
+ sd = state_dict_prefix_replace(sd, replace_prefix)
104
+ return sd
105
+
106
+ def load_clipvision_from_sd(sd, prefix="", convert_keys=False):
107
+ if convert_keys:
108
+ sd = convert_to_transformers(sd, prefix)
109
+ if "vision_model.encoder.layers.47.layer_norm1.weight" in sd:
110
+ json_config = os.path.join(os.path.dirname(os.path.realpath(__file__)), "clip_vision_config_g.json")
111
+ elif "vision_model.encoder.layers.30.layer_norm1.weight" in sd:
112
+ json_config = os.path.join(os.path.dirname(os.path.realpath(__file__)), "clip_vision_config_h.json")
113
+ elif "vision_model.encoder.layers.22.layer_norm1.weight" in sd:
114
+ embed_shape = sd["vision_model.embeddings.position_embedding.weight"].shape[0]
115
+ if sd["vision_model.encoder.layers.0.layer_norm1.weight"].shape[0] == 1152:
116
+ if embed_shape == 729:
117
+ json_config = os.path.join(os.path.dirname(os.path.realpath(__file__)), "clip_vision_siglip_384.json")
118
+ elif embed_shape == 1024:
119
+ json_config = os.path.join(os.path.dirname(os.path.realpath(__file__)), "clip_vision_siglip_512.json")
120
+ elif embed_shape == 577:
121
+ if "multi_modal_projector.linear_1.bias" in sd:
122
+ json_config = os.path.join(os.path.dirname(os.path.realpath(__file__)), "clip_vision_config_vitl_336_llava.json")
123
+ else:
124
+ json_config = os.path.join(os.path.dirname(os.path.realpath(__file__)), "clip_vision_config_vitl_336.json")
125
+ else:
126
+ json_config = os.path.join(os.path.dirname(os.path.realpath(__file__)), "clip_vision_config_vitl.json")
127
+ elif "embeddings.patch_embeddings.projection.weight" in sd:
128
+ json_config = os.path.join(os.path.join(os.path.dirname(os.path.realpath(__file__)), "image_encoders"), "dino2_giant.json")
129
+ else:
130
+ return None
131
+
132
+ clip = ClipVisionModel(json_config)
133
+ m, u = clip.load_sd(sd)
134
+ if len(m) > 0:
135
+ logging.warning("missing clip vision: {}".format(m))
136
+ u = set(u)
137
+ keys = list(sd.keys())
138
+ for k in keys:
139
+ if k not in u:
140
+ sd.pop(k)
141
+ return clip
142
+
143
+ def load(ckpt_path):
144
+ sd = load_torch_file(ckpt_path)
145
+ if "visual.transformer.resblocks.0.attn.in_proj_weight" in sd:
146
+ return load_clipvision_from_sd(sd, prefix="visual.", convert_keys=True)
147
+ else:
148
+ return load_clipvision_from_sd(sd)
comfy/clip_vision_config_g.json ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "attention_dropout": 0.0,
3
+ "dropout": 0.0,
4
+ "hidden_act": "gelu",
5
+ "hidden_size": 1664,
6
+ "image_size": 224,
7
+ "initializer_factor": 1.0,
8
+ "initializer_range": 0.02,
9
+ "intermediate_size": 8192,
10
+ "layer_norm_eps": 1e-05,
11
+ "model_type": "clip_vision_model",
12
+ "num_attention_heads": 16,
13
+ "num_channels": 3,
14
+ "num_hidden_layers": 48,
15
+ "patch_size": 14,
16
+ "projection_dim": 1280,
17
+ "torch_dtype": "float32"
18
+ }
comfy/clip_vision_config_h.json ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "attention_dropout": 0.0,
3
+ "dropout": 0.0,
4
+ "hidden_act": "gelu",
5
+ "hidden_size": 1280,
6
+ "image_size": 224,
7
+ "initializer_factor": 1.0,
8
+ "initializer_range": 0.02,
9
+ "intermediate_size": 5120,
10
+ "layer_norm_eps": 1e-05,
11
+ "model_type": "clip_vision_model",
12
+ "num_attention_heads": 16,
13
+ "num_channels": 3,
14
+ "num_hidden_layers": 32,
15
+ "patch_size": 14,
16
+ "projection_dim": 1024,
17
+ "torch_dtype": "float32"
18
+ }
comfy/clip_vision_config_vitl.json ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "attention_dropout": 0.0,
3
+ "dropout": 0.0,
4
+ "hidden_act": "quick_gelu",
5
+ "hidden_size": 1024,
6
+ "image_size": 224,
7
+ "initializer_factor": 1.0,
8
+ "initializer_range": 0.02,
9
+ "intermediate_size": 4096,
10
+ "layer_norm_eps": 1e-05,
11
+ "model_type": "clip_vision_model",
12
+ "num_attention_heads": 16,
13
+ "num_channels": 3,
14
+ "num_hidden_layers": 24,
15
+ "patch_size": 14,
16
+ "projection_dim": 768,
17
+ "torch_dtype": "float32"
18
+ }
comfy/clip_vision_config_vitl_336.json ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "attention_dropout": 0.0,
3
+ "dropout": 0.0,
4
+ "hidden_act": "quick_gelu",
5
+ "hidden_size": 1024,
6
+ "image_size": 336,
7
+ "initializer_factor": 1.0,
8
+ "initializer_range": 0.02,
9
+ "intermediate_size": 4096,
10
+ "layer_norm_eps": 1e-5,
11
+ "model_type": "clip_vision_model",
12
+ "num_attention_heads": 16,
13
+ "num_channels": 3,
14
+ "num_hidden_layers": 24,
15
+ "patch_size": 14,
16
+ "projection_dim": 768,
17
+ "torch_dtype": "float32"
18
+ }
comfy/clip_vision_config_vitl_336_llava.json ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "attention_dropout": 0.0,
3
+ "dropout": 0.0,
4
+ "hidden_act": "quick_gelu",
5
+ "hidden_size": 1024,
6
+ "image_size": 336,
7
+ "initializer_factor": 1.0,
8
+ "initializer_range": 0.02,
9
+ "intermediate_size": 4096,
10
+ "layer_norm_eps": 1e-5,
11
+ "model_type": "clip_vision_model",
12
+ "num_attention_heads": 16,
13
+ "num_channels": 3,
14
+ "num_hidden_layers": 24,
15
+ "patch_size": 14,
16
+ "projection_dim": 768,
17
+ "projector_type": "llava3",
18
+ "torch_dtype": "float32"
19
+ }
comfy/clip_vision_siglip_384.json ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "num_channels": 3,
3
+ "hidden_act": "gelu_pytorch_tanh",
4
+ "hidden_size": 1152,
5
+ "image_size": 384,
6
+ "intermediate_size": 4304,
7
+ "model_type": "siglip_vision_model",
8
+ "num_attention_heads": 16,
9
+ "num_hidden_layers": 27,
10
+ "patch_size": 14,
11
+ "image_mean": [0.5, 0.5, 0.5],
12
+ "image_std": [0.5, 0.5, 0.5]
13
+ }
comfy/clip_vision_siglip_512.json ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "num_channels": 3,
3
+ "hidden_act": "gelu_pytorch_tanh",
4
+ "hidden_size": 1152,
5
+ "image_size": 512,
6
+ "intermediate_size": 4304,
7
+ "model_type": "siglip_vision_model",
8
+ "num_attention_heads": 16,
9
+ "num_hidden_layers": 27,
10
+ "patch_size": 16,
11
+ "image_mean": [0.5, 0.5, 0.5],
12
+ "image_std": [0.5, 0.5, 0.5]
13
+ }
comfy/comfy_types/README.md ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Comfy Typing
2
+ ## Type hinting for ComfyUI Node development
3
+
4
+ This module provides type hinting and concrete convenience types for node developers.
5
+ If cloned to the custom_nodes directory of ComfyUI, types can be imported using:
6
+
7
+ ```python
8
+ from comfy.comfy_types import IO, ComfyNodeABC, CheckLazyMixin
9
+
10
+ class ExampleNode(ComfyNodeABC):
11
+ @classmethod
12
+ def INPUT_TYPES(s) -> InputTypeDict:
13
+ return {"required": {}}
14
+ ```
15
+
16
+ Full example is in [examples/example_nodes.py](examples/example_nodes.py).
17
+
18
+ # Types
19
+ A few primary types are documented below. More complete information is available via the docstrings on each type.
20
+
21
+ ## `IO`
22
+
23
+ A string enum of built-in and a few custom data types. Includes the following special types and their requisite plumbing:
24
+
25
+ - `ANY`: `"*"`
26
+ - `NUMBER`: `"FLOAT,INT"`
27
+ - `PRIMITIVE`: `"STRING,FLOAT,INT,BOOLEAN"`
28
+
29
+ ## `ComfyNodeABC`
30
+
31
+ An abstract base class for nodes, offering type-hinting / autocomplete, and somewhat-alright docstrings.
32
+
33
+ ### Type hinting for `INPUT_TYPES`
34
+
35
+ ![INPUT_TYPES auto-completion in Visual Studio Code](examples/input_types.png)
36
+
37
+ ### `INPUT_TYPES` return dict
38
+
39
+ ![INPUT_TYPES return value type hinting in Visual Studio Code](examples/required_hint.png)
40
+
41
+ ### Options for individual inputs
42
+
43
+ ![INPUT_TYPES return value option auto-completion in Visual Studio Code](examples/input_options.png)
comfy/comfy_types/__init__.py ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from typing import Callable, Protocol, TypedDict, Optional, List
3
+ from .node_typing import IO, InputTypeDict, ComfyNodeABC, CheckLazyMixin, FileLocator
4
+
5
+
6
+ class UnetApplyFunction(Protocol):
7
+ """Function signature protocol on comfy.model_base.BaseModel.apply_model"""
8
+
9
+ def __call__(self, x: torch.Tensor, t: torch.Tensor, **kwargs) -> torch.Tensor:
10
+ pass
11
+
12
+
13
+ class UnetApplyConds(TypedDict):
14
+ """Optional conditions for unet apply function."""
15
+
16
+ c_concat: Optional[torch.Tensor]
17
+ c_crossattn: Optional[torch.Tensor]
18
+ control: Optional[torch.Tensor]
19
+ transformer_options: Optional[dict]
20
+
21
+
22
+ class UnetParams(TypedDict):
23
+ # Tensor of shape [B, C, H, W]
24
+ input: torch.Tensor
25
+ # Tensor of shape [B]
26
+ timestep: torch.Tensor
27
+ c: UnetApplyConds
28
+ # List of [0, 1], [0], [1], ...
29
+ # 0 means conditional, 1 means conditional unconditional
30
+ cond_or_uncond: List[int]
31
+
32
+
33
+ UnetWrapperFunction = Callable[[UnetApplyFunction, UnetParams], torch.Tensor]
34
+
35
+
36
+ __all__ = [
37
+ "UnetWrapperFunction",
38
+ UnetApplyConds.__name__,
39
+ UnetParams.__name__,
40
+ UnetApplyFunction.__name__,
41
+ IO.__name__,
42
+ InputTypeDict.__name__,
43
+ ComfyNodeABC.__name__,
44
+ CheckLazyMixin.__name__,
45
+ FileLocator.__name__,
46
+ ]
comfy/comfy_types/examples/example_nodes.py ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from comfy.comfy_types import IO, ComfyNodeABC, InputTypeDict
2
+ from inspect import cleandoc
3
+
4
+
5
+ class ExampleNode(ComfyNodeABC):
6
+ """An example node that just adds 1 to an input integer.
7
+
8
+ * Requires a modern IDE to provide any benefit (detail: an IDE configured with analysis paths etc).
9
+ * This node is intended as an example for developers only.
10
+ """
11
+
12
+ DESCRIPTION = cleandoc(__doc__)
13
+ CATEGORY = "examples"
14
+
15
+ @classmethod
16
+ def INPUT_TYPES(s) -> InputTypeDict:
17
+ return {
18
+ "required": {
19
+ "input_int": (IO.INT, {"defaultInput": True}),
20
+ }
21
+ }
22
+
23
+ RETURN_TYPES = (IO.INT,)
24
+ RETURN_NAMES = ("input_plus_one",)
25
+ FUNCTION = "execute"
26
+
27
+ def execute(self, input_int: int):
28
+ return (input_int + 1,)
comfy/comfy_types/examples/input_options.png ADDED
comfy/comfy_types/examples/input_types.png ADDED
comfy/comfy_types/examples/required_hint.png ADDED
comfy/comfy_types/node_typing.py ADDED
@@ -0,0 +1,348 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Comfy-specific type hinting"""
2
+
3
+ from __future__ import annotations
4
+ from typing import Literal, TypedDict, Optional
5
+ from typing_extensions import NotRequired
6
+ from abc import ABC, abstractmethod
7
+ from enum import Enum
8
+
9
+
10
+ class StrEnum(str, Enum):
11
+ """Base class for string enums. Python's StrEnum is not available until 3.11."""
12
+
13
+ def __str__(self) -> str:
14
+ return self.value
15
+
16
+
17
+ class IO(StrEnum):
18
+ """Node input/output data types.
19
+
20
+ Includes functionality for ``"*"`` (`ANY`) and ``"MULTI,TYPES"``.
21
+ """
22
+
23
+ STRING = "STRING"
24
+ IMAGE = "IMAGE"
25
+ MASK = "MASK"
26
+ LATENT = "LATENT"
27
+ BOOLEAN = "BOOLEAN"
28
+ INT = "INT"
29
+ FLOAT = "FLOAT"
30
+ COMBO = "COMBO"
31
+ CONDITIONING = "CONDITIONING"
32
+ SAMPLER = "SAMPLER"
33
+ SIGMAS = "SIGMAS"
34
+ GUIDER = "GUIDER"
35
+ NOISE = "NOISE"
36
+ CLIP = "CLIP"
37
+ CONTROL_NET = "CONTROL_NET"
38
+ VAE = "VAE"
39
+ MODEL = "MODEL"
40
+ CLIP_VISION = "CLIP_VISION"
41
+ CLIP_VISION_OUTPUT = "CLIP_VISION_OUTPUT"
42
+ STYLE_MODEL = "STYLE_MODEL"
43
+ GLIGEN = "GLIGEN"
44
+ UPSCALE_MODEL = "UPSCALE_MODEL"
45
+ AUDIO = "AUDIO"
46
+ WEBCAM = "WEBCAM"
47
+ POINT = "POINT"
48
+ FACE_ANALYSIS = "FACE_ANALYSIS"
49
+ BBOX = "BBOX"
50
+ SEGS = "SEGS"
51
+ VIDEO = "VIDEO"
52
+
53
+ ANY = "*"
54
+ """Always matches any type, but at a price.
55
+
56
+ Causes some functionality issues (e.g. reroutes, link types), and should be avoided whenever possible.
57
+ """
58
+ NUMBER = "FLOAT,INT"
59
+ """A float or an int - could be either"""
60
+ PRIMITIVE = "STRING,FLOAT,INT,BOOLEAN"
61
+ """Could be any of: string, float, int, or bool"""
62
+
63
+ def __ne__(self, value: object) -> bool:
64
+ if self == "*" or value == "*":
65
+ return False
66
+ if not isinstance(value, str):
67
+ return True
68
+ a = frozenset(self.split(","))
69
+ b = frozenset(value.split(","))
70
+ return not (b.issubset(a) or a.issubset(b))
71
+
72
+
73
+ class RemoteInputOptions(TypedDict):
74
+ route: str
75
+ """The route to the remote source."""
76
+ refresh_button: bool
77
+ """Specifies whether to show a refresh button in the UI below the widget."""
78
+ control_after_refresh: Literal["first", "last"]
79
+ """Specifies the control after the refresh button is clicked. If "first", the first item will be automatically selected, and so on."""
80
+ timeout: int
81
+ """The maximum amount of time to wait for a response from the remote source in milliseconds."""
82
+ max_retries: int
83
+ """The maximum number of retries before aborting the request."""
84
+ refresh: int
85
+ """The TTL of the remote input's value in milliseconds. Specifies the interval at which the remote input's value is refreshed."""
86
+
87
+
88
+ class MultiSelectOptions(TypedDict):
89
+ placeholder: NotRequired[str]
90
+ """The placeholder text to display in the multi-select widget when no items are selected."""
91
+ chip: NotRequired[bool]
92
+ """Specifies whether to use chips instead of comma separated values for the multi-select widget."""
93
+
94
+
95
+ class InputTypeOptions(TypedDict):
96
+ """Provides type hinting for the return type of the INPUT_TYPES node function.
97
+
98
+ Due to IDE limitations with unions, for now all options are available for all types (e.g. `label_on` is hinted even when the type is not `IO.BOOLEAN`).
99
+
100
+ Comfy Docs: https://docs.comfy.org/custom-nodes/backend/datatypes
101
+ """
102
+
103
+ default: NotRequired[bool | str | float | int | list | tuple]
104
+ """The default value of the widget"""
105
+ defaultInput: NotRequired[bool]
106
+ """@deprecated in v1.16 frontend. v1.16 frontend allows input socket and widget to co-exist.
107
+ - defaultInput on required inputs should be dropped.
108
+ - defaultInput on optional inputs should be replaced with forceInput.
109
+ Ref: https://github.com/Comfy-Org/ComfyUI_frontend/pull/3364
110
+ """
111
+ forceInput: NotRequired[bool]
112
+ """Forces the input to be an input slot rather than a widget even a widget is available for the input type."""
113
+ lazy: NotRequired[bool]
114
+ """Declares that this input uses lazy evaluation"""
115
+ rawLink: NotRequired[bool]
116
+ """When a link exists, rather than receiving the evaluated value, you will receive the link (i.e. `["nodeId", <outputIndex>]`). Designed for node expansion."""
117
+ tooltip: NotRequired[str]
118
+ """Tooltip for the input (or widget), shown on pointer hover"""
119
+ socketless: NotRequired[bool]
120
+ """All inputs (including widgets) have an input socket to connect links. When ``true``, if there is a widget for this input, no socket will be created.
121
+ Available from frontend v1.17.5
122
+ Ref: https://github.com/Comfy-Org/ComfyUI_frontend/pull/3548
123
+ """
124
+ widgetType: NotRequired[str]
125
+ """Specifies a type to be used for widget initialization if different from the input type.
126
+ Available from frontend v1.18.0
127
+ https://github.com/Comfy-Org/ComfyUI_frontend/pull/3550"""
128
+ # class InputTypeNumber(InputTypeOptions):
129
+ # default: float | int
130
+ min: NotRequired[float]
131
+ """The minimum value of a number (``FLOAT`` | ``INT``)"""
132
+ max: NotRequired[float]
133
+ """The maximum value of a number (``FLOAT`` | ``INT``)"""
134
+ step: NotRequired[float]
135
+ """The amount to increment or decrement a widget by when stepping up/down (``FLOAT`` | ``INT``)"""
136
+ round: NotRequired[float]
137
+ """Floats are rounded by this value (``FLOAT``)"""
138
+ # class InputTypeBoolean(InputTypeOptions):
139
+ # default: bool
140
+ label_on: NotRequired[str]
141
+ """The label to use in the UI when the bool is True (``BOOLEAN``)"""
142
+ label_off: NotRequired[str]
143
+ """The label to use in the UI when the bool is False (``BOOLEAN``)"""
144
+ # class InputTypeString(InputTypeOptions):
145
+ # default: str
146
+ multiline: NotRequired[bool]
147
+ """Use a multiline text box (``STRING``)"""
148
+ placeholder: NotRequired[str]
149
+ """Placeholder text to display in the UI when empty (``STRING``)"""
150
+ # Deprecated:
151
+ # defaultVal: str
152
+ dynamicPrompts: NotRequired[bool]
153
+ """Causes the front-end to evaluate dynamic prompts (``STRING``)"""
154
+ # class InputTypeCombo(InputTypeOptions):
155
+ image_upload: NotRequired[bool]
156
+ """Specifies whether the input should have an image upload button and image preview attached to it. Requires that the input's name is `image`."""
157
+ image_folder: NotRequired[Literal["input", "output", "temp"]]
158
+ """Specifies which folder to get preview images from if the input has the ``image_upload`` flag.
159
+ """
160
+ remote: NotRequired[RemoteInputOptions]
161
+ """Specifies the configuration for a remote input.
162
+ Available after ComfyUI frontend v1.9.7
163
+ https://github.com/Comfy-Org/ComfyUI_frontend/pull/2422"""
164
+ control_after_generate: NotRequired[bool]
165
+ """Specifies whether a control widget should be added to the input, adding options to automatically change the value after each prompt is queued. Currently only used for INT and COMBO types."""
166
+ options: NotRequired[list[str | int | float]]
167
+ """COMBO type only. Specifies the selectable options for the combo widget.
168
+ Prefer:
169
+ ["COMBO", {"options": ["Option 1", "Option 2", "Option 3"]}]
170
+ Over:
171
+ [["Option 1", "Option 2", "Option 3"]]
172
+ """
173
+ multi_select: NotRequired[MultiSelectOptions]
174
+ """COMBO type only. Specifies the configuration for a multi-select widget.
175
+ Available after ComfyUI frontend v1.13.4
176
+ https://github.com/Comfy-Org/ComfyUI_frontend/pull/2987"""
177
+
178
+
179
+ class HiddenInputTypeDict(TypedDict):
180
+ """Provides type hinting for the hidden entry of node INPUT_TYPES."""
181
+
182
+ node_id: NotRequired[Literal["UNIQUE_ID"]]
183
+ """UNIQUE_ID is the unique identifier of the node, and matches the id property of the node on the client side. It is commonly used in client-server communications (see messages)."""
184
+ unique_id: NotRequired[Literal["UNIQUE_ID"]]
185
+ """UNIQUE_ID is the unique identifier of the node, and matches the id property of the node on the client side. It is commonly used in client-server communications (see messages)."""
186
+ prompt: NotRequired[Literal["PROMPT"]]
187
+ """PROMPT is the complete prompt sent by the client to the server. See the prompt object for a full description."""
188
+ extra_pnginfo: NotRequired[Literal["EXTRA_PNGINFO"]]
189
+ """EXTRA_PNGINFO is a dictionary that will be copied into the metadata of any .png files saved. Custom nodes can store additional information in this dictionary for saving (or as a way to communicate with a downstream node)."""
190
+ dynprompt: NotRequired[Literal["DYNPROMPT"]]
191
+ """DYNPROMPT is an instance of comfy_execution.graph.DynamicPrompt. It differs from PROMPT in that it may mutate during the course of execution in response to Node Expansion."""
192
+
193
+
194
+ class InputTypeDict(TypedDict):
195
+ """Provides type hinting for node INPUT_TYPES.
196
+
197
+ Comfy Docs: https://docs.comfy.org/custom-nodes/backend/more_on_inputs
198
+ """
199
+
200
+ required: NotRequired[dict[str, tuple[IO, InputTypeOptions]]]
201
+ """Describes all inputs that must be connected for the node to execute."""
202
+ optional: NotRequired[dict[str, tuple[IO, InputTypeOptions]]]
203
+ """Describes inputs which do not need to be connected."""
204
+ hidden: NotRequired[HiddenInputTypeDict]
205
+ """Offers advanced functionality and server-client communication.
206
+
207
+ Comfy Docs: https://docs.comfy.org/custom-nodes/backend/more_on_inputs#hidden-inputs
208
+ """
209
+
210
+
211
+ class ComfyNodeABC(ABC):
212
+ """Abstract base class for Comfy nodes. Includes the names and expected types of attributes.
213
+
214
+ Comfy Docs: https://docs.comfy.org/custom-nodes/backend/server_overview
215
+ """
216
+
217
+ DESCRIPTION: str
218
+ """Node description, shown as a tooltip when hovering over the node.
219
+
220
+ Usage::
221
+
222
+ # Explicitly define the description
223
+ DESCRIPTION = "Example description here."
224
+
225
+ # Use the docstring of the node class.
226
+ DESCRIPTION = cleandoc(__doc__)
227
+ """
228
+ CATEGORY: str
229
+ """The category of the node, as per the "Add Node" menu.
230
+
231
+ Comfy Docs: https://docs.comfy.org/custom-nodes/backend/server_overview#category
232
+ """
233
+ EXPERIMENTAL: bool
234
+ """Flags a node as experimental, informing users that it may change or not work as expected."""
235
+ DEPRECATED: bool
236
+ """Flags a node as deprecated, indicating to users that they should find alternatives to this node."""
237
+ API_NODE: Optional[bool]
238
+ """Flags a node as an API node. See: https://docs.comfy.org/tutorials/api-nodes/overview."""
239
+
240
+ @classmethod
241
+ @abstractmethod
242
+ def INPUT_TYPES(s) -> InputTypeDict:
243
+ """Defines node inputs.
244
+
245
+ * Must include the ``required`` key, which describes all inputs that must be connected for the node to execute.
246
+ * The ``optional`` key can be added to describe inputs which do not need to be connected.
247
+ * The ``hidden`` key offers some advanced functionality. More info at: https://docs.comfy.org/custom-nodes/backend/more_on_inputs#hidden-inputs
248
+
249
+ Comfy Docs: https://docs.comfy.org/custom-nodes/backend/server_overview#input-types
250
+ """
251
+ return {"required": {}}
252
+
253
+ OUTPUT_NODE: bool
254
+ """Flags this node as an output node, causing any inputs it requires to be executed.
255
+
256
+ If a node is not connected to any output nodes, that node will not be executed. Usage::
257
+
258
+ OUTPUT_NODE = True
259
+
260
+ From the docs:
261
+
262
+ By default, a node is not considered an output. Set ``OUTPUT_NODE = True`` to specify that it is.
263
+
264
+ Comfy Docs: https://docs.comfy.org/custom-nodes/backend/server_overview#output-node
265
+ """
266
+ INPUT_IS_LIST: bool
267
+ """A flag indicating if this node implements the additional code necessary to deal with OUTPUT_IS_LIST nodes.
268
+
269
+ All inputs of ``type`` will become ``list[type]``, regardless of how many items are passed in. This also affects ``check_lazy_status``.
270
+
271
+ From the docs:
272
+
273
+ A node can also override the default input behaviour and receive the whole list in a single call. This is done by setting a class attribute `INPUT_IS_LIST` to ``True``.
274
+
275
+ Comfy Docs: https://docs.comfy.org/custom-nodes/backend/lists#list-processing
276
+ """
277
+ OUTPUT_IS_LIST: tuple[bool, ...]
278
+ """A tuple indicating which node outputs are lists, but will be connected to nodes that expect individual items.
279
+
280
+ Connected nodes that do not implement `INPUT_IS_LIST` will be executed once for every item in the list.
281
+
282
+ A ``tuple[bool]``, where the items match those in `RETURN_TYPES`::
283
+
284
+ RETURN_TYPES = (IO.INT, IO.INT, IO.STRING)
285
+ OUTPUT_IS_LIST = (True, True, False) # The string output will be handled normally
286
+
287
+ From the docs:
288
+
289
+ In order to tell Comfy that the list being returned should not be wrapped, but treated as a series of data for sequential processing,
290
+ the node should provide a class attribute `OUTPUT_IS_LIST`, which is a ``tuple[bool]``, of the same length as `RETURN_TYPES`,
291
+ specifying which outputs which should be so treated.
292
+
293
+ Comfy Docs: https://docs.comfy.org/custom-nodes/backend/lists#list-processing
294
+ """
295
+
296
+ RETURN_TYPES: tuple[IO, ...]
297
+ """A tuple representing the outputs of this node.
298
+
299
+ Usage::
300
+
301
+ RETURN_TYPES = (IO.INT, "INT", "CUSTOM_TYPE")
302
+
303
+ Comfy Docs: https://docs.comfy.org/custom-nodes/backend/server_overview#return-types
304
+ """
305
+ RETURN_NAMES: tuple[str, ...]
306
+ """The output slot names for each item in `RETURN_TYPES`, e.g. ``RETURN_NAMES = ("count", "filter_string")``
307
+
308
+ Comfy Docs: https://docs.comfy.org/custom-nodes/backend/server_overview#return-names
309
+ """
310
+ OUTPUT_TOOLTIPS: tuple[str, ...]
311
+ """A tuple of strings to use as tooltips for node outputs, one for each item in `RETURN_TYPES`."""
312
+ FUNCTION: str
313
+ """The name of the function to execute as a literal string, e.g. `FUNCTION = "execute"`
314
+
315
+ Comfy Docs: https://docs.comfy.org/custom-nodes/backend/server_overview#function
316
+ """
317
+
318
+
319
+ class CheckLazyMixin:
320
+ """Provides a basic check_lazy_status implementation and type hinting for nodes that use lazy inputs."""
321
+
322
+ def check_lazy_status(self, **kwargs) -> list[str]:
323
+ """Returns a list of input names that should be evaluated.
324
+
325
+ This basic mixin impl. requires all inputs.
326
+
327
+ :kwargs: All node inputs will be included here. If the input is ``None``, it should be assumed that it has not yet been evaluated. \
328
+ When using ``INPUT_IS_LIST = True``, unevaluated will instead be ``(None,)``.
329
+
330
+ Params should match the nodes execution ``FUNCTION`` (self, and all inputs by name).
331
+ Will be executed repeatedly until it returns an empty list, or all requested items were already evaluated (and sent as params).
332
+
333
+ Comfy Docs: https://docs.comfy.org/custom-nodes/backend/lazy_evaluation#defining-check-lazy-status
334
+ """
335
+
336
+ need = [name for name in kwargs if kwargs[name] is None]
337
+ return need
338
+
339
+
340
+ class FileLocator(TypedDict):
341
+ """Provides type hinting for the file location"""
342
+
343
+ filename: str
344
+ """The filename of the file."""
345
+ subfolder: str
346
+ """The subfolder of the file."""
347
+ type: Literal["input", "output", "temp"]
348
+ """The root folder of the file."""
comfy/conds.py ADDED
@@ -0,0 +1,130 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import math
3
+ import comfy.utils
4
+
5
+
6
+ class CONDRegular:
7
+ def __init__(self, cond):
8
+ self.cond = cond
9
+
10
+ def _copy_with(self, cond):
11
+ return self.__class__(cond)
12
+
13
+ def process_cond(self, batch_size, device, **kwargs):
14
+ return self._copy_with(comfy.utils.repeat_to_batch_size(self.cond, batch_size).to(device))
15
+
16
+ def can_concat(self, other):
17
+ if self.cond.shape != other.cond.shape:
18
+ return False
19
+ return True
20
+
21
+ def concat(self, others):
22
+ conds = [self.cond]
23
+ for x in others:
24
+ conds.append(x.cond)
25
+ return torch.cat(conds)
26
+
27
+ def size(self):
28
+ return list(self.cond.size())
29
+
30
+
31
+ class CONDNoiseShape(CONDRegular):
32
+ def process_cond(self, batch_size, device, area, **kwargs):
33
+ data = self.cond
34
+ if area is not None:
35
+ dims = len(area) // 2
36
+ for i in range(dims):
37
+ data = data.narrow(i + 2, area[i + dims], area[i])
38
+
39
+ return self._copy_with(comfy.utils.repeat_to_batch_size(data, batch_size).to(device))
40
+
41
+
42
+ class CONDCrossAttn(CONDRegular):
43
+ def can_concat(self, other):
44
+ s1 = self.cond.shape
45
+ s2 = other.cond.shape
46
+ if s1 != s2:
47
+ if s1[0] != s2[0] or s1[2] != s2[2]: #these 2 cases should not happen
48
+ return False
49
+
50
+ mult_min = math.lcm(s1[1], s2[1])
51
+ diff = mult_min // min(s1[1], s2[1])
52
+ if diff > 4: #arbitrary limit on the padding because it's probably going to impact performance negatively if it's too much
53
+ return False
54
+ return True
55
+
56
+ def concat(self, others):
57
+ conds = [self.cond]
58
+ crossattn_max_len = self.cond.shape[1]
59
+ for x in others:
60
+ c = x.cond
61
+ crossattn_max_len = math.lcm(crossattn_max_len, c.shape[1])
62
+ conds.append(c)
63
+
64
+ out = []
65
+ for c in conds:
66
+ if c.shape[1] < crossattn_max_len:
67
+ c = c.repeat(1, crossattn_max_len // c.shape[1], 1) #padding with repeat doesn't change result
68
+ out.append(c)
69
+ return torch.cat(out)
70
+
71
+
72
+ class CONDConstant(CONDRegular):
73
+ def __init__(self, cond):
74
+ self.cond = cond
75
+
76
+ def process_cond(self, batch_size, device, **kwargs):
77
+ return self._copy_with(self.cond)
78
+
79
+ def can_concat(self, other):
80
+ if self.cond != other.cond:
81
+ return False
82
+ return True
83
+
84
+ def concat(self, others):
85
+ return self.cond
86
+
87
+ def size(self):
88
+ return [1]
89
+
90
+
91
+ class CONDList(CONDRegular):
92
+ def __init__(self, cond):
93
+ self.cond = cond
94
+
95
+ def process_cond(self, batch_size, device, **kwargs):
96
+ out = []
97
+ for c in self.cond:
98
+ out.append(comfy.utils.repeat_to_batch_size(c, batch_size).to(device))
99
+
100
+ return self._copy_with(out)
101
+
102
+ def can_concat(self, other):
103
+ if len(self.cond) != len(other.cond):
104
+ return False
105
+ for i in range(len(self.cond)):
106
+ if self.cond[i].shape != other.cond[i].shape:
107
+ return False
108
+
109
+ return True
110
+
111
+ def concat(self, others):
112
+ out = []
113
+ for i in range(len(self.cond)):
114
+ o = [self.cond[i]]
115
+ for x in others:
116
+ o.append(x.cond[i])
117
+ out.append(torch.cat(o))
118
+
119
+ return out
120
+
121
+ def size(self): # hackish implementation to make the mem estimation work
122
+ o = 0
123
+ c = 1
124
+ for c in self.cond:
125
+ size = c.size()
126
+ o += math.prod(size)
127
+ if len(size) > 1:
128
+ c = size[1]
129
+
130
+ return [1, c, o // c]
comfy/controlnet.py ADDED
@@ -0,0 +1,857 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ This file is part of ComfyUI.
3
+ Copyright (C) 2024 Comfy
4
+
5
+ This program is free software: you can redistribute it and/or modify
6
+ it under the terms of the GNU General Public License as published by
7
+ the Free Software Foundation, either version 3 of the License, or
8
+ (at your option) any later version.
9
+
10
+ This program is distributed in the hope that it will be useful,
11
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
12
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13
+ GNU General Public License for more details.
14
+
15
+ You should have received a copy of the GNU General Public License
16
+ along with this program. If not, see <https://www.gnu.org/licenses/>.
17
+ """
18
+
19
+
20
+ import torch
21
+ from enum import Enum
22
+ import math
23
+ import os
24
+ import logging
25
+ import comfy.utils
26
+ import comfy.model_management
27
+ import comfy.model_detection
28
+ import comfy.model_patcher
29
+ import comfy.ops
30
+ import comfy.latent_formats
31
+
32
+ import comfy.cldm.cldm
33
+ import comfy.t2i_adapter.adapter
34
+ import comfy.ldm.cascade.controlnet
35
+ import comfy.cldm.mmdit
36
+ import comfy.ldm.hydit.controlnet
37
+ import comfy.ldm.flux.controlnet
38
+ import comfy.cldm.dit_embedder
39
+ from typing import TYPE_CHECKING
40
+ if TYPE_CHECKING:
41
+ from comfy.hooks import HookGroup
42
+
43
+
44
+ def broadcast_image_to(tensor, target_batch_size, batched_number):
45
+ current_batch_size = tensor.shape[0]
46
+ #print(current_batch_size, target_batch_size)
47
+ if current_batch_size == 1:
48
+ return tensor
49
+
50
+ per_batch = target_batch_size // batched_number
51
+ tensor = tensor[:per_batch]
52
+
53
+ if per_batch > tensor.shape[0]:
54
+ tensor = torch.cat([tensor] * (per_batch // tensor.shape[0]) + [tensor[:(per_batch % tensor.shape[0])]], dim=0)
55
+
56
+ current_batch_size = tensor.shape[0]
57
+ if current_batch_size == target_batch_size:
58
+ return tensor
59
+ else:
60
+ return torch.cat([tensor] * batched_number, dim=0)
61
+
62
+ class StrengthType(Enum):
63
+ CONSTANT = 1
64
+ LINEAR_UP = 2
65
+
66
+ class ControlBase:
67
+ def __init__(self):
68
+ self.cond_hint_original = None
69
+ self.cond_hint = None
70
+ self.strength = 1.0
71
+ self.timestep_percent_range = (0.0, 1.0)
72
+ self.latent_format = None
73
+ self.vae = None
74
+ self.global_average_pooling = False
75
+ self.timestep_range = None
76
+ self.compression_ratio = 8
77
+ self.upscale_algorithm = 'nearest-exact'
78
+ self.extra_args = {}
79
+ self.previous_controlnet = None
80
+ self.extra_conds = []
81
+ self.strength_type = StrengthType.CONSTANT
82
+ self.concat_mask = False
83
+ self.extra_concat_orig = []
84
+ self.extra_concat = None
85
+ self.extra_hooks: HookGroup = None
86
+ self.preprocess_image = lambda a: a
87
+
88
+ def set_cond_hint(self, cond_hint, strength=1.0, timestep_percent_range=(0.0, 1.0), vae=None, extra_concat=[]):
89
+ self.cond_hint_original = cond_hint
90
+ self.strength = strength
91
+ self.timestep_percent_range = timestep_percent_range
92
+ if self.latent_format is not None:
93
+ if vae is None:
94
+ logging.warning("WARNING: no VAE provided to the controlnet apply node when this controlnet requires one.")
95
+ self.vae = vae
96
+ self.extra_concat_orig = extra_concat.copy()
97
+ if self.concat_mask and len(self.extra_concat_orig) == 0:
98
+ self.extra_concat_orig.append(torch.tensor([[[[1.0]]]]))
99
+ return self
100
+
101
+ def pre_run(self, model, percent_to_timestep_function):
102
+ self.timestep_range = (percent_to_timestep_function(self.timestep_percent_range[0]), percent_to_timestep_function(self.timestep_percent_range[1]))
103
+ if self.previous_controlnet is not None:
104
+ self.previous_controlnet.pre_run(model, percent_to_timestep_function)
105
+
106
+ def set_previous_controlnet(self, controlnet):
107
+ self.previous_controlnet = controlnet
108
+ return self
109
+
110
+ def cleanup(self):
111
+ if self.previous_controlnet is not None:
112
+ self.previous_controlnet.cleanup()
113
+
114
+ self.cond_hint = None
115
+ self.extra_concat = None
116
+ self.timestep_range = None
117
+
118
+ def get_models(self):
119
+ out = []
120
+ if self.previous_controlnet is not None:
121
+ out += self.previous_controlnet.get_models()
122
+ return out
123
+
124
+ def get_extra_hooks(self):
125
+ out = []
126
+ if self.extra_hooks is not None:
127
+ out.append(self.extra_hooks)
128
+ if self.previous_controlnet is not None:
129
+ out += self.previous_controlnet.get_extra_hooks()
130
+ return out
131
+
132
+ def copy_to(self, c):
133
+ c.cond_hint_original = self.cond_hint_original
134
+ c.strength = self.strength
135
+ c.timestep_percent_range = self.timestep_percent_range
136
+ c.global_average_pooling = self.global_average_pooling
137
+ c.compression_ratio = self.compression_ratio
138
+ c.upscale_algorithm = self.upscale_algorithm
139
+ c.latent_format = self.latent_format
140
+ c.extra_args = self.extra_args.copy()
141
+ c.vae = self.vae
142
+ c.extra_conds = self.extra_conds.copy()
143
+ c.strength_type = self.strength_type
144
+ c.concat_mask = self.concat_mask
145
+ c.extra_concat_orig = self.extra_concat_orig.copy()
146
+ c.extra_hooks = self.extra_hooks.clone() if self.extra_hooks else None
147
+ c.preprocess_image = self.preprocess_image
148
+
149
+ def inference_memory_requirements(self, dtype):
150
+ if self.previous_controlnet is not None:
151
+ return self.previous_controlnet.inference_memory_requirements(dtype)
152
+ return 0
153
+
154
+ def control_merge(self, control, control_prev, output_dtype):
155
+ out = {'input':[], 'middle':[], 'output': []}
156
+
157
+ for key in control:
158
+ control_output = control[key]
159
+ applied_to = set()
160
+ for i in range(len(control_output)):
161
+ x = control_output[i]
162
+ if x is not None:
163
+ if self.global_average_pooling:
164
+ x = torch.mean(x, dim=(2, 3), keepdim=True).repeat(1, 1, x.shape[2], x.shape[3])
165
+
166
+ if x not in applied_to: #memory saving strategy, allow shared tensors and only apply strength to shared tensors once
167
+ applied_to.add(x)
168
+ if self.strength_type == StrengthType.CONSTANT:
169
+ x *= self.strength
170
+ elif self.strength_type == StrengthType.LINEAR_UP:
171
+ x *= (self.strength ** float(len(control_output) - i))
172
+
173
+ if output_dtype is not None and x.dtype != output_dtype:
174
+ x = x.to(output_dtype)
175
+
176
+ out[key].append(x)
177
+
178
+ if control_prev is not None:
179
+ for x in ['input', 'middle', 'output']:
180
+ o = out[x]
181
+ for i in range(len(control_prev[x])):
182
+ prev_val = control_prev[x][i]
183
+ if i >= len(o):
184
+ o.append(prev_val)
185
+ elif prev_val is not None:
186
+ if o[i] is None:
187
+ o[i] = prev_val
188
+ else:
189
+ if o[i].shape[0] < prev_val.shape[0]:
190
+ o[i] = prev_val + o[i]
191
+ else:
192
+ o[i] = prev_val + o[i] #TODO: change back to inplace add if shared tensors stop being an issue
193
+ return out
194
+
195
+ def set_extra_arg(self, argument, value=None):
196
+ self.extra_args[argument] = value
197
+
198
+
199
+ class ControlNet(ControlBase):
200
+ def __init__(self, control_model=None, global_average_pooling=False, compression_ratio=8, latent_format=None, load_device=None, manual_cast_dtype=None, extra_conds=["y"], strength_type=StrengthType.CONSTANT, concat_mask=False, preprocess_image=lambda a: a):
201
+ super().__init__()
202
+ self.control_model = control_model
203
+ self.load_device = load_device
204
+ if control_model is not None:
205
+ self.control_model_wrapped = comfy.model_patcher.ModelPatcher(self.control_model, load_device=load_device, offload_device=comfy.model_management.unet_offload_device())
206
+
207
+ self.compression_ratio = compression_ratio
208
+ self.global_average_pooling = global_average_pooling
209
+ self.model_sampling_current = None
210
+ self.manual_cast_dtype = manual_cast_dtype
211
+ self.latent_format = latent_format
212
+ self.extra_conds += extra_conds
213
+ self.strength_type = strength_type
214
+ self.concat_mask = concat_mask
215
+ self.preprocess_image = preprocess_image
216
+
217
+ def get_control(self, x_noisy, t, cond, batched_number, transformer_options):
218
+ control_prev = None
219
+ if self.previous_controlnet is not None:
220
+ control_prev = self.previous_controlnet.get_control(x_noisy, t, cond, batched_number, transformer_options)
221
+
222
+ if self.timestep_range is not None:
223
+ if t[0] > self.timestep_range[0] or t[0] < self.timestep_range[1]:
224
+ if control_prev is not None:
225
+ return control_prev
226
+ else:
227
+ return None
228
+
229
+ dtype = self.control_model.dtype
230
+ if self.manual_cast_dtype is not None:
231
+ dtype = self.manual_cast_dtype
232
+
233
+ if self.cond_hint is None or x_noisy.shape[2] * self.compression_ratio != self.cond_hint.shape[2] or x_noisy.shape[3] * self.compression_ratio != self.cond_hint.shape[3]:
234
+ if self.cond_hint is not None:
235
+ del self.cond_hint
236
+ self.cond_hint = None
237
+ compression_ratio = self.compression_ratio
238
+ if self.vae is not None:
239
+ compression_ratio *= self.vae.downscale_ratio
240
+ else:
241
+ if self.latent_format is not None:
242
+ raise ValueError("This Controlnet needs a VAE but none was provided, please use a ControlNetApply node with a VAE input and connect it.")
243
+ self.cond_hint = comfy.utils.common_upscale(self.cond_hint_original, x_noisy.shape[3] * compression_ratio, x_noisy.shape[2] * compression_ratio, self.upscale_algorithm, "center")
244
+ self.cond_hint = self.preprocess_image(self.cond_hint)
245
+ if self.vae is not None:
246
+ loaded_models = comfy.model_management.loaded_models(only_currently_used=True)
247
+ self.cond_hint = self.vae.encode(self.cond_hint.movedim(1, -1))
248
+ comfy.model_management.load_models_gpu(loaded_models)
249
+ if self.latent_format is not None:
250
+ self.cond_hint = self.latent_format.process_in(self.cond_hint)
251
+ if len(self.extra_concat_orig) > 0:
252
+ to_concat = []
253
+ for c in self.extra_concat_orig:
254
+ c = c.to(self.cond_hint.device)
255
+ c = comfy.utils.common_upscale(c, self.cond_hint.shape[3], self.cond_hint.shape[2], self.upscale_algorithm, "center")
256
+ to_concat.append(comfy.utils.repeat_to_batch_size(c, self.cond_hint.shape[0]))
257
+ self.cond_hint = torch.cat([self.cond_hint] + to_concat, dim=1)
258
+
259
+ self.cond_hint = self.cond_hint.to(device=x_noisy.device, dtype=dtype)
260
+ if x_noisy.shape[0] != self.cond_hint.shape[0]:
261
+ self.cond_hint = broadcast_image_to(self.cond_hint, x_noisy.shape[0], batched_number)
262
+
263
+ context = cond.get('crossattn_controlnet', cond['c_crossattn'])
264
+ extra = self.extra_args.copy()
265
+ for c in self.extra_conds:
266
+ temp = cond.get(c, None)
267
+ if temp is not None:
268
+ extra[c] = temp.to(dtype)
269
+
270
+ timestep = self.model_sampling_current.timestep(t)
271
+ x_noisy = self.model_sampling_current.calculate_input(t, x_noisy)
272
+
273
+ control = self.control_model(x=x_noisy.to(dtype), hint=self.cond_hint, timesteps=timestep.to(dtype), context=context.to(dtype), **extra)
274
+ return self.control_merge(control, control_prev, output_dtype=None)
275
+
276
+ def copy(self):
277
+ c = ControlNet(None, global_average_pooling=self.global_average_pooling, load_device=self.load_device, manual_cast_dtype=self.manual_cast_dtype)
278
+ c.control_model = self.control_model
279
+ c.control_model_wrapped = self.control_model_wrapped
280
+ self.copy_to(c)
281
+ return c
282
+
283
+ def get_models(self):
284
+ out = super().get_models()
285
+ out.append(self.control_model_wrapped)
286
+ return out
287
+
288
+ def pre_run(self, model, percent_to_timestep_function):
289
+ super().pre_run(model, percent_to_timestep_function)
290
+ self.model_sampling_current = model.model_sampling
291
+
292
+ def cleanup(self):
293
+ self.model_sampling_current = None
294
+ super().cleanup()
295
+
296
+ class ControlLoraOps:
297
+ class Linear(torch.nn.Module, comfy.ops.CastWeightBiasOp):
298
+ def __init__(self, in_features: int, out_features: int, bias: bool = True,
299
+ device=None, dtype=None) -> None:
300
+ super().__init__()
301
+ self.in_features = in_features
302
+ self.out_features = out_features
303
+ self.weight = None
304
+ self.up = None
305
+ self.down = None
306
+ self.bias = None
307
+
308
+ def forward(self, input):
309
+ weight, bias = comfy.ops.cast_bias_weight(self, input)
310
+ if self.up is not None:
311
+ return torch.nn.functional.linear(input, weight + (torch.mm(self.up.flatten(start_dim=1), self.down.flatten(start_dim=1))).reshape(self.weight.shape).type(input.dtype), bias)
312
+ else:
313
+ return torch.nn.functional.linear(input, weight, bias)
314
+
315
+ class Conv2d(torch.nn.Module, comfy.ops.CastWeightBiasOp):
316
+ def __init__(
317
+ self,
318
+ in_channels,
319
+ out_channels,
320
+ kernel_size,
321
+ stride=1,
322
+ padding=0,
323
+ dilation=1,
324
+ groups=1,
325
+ bias=True,
326
+ padding_mode='zeros',
327
+ device=None,
328
+ dtype=None
329
+ ):
330
+ super().__init__()
331
+ self.in_channels = in_channels
332
+ self.out_channels = out_channels
333
+ self.kernel_size = kernel_size
334
+ self.stride = stride
335
+ self.padding = padding
336
+ self.dilation = dilation
337
+ self.transposed = False
338
+ self.output_padding = 0
339
+ self.groups = groups
340
+ self.padding_mode = padding_mode
341
+
342
+ self.weight = None
343
+ self.bias = None
344
+ self.up = None
345
+ self.down = None
346
+
347
+
348
+ def forward(self, input):
349
+ weight, bias = comfy.ops.cast_bias_weight(self, input)
350
+ if self.up is not None:
351
+ return torch.nn.functional.conv2d(input, weight + (torch.mm(self.up.flatten(start_dim=1), self.down.flatten(start_dim=1))).reshape(self.weight.shape).type(input.dtype), bias, self.stride, self.padding, self.dilation, self.groups)
352
+ else:
353
+ return torch.nn.functional.conv2d(input, weight, bias, self.stride, self.padding, self.dilation, self.groups)
354
+
355
+
356
+ class ControlLora(ControlNet):
357
+ def __init__(self, control_weights, global_average_pooling=False, model_options={}): #TODO? model_options
358
+ ControlBase.__init__(self)
359
+ self.control_weights = control_weights
360
+ self.global_average_pooling = global_average_pooling
361
+ self.extra_conds += ["y"]
362
+
363
+ def pre_run(self, model, percent_to_timestep_function):
364
+ super().pre_run(model, percent_to_timestep_function)
365
+ controlnet_config = model.model_config.unet_config.copy()
366
+ controlnet_config.pop("out_channels")
367
+ controlnet_config["hint_channels"] = self.control_weights["input_hint_block.0.weight"].shape[1]
368
+ self.manual_cast_dtype = model.manual_cast_dtype
369
+ dtype = model.get_dtype()
370
+ if self.manual_cast_dtype is None:
371
+ class control_lora_ops(ControlLoraOps, comfy.ops.disable_weight_init):
372
+ pass
373
+ else:
374
+ class control_lora_ops(ControlLoraOps, comfy.ops.manual_cast):
375
+ pass
376
+ dtype = self.manual_cast_dtype
377
+
378
+ controlnet_config["operations"] = control_lora_ops
379
+ controlnet_config["dtype"] = dtype
380
+ self.control_model = comfy.cldm.cldm.ControlNet(**controlnet_config)
381
+ self.control_model.to(comfy.model_management.get_torch_device())
382
+ diffusion_model = model.diffusion_model
383
+ sd = diffusion_model.state_dict()
384
+
385
+ for k in sd:
386
+ weight = sd[k]
387
+ try:
388
+ comfy.utils.set_attr_param(self.control_model, k, weight)
389
+ except:
390
+ pass
391
+
392
+ for k in self.control_weights:
393
+ if k not in {"lora_controlnet"}:
394
+ comfy.utils.set_attr_param(self.control_model, k, self.control_weights[k].to(dtype).to(comfy.model_management.get_torch_device()))
395
+
396
+ def copy(self):
397
+ c = ControlLora(self.control_weights, global_average_pooling=self.global_average_pooling)
398
+ self.copy_to(c)
399
+ return c
400
+
401
+ def cleanup(self):
402
+ del self.control_model
403
+ self.control_model = None
404
+ super().cleanup()
405
+
406
+ def get_models(self):
407
+ out = ControlBase.get_models(self)
408
+ return out
409
+
410
+ def inference_memory_requirements(self, dtype):
411
+ return comfy.utils.calculate_parameters(self.control_weights) * comfy.model_management.dtype_size(dtype) + ControlBase.inference_memory_requirements(self, dtype)
412
+
413
+ def controlnet_config(sd, model_options={}):
414
+ model_config = comfy.model_detection.model_config_from_unet(sd, "", True)
415
+
416
+ unet_dtype = model_options.get("dtype", None)
417
+ if unet_dtype is None:
418
+ weight_dtype = comfy.utils.weight_dtype(sd)
419
+
420
+ supported_inference_dtypes = list(model_config.supported_inference_dtypes)
421
+ unet_dtype = comfy.model_management.unet_dtype(model_params=-1, supported_dtypes=supported_inference_dtypes, weight_dtype=weight_dtype)
422
+
423
+ load_device = comfy.model_management.get_torch_device()
424
+ manual_cast_dtype = comfy.model_management.unet_manual_cast(unet_dtype, load_device)
425
+
426
+ operations = model_options.get("custom_operations", None)
427
+ if operations is None:
428
+ operations = comfy.ops.pick_operations(unet_dtype, manual_cast_dtype, disable_fast_fp8=True)
429
+
430
+ offload_device = comfy.model_management.unet_offload_device()
431
+ return model_config, operations, load_device, unet_dtype, manual_cast_dtype, offload_device
432
+
433
+ def controlnet_load_state_dict(control_model, sd):
434
+ missing, unexpected = control_model.load_state_dict(sd, strict=False)
435
+
436
+ if len(missing) > 0:
437
+ logging.warning("missing controlnet keys: {}".format(missing))
438
+
439
+ if len(unexpected) > 0:
440
+ logging.debug("unexpected controlnet keys: {}".format(unexpected))
441
+ return control_model
442
+
443
+
444
+ def load_controlnet_mmdit(sd, model_options={}):
445
+ new_sd = comfy.model_detection.convert_diffusers_mmdit(sd, "")
446
+ model_config, operations, load_device, unet_dtype, manual_cast_dtype, offload_device = controlnet_config(new_sd, model_options=model_options)
447
+ num_blocks = comfy.model_detection.count_blocks(new_sd, 'joint_blocks.{}.')
448
+ for k in sd:
449
+ new_sd[k] = sd[k]
450
+
451
+ concat_mask = False
452
+ control_latent_channels = new_sd.get("pos_embed_input.proj.weight").shape[1]
453
+ if control_latent_channels == 17: #inpaint controlnet
454
+ concat_mask = True
455
+
456
+ control_model = comfy.cldm.mmdit.ControlNet(num_blocks=num_blocks, control_latent_channels=control_latent_channels, operations=operations, device=offload_device, dtype=unet_dtype, **model_config.unet_config)
457
+ control_model = controlnet_load_state_dict(control_model, new_sd)
458
+
459
+ latent_format = comfy.latent_formats.SD3()
460
+ latent_format.shift_factor = 0 #SD3 controlnet weirdness
461
+ control = ControlNet(control_model, compression_ratio=1, latent_format=latent_format, concat_mask=concat_mask, load_device=load_device, manual_cast_dtype=manual_cast_dtype)
462
+ return control
463
+
464
+
465
+ class ControlNetSD35(ControlNet):
466
+ def pre_run(self, model, percent_to_timestep_function):
467
+ if self.control_model.double_y_emb:
468
+ missing, unexpected = self.control_model.orig_y_embedder.load_state_dict(model.diffusion_model.y_embedder.state_dict(), strict=False)
469
+ else:
470
+ missing, unexpected = self.control_model.x_embedder.load_state_dict(model.diffusion_model.x_embedder.state_dict(), strict=False)
471
+ super().pre_run(model, percent_to_timestep_function)
472
+
473
+ def copy(self):
474
+ c = ControlNetSD35(None, global_average_pooling=self.global_average_pooling, load_device=self.load_device, manual_cast_dtype=self.manual_cast_dtype)
475
+ c.control_model = self.control_model
476
+ c.control_model_wrapped = self.control_model_wrapped
477
+ self.copy_to(c)
478
+ return c
479
+
480
+ def load_controlnet_sd35(sd, model_options={}):
481
+ control_type = -1
482
+ if "control_type" in sd:
483
+ control_type = round(sd.pop("control_type").item())
484
+
485
+ # blur_cnet = control_type == 0
486
+ canny_cnet = control_type == 1
487
+ depth_cnet = control_type == 2
488
+
489
+ new_sd = {}
490
+ for k in comfy.utils.MMDIT_MAP_BASIC:
491
+ if k[1] in sd:
492
+ new_sd[k[0]] = sd.pop(k[1])
493
+ for k in sd:
494
+ new_sd[k] = sd[k]
495
+ sd = new_sd
496
+
497
+ y_emb_shape = sd["y_embedder.mlp.0.weight"].shape
498
+ depth = y_emb_shape[0] // 64
499
+ hidden_size = 64 * depth
500
+ num_heads = depth
501
+ head_dim = hidden_size // num_heads
502
+ num_blocks = comfy.model_detection.count_blocks(new_sd, 'transformer_blocks.{}.')
503
+
504
+ load_device = comfy.model_management.get_torch_device()
505
+ offload_device = comfy.model_management.unet_offload_device()
506
+ unet_dtype = comfy.model_management.unet_dtype(model_params=-1)
507
+
508
+ manual_cast_dtype = comfy.model_management.unet_manual_cast(unet_dtype, load_device)
509
+
510
+ operations = model_options.get("custom_operations", None)
511
+ if operations is None:
512
+ operations = comfy.ops.pick_operations(unet_dtype, manual_cast_dtype, disable_fast_fp8=True)
513
+
514
+ control_model = comfy.cldm.dit_embedder.ControlNetEmbedder(img_size=None,
515
+ patch_size=2,
516
+ in_chans=16,
517
+ num_layers=num_blocks,
518
+ main_model_double=depth,
519
+ double_y_emb=y_emb_shape[0] == y_emb_shape[1],
520
+ attention_head_dim=head_dim,
521
+ num_attention_heads=num_heads,
522
+ adm_in_channels=2048,
523
+ device=offload_device,
524
+ dtype=unet_dtype,
525
+ operations=operations)
526
+
527
+ control_model = controlnet_load_state_dict(control_model, sd)
528
+
529
+ latent_format = comfy.latent_formats.SD3()
530
+ preprocess_image = lambda a: a
531
+ if canny_cnet:
532
+ preprocess_image = lambda a: (a * 255 * 0.5 + 0.5)
533
+ elif depth_cnet:
534
+ preprocess_image = lambda a: 1.0 - a
535
+
536
+ control = ControlNetSD35(control_model, compression_ratio=1, latent_format=latent_format, load_device=load_device, manual_cast_dtype=manual_cast_dtype, preprocess_image=preprocess_image)
537
+ return control
538
+
539
+
540
+
541
+ def load_controlnet_hunyuandit(controlnet_data, model_options={}):
542
+ model_config, operations, load_device, unet_dtype, manual_cast_dtype, offload_device = controlnet_config(controlnet_data, model_options=model_options)
543
+
544
+ control_model = comfy.ldm.hydit.controlnet.HunYuanControlNet(operations=operations, device=offload_device, dtype=unet_dtype)
545
+ control_model = controlnet_load_state_dict(control_model, controlnet_data)
546
+
547
+ latent_format = comfy.latent_formats.SDXL()
548
+ extra_conds = ['text_embedding_mask', 'encoder_hidden_states_t5', 'text_embedding_mask_t5', 'image_meta_size', 'style', 'cos_cis_img', 'sin_cis_img']
549
+ control = ControlNet(control_model, compression_ratio=1, latent_format=latent_format, load_device=load_device, manual_cast_dtype=manual_cast_dtype, extra_conds=extra_conds, strength_type=StrengthType.CONSTANT)
550
+ return control
551
+
552
+ def load_controlnet_flux_xlabs_mistoline(sd, mistoline=False, model_options={}):
553
+ model_config, operations, load_device, unet_dtype, manual_cast_dtype, offload_device = controlnet_config(sd, model_options=model_options)
554
+ control_model = comfy.ldm.flux.controlnet.ControlNetFlux(mistoline=mistoline, operations=operations, device=offload_device, dtype=unet_dtype, **model_config.unet_config)
555
+ control_model = controlnet_load_state_dict(control_model, sd)
556
+ extra_conds = ['y', 'guidance']
557
+ control = ControlNet(control_model, load_device=load_device, manual_cast_dtype=manual_cast_dtype, extra_conds=extra_conds)
558
+ return control
559
+
560
+ def load_controlnet_flux_instantx(sd, model_options={}):
561
+ new_sd = comfy.model_detection.convert_diffusers_mmdit(sd, "")
562
+ model_config, operations, load_device, unet_dtype, manual_cast_dtype, offload_device = controlnet_config(new_sd, model_options=model_options)
563
+ for k in sd:
564
+ new_sd[k] = sd[k]
565
+
566
+ num_union_modes = 0
567
+ union_cnet = "controlnet_mode_embedder.weight"
568
+ if union_cnet in new_sd:
569
+ num_union_modes = new_sd[union_cnet].shape[0]
570
+
571
+ control_latent_channels = new_sd.get("pos_embed_input.weight").shape[1] // 4
572
+ concat_mask = False
573
+ if control_latent_channels == 17:
574
+ concat_mask = True
575
+
576
+ control_model = comfy.ldm.flux.controlnet.ControlNetFlux(latent_input=True, num_union_modes=num_union_modes, control_latent_channels=control_latent_channels, operations=operations, device=offload_device, dtype=unet_dtype, **model_config.unet_config)
577
+ control_model = controlnet_load_state_dict(control_model, new_sd)
578
+
579
+ latent_format = comfy.latent_formats.Flux()
580
+ extra_conds = ['y', 'guidance']
581
+ control = ControlNet(control_model, compression_ratio=1, latent_format=latent_format, concat_mask=concat_mask, load_device=load_device, manual_cast_dtype=manual_cast_dtype, extra_conds=extra_conds)
582
+ return control
583
+
584
+ def convert_mistoline(sd):
585
+ return comfy.utils.state_dict_prefix_replace(sd, {"single_controlnet_blocks.": "controlnet_single_blocks."})
586
+
587
+
588
+ def load_controlnet_state_dict(state_dict, model=None, model_options={}):
589
+ controlnet_data = state_dict
590
+ if 'after_proj_list.18.bias' in controlnet_data.keys(): #Hunyuan DiT
591
+ return load_controlnet_hunyuandit(controlnet_data, model_options=model_options)
592
+
593
+ if "lora_controlnet" in controlnet_data:
594
+ return ControlLora(controlnet_data, model_options=model_options)
595
+
596
+ controlnet_config = None
597
+ supported_inference_dtypes = None
598
+
599
+ if "controlnet_cond_embedding.conv_in.weight" in controlnet_data: #diffusers format
600
+ controlnet_config = comfy.model_detection.unet_config_from_diffusers_unet(controlnet_data)
601
+ diffusers_keys = comfy.utils.unet_to_diffusers(controlnet_config)
602
+ diffusers_keys["controlnet_mid_block.weight"] = "middle_block_out.0.weight"
603
+ diffusers_keys["controlnet_mid_block.bias"] = "middle_block_out.0.bias"
604
+
605
+ count = 0
606
+ loop = True
607
+ while loop:
608
+ suffix = [".weight", ".bias"]
609
+ for s in suffix:
610
+ k_in = "controlnet_down_blocks.{}{}".format(count, s)
611
+ k_out = "zero_convs.{}.0{}".format(count, s)
612
+ if k_in not in controlnet_data:
613
+ loop = False
614
+ break
615
+ diffusers_keys[k_in] = k_out
616
+ count += 1
617
+
618
+ count = 0
619
+ loop = True
620
+ while loop:
621
+ suffix = [".weight", ".bias"]
622
+ for s in suffix:
623
+ if count == 0:
624
+ k_in = "controlnet_cond_embedding.conv_in{}".format(s)
625
+ else:
626
+ k_in = "controlnet_cond_embedding.blocks.{}{}".format(count - 1, s)
627
+ k_out = "input_hint_block.{}{}".format(count * 2, s)
628
+ if k_in not in controlnet_data:
629
+ k_in = "controlnet_cond_embedding.conv_out{}".format(s)
630
+ loop = False
631
+ diffusers_keys[k_in] = k_out
632
+ count += 1
633
+
634
+ new_sd = {}
635
+ for k in diffusers_keys:
636
+ if k in controlnet_data:
637
+ new_sd[diffusers_keys[k]] = controlnet_data.pop(k)
638
+
639
+ if "control_add_embedding.linear_1.bias" in controlnet_data: #Union Controlnet
640
+ controlnet_config["union_controlnet_num_control_type"] = controlnet_data["task_embedding"].shape[0]
641
+ for k in list(controlnet_data.keys()):
642
+ new_k = k.replace('.attn.in_proj_', '.attn.in_proj.')
643
+ new_sd[new_k] = controlnet_data.pop(k)
644
+
645
+ leftover_keys = controlnet_data.keys()
646
+ if len(leftover_keys) > 0:
647
+ logging.warning("leftover keys: {}".format(leftover_keys))
648
+ controlnet_data = new_sd
649
+ elif "controlnet_blocks.0.weight" in controlnet_data:
650
+ if "double_blocks.0.img_attn.norm.key_norm.scale" in controlnet_data:
651
+ return load_controlnet_flux_xlabs_mistoline(controlnet_data, model_options=model_options)
652
+ elif "pos_embed_input.proj.weight" in controlnet_data:
653
+ if "transformer_blocks.0.adaLN_modulation.1.bias" in controlnet_data:
654
+ return load_controlnet_sd35(controlnet_data, model_options=model_options) #Stability sd3.5 format
655
+ else:
656
+ return load_controlnet_mmdit(controlnet_data, model_options=model_options) #SD3 diffusers controlnet
657
+ elif "controlnet_x_embedder.weight" in controlnet_data:
658
+ return load_controlnet_flux_instantx(controlnet_data, model_options=model_options)
659
+ elif "controlnet_blocks.0.linear.weight" in controlnet_data: #mistoline flux
660
+ return load_controlnet_flux_xlabs_mistoline(convert_mistoline(controlnet_data), mistoline=True, model_options=model_options)
661
+
662
+ pth_key = 'control_model.zero_convs.0.0.weight'
663
+ pth = False
664
+ key = 'zero_convs.0.0.weight'
665
+ if pth_key in controlnet_data:
666
+ pth = True
667
+ key = pth_key
668
+ prefix = "control_model."
669
+ elif key in controlnet_data:
670
+ prefix = ""
671
+ else:
672
+ net = load_t2i_adapter(controlnet_data, model_options=model_options)
673
+ if net is None:
674
+ logging.error("error could not detect control model type.")
675
+ return net
676
+
677
+ if controlnet_config is None:
678
+ model_config = comfy.model_detection.model_config_from_unet(controlnet_data, prefix, True)
679
+ supported_inference_dtypes = list(model_config.supported_inference_dtypes)
680
+ controlnet_config = model_config.unet_config
681
+
682
+ unet_dtype = model_options.get("dtype", None)
683
+ if unet_dtype is None:
684
+ weight_dtype = comfy.utils.weight_dtype(controlnet_data)
685
+
686
+ if supported_inference_dtypes is None:
687
+ supported_inference_dtypes = [comfy.model_management.unet_dtype()]
688
+
689
+ unet_dtype = comfy.model_management.unet_dtype(model_params=-1, supported_dtypes=supported_inference_dtypes, weight_dtype=weight_dtype)
690
+
691
+ load_device = comfy.model_management.get_torch_device()
692
+
693
+ manual_cast_dtype = comfy.model_management.unet_manual_cast(unet_dtype, load_device)
694
+ operations = model_options.get("custom_operations", None)
695
+ if operations is None:
696
+ operations = comfy.ops.pick_operations(unet_dtype, manual_cast_dtype)
697
+
698
+ controlnet_config["operations"] = operations
699
+ controlnet_config["dtype"] = unet_dtype
700
+ controlnet_config["device"] = comfy.model_management.unet_offload_device()
701
+ controlnet_config.pop("out_channels")
702
+ controlnet_config["hint_channels"] = controlnet_data["{}input_hint_block.0.weight".format(prefix)].shape[1]
703
+ control_model = comfy.cldm.cldm.ControlNet(**controlnet_config)
704
+
705
+ if pth:
706
+ if 'difference' in controlnet_data:
707
+ if model is not None:
708
+ comfy.model_management.load_models_gpu([model])
709
+ model_sd = model.model_state_dict()
710
+ for x in controlnet_data:
711
+ c_m = "control_model."
712
+ if x.startswith(c_m):
713
+ sd_key = "diffusion_model.{}".format(x[len(c_m):])
714
+ if sd_key in model_sd:
715
+ cd = controlnet_data[x]
716
+ cd += model_sd[sd_key].type(cd.dtype).to(cd.device)
717
+ else:
718
+ logging.warning("WARNING: Loaded a diff controlnet without a model. It will very likely not work.")
719
+
720
+ class WeightsLoader(torch.nn.Module):
721
+ pass
722
+ w = WeightsLoader()
723
+ w.control_model = control_model
724
+ missing, unexpected = w.load_state_dict(controlnet_data, strict=False)
725
+ else:
726
+ missing, unexpected = control_model.load_state_dict(controlnet_data, strict=False)
727
+
728
+ if len(missing) > 0:
729
+ logging.warning("missing controlnet keys: {}".format(missing))
730
+
731
+ if len(unexpected) > 0:
732
+ logging.debug("unexpected controlnet keys: {}".format(unexpected))
733
+
734
+ global_average_pooling = model_options.get("global_average_pooling", False)
735
+ control = ControlNet(control_model, global_average_pooling=global_average_pooling, load_device=load_device, manual_cast_dtype=manual_cast_dtype)
736
+ return control
737
+
738
+ def load_controlnet(ckpt_path, model=None, model_options={}):
739
+ model_options = model_options.copy()
740
+ if "global_average_pooling" not in model_options:
741
+ filename = os.path.splitext(ckpt_path)[0]
742
+ if filename.endswith("_shuffle") or filename.endswith("_shuffle_fp16"): #TODO: smarter way of enabling global_average_pooling
743
+ model_options["global_average_pooling"] = True
744
+
745
+ cnet = load_controlnet_state_dict(comfy.utils.load_torch_file(ckpt_path, safe_load=True), model=model, model_options=model_options)
746
+ if cnet is None:
747
+ logging.error("error checkpoint does not contain controlnet or t2i adapter data {}".format(ckpt_path))
748
+ return cnet
749
+
750
+ class T2IAdapter(ControlBase):
751
+ def __init__(self, t2i_model, channels_in, compression_ratio, upscale_algorithm, device=None):
752
+ super().__init__()
753
+ self.t2i_model = t2i_model
754
+ self.channels_in = channels_in
755
+ self.control_input = None
756
+ self.compression_ratio = compression_ratio
757
+ self.upscale_algorithm = upscale_algorithm
758
+ if device is None:
759
+ device = comfy.model_management.get_torch_device()
760
+ self.device = device
761
+
762
+ def scale_image_to(self, width, height):
763
+ unshuffle_amount = self.t2i_model.unshuffle_amount
764
+ width = math.ceil(width / unshuffle_amount) * unshuffle_amount
765
+ height = math.ceil(height / unshuffle_amount) * unshuffle_amount
766
+ return width, height
767
+
768
+ def get_control(self, x_noisy, t, cond, batched_number, transformer_options):
769
+ control_prev = None
770
+ if self.previous_controlnet is not None:
771
+ control_prev = self.previous_controlnet.get_control(x_noisy, t, cond, batched_number, transformer_options)
772
+
773
+ if self.timestep_range is not None:
774
+ if t[0] > self.timestep_range[0] or t[0] < self.timestep_range[1]:
775
+ if control_prev is not None:
776
+ return control_prev
777
+ else:
778
+ return None
779
+
780
+ if self.cond_hint is None or x_noisy.shape[2] * self.compression_ratio != self.cond_hint.shape[2] or x_noisy.shape[3] * self.compression_ratio != self.cond_hint.shape[3]:
781
+ if self.cond_hint is not None:
782
+ del self.cond_hint
783
+ self.control_input = None
784
+ self.cond_hint = None
785
+ width, height = self.scale_image_to(x_noisy.shape[3] * self.compression_ratio, x_noisy.shape[2] * self.compression_ratio)
786
+ self.cond_hint = comfy.utils.common_upscale(self.cond_hint_original, width, height, self.upscale_algorithm, "center").float().to(self.device)
787
+ if self.channels_in == 1 and self.cond_hint.shape[1] > 1:
788
+ self.cond_hint = torch.mean(self.cond_hint, 1, keepdim=True)
789
+ if x_noisy.shape[0] != self.cond_hint.shape[0]:
790
+ self.cond_hint = broadcast_image_to(self.cond_hint, x_noisy.shape[0], batched_number)
791
+ if self.control_input is None:
792
+ self.t2i_model.to(x_noisy.dtype)
793
+ self.t2i_model.to(self.device)
794
+ self.control_input = self.t2i_model(self.cond_hint.to(x_noisy.dtype))
795
+ self.t2i_model.cpu()
796
+
797
+ control_input = {}
798
+ for k in self.control_input:
799
+ control_input[k] = list(map(lambda a: None if a is None else a.clone(), self.control_input[k]))
800
+
801
+ return self.control_merge(control_input, control_prev, x_noisy.dtype)
802
+
803
+ def copy(self):
804
+ c = T2IAdapter(self.t2i_model, self.channels_in, self.compression_ratio, self.upscale_algorithm)
805
+ self.copy_to(c)
806
+ return c
807
+
808
+ def load_t2i_adapter(t2i_data, model_options={}): #TODO: model_options
809
+ compression_ratio = 8
810
+ upscale_algorithm = 'nearest-exact'
811
+
812
+ if 'adapter' in t2i_data:
813
+ t2i_data = t2i_data['adapter']
814
+ if 'adapter.body.0.resnets.0.block1.weight' in t2i_data: #diffusers format
815
+ prefix_replace = {}
816
+ for i in range(4):
817
+ for j in range(2):
818
+ prefix_replace["adapter.body.{}.resnets.{}.".format(i, j)] = "body.{}.".format(i * 2 + j)
819
+ prefix_replace["adapter.body.{}.".format(i, )] = "body.{}.".format(i * 2)
820
+ prefix_replace["adapter."] = ""
821
+ t2i_data = comfy.utils.state_dict_prefix_replace(t2i_data, prefix_replace)
822
+ keys = t2i_data.keys()
823
+
824
+ if "body.0.in_conv.weight" in keys:
825
+ cin = t2i_data['body.0.in_conv.weight'].shape[1]
826
+ model_ad = comfy.t2i_adapter.adapter.Adapter_light(cin=cin, channels=[320, 640, 1280, 1280], nums_rb=4)
827
+ elif 'conv_in.weight' in keys:
828
+ cin = t2i_data['conv_in.weight'].shape[1]
829
+ channel = t2i_data['conv_in.weight'].shape[0]
830
+ ksize = t2i_data['body.0.block2.weight'].shape[2]
831
+ use_conv = False
832
+ down_opts = list(filter(lambda a: a.endswith("down_opt.op.weight"), keys))
833
+ if len(down_opts) > 0:
834
+ use_conv = True
835
+ xl = False
836
+ if cin == 256 or cin == 768:
837
+ xl = True
838
+ model_ad = comfy.t2i_adapter.adapter.Adapter(cin=cin, channels=[channel, channel*2, channel*4, channel*4][:4], nums_rb=2, ksize=ksize, sk=True, use_conv=use_conv, xl=xl)
839
+ elif "backbone.0.0.weight" in keys:
840
+ model_ad = comfy.ldm.cascade.controlnet.ControlNet(c_in=t2i_data['backbone.0.0.weight'].shape[1], proj_blocks=[0, 4, 8, 12, 51, 55, 59, 63])
841
+ compression_ratio = 32
842
+ upscale_algorithm = 'bilinear'
843
+ elif "backbone.10.blocks.0.weight" in keys:
844
+ model_ad = comfy.ldm.cascade.controlnet.ControlNet(c_in=t2i_data['backbone.0.weight'].shape[1], bottleneck_mode="large", proj_blocks=[0, 4, 8, 12, 51, 55, 59, 63])
845
+ compression_ratio = 1
846
+ upscale_algorithm = 'nearest-exact'
847
+ else:
848
+ return None
849
+
850
+ missing, unexpected = model_ad.load_state_dict(t2i_data)
851
+ if len(missing) > 0:
852
+ logging.warning("t2i missing {}".format(missing))
853
+
854
+ if len(unexpected) > 0:
855
+ logging.debug("t2i unexpected {}".format(unexpected))
856
+
857
+ return T2IAdapter(model_ad, model_ad.input_channels, compression_ratio, upscale_algorithm)
comfy/diffusers_convert.py ADDED
@@ -0,0 +1,189 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import re
2
+ import torch
3
+ import logging
4
+
5
+ # conversion code from https://github.com/huggingface/diffusers/blob/main/scripts/convert_diffusers_to_original_stable_diffusion.py
6
+
7
+ # ================#
8
+ # VAE Conversion #
9
+ # ================#
10
+
11
+ vae_conversion_map = [
12
+ # (stable-diffusion, HF Diffusers)
13
+ ("nin_shortcut", "conv_shortcut"),
14
+ ("norm_out", "conv_norm_out"),
15
+ ("mid.attn_1.", "mid_block.attentions.0."),
16
+ ]
17
+
18
+ for i in range(4):
19
+ # down_blocks have two resnets
20
+ for j in range(2):
21
+ hf_down_prefix = f"encoder.down_blocks.{i}.resnets.{j}."
22
+ sd_down_prefix = f"encoder.down.{i}.block.{j}."
23
+ vae_conversion_map.append((sd_down_prefix, hf_down_prefix))
24
+
25
+ if i < 3:
26
+ hf_downsample_prefix = f"down_blocks.{i}.downsamplers.0."
27
+ sd_downsample_prefix = f"down.{i}.downsample."
28
+ vae_conversion_map.append((sd_downsample_prefix, hf_downsample_prefix))
29
+
30
+ hf_upsample_prefix = f"up_blocks.{i}.upsamplers.0."
31
+ sd_upsample_prefix = f"up.{3 - i}.upsample."
32
+ vae_conversion_map.append((sd_upsample_prefix, hf_upsample_prefix))
33
+
34
+ # up_blocks have three resnets
35
+ # also, up blocks in hf are numbered in reverse from sd
36
+ for j in range(3):
37
+ hf_up_prefix = f"decoder.up_blocks.{i}.resnets.{j}."
38
+ sd_up_prefix = f"decoder.up.{3 - i}.block.{j}."
39
+ vae_conversion_map.append((sd_up_prefix, hf_up_prefix))
40
+
41
+ # this part accounts for mid blocks in both the encoder and the decoder
42
+ for i in range(2):
43
+ hf_mid_res_prefix = f"mid_block.resnets.{i}."
44
+ sd_mid_res_prefix = f"mid.block_{i + 1}."
45
+ vae_conversion_map.append((sd_mid_res_prefix, hf_mid_res_prefix))
46
+
47
+ vae_conversion_map_attn = [
48
+ # (stable-diffusion, HF Diffusers)
49
+ ("norm.", "group_norm."),
50
+ ("q.", "query."),
51
+ ("k.", "key."),
52
+ ("v.", "value."),
53
+ ("q.", "to_q."),
54
+ ("k.", "to_k."),
55
+ ("v.", "to_v."),
56
+ ("proj_out.", "to_out.0."),
57
+ ("proj_out.", "proj_attn."),
58
+ ]
59
+
60
+
61
+ def reshape_weight_for_sd(w, conv3d=False):
62
+ # convert HF linear weights to SD conv2d weights
63
+ if conv3d:
64
+ return w.reshape(*w.shape, 1, 1, 1)
65
+ else:
66
+ return w.reshape(*w.shape, 1, 1)
67
+
68
+
69
+ def convert_vae_state_dict(vae_state_dict):
70
+ mapping = {k: k for k in vae_state_dict.keys()}
71
+ conv3d = False
72
+ for k, v in mapping.items():
73
+ for sd_part, hf_part in vae_conversion_map:
74
+ v = v.replace(hf_part, sd_part)
75
+ if v.endswith(".conv.weight"):
76
+ if not conv3d and vae_state_dict[k].ndim == 5:
77
+ conv3d = True
78
+ mapping[k] = v
79
+ for k, v in mapping.items():
80
+ if "attentions" in k:
81
+ for sd_part, hf_part in vae_conversion_map_attn:
82
+ v = v.replace(hf_part, sd_part)
83
+ mapping[k] = v
84
+ new_state_dict = {v: vae_state_dict[k] for k, v in mapping.items()}
85
+ weights_to_convert = ["q", "k", "v", "proj_out"]
86
+ for k, v in new_state_dict.items():
87
+ for weight_name in weights_to_convert:
88
+ if f"mid.attn_1.{weight_name}.weight" in k:
89
+ logging.debug(f"Reshaping {k} for SD format")
90
+ new_state_dict[k] = reshape_weight_for_sd(v, conv3d=conv3d)
91
+ return new_state_dict
92
+
93
+
94
+ # =========================#
95
+ # Text Encoder Conversion #
96
+ # =========================#
97
+
98
+
99
+ textenc_conversion_lst = [
100
+ # (stable-diffusion, HF Diffusers)
101
+ ("resblocks.", "text_model.encoder.layers."),
102
+ ("ln_1", "layer_norm1"),
103
+ ("ln_2", "layer_norm2"),
104
+ (".c_fc.", ".fc1."),
105
+ (".c_proj.", ".fc2."),
106
+ (".attn", ".self_attn"),
107
+ ("ln_final.", "transformer.text_model.final_layer_norm."),
108
+ ("token_embedding.weight", "transformer.text_model.embeddings.token_embedding.weight"),
109
+ ("positional_embedding", "transformer.text_model.embeddings.position_embedding.weight"),
110
+ ]
111
+ protected = {re.escape(x[1]): x[0] for x in textenc_conversion_lst}
112
+ textenc_pattern = re.compile("|".join(protected.keys()))
113
+
114
+ # Ordering is from https://github.com/pytorch/pytorch/blob/master/test/cpp/api/modules.cpp
115
+ code2idx = {"q": 0, "k": 1, "v": 2}
116
+
117
+
118
+ # This function exists because at the time of writing torch.cat can't do fp8 with cuda
119
+ def cat_tensors(tensors):
120
+ x = 0
121
+ for t in tensors:
122
+ x += t.shape[0]
123
+
124
+ shape = [x] + list(tensors[0].shape)[1:]
125
+ out = torch.empty(shape, device=tensors[0].device, dtype=tensors[0].dtype)
126
+
127
+ x = 0
128
+ for t in tensors:
129
+ out[x:x + t.shape[0]] = t
130
+ x += t.shape[0]
131
+
132
+ return out
133
+
134
+
135
+ def convert_text_enc_state_dict_v20(text_enc_dict, prefix=""):
136
+ new_state_dict = {}
137
+ capture_qkv_weight = {}
138
+ capture_qkv_bias = {}
139
+ for k, v in text_enc_dict.items():
140
+ if not k.startswith(prefix):
141
+ continue
142
+ if (
143
+ k.endswith(".self_attn.q_proj.weight")
144
+ or k.endswith(".self_attn.k_proj.weight")
145
+ or k.endswith(".self_attn.v_proj.weight")
146
+ ):
147
+ k_pre = k[: -len(".q_proj.weight")]
148
+ k_code = k[-len("q_proj.weight")]
149
+ if k_pre not in capture_qkv_weight:
150
+ capture_qkv_weight[k_pre] = [None, None, None]
151
+ capture_qkv_weight[k_pre][code2idx[k_code]] = v
152
+ continue
153
+
154
+ if (
155
+ k.endswith(".self_attn.q_proj.bias")
156
+ or k.endswith(".self_attn.k_proj.bias")
157
+ or k.endswith(".self_attn.v_proj.bias")
158
+ ):
159
+ k_pre = k[: -len(".q_proj.bias")]
160
+ k_code = k[-len("q_proj.bias")]
161
+ if k_pre not in capture_qkv_bias:
162
+ capture_qkv_bias[k_pre] = [None, None, None]
163
+ capture_qkv_bias[k_pre][code2idx[k_code]] = v
164
+ continue
165
+
166
+ text_proj = "transformer.text_projection.weight"
167
+ if k.endswith(text_proj):
168
+ new_state_dict[k.replace(text_proj, "text_projection")] = v.transpose(0, 1).contiguous()
169
+ else:
170
+ relabelled_key = textenc_pattern.sub(lambda m: protected[re.escape(m.group(0))], k)
171
+ new_state_dict[relabelled_key] = v
172
+
173
+ for k_pre, tensors in capture_qkv_weight.items():
174
+ if None in tensors:
175
+ raise Exception("CORRUPTED MODEL: one of the q-k-v values for the text encoder was missing")
176
+ relabelled_key = textenc_pattern.sub(lambda m: protected[re.escape(m.group(0))], k_pre)
177
+ new_state_dict[relabelled_key + ".in_proj_weight"] = cat_tensors(tensors)
178
+
179
+ for k_pre, tensors in capture_qkv_bias.items():
180
+ if None in tensors:
181
+ raise Exception("CORRUPTED MODEL: one of the q-k-v values for the text encoder was missing")
182
+ relabelled_key = textenc_pattern.sub(lambda m: protected[re.escape(m.group(0))], k_pre)
183
+ new_state_dict[relabelled_key + ".in_proj_bias"] = cat_tensors(tensors)
184
+
185
+ return new_state_dict
186
+
187
+
188
+ def convert_text_enc_state_dict(text_enc_dict):
189
+ return text_enc_dict
comfy/diffusers_load.py ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+
3
+ import comfy.sd
4
+
5
+ def first_file(path, filenames):
6
+ for f in filenames:
7
+ p = os.path.join(path, f)
8
+ if os.path.exists(p):
9
+ return p
10
+ return None
11
+
12
+ def load_diffusers(model_path, output_vae=True, output_clip=True, embedding_directory=None):
13
+ diffusion_model_names = ["diffusion_pytorch_model.fp16.safetensors", "diffusion_pytorch_model.safetensors", "diffusion_pytorch_model.fp16.bin", "diffusion_pytorch_model.bin"]
14
+ unet_path = first_file(os.path.join(model_path, "unet"), diffusion_model_names)
15
+ vae_path = first_file(os.path.join(model_path, "vae"), diffusion_model_names)
16
+
17
+ text_encoder_model_names = ["model.fp16.safetensors", "model.safetensors", "pytorch_model.fp16.bin", "pytorch_model.bin"]
18
+ text_encoder1_path = first_file(os.path.join(model_path, "text_encoder"), text_encoder_model_names)
19
+ text_encoder2_path = first_file(os.path.join(model_path, "text_encoder_2"), text_encoder_model_names)
20
+
21
+ text_encoder_paths = [text_encoder1_path]
22
+ if text_encoder2_path is not None:
23
+ text_encoder_paths.append(text_encoder2_path)
24
+
25
+ unet = comfy.sd.load_diffusion_model(unet_path)
26
+
27
+ clip = None
28
+ if output_clip:
29
+ clip = comfy.sd.load_clip(text_encoder_paths, embedding_directory=embedding_directory)
30
+
31
+ vae = None
32
+ if output_vae:
33
+ sd = comfy.utils.load_torch_file(vae_path)
34
+ vae = comfy.sd.VAE(sd=sd)
35
+
36
+ return (unet, clip, vae)
comfy/extra_samplers/uni_pc.py ADDED
@@ -0,0 +1,873 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #code taken from: https://github.com/wl-zhao/UniPC and modified
2
+
3
+ import torch
4
+ import math
5
+ import logging
6
+
7
+ from tqdm.auto import trange
8
+
9
+
10
+ class NoiseScheduleVP:
11
+ def __init__(
12
+ self,
13
+ schedule='discrete',
14
+ betas=None,
15
+ alphas_cumprod=None,
16
+ continuous_beta_0=0.1,
17
+ continuous_beta_1=20.,
18
+ ):
19
+ r"""Create a wrapper class for the forward SDE (VP type).
20
+
21
+ ***
22
+ Update: We support discrete-time diffusion models by implementing a picewise linear interpolation for log_alpha_t.
23
+ We recommend to use schedule='discrete' for the discrete-time diffusion models, especially for high-resolution images.
24
+ ***
25
+
26
+ The forward SDE ensures that the condition distribution q_{t|0}(x_t | x_0) = N ( alpha_t * x_0, sigma_t^2 * I ).
27
+ We further define lambda_t = log(alpha_t) - log(sigma_t), which is the half-logSNR (described in the DPM-Solver paper).
28
+ Therefore, we implement the functions for computing alpha_t, sigma_t and lambda_t. For t in [0, T], we have:
29
+
30
+ log_alpha_t = self.marginal_log_mean_coeff(t)
31
+ sigma_t = self.marginal_std(t)
32
+ lambda_t = self.marginal_lambda(t)
33
+
34
+ Moreover, as lambda(t) is an invertible function, we also support its inverse function:
35
+
36
+ t = self.inverse_lambda(lambda_t)
37
+
38
+ ===============================================================
39
+
40
+ We support both discrete-time DPMs (trained on n = 0, 1, ..., N-1) and continuous-time DPMs (trained on t in [t_0, T]).
41
+
42
+ 1. For discrete-time DPMs:
43
+
44
+ For discrete-time DPMs trained on n = 0, 1, ..., N-1, we convert the discrete steps to continuous time steps by:
45
+ t_i = (i + 1) / N
46
+ e.g. for N = 1000, we have t_0 = 1e-3 and T = t_{N-1} = 1.
47
+ We solve the corresponding diffusion ODE from time T = 1 to time t_0 = 1e-3.
48
+
49
+ Args:
50
+ betas: A `torch.Tensor`. The beta array for the discrete-time DPM. (See the original DDPM paper for details)
51
+ alphas_cumprod: A `torch.Tensor`. The cumprod alphas for the discrete-time DPM. (See the original DDPM paper for details)
52
+
53
+ Note that we always have alphas_cumprod = cumprod(betas). Therefore, we only need to set one of `betas` and `alphas_cumprod`.
54
+
55
+ **Important**: Please pay special attention for the args for `alphas_cumprod`:
56
+ The `alphas_cumprod` is the \hat{alpha_n} arrays in the notations of DDPM. Specifically, DDPMs assume that
57
+ q_{t_n | 0}(x_{t_n} | x_0) = N ( \sqrt{\hat{alpha_n}} * x_0, (1 - \hat{alpha_n}) * I ).
58
+ Therefore, the notation \hat{alpha_n} is different from the notation alpha_t in DPM-Solver. In fact, we have
59
+ alpha_{t_n} = \sqrt{\hat{alpha_n}},
60
+ and
61
+ log(alpha_{t_n}) = 0.5 * log(\hat{alpha_n}).
62
+
63
+
64
+ 2. For continuous-time DPMs:
65
+
66
+ We support two types of VPSDEs: linear (DDPM) and cosine (improved-DDPM). The hyperparameters for the noise
67
+ schedule are the default settings in DDPM and improved-DDPM:
68
+
69
+ Args:
70
+ beta_min: A `float` number. The smallest beta for the linear schedule.
71
+ beta_max: A `float` number. The largest beta for the linear schedule.
72
+ cosine_s: A `float` number. The hyperparameter in the cosine schedule.
73
+ cosine_beta_max: A `float` number. The hyperparameter in the cosine schedule.
74
+ T: A `float` number. The ending time of the forward process.
75
+
76
+ ===============================================================
77
+
78
+ Args:
79
+ schedule: A `str`. The noise schedule of the forward SDE. 'discrete' for discrete-time DPMs,
80
+ 'linear' or 'cosine' for continuous-time DPMs.
81
+ Returns:
82
+ A wrapper object of the forward SDE (VP type).
83
+
84
+ ===============================================================
85
+
86
+ Example:
87
+
88
+ # For discrete-time DPMs, given betas (the beta array for n = 0, 1, ..., N - 1):
89
+ >>> ns = NoiseScheduleVP('discrete', betas=betas)
90
+
91
+ # For discrete-time DPMs, given alphas_cumprod (the \hat{alpha_n} array for n = 0, 1, ..., N - 1):
92
+ >>> ns = NoiseScheduleVP('discrete', alphas_cumprod=alphas_cumprod)
93
+
94
+ # For continuous-time DPMs (VPSDE), linear schedule:
95
+ >>> ns = NoiseScheduleVP('linear', continuous_beta_0=0.1, continuous_beta_1=20.)
96
+
97
+ """
98
+
99
+ if schedule not in ['discrete', 'linear', 'cosine']:
100
+ raise ValueError("Unsupported noise schedule {}. The schedule needs to be 'discrete' or 'linear' or 'cosine'".format(schedule))
101
+
102
+ self.schedule = schedule
103
+ if schedule == 'discrete':
104
+ if betas is not None:
105
+ log_alphas = 0.5 * torch.log(1 - betas).cumsum(dim=0)
106
+ else:
107
+ assert alphas_cumprod is not None
108
+ log_alphas = 0.5 * torch.log(alphas_cumprod)
109
+ self.total_N = len(log_alphas)
110
+ self.T = 1.
111
+ self.t_array = torch.linspace(0., 1., self.total_N + 1)[1:].reshape((1, -1))
112
+ self.log_alpha_array = log_alphas.reshape((1, -1,))
113
+ else:
114
+ self.total_N = 1000
115
+ self.beta_0 = continuous_beta_0
116
+ self.beta_1 = continuous_beta_1
117
+ self.cosine_s = 0.008
118
+ self.cosine_beta_max = 999.
119
+ self.cosine_t_max = math.atan(self.cosine_beta_max * (1. + self.cosine_s) / math.pi) * 2. * (1. + self.cosine_s) / math.pi - self.cosine_s
120
+ self.cosine_log_alpha_0 = math.log(math.cos(self.cosine_s / (1. + self.cosine_s) * math.pi / 2.))
121
+ self.schedule = schedule
122
+ if schedule == 'cosine':
123
+ # For the cosine schedule, T = 1 will have numerical issues. So we manually set the ending time T.
124
+ # Note that T = 0.9946 may be not the optimal setting. However, we find it works well.
125
+ self.T = 0.9946
126
+ else:
127
+ self.T = 1.
128
+
129
+ def marginal_log_mean_coeff(self, t):
130
+ """
131
+ Compute log(alpha_t) of a given continuous-time label t in [0, T].
132
+ """
133
+ if self.schedule == 'discrete':
134
+ return interpolate_fn(t.reshape((-1, 1)), self.t_array.to(t.device), self.log_alpha_array.to(t.device)).reshape((-1))
135
+ elif self.schedule == 'linear':
136
+ return -0.25 * t ** 2 * (self.beta_1 - self.beta_0) - 0.5 * t * self.beta_0
137
+ elif self.schedule == 'cosine':
138
+ log_alpha_fn = lambda s: torch.log(torch.cos((s + self.cosine_s) / (1. + self.cosine_s) * math.pi / 2.))
139
+ log_alpha_t = log_alpha_fn(t) - self.cosine_log_alpha_0
140
+ return log_alpha_t
141
+
142
+ def marginal_alpha(self, t):
143
+ """
144
+ Compute alpha_t of a given continuous-time label t in [0, T].
145
+ """
146
+ return torch.exp(self.marginal_log_mean_coeff(t))
147
+
148
+ def marginal_std(self, t):
149
+ """
150
+ Compute sigma_t of a given continuous-time label t in [0, T].
151
+ """
152
+ return torch.sqrt(1. - torch.exp(2. * self.marginal_log_mean_coeff(t)))
153
+
154
+ def marginal_lambda(self, t):
155
+ """
156
+ Compute lambda_t = log(alpha_t) - log(sigma_t) of a given continuous-time label t in [0, T].
157
+ """
158
+ log_mean_coeff = self.marginal_log_mean_coeff(t)
159
+ log_std = 0.5 * torch.log(1. - torch.exp(2. * log_mean_coeff))
160
+ return log_mean_coeff - log_std
161
+
162
+ def inverse_lambda(self, lamb):
163
+ """
164
+ Compute the continuous-time label t in [0, T] of a given half-logSNR lambda_t.
165
+ """
166
+ if self.schedule == 'linear':
167
+ tmp = 2. * (self.beta_1 - self.beta_0) * torch.logaddexp(-2. * lamb, torch.zeros((1,)).to(lamb))
168
+ Delta = self.beta_0**2 + tmp
169
+ return tmp / (torch.sqrt(Delta) + self.beta_0) / (self.beta_1 - self.beta_0)
170
+ elif self.schedule == 'discrete':
171
+ log_alpha = -0.5 * torch.logaddexp(torch.zeros((1,)).to(lamb.device), -2. * lamb)
172
+ t = interpolate_fn(log_alpha.reshape((-1, 1)), torch.flip(self.log_alpha_array.to(lamb.device), [1]), torch.flip(self.t_array.to(lamb.device), [1]))
173
+ return t.reshape((-1,))
174
+ else:
175
+ log_alpha = -0.5 * torch.logaddexp(-2. * lamb, torch.zeros((1,)).to(lamb))
176
+ t_fn = lambda log_alpha_t: torch.arccos(torch.exp(log_alpha_t + self.cosine_log_alpha_0)) * 2. * (1. + self.cosine_s) / math.pi - self.cosine_s
177
+ t = t_fn(log_alpha)
178
+ return t
179
+
180
+
181
+ def model_wrapper(
182
+ model,
183
+ noise_schedule,
184
+ model_type="noise",
185
+ model_kwargs={},
186
+ guidance_type="uncond",
187
+ condition=None,
188
+ unconditional_condition=None,
189
+ guidance_scale=1.,
190
+ classifier_fn=None,
191
+ classifier_kwargs={},
192
+ ):
193
+ """Create a wrapper function for the noise prediction model.
194
+
195
+ DPM-Solver needs to solve the continuous-time diffusion ODEs. For DPMs trained on discrete-time labels, we need to
196
+ firstly wrap the model function to a noise prediction model that accepts the continuous time as the input.
197
+
198
+ We support four types of the diffusion model by setting `model_type`:
199
+
200
+ 1. "noise": noise prediction model. (Trained by predicting noise).
201
+
202
+ 2. "x_start": data prediction model. (Trained by predicting the data x_0 at time 0).
203
+
204
+ 3. "v": velocity prediction model. (Trained by predicting the velocity).
205
+ The "v" prediction is derivation detailed in Appendix D of [1], and is used in Imagen-Video [2].
206
+
207
+ [1] Salimans, Tim, and Jonathan Ho. "Progressive distillation for fast sampling of diffusion models."
208
+ arXiv preprint arXiv:2202.00512 (2022).
209
+ [2] Ho, Jonathan, et al. "Imagen Video: High Definition Video Generation with Diffusion Models."
210
+ arXiv preprint arXiv:2210.02303 (2022).
211
+
212
+ 4. "score": marginal score function. (Trained by denoising score matching).
213
+ Note that the score function and the noise prediction model follows a simple relationship:
214
+ ```
215
+ noise(x_t, t) = -sigma_t * score(x_t, t)
216
+ ```
217
+
218
+ We support three types of guided sampling by DPMs by setting `guidance_type`:
219
+ 1. "uncond": unconditional sampling by DPMs.
220
+ The input `model` has the following format:
221
+ ``
222
+ model(x, t_input, **model_kwargs) -> noise | x_start | v | score
223
+ ``
224
+
225
+ 2. "classifier": classifier guidance sampling [3] by DPMs and another classifier.
226
+ The input `model` has the following format:
227
+ ``
228
+ model(x, t_input, **model_kwargs) -> noise | x_start | v | score
229
+ ``
230
+
231
+ The input `classifier_fn` has the following format:
232
+ ``
233
+ classifier_fn(x, t_input, cond, **classifier_kwargs) -> logits(x, t_input, cond)
234
+ ``
235
+
236
+ [3] P. Dhariwal and A. Q. Nichol, "Diffusion models beat GANs on image synthesis,"
237
+ in Advances in Neural Information Processing Systems, vol. 34, 2021, pp. 8780-8794.
238
+
239
+ 3. "classifier-free": classifier-free guidance sampling by conditional DPMs.
240
+ The input `model` has the following format:
241
+ ``
242
+ model(x, t_input, cond, **model_kwargs) -> noise | x_start | v | score
243
+ ``
244
+ And if cond == `unconditional_condition`, the model output is the unconditional DPM output.
245
+
246
+ [4] Ho, Jonathan, and Tim Salimans. "Classifier-free diffusion guidance."
247
+ arXiv preprint arXiv:2207.12598 (2022).
248
+
249
+
250
+ The `t_input` is the time label of the model, which may be discrete-time labels (i.e. 0 to 999)
251
+ or continuous-time labels (i.e. epsilon to T).
252
+
253
+ We wrap the model function to accept only `x` and `t_continuous` as inputs, and outputs the predicted noise:
254
+ ``
255
+ def model_fn(x, t_continuous) -> noise:
256
+ t_input = get_model_input_time(t_continuous)
257
+ return noise_pred(model, x, t_input, **model_kwargs)
258
+ ``
259
+ where `t_continuous` is the continuous time labels (i.e. epsilon to T). And we use `model_fn` for DPM-Solver.
260
+
261
+ ===============================================================
262
+
263
+ Args:
264
+ model: A diffusion model with the corresponding format described above.
265
+ noise_schedule: A noise schedule object, such as NoiseScheduleVP.
266
+ model_type: A `str`. The parameterization type of the diffusion model.
267
+ "noise" or "x_start" or "v" or "score".
268
+ model_kwargs: A `dict`. A dict for the other inputs of the model function.
269
+ guidance_type: A `str`. The type of the guidance for sampling.
270
+ "uncond" or "classifier" or "classifier-free".
271
+ condition: A pytorch tensor. The condition for the guided sampling.
272
+ Only used for "classifier" or "classifier-free" guidance type.
273
+ unconditional_condition: A pytorch tensor. The condition for the unconditional sampling.
274
+ Only used for "classifier-free" guidance type.
275
+ guidance_scale: A `float`. The scale for the guided sampling.
276
+ classifier_fn: A classifier function. Only used for the classifier guidance.
277
+ classifier_kwargs: A `dict`. A dict for the other inputs of the classifier function.
278
+ Returns:
279
+ A noise prediction model that accepts the noised data and the continuous time as the inputs.
280
+ """
281
+
282
+ def get_model_input_time(t_continuous):
283
+ """
284
+ Convert the continuous-time `t_continuous` (in [epsilon, T]) to the model input time.
285
+ For discrete-time DPMs, we convert `t_continuous` in [1 / N, 1] to `t_input` in [0, 1000 * (N - 1) / N].
286
+ For continuous-time DPMs, we just use `t_continuous`.
287
+ """
288
+ if noise_schedule.schedule == 'discrete':
289
+ return (t_continuous - 1. / noise_schedule.total_N) * 1000.
290
+ else:
291
+ return t_continuous
292
+
293
+ def noise_pred_fn(x, t_continuous, cond=None):
294
+ if t_continuous.reshape((-1,)).shape[0] == 1:
295
+ t_continuous = t_continuous.expand((x.shape[0]))
296
+ t_input = get_model_input_time(t_continuous)
297
+ output = model(x, t_input, **model_kwargs)
298
+ if model_type == "noise":
299
+ return output
300
+ elif model_type == "x_start":
301
+ alpha_t, sigma_t = noise_schedule.marginal_alpha(t_continuous), noise_schedule.marginal_std(t_continuous)
302
+ dims = x.dim()
303
+ return (x - expand_dims(alpha_t, dims) * output) / expand_dims(sigma_t, dims)
304
+ elif model_type == "v":
305
+ alpha_t, sigma_t = noise_schedule.marginal_alpha(t_continuous), noise_schedule.marginal_std(t_continuous)
306
+ dims = x.dim()
307
+ return expand_dims(alpha_t, dims) * output + expand_dims(sigma_t, dims) * x
308
+ elif model_type == "score":
309
+ sigma_t = noise_schedule.marginal_std(t_continuous)
310
+ dims = x.dim()
311
+ return -expand_dims(sigma_t, dims) * output
312
+
313
+ def cond_grad_fn(x, t_input):
314
+ """
315
+ Compute the gradient of the classifier, i.e. nabla_{x} log p_t(cond | x_t).
316
+ """
317
+ with torch.enable_grad():
318
+ x_in = x.detach().requires_grad_(True)
319
+ log_prob = classifier_fn(x_in, t_input, condition, **classifier_kwargs)
320
+ return torch.autograd.grad(log_prob.sum(), x_in)[0]
321
+
322
+ def model_fn(x, t_continuous):
323
+ """
324
+ The noise predicition model function that is used for DPM-Solver.
325
+ """
326
+ if t_continuous.reshape((-1,)).shape[0] == 1:
327
+ t_continuous = t_continuous.expand((x.shape[0]))
328
+ if guidance_type == "uncond":
329
+ return noise_pred_fn(x, t_continuous)
330
+ elif guidance_type == "classifier":
331
+ assert classifier_fn is not None
332
+ t_input = get_model_input_time(t_continuous)
333
+ cond_grad = cond_grad_fn(x, t_input)
334
+ sigma_t = noise_schedule.marginal_std(t_continuous)
335
+ noise = noise_pred_fn(x, t_continuous)
336
+ return noise - guidance_scale * expand_dims(sigma_t, dims=cond_grad.dim()) * cond_grad
337
+ elif guidance_type == "classifier-free":
338
+ if guidance_scale == 1. or unconditional_condition is None:
339
+ return noise_pred_fn(x, t_continuous, cond=condition)
340
+ else:
341
+ x_in = torch.cat([x] * 2)
342
+ t_in = torch.cat([t_continuous] * 2)
343
+ c_in = torch.cat([unconditional_condition, condition])
344
+ noise_uncond, noise = noise_pred_fn(x_in, t_in, cond=c_in).chunk(2)
345
+ return noise_uncond + guidance_scale * (noise - noise_uncond)
346
+
347
+ assert model_type in ["noise", "x_start", "v"]
348
+ assert guidance_type in ["uncond", "classifier", "classifier-free"]
349
+ return model_fn
350
+
351
+
352
+ class UniPC:
353
+ def __init__(
354
+ self,
355
+ model_fn,
356
+ noise_schedule,
357
+ predict_x0=True,
358
+ thresholding=False,
359
+ max_val=1.,
360
+ variant='bh1',
361
+ ):
362
+ """Construct a UniPC.
363
+
364
+ We support both data_prediction and noise_prediction.
365
+ """
366
+ self.model = model_fn
367
+ self.noise_schedule = noise_schedule
368
+ self.variant = variant
369
+ self.predict_x0 = predict_x0
370
+ self.thresholding = thresholding
371
+ self.max_val = max_val
372
+
373
+ def dynamic_thresholding_fn(self, x0, t=None):
374
+ """
375
+ The dynamic thresholding method.
376
+ """
377
+ dims = x0.dim()
378
+ p = self.dynamic_thresholding_ratio
379
+ s = torch.quantile(torch.abs(x0).reshape((x0.shape[0], -1)), p, dim=1)
380
+ s = expand_dims(torch.maximum(s, self.thresholding_max_val * torch.ones_like(s).to(s.device)), dims)
381
+ x0 = torch.clamp(x0, -s, s) / s
382
+ return x0
383
+
384
+ def noise_prediction_fn(self, x, t):
385
+ """
386
+ Return the noise prediction model.
387
+ """
388
+ return self.model(x, t)
389
+
390
+ def data_prediction_fn(self, x, t):
391
+ """
392
+ Return the data prediction model (with thresholding).
393
+ """
394
+ noise = self.noise_prediction_fn(x, t)
395
+ dims = x.dim()
396
+ alpha_t, sigma_t = self.noise_schedule.marginal_alpha(t), self.noise_schedule.marginal_std(t)
397
+ x0 = (x - expand_dims(sigma_t, dims) * noise) / expand_dims(alpha_t, dims)
398
+ if self.thresholding:
399
+ p = 0.995 # A hyperparameter in the paper of "Imagen" [1].
400
+ s = torch.quantile(torch.abs(x0).reshape((x0.shape[0], -1)), p, dim=1)
401
+ s = expand_dims(torch.maximum(s, self.max_val * torch.ones_like(s).to(s.device)), dims)
402
+ x0 = torch.clamp(x0, -s, s) / s
403
+ return x0
404
+
405
+ def model_fn(self, x, t):
406
+ """
407
+ Convert the model to the noise prediction model or the data prediction model.
408
+ """
409
+ if self.predict_x0:
410
+ return self.data_prediction_fn(x, t)
411
+ else:
412
+ return self.noise_prediction_fn(x, t)
413
+
414
+ def get_time_steps(self, skip_type, t_T, t_0, N, device):
415
+ """Compute the intermediate time steps for sampling.
416
+ """
417
+ if skip_type == 'logSNR':
418
+ lambda_T = self.noise_schedule.marginal_lambda(torch.tensor(t_T).to(device))
419
+ lambda_0 = self.noise_schedule.marginal_lambda(torch.tensor(t_0).to(device))
420
+ logSNR_steps = torch.linspace(lambda_T.cpu().item(), lambda_0.cpu().item(), N + 1).to(device)
421
+ return self.noise_schedule.inverse_lambda(logSNR_steps)
422
+ elif skip_type == 'time_uniform':
423
+ return torch.linspace(t_T, t_0, N + 1).to(device)
424
+ elif skip_type == 'time_quadratic':
425
+ t_order = 2
426
+ t = torch.linspace(t_T**(1. / t_order), t_0**(1. / t_order), N + 1).pow(t_order).to(device)
427
+ return t
428
+ else:
429
+ raise ValueError("Unsupported skip_type {}, need to be 'logSNR' or 'time_uniform' or 'time_quadratic'".format(skip_type))
430
+
431
+ def get_orders_and_timesteps_for_singlestep_solver(self, steps, order, skip_type, t_T, t_0, device):
432
+ """
433
+ Get the order of each step for sampling by the singlestep DPM-Solver.
434
+ """
435
+ if order == 3:
436
+ K = steps // 3 + 1
437
+ if steps % 3 == 0:
438
+ orders = [3,] * (K - 2) + [2, 1]
439
+ elif steps % 3 == 1:
440
+ orders = [3,] * (K - 1) + [1]
441
+ else:
442
+ orders = [3,] * (K - 1) + [2]
443
+ elif order == 2:
444
+ if steps % 2 == 0:
445
+ K = steps // 2
446
+ orders = [2,] * K
447
+ else:
448
+ K = steps // 2 + 1
449
+ orders = [2,] * (K - 1) + [1]
450
+ elif order == 1:
451
+ K = steps
452
+ orders = [1,] * steps
453
+ else:
454
+ raise ValueError("'order' must be '1' or '2' or '3'.")
455
+ if skip_type == 'logSNR':
456
+ # To reproduce the results in DPM-Solver paper
457
+ timesteps_outer = self.get_time_steps(skip_type, t_T, t_0, K, device)
458
+ else:
459
+ timesteps_outer = self.get_time_steps(skip_type, t_T, t_0, steps, device)[torch.cumsum(torch.tensor([0,] + orders), 0).to(device)]
460
+ return timesteps_outer, orders
461
+
462
+ def denoise_to_zero_fn(self, x, s):
463
+ """
464
+ Denoise at the final step, which is equivalent to solve the ODE from lambda_s to infty by first-order discretization.
465
+ """
466
+ return self.data_prediction_fn(x, s)
467
+
468
+ def multistep_uni_pc_update(self, x, model_prev_list, t_prev_list, t, order, **kwargs):
469
+ if len(t.shape) == 0:
470
+ t = t.view(-1)
471
+ if 'bh' in self.variant:
472
+ return self.multistep_uni_pc_bh_update(x, model_prev_list, t_prev_list, t, order, **kwargs)
473
+ else:
474
+ assert self.variant == 'vary_coeff'
475
+ return self.multistep_uni_pc_vary_update(x, model_prev_list, t_prev_list, t, order, **kwargs)
476
+
477
+ def multistep_uni_pc_vary_update(self, x, model_prev_list, t_prev_list, t, order, use_corrector=True):
478
+ logging.info(f'using unified predictor-corrector with order {order} (solver type: vary coeff)')
479
+ ns = self.noise_schedule
480
+ assert order <= len(model_prev_list)
481
+
482
+ # first compute rks
483
+ t_prev_0 = t_prev_list[-1]
484
+ lambda_prev_0 = ns.marginal_lambda(t_prev_0)
485
+ lambda_t = ns.marginal_lambda(t)
486
+ model_prev_0 = model_prev_list[-1]
487
+ sigma_prev_0, sigma_t = ns.marginal_std(t_prev_0), ns.marginal_std(t)
488
+ log_alpha_t = ns.marginal_log_mean_coeff(t)
489
+ alpha_t = torch.exp(log_alpha_t)
490
+
491
+ h = lambda_t - lambda_prev_0
492
+
493
+ rks = []
494
+ D1s = []
495
+ for i in range(1, order):
496
+ t_prev_i = t_prev_list[-(i + 1)]
497
+ model_prev_i = model_prev_list[-(i + 1)]
498
+ lambda_prev_i = ns.marginal_lambda(t_prev_i)
499
+ rk = (lambda_prev_i - lambda_prev_0) / h
500
+ rks.append(rk)
501
+ D1s.append((model_prev_i - model_prev_0) / rk)
502
+
503
+ rks.append(1.)
504
+ rks = torch.tensor(rks, device=x.device)
505
+
506
+ K = len(rks)
507
+ # build C matrix
508
+ C = []
509
+
510
+ col = torch.ones_like(rks)
511
+ for k in range(1, K + 1):
512
+ C.append(col)
513
+ col = col * rks / (k + 1)
514
+ C = torch.stack(C, dim=1)
515
+
516
+ if len(D1s) > 0:
517
+ D1s = torch.stack(D1s, dim=1) # (B, K)
518
+ C_inv_p = torch.linalg.inv(C[:-1, :-1])
519
+ A_p = C_inv_p
520
+
521
+ if use_corrector:
522
+ C_inv = torch.linalg.inv(C)
523
+ A_c = C_inv
524
+
525
+ hh = -h if self.predict_x0 else h
526
+ h_phi_1 = torch.expm1(hh)
527
+ h_phi_ks = []
528
+ factorial_k = 1
529
+ h_phi_k = h_phi_1
530
+ for k in range(1, K + 2):
531
+ h_phi_ks.append(h_phi_k)
532
+ h_phi_k = h_phi_k / hh - 1 / factorial_k
533
+ factorial_k *= (k + 1)
534
+
535
+ model_t = None
536
+ if self.predict_x0:
537
+ x_t_ = (
538
+ sigma_t / sigma_prev_0 * x
539
+ - alpha_t * h_phi_1 * model_prev_0
540
+ )
541
+ # now predictor
542
+ x_t = x_t_
543
+ if len(D1s) > 0:
544
+ # compute the residuals for predictor
545
+ for k in range(K - 1):
546
+ x_t = x_t - alpha_t * h_phi_ks[k + 1] * torch.einsum('bkchw,k->bchw', D1s, A_p[k])
547
+ # now corrector
548
+ if use_corrector:
549
+ model_t = self.model_fn(x_t, t)
550
+ D1_t = (model_t - model_prev_0)
551
+ x_t = x_t_
552
+ k = 0
553
+ for k in range(K - 1):
554
+ x_t = x_t - alpha_t * h_phi_ks[k + 1] * torch.einsum('bkchw,k->bchw', D1s, A_c[k][:-1])
555
+ x_t = x_t - alpha_t * h_phi_ks[K] * (D1_t * A_c[k][-1])
556
+ else:
557
+ log_alpha_prev_0, log_alpha_t = ns.marginal_log_mean_coeff(t_prev_0), ns.marginal_log_mean_coeff(t)
558
+ x_t_ = (
559
+ (torch.exp(log_alpha_t - log_alpha_prev_0)) * x
560
+ - (sigma_t * h_phi_1) * model_prev_0
561
+ )
562
+ # now predictor
563
+ x_t = x_t_
564
+ if len(D1s) > 0:
565
+ # compute the residuals for predictor
566
+ for k in range(K - 1):
567
+ x_t = x_t - sigma_t * h_phi_ks[k + 1] * torch.einsum('bkchw,k->bchw', D1s, A_p[k])
568
+ # now corrector
569
+ if use_corrector:
570
+ model_t = self.model_fn(x_t, t)
571
+ D1_t = (model_t - model_prev_0)
572
+ x_t = x_t_
573
+ k = 0
574
+ for k in range(K - 1):
575
+ x_t = x_t - sigma_t * h_phi_ks[k + 1] * torch.einsum('bkchw,k->bchw', D1s, A_c[k][:-1])
576
+ x_t = x_t - sigma_t * h_phi_ks[K] * (D1_t * A_c[k][-1])
577
+ return x_t, model_t
578
+
579
+ def multistep_uni_pc_bh_update(self, x, model_prev_list, t_prev_list, t, order, x_t=None, use_corrector=True):
580
+ # print(f'using unified predictor-corrector with order {order} (solver type: B(h))')
581
+ ns = self.noise_schedule
582
+ assert order <= len(model_prev_list)
583
+ dims = x.dim()
584
+
585
+ # first compute rks
586
+ t_prev_0 = t_prev_list[-1]
587
+ lambda_prev_0 = ns.marginal_lambda(t_prev_0)
588
+ lambda_t = ns.marginal_lambda(t)
589
+ model_prev_0 = model_prev_list[-1]
590
+ sigma_prev_0, sigma_t = ns.marginal_std(t_prev_0), ns.marginal_std(t)
591
+ log_alpha_prev_0, log_alpha_t = ns.marginal_log_mean_coeff(t_prev_0), ns.marginal_log_mean_coeff(t)
592
+ alpha_t = torch.exp(log_alpha_t)
593
+
594
+ h = lambda_t - lambda_prev_0
595
+
596
+ rks = []
597
+ D1s = []
598
+ for i in range(1, order):
599
+ t_prev_i = t_prev_list[-(i + 1)]
600
+ model_prev_i = model_prev_list[-(i + 1)]
601
+ lambda_prev_i = ns.marginal_lambda(t_prev_i)
602
+ rk = ((lambda_prev_i - lambda_prev_0) / h)[0]
603
+ rks.append(rk)
604
+ D1s.append((model_prev_i - model_prev_0) / rk)
605
+
606
+ rks.append(1.)
607
+ rks = torch.tensor(rks, device=x.device)
608
+
609
+ R = []
610
+ b = []
611
+
612
+ hh = -h[0] if self.predict_x0 else h[0]
613
+ h_phi_1 = torch.expm1(hh) # h\phi_1(h) = e^h - 1
614
+ h_phi_k = h_phi_1 / hh - 1
615
+
616
+ factorial_i = 1
617
+
618
+ if self.variant == 'bh1':
619
+ B_h = hh
620
+ elif self.variant == 'bh2':
621
+ B_h = torch.expm1(hh)
622
+ else:
623
+ raise NotImplementedError()
624
+
625
+ for i in range(1, order + 1):
626
+ R.append(torch.pow(rks, i - 1))
627
+ b.append(h_phi_k * factorial_i / B_h)
628
+ factorial_i *= (i + 1)
629
+ h_phi_k = h_phi_k / hh - 1 / factorial_i
630
+
631
+ R = torch.stack(R)
632
+ b = torch.tensor(b, device=x.device)
633
+
634
+ # now predictor
635
+ use_predictor = len(D1s) > 0 and x_t is None
636
+ if len(D1s) > 0:
637
+ D1s = torch.stack(D1s, dim=1) # (B, K)
638
+ if x_t is None:
639
+ # for order 2, we use a simplified version
640
+ if order == 2:
641
+ rhos_p = torch.tensor([0.5], device=b.device)
642
+ else:
643
+ rhos_p = torch.linalg.solve(R[:-1, :-1], b[:-1])
644
+ else:
645
+ D1s = None
646
+
647
+ if use_corrector:
648
+ # print('using corrector')
649
+ # for order 1, we use a simplified version
650
+ if order == 1:
651
+ rhos_c = torch.tensor([0.5], device=b.device)
652
+ else:
653
+ rhos_c = torch.linalg.solve(R, b)
654
+
655
+ model_t = None
656
+ if self.predict_x0:
657
+ x_t_ = (
658
+ expand_dims(sigma_t / sigma_prev_0, dims) * x
659
+ - expand_dims(alpha_t * h_phi_1, dims)* model_prev_0
660
+ )
661
+
662
+ if x_t is None:
663
+ if use_predictor:
664
+ pred_res = torch.tensordot(D1s, rhos_p, dims=([1], [0])) # torch.einsum('k,bkchw->bchw', rhos_p, D1s)
665
+ else:
666
+ pred_res = 0
667
+ x_t = x_t_ - expand_dims(alpha_t * B_h, dims) * pred_res
668
+
669
+ if use_corrector:
670
+ model_t = self.model_fn(x_t, t)
671
+ if D1s is not None:
672
+ corr_res = torch.tensordot(D1s, rhos_c[:-1], dims=([1], [0])) # torch.einsum('k,bkchw->bchw', rhos_c[:-1], D1s)
673
+ else:
674
+ corr_res = 0
675
+ D1_t = (model_t - model_prev_0)
676
+ x_t = x_t_ - expand_dims(alpha_t * B_h, dims) * (corr_res + rhos_c[-1] * D1_t)
677
+ else:
678
+ x_t_ = (
679
+ expand_dims(torch.exp(log_alpha_t - log_alpha_prev_0), dims) * x
680
+ - expand_dims(sigma_t * h_phi_1, dims) * model_prev_0
681
+ )
682
+ if x_t is None:
683
+ if use_predictor:
684
+ pred_res = torch.einsum('k,bkchw->bchw', rhos_p, D1s)
685
+ else:
686
+ pred_res = 0
687
+ x_t = x_t_ - expand_dims(sigma_t * B_h, dims) * pred_res
688
+
689
+ if use_corrector:
690
+ model_t = self.model_fn(x_t, t)
691
+ if D1s is not None:
692
+ corr_res = torch.einsum('k,bkchw->bchw', rhos_c[:-1], D1s)
693
+ else:
694
+ corr_res = 0
695
+ D1_t = (model_t - model_prev_0)
696
+ x_t = x_t_ - expand_dims(sigma_t * B_h, dims) * (corr_res + rhos_c[-1] * D1_t)
697
+ return x_t, model_t
698
+
699
+
700
+ def sample(self, x, timesteps, t_start=None, t_end=None, order=3, skip_type='time_uniform',
701
+ method='singlestep', lower_order_final=True, denoise_to_zero=False, solver_type='dpm_solver',
702
+ atol=0.0078, rtol=0.05, corrector=False, callback=None, disable_pbar=False
703
+ ):
704
+ # t_0 = 1. / self.noise_schedule.total_N if t_end is None else t_end
705
+ # t_T = self.noise_schedule.T if t_start is None else t_start
706
+ steps = len(timesteps) - 1
707
+ if method == 'multistep':
708
+ assert steps >= order
709
+ # timesteps = self.get_time_steps(skip_type=skip_type, t_T=t_T, t_0=t_0, N=steps, device=device)
710
+ assert timesteps.shape[0] - 1 == steps
711
+ # with torch.no_grad():
712
+ for step_index in trange(steps, disable=disable_pbar):
713
+ if step_index == 0:
714
+ vec_t = timesteps[0].expand((x.shape[0]))
715
+ model_prev_list = [self.model_fn(x, vec_t)]
716
+ t_prev_list = [vec_t]
717
+ elif step_index < order:
718
+ init_order = step_index
719
+ # Init the first `order` values by lower order multistep DPM-Solver.
720
+ # for init_order in range(1, order):
721
+ vec_t = timesteps[init_order].expand(x.shape[0])
722
+ x, model_x = self.multistep_uni_pc_update(x, model_prev_list, t_prev_list, vec_t, init_order, use_corrector=True)
723
+ if model_x is None:
724
+ model_x = self.model_fn(x, vec_t)
725
+ model_prev_list.append(model_x)
726
+ t_prev_list.append(vec_t)
727
+ else:
728
+ extra_final_step = 0
729
+ if step_index == (steps - 1):
730
+ extra_final_step = 1
731
+ for step in range(step_index, step_index + 1 + extra_final_step):
732
+ vec_t = timesteps[step].expand(x.shape[0])
733
+ if lower_order_final:
734
+ step_order = min(order, steps + 1 - step)
735
+ else:
736
+ step_order = order
737
+ # print('this step order:', step_order)
738
+ if step == steps:
739
+ # print('do not run corrector at the last step')
740
+ use_corrector = False
741
+ else:
742
+ use_corrector = True
743
+ x, model_x = self.multistep_uni_pc_update(x, model_prev_list, t_prev_list, vec_t, step_order, use_corrector=use_corrector)
744
+ for i in range(order - 1):
745
+ t_prev_list[i] = t_prev_list[i + 1]
746
+ model_prev_list[i] = model_prev_list[i + 1]
747
+ t_prev_list[-1] = vec_t
748
+ # We do not need to evaluate the final model value.
749
+ if step < steps:
750
+ if model_x is None:
751
+ model_x = self.model_fn(x, vec_t)
752
+ model_prev_list[-1] = model_x
753
+ if callback is not None:
754
+ callback({'x': x, 'i': step_index, 'denoised': model_prev_list[-1]})
755
+ else:
756
+ raise NotImplementedError()
757
+ # if denoise_to_zero:
758
+ # x = self.denoise_to_zero_fn(x, torch.ones((x.shape[0],)).to(device) * t_0)
759
+ return x
760
+
761
+
762
+ #############################################################
763
+ # other utility functions
764
+ #############################################################
765
+
766
+ def interpolate_fn(x, xp, yp):
767
+ """
768
+ A piecewise linear function y = f(x), using xp and yp as keypoints.
769
+ We implement f(x) in a differentiable way (i.e. applicable for autograd).
770
+ The function f(x) is well-defined for all x-axis. (For x beyond the bounds of xp, we use the outmost points of xp to define the linear function.)
771
+
772
+ Args:
773
+ x: PyTorch tensor with shape [N, C], where N is the batch size, C is the number of channels (we use C = 1 for DPM-Solver).
774
+ xp: PyTorch tensor with shape [C, K], where K is the number of keypoints.
775
+ yp: PyTorch tensor with shape [C, K].
776
+ Returns:
777
+ The function values f(x), with shape [N, C].
778
+ """
779
+ N, K = x.shape[0], xp.shape[1]
780
+ all_x = torch.cat([x.unsqueeze(2), xp.unsqueeze(0).repeat((N, 1, 1))], dim=2)
781
+ sorted_all_x, x_indices = torch.sort(all_x, dim=2)
782
+ x_idx = torch.argmin(x_indices, dim=2)
783
+ cand_start_idx = x_idx - 1
784
+ start_idx = torch.where(
785
+ torch.eq(x_idx, 0),
786
+ torch.tensor(1, device=x.device),
787
+ torch.where(
788
+ torch.eq(x_idx, K), torch.tensor(K - 2, device=x.device), cand_start_idx,
789
+ ),
790
+ )
791
+ end_idx = torch.where(torch.eq(start_idx, cand_start_idx), start_idx + 2, start_idx + 1)
792
+ start_x = torch.gather(sorted_all_x, dim=2, index=start_idx.unsqueeze(2)).squeeze(2)
793
+ end_x = torch.gather(sorted_all_x, dim=2, index=end_idx.unsqueeze(2)).squeeze(2)
794
+ start_idx2 = torch.where(
795
+ torch.eq(x_idx, 0),
796
+ torch.tensor(0, device=x.device),
797
+ torch.where(
798
+ torch.eq(x_idx, K), torch.tensor(K - 2, device=x.device), cand_start_idx,
799
+ ),
800
+ )
801
+ y_positions_expanded = yp.unsqueeze(0).expand(N, -1, -1)
802
+ start_y = torch.gather(y_positions_expanded, dim=2, index=start_idx2.unsqueeze(2)).squeeze(2)
803
+ end_y = torch.gather(y_positions_expanded, dim=2, index=(start_idx2 + 1).unsqueeze(2)).squeeze(2)
804
+ cand = start_y + (x - start_x) * (end_y - start_y) / (end_x - start_x)
805
+ return cand
806
+
807
+
808
+ def expand_dims(v, dims):
809
+ """
810
+ Expand the tensor `v` to the dim `dims`.
811
+
812
+ Args:
813
+ `v`: a PyTorch tensor with shape [N].
814
+ `dim`: a `int`.
815
+ Returns:
816
+ a PyTorch tensor with shape [N, 1, 1, ..., 1] and the total dimension is `dims`.
817
+ """
818
+ return v[(...,) + (None,)*(dims - 1)]
819
+
820
+
821
+ class SigmaConvert:
822
+ schedule = ""
823
+ def marginal_log_mean_coeff(self, sigma):
824
+ return 0.5 * torch.log(1 / ((sigma * sigma) + 1))
825
+
826
+ def marginal_alpha(self, t):
827
+ return torch.exp(self.marginal_log_mean_coeff(t))
828
+
829
+ def marginal_std(self, t):
830
+ return torch.sqrt(1. - torch.exp(2. * self.marginal_log_mean_coeff(t)))
831
+
832
+ def marginal_lambda(self, t):
833
+ """
834
+ Compute lambda_t = log(alpha_t) - log(sigma_t) of a given continuous-time label t in [0, T].
835
+ """
836
+ log_mean_coeff = self.marginal_log_mean_coeff(t)
837
+ log_std = 0.5 * torch.log(1. - torch.exp(2. * log_mean_coeff))
838
+ return log_mean_coeff - log_std
839
+
840
+ def predict_eps_sigma(model, input, sigma_in, **kwargs):
841
+ sigma = sigma_in.view(sigma_in.shape[:1] + (1,) * (input.ndim - 1))
842
+ input = input * ((sigma ** 2 + 1.0) ** 0.5)
843
+ return (input - model(input, sigma_in, **kwargs)) / sigma
844
+
845
+
846
+ def sample_unipc(model, noise, sigmas, extra_args=None, callback=None, disable=False, variant='bh1'):
847
+ timesteps = sigmas.clone()
848
+ if sigmas[-1] == 0:
849
+ timesteps = sigmas[:]
850
+ timesteps[-1] = 0.001
851
+ else:
852
+ timesteps = sigmas.clone()
853
+ ns = SigmaConvert()
854
+
855
+ noise = noise / torch.sqrt(1.0 + timesteps[0] ** 2.0)
856
+ model_type = "noise"
857
+
858
+ model_fn = model_wrapper(
859
+ lambda input, sigma, **kwargs: predict_eps_sigma(model, input, sigma, **kwargs),
860
+ ns,
861
+ model_type=model_type,
862
+ guidance_type="uncond",
863
+ model_kwargs=extra_args,
864
+ )
865
+
866
+ order = min(3, len(timesteps) - 2)
867
+ uni_pc = UniPC(model_fn, ns, predict_x0=True, thresholding=False, variant=variant)
868
+ x = uni_pc.sample(noise, timesteps=timesteps, skip_type="time_uniform", method="multistep", order=order, lower_order_final=True, callback=callback, disable_pbar=disable)
869
+ x /= ns.marginal_alpha(timesteps[-1])
870
+ return x
871
+
872
+ def sample_unipc_bh2(model, noise, sigmas, extra_args=None, callback=None, disable=False):
873
+ return sample_unipc(model, noise, sigmas, extra_args, callback, disable, variant='bh2')
comfy/float.py ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+
3
+ def calc_mantissa(abs_x, exponent, normal_mask, MANTISSA_BITS, EXPONENT_BIAS, generator=None):
4
+ mantissa_scaled = torch.where(
5
+ normal_mask,
6
+ (abs_x / (2.0 ** (exponent - EXPONENT_BIAS)) - 1.0) * (2**MANTISSA_BITS),
7
+ (abs_x / (2.0 ** (-EXPONENT_BIAS + 1 - MANTISSA_BITS)))
8
+ )
9
+
10
+ mantissa_scaled += torch.rand(mantissa_scaled.size(), dtype=mantissa_scaled.dtype, layout=mantissa_scaled.layout, device=mantissa_scaled.device, generator=generator)
11
+ return mantissa_scaled.floor() / (2**MANTISSA_BITS)
12
+
13
+ #Not 100% sure about this
14
+ def manual_stochastic_round_to_float8(x, dtype, generator=None):
15
+ if dtype == torch.float8_e4m3fn:
16
+ EXPONENT_BITS, MANTISSA_BITS, EXPONENT_BIAS = 4, 3, 7
17
+ elif dtype == torch.float8_e5m2:
18
+ EXPONENT_BITS, MANTISSA_BITS, EXPONENT_BIAS = 5, 2, 15
19
+ else:
20
+ raise ValueError("Unsupported dtype")
21
+
22
+ x = x.half()
23
+ sign = torch.sign(x)
24
+ abs_x = x.abs()
25
+ sign = torch.where(abs_x == 0, 0, sign)
26
+
27
+ # Combine exponent calculation and clamping
28
+ exponent = torch.clamp(
29
+ torch.floor(torch.log2(abs_x)) + EXPONENT_BIAS,
30
+ 0, 2**EXPONENT_BITS - 1
31
+ )
32
+
33
+ # Combine mantissa calculation and rounding
34
+ normal_mask = ~(exponent == 0)
35
+
36
+ abs_x[:] = calc_mantissa(abs_x, exponent, normal_mask, MANTISSA_BITS, EXPONENT_BIAS, generator=generator)
37
+
38
+ sign *= torch.where(
39
+ normal_mask,
40
+ (2.0 ** (exponent - EXPONENT_BIAS)) * (1.0 + abs_x),
41
+ (2.0 ** (-EXPONENT_BIAS + 1)) * abs_x
42
+ )
43
+
44
+ inf = torch.finfo(dtype)
45
+ torch.clamp(sign, min=inf.min, max=inf.max, out=sign)
46
+ return sign
47
+
48
+
49
+
50
+ def stochastic_rounding(value, dtype, seed=0):
51
+ if dtype == torch.float32:
52
+ return value.to(dtype=torch.float32)
53
+ if dtype == torch.float16:
54
+ return value.to(dtype=torch.float16)
55
+ if dtype == torch.bfloat16:
56
+ return value.to(dtype=torch.bfloat16)
57
+ if dtype == torch.float8_e4m3fn or dtype == torch.float8_e5m2:
58
+ generator = torch.Generator(device=value.device)
59
+ generator.manual_seed(seed)
60
+ output = torch.empty_like(value, dtype=dtype)
61
+ num_slices = max(1, (value.numel() / (4096 * 4096)))
62
+ slice_size = max(1, round(value.shape[0] / num_slices))
63
+ for i in range(0, value.shape[0], slice_size):
64
+ output[i:i+slice_size].copy_(manual_stochastic_round_to_float8(value[i:i+slice_size], dtype, generator=generator))
65
+ return output
66
+
67
+ return value.to(dtype=dtype)
comfy/gligen.py ADDED
@@ -0,0 +1,344 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ import torch
3
+ from torch import nn
4
+ from .ldm.modules.attention import CrossAttention
5
+ from inspect import isfunction
6
+ import comfy.ops
7
+ ops = comfy.ops.manual_cast
8
+
9
+ def exists(val):
10
+ return val is not None
11
+
12
+
13
+ def uniq(arr):
14
+ return{el: True for el in arr}.keys()
15
+
16
+
17
+ def default(val, d):
18
+ if exists(val):
19
+ return val
20
+ return d() if isfunction(d) else d
21
+
22
+
23
+ # feedforward
24
+ class GEGLU(nn.Module):
25
+ def __init__(self, dim_in, dim_out):
26
+ super().__init__()
27
+ self.proj = ops.Linear(dim_in, dim_out * 2)
28
+
29
+ def forward(self, x):
30
+ x, gate = self.proj(x).chunk(2, dim=-1)
31
+ return x * torch.nn.functional.gelu(gate)
32
+
33
+
34
+ class FeedForward(nn.Module):
35
+ def __init__(self, dim, dim_out=None, mult=4, glu=False, dropout=0.):
36
+ super().__init__()
37
+ inner_dim = int(dim * mult)
38
+ dim_out = default(dim_out, dim)
39
+ project_in = nn.Sequential(
40
+ ops.Linear(dim, inner_dim),
41
+ nn.GELU()
42
+ ) if not glu else GEGLU(dim, inner_dim)
43
+
44
+ self.net = nn.Sequential(
45
+ project_in,
46
+ nn.Dropout(dropout),
47
+ ops.Linear(inner_dim, dim_out)
48
+ )
49
+
50
+ def forward(self, x):
51
+ return self.net(x)
52
+
53
+
54
+ class GatedCrossAttentionDense(nn.Module):
55
+ def __init__(self, query_dim, context_dim, n_heads, d_head):
56
+ super().__init__()
57
+
58
+ self.attn = CrossAttention(
59
+ query_dim=query_dim,
60
+ context_dim=context_dim,
61
+ heads=n_heads,
62
+ dim_head=d_head,
63
+ operations=ops)
64
+ self.ff = FeedForward(query_dim, glu=True)
65
+
66
+ self.norm1 = ops.LayerNorm(query_dim)
67
+ self.norm2 = ops.LayerNorm(query_dim)
68
+
69
+ self.register_parameter('alpha_attn', nn.Parameter(torch.tensor(0.)))
70
+ self.register_parameter('alpha_dense', nn.Parameter(torch.tensor(0.)))
71
+
72
+ # this can be useful: we can externally change magnitude of tanh(alpha)
73
+ # for example, when it is set to 0, then the entire model is same as
74
+ # original one
75
+ self.scale = 1
76
+
77
+ def forward(self, x, objs):
78
+
79
+ x = x + self.scale * \
80
+ torch.tanh(self.alpha_attn) * self.attn(self.norm1(x), objs, objs)
81
+ x = x + self.scale * \
82
+ torch.tanh(self.alpha_dense) * self.ff(self.norm2(x))
83
+
84
+ return x
85
+
86
+
87
+ class GatedSelfAttentionDense(nn.Module):
88
+ def __init__(self, query_dim, context_dim, n_heads, d_head):
89
+ super().__init__()
90
+
91
+ # we need a linear projection since we need cat visual feature and obj
92
+ # feature
93
+ self.linear = ops.Linear(context_dim, query_dim)
94
+
95
+ self.attn = CrossAttention(
96
+ query_dim=query_dim,
97
+ context_dim=query_dim,
98
+ heads=n_heads,
99
+ dim_head=d_head,
100
+ operations=ops)
101
+ self.ff = FeedForward(query_dim, glu=True)
102
+
103
+ self.norm1 = ops.LayerNorm(query_dim)
104
+ self.norm2 = ops.LayerNorm(query_dim)
105
+
106
+ self.register_parameter('alpha_attn', nn.Parameter(torch.tensor(0.)))
107
+ self.register_parameter('alpha_dense', nn.Parameter(torch.tensor(0.)))
108
+
109
+ # this can be useful: we can externally change magnitude of tanh(alpha)
110
+ # for example, when it is set to 0, then the entire model is same as
111
+ # original one
112
+ self.scale = 1
113
+
114
+ def forward(self, x, objs):
115
+
116
+ N_visual = x.shape[1]
117
+ objs = self.linear(objs)
118
+
119
+ x = x + self.scale * torch.tanh(self.alpha_attn) * self.attn(
120
+ self.norm1(torch.cat([x, objs], dim=1)))[:, 0:N_visual, :]
121
+ x = x + self.scale * \
122
+ torch.tanh(self.alpha_dense) * self.ff(self.norm2(x))
123
+
124
+ return x
125
+
126
+
127
+ class GatedSelfAttentionDense2(nn.Module):
128
+ def __init__(self, query_dim, context_dim, n_heads, d_head):
129
+ super().__init__()
130
+
131
+ # we need a linear projection since we need cat visual feature and obj
132
+ # feature
133
+ self.linear = ops.Linear(context_dim, query_dim)
134
+
135
+ self.attn = CrossAttention(
136
+ query_dim=query_dim, context_dim=query_dim, dim_head=d_head, operations=ops)
137
+ self.ff = FeedForward(query_dim, glu=True)
138
+
139
+ self.norm1 = ops.LayerNorm(query_dim)
140
+ self.norm2 = ops.LayerNorm(query_dim)
141
+
142
+ self.register_parameter('alpha_attn', nn.Parameter(torch.tensor(0.)))
143
+ self.register_parameter('alpha_dense', nn.Parameter(torch.tensor(0.)))
144
+
145
+ # this can be useful: we can externally change magnitude of tanh(alpha)
146
+ # for example, when it is set to 0, then the entire model is same as
147
+ # original one
148
+ self.scale = 1
149
+
150
+ def forward(self, x, objs):
151
+
152
+ B, N_visual, _ = x.shape
153
+ B, N_ground, _ = objs.shape
154
+
155
+ objs = self.linear(objs)
156
+
157
+ # sanity check
158
+ size_v = math.sqrt(N_visual)
159
+ size_g = math.sqrt(N_ground)
160
+ assert int(size_v) == size_v, "Visual tokens must be square rootable"
161
+ assert int(size_g) == size_g, "Grounding tokens must be square rootable"
162
+ size_v = int(size_v)
163
+ size_g = int(size_g)
164
+
165
+ # select grounding token and resize it to visual token size as residual
166
+ out = self.attn(self.norm1(torch.cat([x, objs], dim=1)))[
167
+ :, N_visual:, :]
168
+ out = out.permute(0, 2, 1).reshape(B, -1, size_g, size_g)
169
+ out = torch.nn.functional.interpolate(
170
+ out, (size_v, size_v), mode='bicubic')
171
+ residual = out.reshape(B, -1, N_visual).permute(0, 2, 1)
172
+
173
+ # add residual to visual feature
174
+ x = x + self.scale * torch.tanh(self.alpha_attn) * residual
175
+ x = x + self.scale * \
176
+ torch.tanh(self.alpha_dense) * self.ff(self.norm2(x))
177
+
178
+ return x
179
+
180
+
181
+ class FourierEmbedder():
182
+ def __init__(self, num_freqs=64, temperature=100):
183
+
184
+ self.num_freqs = num_freqs
185
+ self.temperature = temperature
186
+ self.freq_bands = temperature ** (torch.arange(num_freqs) / num_freqs)
187
+
188
+ @torch.no_grad()
189
+ def __call__(self, x, cat_dim=-1):
190
+ "x: arbitrary shape of tensor. dim: cat dim"
191
+ out = []
192
+ for freq in self.freq_bands:
193
+ out.append(torch.sin(freq * x))
194
+ out.append(torch.cos(freq * x))
195
+ return torch.cat(out, cat_dim)
196
+
197
+
198
+ class PositionNet(nn.Module):
199
+ def __init__(self, in_dim, out_dim, fourier_freqs=8):
200
+ super().__init__()
201
+ self.in_dim = in_dim
202
+ self.out_dim = out_dim
203
+
204
+ self.fourier_embedder = FourierEmbedder(num_freqs=fourier_freqs)
205
+ self.position_dim = fourier_freqs * 2 * 4 # 2 is sin&cos, 4 is xyxy
206
+
207
+ self.linears = nn.Sequential(
208
+ ops.Linear(self.in_dim + self.position_dim, 512),
209
+ nn.SiLU(),
210
+ ops.Linear(512, 512),
211
+ nn.SiLU(),
212
+ ops.Linear(512, out_dim),
213
+ )
214
+
215
+ self.null_positive_feature = torch.nn.Parameter(
216
+ torch.zeros([self.in_dim]))
217
+ self.null_position_feature = torch.nn.Parameter(
218
+ torch.zeros([self.position_dim]))
219
+
220
+ def forward(self, boxes, masks, positive_embeddings):
221
+ B, N, _ = boxes.shape
222
+ masks = masks.unsqueeze(-1)
223
+ positive_embeddings = positive_embeddings
224
+
225
+ # embedding position (it may includes padding as placeholder)
226
+ xyxy_embedding = self.fourier_embedder(boxes) # B*N*4 --> B*N*C
227
+
228
+ # learnable null embedding
229
+ positive_null = self.null_positive_feature.to(device=boxes.device, dtype=boxes.dtype).view(1, 1, -1)
230
+ xyxy_null = self.null_position_feature.to(device=boxes.device, dtype=boxes.dtype).view(1, 1, -1)
231
+
232
+ # replace padding with learnable null embedding
233
+ positive_embeddings = positive_embeddings * \
234
+ masks + (1 - masks) * positive_null
235
+ xyxy_embedding = xyxy_embedding * masks + (1 - masks) * xyxy_null
236
+
237
+ objs = self.linears(
238
+ torch.cat([positive_embeddings, xyxy_embedding], dim=-1))
239
+ assert objs.shape == torch.Size([B, N, self.out_dim])
240
+ return objs
241
+
242
+
243
+ class Gligen(nn.Module):
244
+ def __init__(self, modules, position_net, key_dim):
245
+ super().__init__()
246
+ self.module_list = nn.ModuleList(modules)
247
+ self.position_net = position_net
248
+ self.key_dim = key_dim
249
+ self.max_objs = 30
250
+ self.current_device = torch.device("cpu")
251
+
252
+ def _set_position(self, boxes, masks, positive_embeddings):
253
+ objs = self.position_net(boxes, masks, positive_embeddings)
254
+ def func(x, extra_options):
255
+ key = extra_options["transformer_index"]
256
+ module = self.module_list[key]
257
+ return module(x, objs.to(device=x.device, dtype=x.dtype))
258
+ return func
259
+
260
+ def set_position(self, latent_image_shape, position_params, device):
261
+ batch, c, h, w = latent_image_shape
262
+ masks = torch.zeros([self.max_objs], device="cpu")
263
+ boxes = []
264
+ positive_embeddings = []
265
+ for p in position_params:
266
+ x1 = (p[4]) / w
267
+ y1 = (p[3]) / h
268
+ x2 = (p[4] + p[2]) / w
269
+ y2 = (p[3] + p[1]) / h
270
+ masks[len(boxes)] = 1.0
271
+ boxes += [torch.tensor((x1, y1, x2, y2)).unsqueeze(0)]
272
+ positive_embeddings += [p[0]]
273
+ append_boxes = []
274
+ append_conds = []
275
+ if len(boxes) < self.max_objs:
276
+ append_boxes = [torch.zeros(
277
+ [self.max_objs - len(boxes), 4], device="cpu")]
278
+ append_conds = [torch.zeros(
279
+ [self.max_objs - len(boxes), self.key_dim], device="cpu")]
280
+
281
+ box_out = torch.cat(
282
+ boxes + append_boxes).unsqueeze(0).repeat(batch, 1, 1)
283
+ masks = masks.unsqueeze(0).repeat(batch, 1)
284
+ conds = torch.cat(positive_embeddings +
285
+ append_conds).unsqueeze(0).repeat(batch, 1, 1)
286
+ return self._set_position(
287
+ box_out.to(device),
288
+ masks.to(device),
289
+ conds.to(device))
290
+
291
+ def set_empty(self, latent_image_shape, device):
292
+ batch, c, h, w = latent_image_shape
293
+ masks = torch.zeros([self.max_objs], device="cpu").repeat(batch, 1)
294
+ box_out = torch.zeros([self.max_objs, 4],
295
+ device="cpu").repeat(batch, 1, 1)
296
+ conds = torch.zeros([self.max_objs, self.key_dim],
297
+ device="cpu").repeat(batch, 1, 1)
298
+ return self._set_position(
299
+ box_out.to(device),
300
+ masks.to(device),
301
+ conds.to(device))
302
+
303
+
304
+ def load_gligen(sd):
305
+ sd_k = sd.keys()
306
+ output_list = []
307
+ key_dim = 768
308
+ for a in ["input_blocks", "middle_block", "output_blocks"]:
309
+ for b in range(20):
310
+ k_temp = filter(lambda k: "{}.{}.".format(a, b)
311
+ in k and ".fuser." in k, sd_k)
312
+ k_temp = map(lambda k: (k, k.split(".fuser.")[-1]), k_temp)
313
+
314
+ n_sd = {}
315
+ for k in k_temp:
316
+ n_sd[k[1]] = sd[k[0]]
317
+ if len(n_sd) > 0:
318
+ query_dim = n_sd["linear.weight"].shape[0]
319
+ key_dim = n_sd["linear.weight"].shape[1]
320
+
321
+ if key_dim == 768: # SD1.x
322
+ n_heads = 8
323
+ d_head = query_dim // n_heads
324
+ else:
325
+ d_head = 64
326
+ n_heads = query_dim // d_head
327
+
328
+ gated = GatedSelfAttentionDense(
329
+ query_dim, key_dim, n_heads, d_head)
330
+ gated.load_state_dict(n_sd, strict=False)
331
+ output_list.append(gated)
332
+
333
+ if "position_net.null_positive_feature" in sd_k:
334
+ in_dim = sd["position_net.null_positive_feature"].shape[0]
335
+ out_dim = sd["position_net.linears.4.weight"].shape[0]
336
+
337
+ class WeightsLoader(torch.nn.Module):
338
+ pass
339
+ w = WeightsLoader()
340
+ w.position_net = PositionNet(in_dim, out_dim)
341
+ w.load_state_dict(sd, strict=False)
342
+
343
+ gligen = Gligen(output_list, w.position_net, key_dim)
344
+ return gligen
comfy/hooks.py ADDED
@@ -0,0 +1,785 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+ from typing import TYPE_CHECKING, Callable
3
+ import enum
4
+ import math
5
+ import torch
6
+ import numpy as np
7
+ import itertools
8
+ import logging
9
+
10
+ if TYPE_CHECKING:
11
+ from comfy.model_patcher import ModelPatcher, PatcherInjection
12
+ from comfy.model_base import BaseModel
13
+ from comfy.sd import CLIP
14
+ import comfy.lora
15
+ import comfy.model_management
16
+ import comfy.patcher_extension
17
+ from node_helpers import conditioning_set_values
18
+
19
+ # #######################################################################################################
20
+ # Hooks explanation
21
+ # -------------------
22
+ # The purpose of hooks is to allow conds to influence sampling without the need for ComfyUI core code to
23
+ # make explicit special cases like it does for ControlNet and GLIGEN.
24
+ #
25
+ # This is necessary for nodes/features that are intended for use with masked or scheduled conds, or those
26
+ # that should run special code when a 'marked' cond is used in sampling.
27
+ # #######################################################################################################
28
+
29
+ class EnumHookMode(enum.Enum):
30
+ '''
31
+ Priority of hook memory optimization vs. speed, mostly related to WeightHooks.
32
+
33
+ MinVram: No caching will occur for any operations related to hooks.
34
+ MaxSpeed: Excess VRAM (and RAM, once VRAM is sufficiently depleted) will be used to cache hook weights when switching hook groups.
35
+ '''
36
+ MinVram = "minvram"
37
+ MaxSpeed = "maxspeed"
38
+
39
+ class EnumHookType(enum.Enum):
40
+ '''
41
+ Hook types, each of which has different expected behavior.
42
+ '''
43
+ Weight = "weight"
44
+ ObjectPatch = "object_patch"
45
+ AdditionalModels = "add_models"
46
+ TransformerOptions = "transformer_options"
47
+ Injections = "add_injections"
48
+
49
+ class EnumWeightTarget(enum.Enum):
50
+ Model = "model"
51
+ Clip = "clip"
52
+
53
+ class EnumHookScope(enum.Enum):
54
+ '''
55
+ Determines if hook should be limited in its influence over sampling.
56
+
57
+ AllConditioning: hook will affect all conds used in sampling.
58
+ HookedOnly: hook will only affect the conds it was attached to.
59
+ '''
60
+ AllConditioning = "all_conditioning"
61
+ HookedOnly = "hooked_only"
62
+
63
+
64
+ class _HookRef:
65
+ pass
66
+
67
+
68
+ def default_should_register(hook: Hook, model: ModelPatcher, model_options: dict, target_dict: dict[str], registered: HookGroup):
69
+ '''Example for how custom_should_register function can look like.'''
70
+ return True
71
+
72
+
73
+ def create_target_dict(target: EnumWeightTarget=None, **kwargs) -> dict[str]:
74
+ '''Creates base dictionary for use with Hooks' target param.'''
75
+ d = {}
76
+ if target is not None:
77
+ d['target'] = target
78
+ d.update(kwargs)
79
+ return d
80
+
81
+
82
+ class Hook:
83
+ def __init__(self, hook_type: EnumHookType=None, hook_ref: _HookRef=None, hook_id: str=None,
84
+ hook_keyframe: HookKeyframeGroup=None, hook_scope=EnumHookScope.AllConditioning):
85
+ self.hook_type = hook_type
86
+ '''Enum identifying the general class of this hook.'''
87
+ self.hook_ref = hook_ref if hook_ref else _HookRef()
88
+ '''Reference shared between hook clones that have the same value. Should NOT be modified.'''
89
+ self.hook_id = hook_id
90
+ '''Optional string ID to identify hook; useful if need to consolidate duplicates at registration time.'''
91
+ self.hook_keyframe = hook_keyframe if hook_keyframe else HookKeyframeGroup()
92
+ '''Keyframe storage that can be referenced to get strength for current sampling step.'''
93
+ self.hook_scope = hook_scope
94
+ '''Scope of where this hook should apply in terms of the conds used in sampling run.'''
95
+ self.custom_should_register = default_should_register
96
+ '''Can be overriden with a compatible function to decide if this hook should be registered without the need to override .should_register'''
97
+
98
+ @property
99
+ def strength(self):
100
+ return self.hook_keyframe.strength
101
+
102
+ def initialize_timesteps(self, model: BaseModel):
103
+ self.reset()
104
+ self.hook_keyframe.initialize_timesteps(model)
105
+
106
+ def reset(self):
107
+ self.hook_keyframe.reset()
108
+
109
+ def clone(self):
110
+ c: Hook = self.__class__()
111
+ c.hook_type = self.hook_type
112
+ c.hook_ref = self.hook_ref
113
+ c.hook_id = self.hook_id
114
+ c.hook_keyframe = self.hook_keyframe
115
+ c.hook_scope = self.hook_scope
116
+ c.custom_should_register = self.custom_should_register
117
+ return c
118
+
119
+ def should_register(self, model: ModelPatcher, model_options: dict, target_dict: dict[str], registered: HookGroup):
120
+ return self.custom_should_register(self, model, model_options, target_dict, registered)
121
+
122
+ def add_hook_patches(self, model: ModelPatcher, model_options: dict, target_dict: dict[str], registered: HookGroup):
123
+ raise NotImplementedError("add_hook_patches should be defined for Hook subclasses")
124
+
125
+ def __eq__(self, other: Hook):
126
+ return self.__class__ == other.__class__ and self.hook_ref == other.hook_ref
127
+
128
+ def __hash__(self):
129
+ return hash(self.hook_ref)
130
+
131
+ class WeightHook(Hook):
132
+ '''
133
+ Hook responsible for tracking weights to be applied to some model/clip.
134
+
135
+ Note, value of hook_scope is ignored and is treated as HookedOnly.
136
+ '''
137
+ def __init__(self, strength_model=1.0, strength_clip=1.0):
138
+ super().__init__(hook_type=EnumHookType.Weight, hook_scope=EnumHookScope.HookedOnly)
139
+ self.weights: dict = None
140
+ self.weights_clip: dict = None
141
+ self.need_weight_init = True
142
+ self._strength_model = strength_model
143
+ self._strength_clip = strength_clip
144
+ self.hook_scope = EnumHookScope.HookedOnly # this value does not matter for WeightHooks, just for docs
145
+
146
+ @property
147
+ def strength_model(self):
148
+ return self._strength_model * self.strength
149
+
150
+ @property
151
+ def strength_clip(self):
152
+ return self._strength_clip * self.strength
153
+
154
+ def add_hook_patches(self, model: ModelPatcher, model_options: dict, target_dict: dict[str], registered: HookGroup):
155
+ if not self.should_register(model, model_options, target_dict, registered):
156
+ return False
157
+ weights = None
158
+
159
+ target = target_dict.get('target', None)
160
+ if target == EnumWeightTarget.Clip:
161
+ strength = self._strength_clip
162
+ else:
163
+ strength = self._strength_model
164
+
165
+ if self.need_weight_init:
166
+ key_map = {}
167
+ if target == EnumWeightTarget.Clip:
168
+ key_map = comfy.lora.model_lora_keys_clip(model.model, key_map)
169
+ else:
170
+ key_map = comfy.lora.model_lora_keys_unet(model.model, key_map)
171
+ weights = comfy.lora.load_lora(self.weights, key_map, log_missing=False)
172
+ else:
173
+ if target == EnumWeightTarget.Clip:
174
+ weights = self.weights_clip
175
+ else:
176
+ weights = self.weights
177
+ model.add_hook_patches(hook=self, patches=weights, strength_patch=strength)
178
+ registered.add(self)
179
+ return True
180
+ # TODO: add logs about any keys that were not applied
181
+
182
+ def clone(self):
183
+ c: WeightHook = super().clone()
184
+ c.weights = self.weights
185
+ c.weights_clip = self.weights_clip
186
+ c.need_weight_init = self.need_weight_init
187
+ c._strength_model = self._strength_model
188
+ c._strength_clip = self._strength_clip
189
+ return c
190
+
191
+ class ObjectPatchHook(Hook):
192
+ def __init__(self, object_patches: dict[str]=None,
193
+ hook_scope=EnumHookScope.AllConditioning):
194
+ super().__init__(hook_type=EnumHookType.ObjectPatch)
195
+ self.object_patches = object_patches
196
+ self.hook_scope = hook_scope
197
+
198
+ def clone(self):
199
+ c: ObjectPatchHook = super().clone()
200
+ c.object_patches = self.object_patches
201
+ return c
202
+
203
+ def add_hook_patches(self, model: ModelPatcher, model_options: dict, target_dict: dict[str], registered: HookGroup):
204
+ raise NotImplementedError("ObjectPatchHook is not supported yet in ComfyUI.")
205
+
206
+ class AdditionalModelsHook(Hook):
207
+ '''
208
+ Hook responsible for telling model management any additional models that should be loaded.
209
+
210
+ Note, value of hook_scope is ignored and is treated as AllConditioning.
211
+ '''
212
+ def __init__(self, models: list[ModelPatcher]=None, key: str=None):
213
+ super().__init__(hook_type=EnumHookType.AdditionalModels)
214
+ self.models = models
215
+ self.key = key
216
+
217
+ def clone(self):
218
+ c: AdditionalModelsHook = super().clone()
219
+ c.models = self.models.copy() if self.models else self.models
220
+ c.key = self.key
221
+ return c
222
+
223
+ def add_hook_patches(self, model: ModelPatcher, model_options: dict, target_dict: dict[str], registered: HookGroup):
224
+ if not self.should_register(model, model_options, target_dict, registered):
225
+ return False
226
+ registered.add(self)
227
+ return True
228
+
229
+ class TransformerOptionsHook(Hook):
230
+ '''
231
+ Hook responsible for adding wrappers, callbacks, patches, or anything else related to transformer_options.
232
+ '''
233
+ def __init__(self, transformers_dict: dict[str, dict[str, dict[str, list[Callable]]]]=None,
234
+ hook_scope=EnumHookScope.AllConditioning):
235
+ super().__init__(hook_type=EnumHookType.TransformerOptions)
236
+ self.transformers_dict = transformers_dict
237
+ self.hook_scope = hook_scope
238
+ self._skip_adding = False
239
+ '''Internal value used to avoid double load of transformer_options when hook_scope is AllConditioning.'''
240
+
241
+ def clone(self):
242
+ c: TransformerOptionsHook = super().clone()
243
+ c.transformers_dict = self.transformers_dict
244
+ c._skip_adding = self._skip_adding
245
+ return c
246
+
247
+ def add_hook_patches(self, model: ModelPatcher, model_options: dict, target_dict: dict[str], registered: HookGroup):
248
+ if not self.should_register(model, model_options, target_dict, registered):
249
+ return False
250
+ # NOTE: to_load_options will be used to manually load patches/wrappers/callbacks from hooks
251
+ self._skip_adding = False
252
+ if self.hook_scope == EnumHookScope.AllConditioning:
253
+ add_model_options = {"transformer_options": self.transformers_dict,
254
+ "to_load_options": self.transformers_dict}
255
+ # skip_adding if included in AllConditioning to avoid double loading
256
+ self._skip_adding = True
257
+ else:
258
+ add_model_options = {"to_load_options": self.transformers_dict}
259
+ registered.add(self)
260
+ comfy.patcher_extension.merge_nested_dicts(model_options, add_model_options, copy_dict1=False)
261
+ return True
262
+
263
+ def on_apply_hooks(self, model: ModelPatcher, transformer_options: dict[str]):
264
+ if not self._skip_adding:
265
+ comfy.patcher_extension.merge_nested_dicts(transformer_options, self.transformers_dict, copy_dict1=False)
266
+
267
+ WrapperHook = TransformerOptionsHook
268
+ '''Only here for backwards compatibility, WrapperHook is identical to TransformerOptionsHook.'''
269
+
270
+ class InjectionsHook(Hook):
271
+ def __init__(self, key: str=None, injections: list[PatcherInjection]=None,
272
+ hook_scope=EnumHookScope.AllConditioning):
273
+ super().__init__(hook_type=EnumHookType.Injections)
274
+ self.key = key
275
+ self.injections = injections
276
+ self.hook_scope = hook_scope
277
+
278
+ def clone(self):
279
+ c: InjectionsHook = super().clone()
280
+ c.key = self.key
281
+ c.injections = self.injections.copy() if self.injections else self.injections
282
+ return c
283
+
284
+ def add_hook_patches(self, model: ModelPatcher, model_options: dict, target_dict: dict[str], registered: HookGroup):
285
+ raise NotImplementedError("InjectionsHook is not supported yet in ComfyUI.")
286
+
287
+ class HookGroup:
288
+ '''
289
+ Stores groups of hooks, and allows them to be queried by type.
290
+
291
+ To prevent breaking their functionality, never modify the underlying self.hooks or self._hook_dict vars directly;
292
+ always use the provided functions on HookGroup.
293
+ '''
294
+ def __init__(self):
295
+ self.hooks: list[Hook] = []
296
+ self._hook_dict: dict[EnumHookType, list[Hook]] = {}
297
+
298
+ def __len__(self):
299
+ return len(self.hooks)
300
+
301
+ def add(self, hook: Hook):
302
+ if hook not in self.hooks:
303
+ self.hooks.append(hook)
304
+ self._hook_dict.setdefault(hook.hook_type, []).append(hook)
305
+
306
+ def remove(self, hook: Hook):
307
+ if hook in self.hooks:
308
+ self.hooks.remove(hook)
309
+ self._hook_dict[hook.hook_type].remove(hook)
310
+
311
+ def get_type(self, hook_type: EnumHookType):
312
+ return self._hook_dict.get(hook_type, [])
313
+
314
+ def contains(self, hook: Hook):
315
+ return hook in self.hooks
316
+
317
+ def is_subset_of(self, other: HookGroup):
318
+ self_hooks = set(self.hooks)
319
+ other_hooks = set(other.hooks)
320
+ return self_hooks.issubset(other_hooks)
321
+
322
+ def new_with_common_hooks(self, other: HookGroup):
323
+ c = HookGroup()
324
+ for hook in self.hooks:
325
+ if other.contains(hook):
326
+ c.add(hook.clone())
327
+ return c
328
+
329
+ def clone(self):
330
+ c = HookGroup()
331
+ for hook in self.hooks:
332
+ c.add(hook.clone())
333
+ return c
334
+
335
+ def clone_and_combine(self, other: HookGroup):
336
+ c = self.clone()
337
+ if other is not None:
338
+ for hook in other.hooks:
339
+ c.add(hook.clone())
340
+ return c
341
+
342
+ def set_keyframes_on_hooks(self, hook_kf: HookKeyframeGroup):
343
+ if hook_kf is None:
344
+ hook_kf = HookKeyframeGroup()
345
+ else:
346
+ hook_kf = hook_kf.clone()
347
+ for hook in self.hooks:
348
+ hook.hook_keyframe = hook_kf
349
+
350
+ def get_hooks_for_clip_schedule(self):
351
+ scheduled_hooks: dict[WeightHook, list[tuple[tuple[float,float], HookKeyframe]]] = {}
352
+ # only care about WeightHooks, for now
353
+ for hook in self.get_type(EnumHookType.Weight):
354
+ hook: WeightHook
355
+ hook_schedule = []
356
+ # if no hook keyframes, assign default value
357
+ if len(hook.hook_keyframe.keyframes) == 0:
358
+ hook_schedule.append(((0.0, 1.0), None))
359
+ scheduled_hooks[hook] = hook_schedule
360
+ continue
361
+ # find ranges of values
362
+ prev_keyframe = hook.hook_keyframe.keyframes[0]
363
+ for keyframe in hook.hook_keyframe.keyframes:
364
+ if keyframe.start_percent > prev_keyframe.start_percent and not math.isclose(keyframe.strength, prev_keyframe.strength):
365
+ hook_schedule.append(((prev_keyframe.start_percent, keyframe.start_percent), prev_keyframe))
366
+ prev_keyframe = keyframe
367
+ elif keyframe.start_percent == prev_keyframe.start_percent:
368
+ prev_keyframe = keyframe
369
+ # create final range, assuming last start_percent was not 1.0
370
+ if not math.isclose(prev_keyframe.start_percent, 1.0):
371
+ hook_schedule.append(((prev_keyframe.start_percent, 1.0), prev_keyframe))
372
+ scheduled_hooks[hook] = hook_schedule
373
+ # hooks should not have their schedules in a list of tuples
374
+ all_ranges: list[tuple[float, float]] = []
375
+ for range_kfs in scheduled_hooks.values():
376
+ for t_range, keyframe in range_kfs:
377
+ all_ranges.append(t_range)
378
+ # turn list of ranges into boundaries
379
+ boundaries_set = set(itertools.chain.from_iterable(all_ranges))
380
+ boundaries_set.add(0.0)
381
+ boundaries = sorted(boundaries_set)
382
+ real_ranges = [(boundaries[i], boundaries[i + 1]) for i in range(len(boundaries) - 1)]
383
+ # with real ranges defined, give appropriate hooks w/ keyframes for each range
384
+ scheduled_keyframes: list[tuple[tuple[float,float], list[tuple[WeightHook, HookKeyframe]]]] = []
385
+ for t_range in real_ranges:
386
+ hooks_schedule = []
387
+ for hook, val in scheduled_hooks.items():
388
+ keyframe = None
389
+ # check if is a keyframe that works for the current t_range
390
+ for stored_range, stored_kf in val:
391
+ # if stored start is less than current end, then fits - give it assigned keyframe
392
+ if stored_range[0] < t_range[1] and stored_range[1] > t_range[0]:
393
+ keyframe = stored_kf
394
+ break
395
+ hooks_schedule.append((hook, keyframe))
396
+ scheduled_keyframes.append((t_range, hooks_schedule))
397
+ return scheduled_keyframes
398
+
399
+ def reset(self):
400
+ for hook in self.hooks:
401
+ hook.reset()
402
+
403
+ @staticmethod
404
+ def combine_all_hooks(hooks_list: list[HookGroup], require_count=0) -> HookGroup:
405
+ actual: list[HookGroup] = []
406
+ for group in hooks_list:
407
+ if group is not None:
408
+ actual.append(group)
409
+ if len(actual) < require_count:
410
+ raise Exception(f"Need at least {require_count} hooks to combine, but only had {len(actual)}.")
411
+ # if no hooks, then return None
412
+ if len(actual) == 0:
413
+ return None
414
+ # if only 1 hook, just return itself without cloning
415
+ elif len(actual) == 1:
416
+ return actual[0]
417
+ final_hook: HookGroup = None
418
+ for hook in actual:
419
+ if final_hook is None:
420
+ final_hook = hook.clone()
421
+ else:
422
+ final_hook = final_hook.clone_and_combine(hook)
423
+ return final_hook
424
+
425
+
426
+ class HookKeyframe:
427
+ def __init__(self, strength: float, start_percent=0.0, guarantee_steps=1):
428
+ self.strength = strength
429
+ # scheduling
430
+ self.start_percent = float(start_percent)
431
+ self.start_t = 999999999.9
432
+ self.guarantee_steps = guarantee_steps
433
+
434
+ def get_effective_guarantee_steps(self, max_sigma: torch.Tensor):
435
+ '''If keyframe starts before current sampling range (max_sigma), treat as 0.'''
436
+ if self.start_t > max_sigma:
437
+ return 0
438
+ return self.guarantee_steps
439
+
440
+ def clone(self):
441
+ c = HookKeyframe(strength=self.strength,
442
+ start_percent=self.start_percent, guarantee_steps=self.guarantee_steps)
443
+ c.start_t = self.start_t
444
+ return c
445
+
446
+ class HookKeyframeGroup:
447
+ def __init__(self):
448
+ self.keyframes: list[HookKeyframe] = []
449
+ self._current_keyframe: HookKeyframe = None
450
+ self._current_used_steps = 0
451
+ self._current_index = 0
452
+ self._current_strength = None
453
+ self._curr_t = -1.
454
+
455
+ # properties shadow those of HookWeightsKeyframe
456
+ @property
457
+ def strength(self):
458
+ if self._current_keyframe is not None:
459
+ return self._current_keyframe.strength
460
+ return 1.0
461
+
462
+ def reset(self):
463
+ self._current_keyframe = None
464
+ self._current_used_steps = 0
465
+ self._current_index = 0
466
+ self._current_strength = None
467
+ self.curr_t = -1.
468
+ self._set_first_as_current()
469
+
470
+ def add(self, keyframe: HookKeyframe):
471
+ # add to end of list, then sort
472
+ self.keyframes.append(keyframe)
473
+ self.keyframes = get_sorted_list_via_attr(self.keyframes, "start_percent")
474
+ self._set_first_as_current()
475
+
476
+ def _set_first_as_current(self):
477
+ if len(self.keyframes) > 0:
478
+ self._current_keyframe = self.keyframes[0]
479
+ else:
480
+ self._current_keyframe = None
481
+
482
+ def has_guarantee_steps(self):
483
+ for kf in self.keyframes:
484
+ if kf.guarantee_steps > 0:
485
+ return True
486
+ return False
487
+
488
+ def has_index(self, index: int):
489
+ return index >= 0 and index < len(self.keyframes)
490
+
491
+ def is_empty(self):
492
+ return len(self.keyframes) == 0
493
+
494
+ def clone(self):
495
+ c = HookKeyframeGroup()
496
+ for keyframe in self.keyframes:
497
+ c.keyframes.append(keyframe.clone())
498
+ c._set_first_as_current()
499
+ return c
500
+
501
+ def initialize_timesteps(self, model: BaseModel):
502
+ for keyframe in self.keyframes:
503
+ keyframe.start_t = model.model_sampling.percent_to_sigma(keyframe.start_percent)
504
+
505
+ def prepare_current_keyframe(self, curr_t: float, transformer_options: dict[str, torch.Tensor]) -> bool:
506
+ if self.is_empty():
507
+ return False
508
+ if curr_t == self._curr_t:
509
+ return False
510
+ max_sigma = torch.max(transformer_options["sample_sigmas"])
511
+ prev_index = self._current_index
512
+ prev_strength = self._current_strength
513
+ # if met guaranteed steps, look for next keyframe in case need to switch
514
+ if self._current_used_steps >= self._current_keyframe.get_effective_guarantee_steps(max_sigma):
515
+ # if has next index, loop through and see if need to switch
516
+ if self.has_index(self._current_index+1):
517
+ for i in range(self._current_index+1, len(self.keyframes)):
518
+ eval_c = self.keyframes[i]
519
+ # check if start_t is greater or equal to curr_t
520
+ # NOTE: t is in terms of sigmas, not percent, so bigger number = earlier step in sampling
521
+ if eval_c.start_t >= curr_t:
522
+ self._current_index = i
523
+ self._current_strength = eval_c.strength
524
+ self._current_keyframe = eval_c
525
+ self._current_used_steps = 0
526
+ # if guarantee_steps greater than zero, stop searching for other keyframes
527
+ if self._current_keyframe.get_effective_guarantee_steps(max_sigma) > 0:
528
+ break
529
+ # if eval_c is outside the percent range, stop looking further
530
+ else: break
531
+ # update steps current context is used
532
+ self._current_used_steps += 1
533
+ # update current timestep this was performed on
534
+ self._curr_t = curr_t
535
+ # return True if keyframe changed, False if no change
536
+ return prev_index != self._current_index and prev_strength != self._current_strength
537
+
538
+
539
+ class InterpolationMethod:
540
+ LINEAR = "linear"
541
+ EASE_IN = "ease_in"
542
+ EASE_OUT = "ease_out"
543
+ EASE_IN_OUT = "ease_in_out"
544
+
545
+ _LIST = [LINEAR, EASE_IN, EASE_OUT, EASE_IN_OUT]
546
+
547
+ @classmethod
548
+ def get_weights(cls, num_from: float, num_to: float, length: int, method: str, reverse=False):
549
+ diff = num_to - num_from
550
+ if method == cls.LINEAR:
551
+ weights = torch.linspace(num_from, num_to, length)
552
+ elif method == cls.EASE_IN:
553
+ index = torch.linspace(0, 1, length)
554
+ weights = diff * np.power(index, 2) + num_from
555
+ elif method == cls.EASE_OUT:
556
+ index = torch.linspace(0, 1, length)
557
+ weights = diff * (1 - np.power(1 - index, 2)) + num_from
558
+ elif method == cls.EASE_IN_OUT:
559
+ index = torch.linspace(0, 1, length)
560
+ weights = diff * ((1 - np.cos(index * np.pi)) / 2) + num_from
561
+ else:
562
+ raise ValueError(f"Unrecognized interpolation method '{method}'.")
563
+ if reverse:
564
+ weights = weights.flip(dims=(0,))
565
+ return weights
566
+
567
+ def get_sorted_list_via_attr(objects: list, attr: str) -> list:
568
+ if not objects:
569
+ return objects
570
+ elif len(objects) <= 1:
571
+ return [x for x in objects]
572
+ # now that we know we have to sort, do it following these rules:
573
+ # a) if objects have same value of attribute, maintain their relative order
574
+ # b) perform sorting of the groups of objects with same attributes
575
+ unique_attrs = {}
576
+ for o in objects:
577
+ val_attr = getattr(o, attr)
578
+ attr_list: list = unique_attrs.get(val_attr, list())
579
+ attr_list.append(o)
580
+ if val_attr not in unique_attrs:
581
+ unique_attrs[val_attr] = attr_list
582
+ # now that we have the unique attr values grouped together in relative order, sort them by key
583
+ sorted_attrs = dict(sorted(unique_attrs.items()))
584
+ # now flatten out the dict into a list to return
585
+ sorted_list = []
586
+ for object_list in sorted_attrs.values():
587
+ sorted_list.extend(object_list)
588
+ return sorted_list
589
+
590
+ def create_transformer_options_from_hooks(model: ModelPatcher, hooks: HookGroup, transformer_options: dict[str]=None):
591
+ # if no hooks or is not a ModelPatcher for sampling, return empty dict
592
+ if hooks is None or model.is_clip:
593
+ return {}
594
+ if transformer_options is None:
595
+ transformer_options = {}
596
+ for hook in hooks.get_type(EnumHookType.TransformerOptions):
597
+ hook: TransformerOptionsHook
598
+ hook.on_apply_hooks(model, transformer_options)
599
+ return transformer_options
600
+
601
+ def create_hook_lora(lora: dict[str, torch.Tensor], strength_model: float, strength_clip: float):
602
+ hook_group = HookGroup()
603
+ hook = WeightHook(strength_model=strength_model, strength_clip=strength_clip)
604
+ hook_group.add(hook)
605
+ hook.weights = lora
606
+ return hook_group
607
+
608
+ def create_hook_model_as_lora(weights_model, weights_clip, strength_model: float, strength_clip: float):
609
+ hook_group = HookGroup()
610
+ hook = WeightHook(strength_model=strength_model, strength_clip=strength_clip)
611
+ hook_group.add(hook)
612
+ patches_model = None
613
+ patches_clip = None
614
+ if weights_model is not None:
615
+ patches_model = {}
616
+ for key in weights_model:
617
+ patches_model[key] = ("model_as_lora", (weights_model[key],))
618
+ if weights_clip is not None:
619
+ patches_clip = {}
620
+ for key in weights_clip:
621
+ patches_clip[key] = ("model_as_lora", (weights_clip[key],))
622
+ hook.weights = patches_model
623
+ hook.weights_clip = patches_clip
624
+ hook.need_weight_init = False
625
+ return hook_group
626
+
627
+ def get_patch_weights_from_model(model: ModelPatcher, discard_model_sampling=True):
628
+ if model is None:
629
+ return None
630
+ patches_model: dict[str, torch.Tensor] = model.model.state_dict()
631
+ if discard_model_sampling:
632
+ # do not include ANY model_sampling components of the model that should act as a patch
633
+ for key in list(patches_model.keys()):
634
+ if key.startswith("model_sampling"):
635
+ patches_model.pop(key, None)
636
+ return patches_model
637
+
638
+ # NOTE: this function shows how to register weight hooks directly on the ModelPatchers
639
+ def load_hook_lora_for_models(model: ModelPatcher, clip: CLIP, lora: dict[str, torch.Tensor],
640
+ strength_model: float, strength_clip: float):
641
+ key_map = {}
642
+ if model is not None:
643
+ key_map = comfy.lora.model_lora_keys_unet(model.model, key_map)
644
+ if clip is not None:
645
+ key_map = comfy.lora.model_lora_keys_clip(clip.cond_stage_model, key_map)
646
+
647
+ hook_group = HookGroup()
648
+ hook = WeightHook()
649
+ hook_group.add(hook)
650
+ loaded: dict[str] = comfy.lora.load_lora(lora, key_map)
651
+ if model is not None:
652
+ new_modelpatcher = model.clone()
653
+ k = new_modelpatcher.add_hook_patches(hook=hook, patches=loaded, strength_patch=strength_model)
654
+ else:
655
+ k = ()
656
+ new_modelpatcher = None
657
+
658
+ if clip is not None:
659
+ new_clip = clip.clone()
660
+ k1 = new_clip.patcher.add_hook_patches(hook=hook, patches=loaded, strength_patch=strength_clip)
661
+ else:
662
+ k1 = ()
663
+ new_clip = None
664
+ k = set(k)
665
+ k1 = set(k1)
666
+ for x in loaded:
667
+ if (x not in k) and (x not in k1):
668
+ logging.warning(f"NOT LOADED {x}")
669
+ return (new_modelpatcher, new_clip, hook_group)
670
+
671
+ def _combine_hooks_from_values(c_dict: dict[str, HookGroup], values: dict[str, HookGroup], cache: dict[tuple[HookGroup, HookGroup], HookGroup]):
672
+ hooks_key = 'hooks'
673
+ # if hooks only exist in one dict, do what's needed so that it ends up in c_dict
674
+ if hooks_key not in values:
675
+ return
676
+ if hooks_key not in c_dict:
677
+ hooks_value = values.get(hooks_key, None)
678
+ if hooks_value is not None:
679
+ c_dict[hooks_key] = hooks_value
680
+ return
681
+ # otherwise, need to combine with minimum duplication via cache
682
+ hooks_tuple = (c_dict[hooks_key], values[hooks_key])
683
+ cached_hooks = cache.get(hooks_tuple, None)
684
+ if cached_hooks is None:
685
+ new_hooks = hooks_tuple[0].clone_and_combine(hooks_tuple[1])
686
+ cache[hooks_tuple] = new_hooks
687
+ c_dict[hooks_key] = new_hooks
688
+ else:
689
+ c_dict[hooks_key] = cache[hooks_tuple]
690
+
691
+ def conditioning_set_values_with_hooks(conditioning, values={}, append_hooks=True,
692
+ cache: dict[tuple[HookGroup, HookGroup], HookGroup]=None):
693
+ c = []
694
+ if cache is None:
695
+ cache = {}
696
+ for t in conditioning:
697
+ n = [t[0], t[1].copy()]
698
+ for k in values:
699
+ if append_hooks and k == 'hooks':
700
+ _combine_hooks_from_values(n[1], values, cache)
701
+ else:
702
+ n[1][k] = values[k]
703
+ c.append(n)
704
+
705
+ return c
706
+
707
+ def set_hooks_for_conditioning(cond, hooks: HookGroup, append_hooks=True, cache: dict[tuple[HookGroup, HookGroup], HookGroup]=None):
708
+ if hooks is None:
709
+ return cond
710
+ return conditioning_set_values_with_hooks(cond, {'hooks': hooks}, append_hooks=append_hooks, cache=cache)
711
+
712
+ def set_timesteps_for_conditioning(cond, timestep_range: tuple[float,float]):
713
+ if timestep_range is None:
714
+ return cond
715
+ return conditioning_set_values(cond, {"start_percent": timestep_range[0],
716
+ "end_percent": timestep_range[1]})
717
+
718
+ def set_mask_for_conditioning(cond, mask: torch.Tensor, set_cond_area: str, strength: float):
719
+ if mask is None:
720
+ return cond
721
+ set_area_to_bounds = False
722
+ if set_cond_area != 'default':
723
+ set_area_to_bounds = True
724
+ if len(mask.shape) < 3:
725
+ mask = mask.unsqueeze(0)
726
+ return conditioning_set_values(cond, {'mask': mask,
727
+ 'set_area_to_bounds': set_area_to_bounds,
728
+ 'mask_strength': strength})
729
+
730
+ def combine_conditioning(conds: list):
731
+ combined_conds = []
732
+ for cond in conds:
733
+ combined_conds.extend(cond)
734
+ return combined_conds
735
+
736
+ def combine_with_new_conds(conds: list, new_conds: list):
737
+ combined_conds = []
738
+ for c, new_c in zip(conds, new_conds):
739
+ combined_conds.append(combine_conditioning([c, new_c]))
740
+ return combined_conds
741
+
742
+ def set_conds_props(conds: list, strength: float, set_cond_area: str,
743
+ mask: torch.Tensor=None, hooks: HookGroup=None, timesteps_range: tuple[float,float]=None, append_hooks=True):
744
+ final_conds = []
745
+ cache = {}
746
+ for c in conds:
747
+ # first, apply lora_hook to conditioning, if provided
748
+ c = set_hooks_for_conditioning(c, hooks, append_hooks=append_hooks, cache=cache)
749
+ # next, apply mask to conditioning
750
+ c = set_mask_for_conditioning(cond=c, mask=mask, strength=strength, set_cond_area=set_cond_area)
751
+ # apply timesteps, if present
752
+ c = set_timesteps_for_conditioning(cond=c, timestep_range=timesteps_range)
753
+ # finally, apply mask to conditioning and store
754
+ final_conds.append(c)
755
+ return final_conds
756
+
757
+ def set_conds_props_and_combine(conds: list, new_conds: list, strength: float=1.0, set_cond_area: str="default",
758
+ mask: torch.Tensor=None, hooks: HookGroup=None, timesteps_range: tuple[float,float]=None, append_hooks=True):
759
+ combined_conds = []
760
+ cache = {}
761
+ for c, masked_c in zip(conds, new_conds):
762
+ # first, apply lora_hook to new conditioning, if provided
763
+ masked_c = set_hooks_for_conditioning(masked_c, hooks, append_hooks=append_hooks, cache=cache)
764
+ # next, apply mask to new conditioning, if provided
765
+ masked_c = set_mask_for_conditioning(cond=masked_c, mask=mask, set_cond_area=set_cond_area, strength=strength)
766
+ # apply timesteps, if present
767
+ masked_c = set_timesteps_for_conditioning(cond=masked_c, timestep_range=timesteps_range)
768
+ # finally, combine with existing conditioning and store
769
+ combined_conds.append(combine_conditioning([c, masked_c]))
770
+ return combined_conds
771
+
772
+ def set_default_conds_and_combine(conds: list, new_conds: list,
773
+ hooks: HookGroup=None, timesteps_range: tuple[float,float]=None, append_hooks=True):
774
+ combined_conds = []
775
+ cache = {}
776
+ for c, new_c in zip(conds, new_conds):
777
+ # first, apply lora_hook to new conditioning, if provided
778
+ new_c = set_hooks_for_conditioning(new_c, hooks, append_hooks=append_hooks, cache=cache)
779
+ # next, add default_cond key to cond so that during sampling, it can be identified
780
+ new_c = conditioning_set_values(new_c, {'default': True})
781
+ # apply timesteps, if present
782
+ new_c = set_timesteps_for_conditioning(cond=new_c, timestep_range=timesteps_range)
783
+ # finally, combine with existing conditioning and store
784
+ combined_conds.append(combine_conditioning([c, new_c]))
785
+ return combined_conds
comfy/image_encoders/dino2.py ADDED
@@ -0,0 +1,141 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from comfy.text_encoders.bert import BertAttention
3
+ import comfy.model_management
4
+ from comfy.ldm.modules.attention import optimized_attention_for_device
5
+
6
+
7
+ class Dino2AttentionOutput(torch.nn.Module):
8
+ def __init__(self, input_dim, output_dim, layer_norm_eps, dtype, device, operations):
9
+ super().__init__()
10
+ self.dense = operations.Linear(input_dim, output_dim, dtype=dtype, device=device)
11
+
12
+ def forward(self, x):
13
+ return self.dense(x)
14
+
15
+
16
+ class Dino2AttentionBlock(torch.nn.Module):
17
+ def __init__(self, embed_dim, heads, layer_norm_eps, dtype, device, operations):
18
+ super().__init__()
19
+ self.attention = BertAttention(embed_dim, heads, dtype, device, operations)
20
+ self.output = Dino2AttentionOutput(embed_dim, embed_dim, layer_norm_eps, dtype, device, operations)
21
+
22
+ def forward(self, x, mask, optimized_attention):
23
+ return self.output(self.attention(x, mask, optimized_attention))
24
+
25
+
26
+ class LayerScale(torch.nn.Module):
27
+ def __init__(self, dim, dtype, device, operations):
28
+ super().__init__()
29
+ self.lambda1 = torch.nn.Parameter(torch.empty(dim, device=device, dtype=dtype))
30
+
31
+ def forward(self, x):
32
+ return x * comfy.model_management.cast_to_device(self.lambda1, x.device, x.dtype)
33
+
34
+
35
+ class SwiGLUFFN(torch.nn.Module):
36
+ def __init__(self, dim, dtype, device, operations):
37
+ super().__init__()
38
+ in_features = out_features = dim
39
+ hidden_features = int(dim * 4)
40
+ hidden_features = (int(hidden_features * 2 / 3) + 7) // 8 * 8
41
+
42
+ self.weights_in = operations.Linear(in_features, 2 * hidden_features, bias=True, device=device, dtype=dtype)
43
+ self.weights_out = operations.Linear(hidden_features, out_features, bias=True, device=device, dtype=dtype)
44
+
45
+ def forward(self, x):
46
+ x = self.weights_in(x)
47
+ x1, x2 = x.chunk(2, dim=-1)
48
+ x = torch.nn.functional.silu(x1) * x2
49
+ return self.weights_out(x)
50
+
51
+
52
+ class Dino2Block(torch.nn.Module):
53
+ def __init__(self, dim, num_heads, layer_norm_eps, dtype, device, operations):
54
+ super().__init__()
55
+ self.attention = Dino2AttentionBlock(dim, num_heads, layer_norm_eps, dtype, device, operations)
56
+ self.layer_scale1 = LayerScale(dim, dtype, device, operations)
57
+ self.layer_scale2 = LayerScale(dim, dtype, device, operations)
58
+ self.mlp = SwiGLUFFN(dim, dtype, device, operations)
59
+ self.norm1 = operations.LayerNorm(dim, eps=layer_norm_eps, dtype=dtype, device=device)
60
+ self.norm2 = operations.LayerNorm(dim, eps=layer_norm_eps, dtype=dtype, device=device)
61
+
62
+ def forward(self, x, optimized_attention):
63
+ x = x + self.layer_scale1(self.attention(self.norm1(x), None, optimized_attention))
64
+ x = x + self.layer_scale2(self.mlp(self.norm2(x)))
65
+ return x
66
+
67
+
68
+ class Dino2Encoder(torch.nn.Module):
69
+ def __init__(self, dim, num_heads, layer_norm_eps, num_layers, dtype, device, operations):
70
+ super().__init__()
71
+ self.layer = torch.nn.ModuleList([Dino2Block(dim, num_heads, layer_norm_eps, dtype, device, operations) for _ in range(num_layers)])
72
+
73
+ def forward(self, x, intermediate_output=None):
74
+ optimized_attention = optimized_attention_for_device(x.device, False, small_input=True)
75
+
76
+ if intermediate_output is not None:
77
+ if intermediate_output < 0:
78
+ intermediate_output = len(self.layer) + intermediate_output
79
+
80
+ intermediate = None
81
+ for i, l in enumerate(self.layer):
82
+ x = l(x, optimized_attention)
83
+ if i == intermediate_output:
84
+ intermediate = x.clone()
85
+ return x, intermediate
86
+
87
+
88
+ class Dino2PatchEmbeddings(torch.nn.Module):
89
+ def __init__(self, dim, num_channels=3, patch_size=14, image_size=518, dtype=None, device=None, operations=None):
90
+ super().__init__()
91
+ self.projection = operations.Conv2d(
92
+ in_channels=num_channels,
93
+ out_channels=dim,
94
+ kernel_size=patch_size,
95
+ stride=patch_size,
96
+ bias=True,
97
+ dtype=dtype,
98
+ device=device
99
+ )
100
+
101
+ def forward(self, pixel_values):
102
+ return self.projection(pixel_values).flatten(2).transpose(1, 2)
103
+
104
+
105
+ class Dino2Embeddings(torch.nn.Module):
106
+ def __init__(self, dim, dtype, device, operations):
107
+ super().__init__()
108
+ patch_size = 14
109
+ image_size = 518
110
+
111
+ self.patch_embeddings = Dino2PatchEmbeddings(dim, patch_size=patch_size, image_size=image_size, dtype=dtype, device=device, operations=operations)
112
+ self.position_embeddings = torch.nn.Parameter(torch.empty(1, (image_size // patch_size) ** 2 + 1, dim, dtype=dtype, device=device))
113
+ self.cls_token = torch.nn.Parameter(torch.empty(1, 1, dim, dtype=dtype, device=device))
114
+ self.mask_token = torch.nn.Parameter(torch.empty(1, dim, dtype=dtype, device=device))
115
+
116
+ def forward(self, pixel_values):
117
+ x = self.patch_embeddings(pixel_values)
118
+ # TODO: mask_token?
119
+ x = torch.cat((self.cls_token.to(device=x.device, dtype=x.dtype).expand(x.shape[0], -1, -1), x), dim=1)
120
+ x = x + comfy.model_management.cast_to_device(self.position_embeddings, x.device, x.dtype)
121
+ return x
122
+
123
+
124
+ class Dinov2Model(torch.nn.Module):
125
+ def __init__(self, config_dict, dtype, device, operations):
126
+ super().__init__()
127
+ num_layers = config_dict["num_hidden_layers"]
128
+ dim = config_dict["hidden_size"]
129
+ heads = config_dict["num_attention_heads"]
130
+ layer_norm_eps = config_dict["layer_norm_eps"]
131
+
132
+ self.embeddings = Dino2Embeddings(dim, dtype, device, operations)
133
+ self.encoder = Dino2Encoder(dim, heads, layer_norm_eps, num_layers, dtype, device, operations)
134
+ self.layernorm = operations.LayerNorm(dim, eps=layer_norm_eps, dtype=dtype, device=device)
135
+
136
+ def forward(self, pixel_values, attention_mask=None, intermediate_output=None):
137
+ x = self.embeddings(pixel_values)
138
+ x, i = self.encoder(x, intermediate_output=intermediate_output)
139
+ x = self.layernorm(x)
140
+ pooled_output = x[:, 0, :]
141
+ return x, i, pooled_output, None