Nef Caballero commited on
Commit
753dcdd
·
1 Parent(s): 2589026

init commit

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +3 -0
  2. .gitignore +23 -0
  3. .python-version +1 -0
  4. CODEOWNERS +23 -0
  5. CONTRIBUTING.md +41 -0
  6. LICENSE +674 -0
  7. README.md +344 -0
  8. api_server/__init__.py +0 -0
  9. api_server/routes/__init__.py +0 -0
  10. api_server/routes/internal/README.md +3 -0
  11. api_server/routes/internal/__init__.py +0 -0
  12. api_server/routes/internal/internal_routes.py +75 -0
  13. api_server/services/__init__.py +0 -0
  14. api_server/services/file_service.py +13 -0
  15. api_server/services/terminal_service.py +60 -0
  16. api_server/utils/file_operations.py +42 -0
  17. app.py +397 -0
  18. app/__init__.py +0 -0
  19. app/app_settings.py +59 -0
  20. app/custom_node_manager.py +34 -0
  21. app/frontend_management.py +204 -0
  22. app/logger.py +84 -0
  23. app/model_manager.py +184 -0
  24. app/user_manager.py +330 -0
  25. comfy/checkpoint_pickle.py +13 -0
  26. comfy/cldm/cldm.py +433 -0
  27. comfy/cldm/control_types.py +10 -0
  28. comfy/cldm/dit_embedder.py +120 -0
  29. comfy/cldm/mmdit.py +81 -0
  30. comfy/cli_args.py +190 -0
  31. comfy/clip_config_bigg.json +23 -0
  32. comfy/clip_model.py +218 -0
  33. comfy/clip_vision.py +129 -0
  34. comfy/clip_vision_config_g.json +18 -0
  35. comfy/clip_vision_config_h.json +18 -0
  36. comfy/clip_vision_config_vitl.json +18 -0
  37. comfy/clip_vision_config_vitl_336.json +18 -0
  38. comfy/clip_vision_siglip_384.json +13 -0
  39. comfy/comfy_types/README.md +43 -0
  40. comfy/comfy_types/__init__.py +45 -0
  41. comfy/comfy_types/examples/example_nodes.py +28 -0
  42. comfy/comfy_types/examples/input_options.png +0 -0
  43. comfy/comfy_types/examples/input_types.png +0 -0
  44. comfy/comfy_types/examples/required_hint.png +0 -0
  45. comfy/comfy_types/node_typing.py +274 -0
  46. comfy/conds.py +83 -0
  47. comfy/controlnet.py +862 -0
  48. comfy/diffusers_convert.py +288 -0
  49. comfy/diffusers_load.py +36 -0
  50. comfy/extra_samplers/uni_pc.py +873 -0
.gitattributes CHANGED
@@ -33,3 +33,6 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ /web/assets/** linguist-generated
37
+ /web/** linguist-vendored
38
+
.gitignore ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ __pycache__/
2
+ *.py[cod]
3
+ /output/
4
+ /input/
5
+ !/input/example.png
6
+ /models/
7
+ /temp/
8
+ /custom_nodes/
9
+ !custom_nodes/example_node.py.example
10
+ extra_model_paths.yaml
11
+ /.vs
12
+ .vscode/
13
+ .idea/
14
+ venv/
15
+ .venv/
16
+ /web/extensions/*
17
+ !/web/extensions/logging.js.example
18
+ !/web/extensions/core/
19
+ /tests-ui/data/object_info.json
20
+ /user/
21
+ *.log
22
+ web_custom_versions/
23
+ .DS_Store
.python-version ADDED
@@ -0,0 +1 @@
 
 
1
+ 3.12
CODEOWNERS ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 @huchenlei @webfiltered @pythongosssss @ltdrdata @Kosinkadink
9
+ /tests/ @yoland68 @robinjhuang @huchenlei @webfiltered @pythongosssss @ltdrdata @Kosinkadink
10
+ /tests-unit/ @yoland68 @robinjhuang @huchenlei @webfiltered @pythongosssss @ltdrdata @Kosinkadink
11
+ /notebooks/ @yoland68 @robinjhuang @huchenlei @webfiltered @pythongosssss @ltdrdata @Kosinkadink
12
+ /script_examples/ @yoland68 @robinjhuang @huchenlei @webfiltered @pythongosssss @ltdrdata @Kosinkadink
13
+ /.github/ @yoland68 @robinjhuang @huchenlei @webfiltered @pythongosssss @ltdrdata @Kosinkadink
14
+
15
+ # Python web server
16
+ /api_server/ @yoland68 @robinjhuang @huchenlei @webfiltered @pythongosssss @ltdrdata
17
+ /app/ @yoland68 @robinjhuang @huchenlei @webfiltered @pythongosssss @ltdrdata
18
+
19
+ # Frontend assets
20
+ /web/ @huchenlei @webfiltered @pythongosssss @yoland68 @robinjhuang
21
+
22
+ # Extra nodes
23
+ /comfy_extras/ @yoland68 @robinjhuang @huchenlei @pythongosssss @ltdrdata @Kosinkadink
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>.
README.md CHANGED
@@ -11,3 +11,347 @@ short_description: test
11
  ---
12
 
13
  Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
11
  ---
12
 
13
  Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
14
+
15
+ <div align="center">
16
+
17
+ # ComfyUI
18
+
19
+ **The most powerful and modular diffusion model GUI and backend.**
20
+
21
+ [![Website][website-shield]][website-url]
22
+ [![Dynamic JSON Badge][discord-shield]][discord-url]
23
+ [![Matrix][matrix-shield]][matrix-url]
24
+ <br>
25
+ [![][github-release-shield]][github-release-link]
26
+ [![][github-release-date-shield]][github-release-link]
27
+ [![][github-downloads-shield]][github-downloads-link]
28
+ [![][github-downloads-latest-shield]][github-downloads-link]
29
+
30
+ [matrix-shield]: https://img.shields.io/badge/Matrix-000000?style=flat&logo=matrix&logoColor=white
31
+ [matrix-url]: https://app.element.io/#/room/%23comfyui_space%3Amatrix.org
32
+ [website-shield]: https://img.shields.io/badge/ComfyOrg-4285F4?style=flat
33
+ [website-url]: https://www.comfy.org/
34
+
35
+ <!-- Workaround to display total user from https://github.com/badges/shields/issues/4500#issuecomment-2060079995 -->
36
+
37
+ [discord-shield]: https://img.shields.io/badge/dynamic/json?url=https%3A%2F%2Fdiscord.com%2Fapi%2Finvites%2Fcomfyorg%3Fwith_counts%3Dtrue&query=%24.approximate_member_count&logo=discord&logoColor=white&label=Discord&color=green&suffix=%20total
38
+ [discord-url]: https://www.comfy.org/discord
39
+ [github-release-shield]: https://img.shields.io/github/v/release/comfyanonymous/ComfyUI?style=flat&sort=semver
40
+ [github-release-link]: https://github.com/comfyanonymous/ComfyUI/releases
41
+ [github-release-date-shield]: https://img.shields.io/github/release-date/comfyanonymous/ComfyUI?style=flat
42
+ [github-downloads-shield]: https://img.shields.io/github/downloads/comfyanonymous/ComfyUI/total?style=flat
43
+ [github-downloads-latest-shield]: https://img.shields.io/github/downloads/comfyanonymous/ComfyUI/latest/total?style=flat&label=downloads%40latest
44
+ [github-downloads-link]: https://github.com/comfyanonymous/ComfyUI/releases
45
+
46
+ ![ComfyUI Screenshot](https://github.com/user-attachments/assets/7ccaf2c1-9b72-41ae-9a89-5688c94b7abe)
47
+
48
+ </div>
49
+
50
+ This ui will let you design and execute advanced stable diffusion pipelines using a graph/nodes/flowchart based interface. For some workflow examples and see what ComfyUI can do you can check out:
51
+
52
+ ### [ComfyUI Examples](https://comfyanonymous.github.io/ComfyUI_examples/)
53
+
54
+ ### [Installing ComfyUI](#installing)
55
+
56
+ ## Features
57
+
58
+ - Nodes/graph/flowchart interface to experiment and create complex Stable Diffusion workflows without needing to code anything.
59
+ - Image Models
60
+ - SD1.x, SD2.x,
61
+ - [SDXL](https://comfyanonymous.github.io/ComfyUI_examples/sdxl/), [SDXL Turbo](https://comfyanonymous.github.io/ComfyUI_examples/sdturbo/)
62
+ - [Stable Cascade](https://comfyanonymous.github.io/ComfyUI_examples/stable_cascade/)
63
+ - [SD3 and SD3.5](https://comfyanonymous.github.io/ComfyUI_examples/sd3/)
64
+ - Pixart Alpha and Sigma
65
+ - [AuraFlow](https://comfyanonymous.github.io/ComfyUI_examples/aura_flow/)
66
+ - [HunyuanDiT](https://comfyanonymous.github.io/ComfyUI_examples/hunyuan_dit/)
67
+ - [Flux](https://comfyanonymous.github.io/ComfyUI_examples/flux/)
68
+ - Video Models
69
+ - [Stable Video Diffusion](https://comfyanonymous.github.io/ComfyUI_examples/video/)
70
+ - [Mochi](https://comfyanonymous.github.io/ComfyUI_examples/mochi/)
71
+ - [LTX-Video](https://comfyanonymous.github.io/ComfyUI_examples/ltxv/)
72
+ - [Hunyuan Video](https://comfyanonymous.github.io/ComfyUI_examples/hunyuan_video/)
73
+ - [Stable Audio](https://comfyanonymous.github.io/ComfyUI_examples/audio/)
74
+ - Asynchronous Queue system
75
+ - Many optimizations: Only re-executes the parts of the workflow that changes between executions.
76
+ - Smart memory management: can automatically run models on GPUs with as low as 1GB vram.
77
+ - Works even if you don't have a GPU with: `--cpu` (slow)
78
+ - Can load ckpt, safetensors and diffusers models/checkpoints. Standalone VAEs and CLIP models.
79
+ - Embeddings/Textual inversion
80
+ - [Loras (regular, locon and loha)](https://comfyanonymous.github.io/ComfyUI_examples/lora/)
81
+ - [Hypernetworks](https://comfyanonymous.github.io/ComfyUI_examples/hypernetworks/)
82
+ - Loading full workflows (with seeds) from generated PNG, WebP and FLAC files.
83
+ - Saving/Loading workflows as Json files.
84
+ - Nodes interface can be used to create complex workflows like one for [Hires fix](https://comfyanonymous.github.io/ComfyUI_examples/2_pass_txt2img/) or much more advanced ones.
85
+ - [Area Composition](https://comfyanonymous.github.io/ComfyUI_examples/area_composition/)
86
+ - [Inpainting](https://comfyanonymous.github.io/ComfyUI_examples/inpaint/) with both regular and inpainting models.
87
+ - [ControlNet and T2I-Adapter](https://comfyanonymous.github.io/ComfyUI_examples/controlnet/)
88
+ - [Upscale Models (ESRGAN, ESRGAN variants, SwinIR, Swin2SR, etc...)](https://comfyanonymous.github.io/ComfyUI_examples/upscale_models/)
89
+ - [unCLIP Models](https://comfyanonymous.github.io/ComfyUI_examples/unclip/)
90
+ - [GLIGEN](https://comfyanonymous.github.io/ComfyUI_examples/gligen/)
91
+ - [Model Merging](https://comfyanonymous.github.io/ComfyUI_examples/model_merging/)
92
+ - [LCM models and Loras](https://comfyanonymous.github.io/ComfyUI_examples/lcm/)
93
+ - Latent previews with [TAESD](#how-to-show-high-quality-previews)
94
+ - Starts up very fast.
95
+ - Works fully offline: will never download anything.
96
+ - [Config file](extra_model_paths.yaml.example) to set the search paths for models.
97
+
98
+ Workflow examples can be found on the [Examples page](https://comfyanonymous.github.io/ComfyUI_examples/)
99
+
100
+ ## Shortcuts
101
+
102
+ | Keybind | Explanation |
103
+ | -------------------------------------- | ------------------------------------------------------------------------------------------------------------------ |
104
+ | `Ctrl` + `Enter` | Queue up current graph for generation |
105
+ | `Ctrl` + `Shift` + `Enter` | Queue up current graph as first for generation |
106
+ | `Ctrl` + `Alt` + `Enter` | Cancel current generation |
107
+ | `Ctrl` + `Z`/`Ctrl` + `Y` | Undo/Redo |
108
+ | `Ctrl` + `S` | Save workflow |
109
+ | `Ctrl` + `O` | Load workflow |
110
+ | `Ctrl` + `A` | Select all nodes |
111
+ | `Alt `+ `C` | Collapse/uncollapse selected nodes |
112
+ | `Ctrl` + `M` | Mute/unmute selected nodes |
113
+ | `Ctrl` + `B` | Bypass selected nodes (acts like the node was removed from the graph and the wires reconnected through) |
114
+ | `Delete`/`Backspace` | Delete selected nodes |
115
+ | `Ctrl` + `Backspace` | Delete the current graph |
116
+ | `Space` | Move the canvas around when held and moving the cursor |
117
+ | `Ctrl`/`Shift` + `Click` | Add clicked node to selection |
118
+ | `Ctrl` + `C`/`Ctrl` + `V` | Copy and paste selected nodes (without maintaining connections to outputs of unselected nodes) |
119
+ | `Ctrl` + `C`/`Ctrl` + `Shift` + `V` | Copy and paste selected nodes (maintaining connections from outputs of unselected nodes to inputs of pasted nodes) |
120
+ | `Shift` + `Drag` | Move multiple selected nodes at the same time |
121
+ | `Ctrl` + `D` | Load default graph |
122
+ | `Alt` + `+` | Canvas Zoom in |
123
+ | `Alt` + `-` | Canvas Zoom out |
124
+ | `Ctrl` + `Shift` + LMB + Vertical drag | Canvas Zoom in/out |
125
+ | `P` | Pin/Unpin selected nodes |
126
+ | `Ctrl` + `G` | Group selected nodes |
127
+ | `Q` | Toggle visibility of the queue |
128
+ | `H` | Toggle visibility of history |
129
+ | `R` | Refresh graph |
130
+ | `F` | Show/Hide menu |
131
+ | `.` | Fit view to selection (Whole graph when nothing is selected) |
132
+ | Double-Click LMB | Open node quick search palette |
133
+ | `Shift` + Drag | Move multiple wires at once |
134
+ | `Ctrl` + `Alt` + LMB | Disconnect all wires from clicked slot |
135
+
136
+ `Ctrl` can also be replaced with `Cmd` instead for macOS users
137
+
138
+ # Installing
139
+
140
+ ## Windows
141
+
142
+ There is a portable standalone build for Windows that should work for running on Nvidia GPUs or for running on your CPU only on the [releases page](https://github.com/comfyanonymous/ComfyUI/releases).
143
+
144
+ ### [Direct link to download](https://github.com/comfyanonymous/ComfyUI/releases/latest/download/ComfyUI_windows_portable_nvidia.7z)
145
+
146
+ Simply download, extract with [7-Zip](https://7-zip.org) and run. Make sure you put your Stable Diffusion checkpoints/models (the huge ckpt/safetensors files) in: ComfyUI\models\checkpoints
147
+
148
+ If you have trouble extracting it, right click the file -> properties -> unblock
149
+
150
+ #### How do I share models between another UI and ComfyUI?
151
+
152
+ See the [Config file](extra_model_paths.yaml.example) to set the search paths for models. In the standalone windows build you can find this file in the ComfyUI directory. Rename this file to extra_model_paths.yaml and edit it with your favorite text editor.
153
+
154
+ ## Jupyter Notebook
155
+
156
+ To run it on services like paperspace, kaggle or colab you can use my [Jupyter Notebook](notebooks/comfyui_colab.ipynb)
157
+
158
+ ## Manual Install (Windows, Linux)
159
+
160
+ Note that some dependencies do not yet support python 3.13 so using 3.12 is recommended.
161
+
162
+ Git clone this repo.
163
+
164
+ Put your SD checkpoints (the huge ckpt/safetensors files) in: models/checkpoints
165
+
166
+ Put your VAE in: models/vae
167
+
168
+ ### AMD GPUs (Linux only)
169
+
170
+ AMD users can install rocm and pytorch with pip if you don't have it already installed, this is the command to install the stable version:
171
+
172
+ `pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/rocm6.2`
173
+
174
+ This is the command to install the nightly with ROCm 6.2 which might have some performance improvements:
175
+
176
+ `pip install --pre torch torchvision torchaudio --index-url https://download.pytorch.org/whl/nightly/rocm6.2.4`
177
+
178
+ ### Intel GPUs (Windows and Linux)
179
+
180
+ (Option 1) Intel Arc GPU users can install native PyTorch with torch.xpu support using pip (currently available in PyTorch nightly builds). More information can be found [here](https://pytorch.org/docs/main/notes/get_start_xpu.html)
181
+
182
+ 1. To install PyTorch nightly, use the following command:
183
+
184
+ `pip install --pre torch torchvision torchaudio --index-url https://download.pytorch.org/whl/nightly/xpu`
185
+
186
+ 2. Launch ComfyUI by running `python main.py`
187
+
188
+ (Option 2) Alternatively, Intel GPUs supported by Intel Extension for PyTorch (IPEX) can leverage IPEX for improved performance.
189
+
190
+ 1. For Intel® Arc™ A-Series Graphics utilizing IPEX, create a conda environment and use the commands below:
191
+
192
+ ```
193
+ conda install libuv
194
+ pip install torch==2.3.1.post0+cxx11.abi torchvision==0.18.1.post0+cxx11.abi torchaudio==2.3.1.post0+cxx11.abi intel-extension-for-pytorch==2.3.110.post0+xpu --extra-index-url https://pytorch-extension.intel.com/release-whl/stable/xpu/us/ --extra-index-url https://pytorch-extension.intel.com/release-whl/stable/xpu/cn/
195
+ ```
196
+
197
+ For other supported Intel GPUs with IPEX, visit [Installation](https://intel.github.io/intel-extension-for-pytorch/index.html#installation?platform=gpu) for more information.
198
+
199
+ Additional discussion and help can be found [here](https://github.com/comfyanonymous/ComfyUI/discussions/476).
200
+
201
+ ### NVIDIA
202
+
203
+ Nvidia users should install stable pytorch using this command:
204
+
205
+ `pip install torch torchvision torchaudio --extra-index-url https://download.pytorch.org/whl/cu124`
206
+
207
+ This is the command to install pytorch nightly instead which might have performance improvements:
208
+
209
+ `pip install --pre torch torchvision torchaudio --index-url https://download.pytorch.org/whl/nightly/cu126`
210
+
211
+ #### Troubleshooting
212
+
213
+ If you get the "Torch not compiled with CUDA enabled" error, uninstall torch with:
214
+
215
+ `pip uninstall torch`
216
+
217
+ And install it again with the command above.
218
+
219
+ ### Dependencies
220
+
221
+ Install the dependencies by opening your terminal inside the ComfyUI folder and:
222
+
223
+ `pip install -r requirements.txt`
224
+
225
+ After this you should have everything installed and can proceed to running ComfyUI.
226
+
227
+ ### Others:
228
+
229
+ #### Apple Mac silicon
230
+
231
+ You can install ComfyUI in Apple Mac silicon (M1 or M2) with any recent macOS version.
232
+
233
+ 1. Install pytorch nightly. For instructions, read the [Accelerated PyTorch training on Mac](https://developer.apple.com/metal/pytorch/) Apple Developer guide (make sure to install the latest pytorch nightly).
234
+ 1. Follow the [ComfyUI manual installation](#manual-install-windows-linux) instructions for Windows and Linux.
235
+ 1. Install the ComfyUI [dependencies](#dependencies). If you have another Stable Diffusion UI [you might be able to reuse the dependencies](#i-already-have-another-ui-for-stable-diffusion-installed-do-i-really-have-to-install-all-of-these-dependencies).
236
+ 1. Launch ComfyUI by running `python main.py`
237
+
238
+ > **Note**: Remember to add your models, VAE, LoRAs etc. to the corresponding Comfy folders, as discussed in [ComfyUI manual installation](#manual-install-windows-linux).
239
+
240
+ #### DirectML (AMD Cards on Windows)
241
+
242
+ `pip install torch-directml` Then you can launch ComfyUI with: `python main.py --directml`
243
+
244
+ #### Ascend NPUs
245
+
246
+ For models compatible with Ascend Extension for PyTorch (torch_npu). To get started, ensure your environment meets the prerequisites outlined on the [installation](https://ascend.github.io/docs/sources/ascend/quick_install.html) page. Here's a step-by-step guide tailored to your platform and installation method:
247
+
248
+ 1. Begin by installing the recommended or newer kernel version for Linux as specified in the Installation page of torch-npu, if necessary.
249
+ 2. Proceed with the installation of Ascend Basekit, which includes the driver, firmware, and CANN, following the instructions provided for your specific platform.
250
+ 3. Next, install the necessary packages for torch-npu by adhering to the platform-specific instructions on the [Installation](https://ascend.github.io/docs/sources/pytorch/install.html#pytorch) page.
251
+ 4. Finally, adhere to the [ComfyUI manual installation](#manual-install-windows-linux) guide for Linux. Once all components are installed, you can run ComfyUI as described earlier.
252
+
253
+ # Running
254
+
255
+ `python main.py`
256
+
257
+ ### For AMD cards not officially supported by ROCm
258
+
259
+ Try running it with this command if you have issues:
260
+
261
+ For 6700, 6600 and maybe other RDNA2 or older: `HSA_OVERRIDE_GFX_VERSION=10.3.0 python main.py`
262
+
263
+ For AMD 7600 and maybe other RDNA3 cards: `HSA_OVERRIDE_GFX_VERSION=11.0.0 python main.py`
264
+
265
+ ### AMD ROCm Tips
266
+
267
+ You can enable experimental memory efficient attention on pytorch 2.5 in ComfyUI on RDNA3 and potentially other AMD GPUs using this command:
268
+
269
+ `TORCH_ROCM_AOTRITON_ENABLE_EXPERIMENTAL=1 python main.py --use-pytorch-cross-attention`
270
+
271
+ You can also try setting this env variable `PYTORCH_TUNABLEOP_ENABLED=1` which might speed things up at the cost of a very slow initial run.
272
+
273
+ # Notes
274
+
275
+ Only parts of the graph that have an output with all the correct inputs will be executed.
276
+
277
+ Only parts of the graph that change from each execution to the next will be executed, if you submit the same graph twice only the first will be executed. If you change the last part of the graph only the part you changed and the part that depends on it will be executed.
278
+
279
+ Dragging a generated png on the webpage or loading one will give you the full workflow including seeds that were used to create it.
280
+
281
+ You can use () to change emphasis of a word or phrase like: (good code:1.2) or (bad code:0.8). The default emphasis for () is 1.1. To use () characters in your actual prompt escape them like \\( or \\).
282
+
283
+ You can use {day|night}, for wildcard/dynamic prompts. With this syntax "{wild|card|test}" will be randomly replaced by either "wild", "card" or "test" by the frontend every time you queue the prompt. To use {} characters in your actual prompt escape them like: \\{ or \\}.
284
+
285
+ Dynamic prompts also support C-style comments, like `// comment` or `/* comment */`.
286
+
287
+ To use a textual inversion concepts/embeddings in a text prompt put them in the models/embeddings directory and use them in the CLIPTextEncode node like this (you can omit the .pt extension):
288
+
289
+ `embedding:embedding_filename.pt`
290
+
291
+ ## How to show high-quality previews?
292
+
293
+ Use `--preview-method auto` to enable previews.
294
+
295
+ The default installation includes a fast latent preview method that's low-resolution. To enable higher-quality previews with [TAESD](https://github.com/madebyollin/taesd), download the [taesd_decoder.pth, taesdxl_decoder.pth, taesd3_decoder.pth and taef1_decoder.pth](https://github.com/madebyollin/taesd/) and place them in the `models/vae_approx` folder. Once they're installed, restart ComfyUI and launch it with `--preview-method taesd` to enable high-quality previews.
296
+
297
+ ## How to use TLS/SSL?
298
+
299
+ Generate a self-signed certificate (not appropriate for shared/production use) and key by running the command: `openssl req -x509 -newkey rsa:4096 -keyout key.pem -out cert.pem -sha256 -days 3650 -nodes -subj "/C=XX/ST=StateName/L=CityName/O=CompanyName/OU=CompanySectionName/CN=CommonNameOrHostname"`
300
+
301
+ Use `--tls-keyfile key.pem --tls-certfile cert.pem` to enable TLS/SSL, the app will now be accessible with `https://...` instead of `http://...`.
302
+
303
+ > Note: Windows users can use [alexisrolland/docker-openssl](https://github.com/alexisrolland/docker-openssl) or one of the [3rd party binary distributions](https://wiki.openssl.org/index.php/Binaries) to run the command example above.
304
+ > <br/><br/>If you use a container, note that the volume mount `-v` can be a relative path so `... -v ".\:/openssl-certs" ...` would create the key & cert files in the current directory of your command prompt or powershell terminal.
305
+
306
+ ## Support and dev channel
307
+
308
+ [Matrix space: #comfyui_space:matrix.org](https://app.element.io/#/room/%23comfyui_space%3Amatrix.org) (it's like discord but open source).
309
+
310
+ See also: [https://www.comfy.org/](https://www.comfy.org/)
311
+
312
+ ## Frontend Development
313
+
314
+ As of August 15, 2024, we have transitioned to a new frontend, which is now hosted in a separate repository: [ComfyUI Frontend](https://github.com/Comfy-Org/ComfyUI_frontend). This repository now hosts the compiled JS (from TS/Vue) under the `web/` directory.
315
+
316
+ ### Reporting Issues and Requesting Features
317
+
318
+ For any bugs, issues, or feature requests related to the frontend, please use the [ComfyUI Frontend repository](https://github.com/Comfy-Org/ComfyUI_frontend). This will help us manage and address frontend-specific concerns more efficiently.
319
+
320
+ ### Using the Latest Frontend
321
+
322
+ The new frontend is now the default for ComfyUI. However, please note:
323
+
324
+ 1. The frontend in the main ComfyUI repository is updated weekly.
325
+ 2. Daily releases are available in the separate frontend repository.
326
+
327
+ To use the most up-to-date frontend version:
328
+
329
+ 1. For the latest daily release, launch ComfyUI with this command line argument:
330
+
331
+ ```
332
+ --front-end-version Comfy-Org/ComfyUI_frontend@latest
333
+ ```
334
+
335
+ 2. For a specific version, replace `latest` with the desired version number:
336
+
337
+ ```
338
+ --front-end-version Comfy-Org/ComfyUI_frontend@1.2.2
339
+ ```
340
+
341
+ This approach allows you to easily switch between the stable weekly release and the cutting-edge daily updates, or even specific versions for testing purposes.
342
+
343
+ ### Accessing the Legacy Frontend
344
+
345
+ If you need to use the legacy frontend for any reason, you can access it using the following command line argument:
346
+
347
+ ```
348
+ --front-end-version Comfy-Org/ComfyUI_legacy_frontend@latest
349
+ ```
350
+
351
+ This will use a snapshot of the legacy frontend preserved in the [ComfyUI Legacy Frontend repository](https://github.com/Comfy-Org/ComfyUI_legacy_frontend).
352
+
353
+ # QA
354
+
355
+ ### Which GPU should I buy for this?
356
+
357
+ [See this page for some recommendations](https://github.com/comfyanonymous/ComfyUI/wiki/Which-GPU-should-I-buy-for-ComfyUI)
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,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from aiohttp import web
2
+ from typing import Optional
3
+ from folder_paths import models_dir, user_directory, output_directory, folder_names_and_paths
4
+ from api_server.services.file_service import FileService
5
+ from api_server.services.terminal_service import TerminalService
6
+ import app.logger
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.file_service = FileService({
19
+ "models": models_dir,
20
+ "user": user_directory,
21
+ "output": output_directory
22
+ })
23
+ self.prompt_server = prompt_server
24
+ self.terminal_service = TerminalService(prompt_server)
25
+
26
+ def setup_routes(self):
27
+ @self.routes.get('/files')
28
+ async def list_files(request):
29
+ directory_key = request.query.get('directory', '')
30
+ try:
31
+ file_list = self.file_service.list_files(directory_key)
32
+ return web.json_response({"files": file_list})
33
+ except ValueError as e:
34
+ return web.json_response({"error": str(e)}, status=400)
35
+ except Exception as e:
36
+ return web.json_response({"error": str(e)}, status=500)
37
+
38
+ @self.routes.get('/logs')
39
+ async def get_logs(request):
40
+ return web.json_response("".join([(l["t"] + " - " + l["m"]) for l in app.logger.get_logs()]))
41
+
42
+ @self.routes.get('/logs/raw')
43
+ async def get_raw_logs(request):
44
+ self.terminal_service.update_size()
45
+ return web.json_response({
46
+ "entries": list(app.logger.get_logs()),
47
+ "size": {"cols": self.terminal_service.cols, "rows": self.terminal_service.rows}
48
+ })
49
+
50
+ @self.routes.patch('/logs/subscribe')
51
+ async def subscribe_logs(request):
52
+ json_data = await request.json()
53
+ client_id = json_data["clientId"]
54
+ enabled = json_data["enabled"]
55
+ if enabled:
56
+ self.terminal_service.subscribe(client_id)
57
+ else:
58
+ self.terminal_service.unsubscribe(client_id)
59
+
60
+ return web.Response(status=200)
61
+
62
+
63
+ @self.routes.get('/folder_paths')
64
+ async def get_folder_paths(request):
65
+ response = {}
66
+ for key in folder_names_and_paths:
67
+ response[key] = folder_names_and_paths[key][0]
68
+ return web.json_response(response)
69
+
70
+ def get_app(self):
71
+ if self._app is None:
72
+ self._app = web.Application()
73
+ self.setup_routes()
74
+ self._app.add_routes(self.routes)
75
+ return self._app
api_server/services/__init__.py ADDED
File without changes
api_server/services/file_service.py ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Dict, List, Optional
2
+ from api_server.utils.file_operations import FileSystemOperations, FileSystemItem
3
+
4
+ class FileService:
5
+ def __init__(self, allowed_directories: Dict[str, str], file_system_ops: Optional[FileSystemOperations] = None):
6
+ self.allowed_directories: Dict[str, str] = allowed_directories
7
+ self.file_system_ops: FileSystemOperations = file_system_ops or FileSystemOperations()
8
+
9
+ def list_files(self, directory_key: str) -> List[FileSystemItem]:
10
+ if directory_key not in self.allowed_directories:
11
+ raise ValueError("Invalid directory key")
12
+ directory_path: str = self.allowed_directories[directory_key]
13
+ return self.file_system_ops.walk_directory(directory_path)
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.py ADDED
@@ -0,0 +1,397 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import random
3
+ import sys
4
+ from typing import Sequence, Mapping, Any, Union
5
+ import torch
6
+ import gradio as gr
7
+ from huggingface_hub import hf_hub_download
8
+ import spaces
9
+ from comfy import model_management
10
+
11
+ hf_hub_download(repo_id="black-forest-labs/FLUX.1-Redux-dev", filename="flux1-redux-dev.safetensors", local_dir="models/style_models")
12
+ hf_hub_download(repo_id="black-forest-labs/FLUX.1-Depth-dev", filename="flux1-depth-dev.safetensors", local_dir="models/diffusion_models")
13
+ hf_hub_download(repo_id="Comfy-Org/sigclip_vision_384", filename="sigclip_vision_patch14_384.safetensors", local_dir="models/clip_vision")
14
+ hf_hub_download(repo_id="Kijai/DepthAnythingV2-safetensors", filename="depth_anything_v2_vitl_fp32.safetensors", local_dir="models/depthanything")
15
+ hf_hub_download(repo_id="black-forest-labs/FLUX.1-dev", filename="ae.safetensors", local_dir="models/vae/FLUX1")
16
+ hf_hub_download(repo_id="comfyanonymous/flux_text_encoders", filename="clip_l.safetensors", local_dir="models/text_encoders")
17
+ hf_hub_download(repo_id="comfyanonymous/flux_text_encoders", filename="t5xxl_fp16.safetensors", local_dir="models/text_encoders/t5")
18
+
19
+ def get_value_at_index(obj: Union[Sequence, Mapping], index: int) -> Any:
20
+ """Returns the value at the given index of a sequence or mapping.
21
+ If the object is a sequence (like list or string), returns the value at the given index.
22
+ If the object is a mapping (like a dictionary), returns the value at the index-th key.
23
+ Some return a dictionary, in these cases, we look for the "results" key
24
+ Args:
25
+ obj (Union[Sequence, Mapping]): The object to retrieve the value from.
26
+ index (int): The index of the value to retrieve.
27
+ Returns:
28
+ Any: The value at the given index.
29
+ Raises:
30
+ IndexError: If the index is out of bounds for the object and the object is not a mapping.
31
+ """
32
+ try:
33
+ return obj[index]
34
+ except KeyError:
35
+ return obj["result"][index]
36
+
37
+
38
+ def find_path(name: str, path: str = None) -> str:
39
+ """
40
+ Recursively looks at parent folders starting from the given path until it finds the given name.
41
+ Returns the path as a Path object if found, or None otherwise.
42
+ """
43
+ # If no path is given, use the current working directory
44
+ if path is None:
45
+ path = os.getcwd()
46
+
47
+ # Check if the current directory contains the name
48
+ if name in os.listdir(path):
49
+ path_name = os.path.join(path, name)
50
+ print(f"{name} found: {path_name}")
51
+ return path_name
52
+
53
+ # Get the parent directory
54
+ parent_directory = os.path.dirname(path)
55
+
56
+ # If the parent directory is the same as the current directory, we've reached the root and stop the search
57
+ if parent_directory == path:
58
+ return None
59
+
60
+ # Recursively call the function with the parent directory
61
+ return find_path(name, parent_directory)
62
+
63
+
64
+ def add_comfyui_directory_to_sys_path() -> None:
65
+ """
66
+ Add 'ComfyUI' to the sys.path
67
+ """
68
+ comfyui_path = find_path("ComfyUI")
69
+ if comfyui_path is not None and os.path.isdir(comfyui_path):
70
+ sys.path.append(comfyui_path)
71
+ print(f"'{comfyui_path}' added to sys.path")
72
+
73
+
74
+ def add_extra_model_paths() -> None:
75
+ """
76
+ Parse the optional extra_model_paths.yaml file and add the parsed paths to the sys.path.
77
+ """
78
+ try:
79
+ from main import load_extra_path_config
80
+ except ImportError:
81
+ print(
82
+ "Could not import load_extra_path_config from main.py. Looking in utils.extra_config instead."
83
+ )
84
+ from utils.extra_config import load_extra_path_config
85
+
86
+ extra_model_paths = find_path("extra_model_paths.yaml")
87
+
88
+ if extra_model_paths is not None:
89
+ load_extra_path_config(extra_model_paths)
90
+ else:
91
+ print("Could not find the extra_model_paths config file.")
92
+
93
+
94
+ add_comfyui_directory_to_sys_path()
95
+ add_extra_model_paths()
96
+
97
+
98
+ def import_custom_nodes() -> None:
99
+ """Find all custom nodes in the custom_nodes folder and add those node objects to NODE_CLASS_MAPPINGS
100
+ This function sets up a new asyncio event loop, initializes the PromptServer,
101
+ creates a PromptQueue, and initializes the custom nodes.
102
+ """
103
+ import asyncio
104
+ import execution
105
+ from nodes import init_extra_nodes
106
+ import server
107
+
108
+ # Creating a new event loop and setting it as the default loop
109
+ loop = asyncio.new_event_loop()
110
+ asyncio.set_event_loop(loop)
111
+
112
+ # Creating an instance of PromptServer with the loop
113
+ server_instance = server.PromptServer(loop)
114
+ execution.PromptQueue(server_instance)
115
+
116
+ # Initializing custom nodes
117
+ init_extra_nodes()
118
+
119
+
120
+ from nodes import NODE_CLASS_MAPPINGS
121
+
122
+ intconstant = NODE_CLASS_MAPPINGS["INTConstant"]()
123
+ dualcliploader = NODE_CLASS_MAPPINGS["DualCLIPLoader"]()
124
+
125
+ #To be added to `model_loaders` as it loads a model
126
+ dualcliploader_357 = dualcliploader.load_clip(
127
+ clip_name1="t5/t5xxl_fp16.safetensors",
128
+ clip_name2="clip_l.safetensors",
129
+ type="flux",
130
+ )
131
+ cr_clip_input_switch = NODE_CLASS_MAPPINGS["CR Clip Input Switch"]()
132
+ cliptextencode = NODE_CLASS_MAPPINGS["CLIPTextEncode"]()
133
+ loadimage = NODE_CLASS_MAPPINGS["LoadImage"]()
134
+ imageresize = NODE_CLASS_MAPPINGS["ImageResize+"]()
135
+ getimagesizeandcount = NODE_CLASS_MAPPINGS["GetImageSizeAndCount"]()
136
+ vaeloader = NODE_CLASS_MAPPINGS["VAELoader"]()
137
+
138
+ #To be added to `model_loaders` as it loads a model
139
+ vaeloader_359 = vaeloader.load_vae(vae_name="FLUX1/ae.safetensors")
140
+
141
+ vaeencode = NODE_CLASS_MAPPINGS["VAEEncode"]()
142
+ unetloader = NODE_CLASS_MAPPINGS["UNETLoader"]()
143
+
144
+ #To be added to `model_loaders` as it loads a model
145
+ unetloader_358 = unetloader.load_unet(
146
+ unet_name="flux1-depth-dev.safetensors", weight_dtype="default"
147
+ )
148
+ ksamplerselect = NODE_CLASS_MAPPINGS["KSamplerSelect"]()
149
+ randomnoise = NODE_CLASS_MAPPINGS["RandomNoise"]()
150
+ fluxguidance = NODE_CLASS_MAPPINGS["FluxGuidance"]()
151
+ depthanything_v2 = NODE_CLASS_MAPPINGS["DepthAnything_V2"]()
152
+ downloadandloaddepthanythingv2model = NODE_CLASS_MAPPINGS[
153
+ "DownloadAndLoadDepthAnythingV2Model"
154
+ ]()
155
+
156
+ #To be added to `model_loaders` as it loads a model
157
+ downloadandloaddepthanythingv2model_437 = (
158
+ downloadandloaddepthanythingv2model.loadmodel(
159
+ model="depth_anything_v2_vitl_fp32.safetensors"
160
+ )
161
+ )
162
+ instructpixtopixconditioning = NODE_CLASS_MAPPINGS[
163
+ "InstructPixToPixConditioning"
164
+ ]()
165
+ text_multiline_454 = text_multiline.text_multiline(text="FLUX_Redux")
166
+ clipvisionloader = NODE_CLASS_MAPPINGS["CLIPVisionLoader"]()
167
+
168
+ #To be added to `model_loaders` as it loads a model
169
+ clipvisionloader_438 = clipvisionloader.load_clip(
170
+ clip_name="sigclip_vision_patch14_384.safetensors"
171
+ )
172
+ clipvisionencode = NODE_CLASS_MAPPINGS["CLIPVisionEncode"]()
173
+ stylemodelloader = NODE_CLASS_MAPPINGS["StyleModelLoader"]()
174
+
175
+ #To be added to `model_loaders` as it loads a model
176
+ stylemodelloader_441 = stylemodelloader.load_style_model(
177
+ style_model_name="flux1-redux-dev.safetensors"
178
+ )
179
+ text_multiline = NODE_CLASS_MAPPINGS["Text Multiline"]()
180
+ emptylatentimage = NODE_CLASS_MAPPINGS["EmptyLatentImage"]()
181
+ cr_conditioning_input_switch = NODE_CLASS_MAPPINGS[
182
+ "CR Conditioning Input Switch"
183
+ ]()
184
+ cr_model_input_switch = NODE_CLASS_MAPPINGS["CR Model Input Switch"]()
185
+ stylemodelapplyadvanced = NODE_CLASS_MAPPINGS["StyleModelApplyAdvanced"]()
186
+ basicguider = NODE_CLASS_MAPPINGS["BasicGuider"]()
187
+ basicscheduler = NODE_CLASS_MAPPINGS["BasicScheduler"]()
188
+ samplercustomadvanced = NODE_CLASS_MAPPINGS["SamplerCustomAdvanced"]()
189
+ vaedecode = NODE_CLASS_MAPPINGS["VAEDecode"]()
190
+ saveimage = NODE_CLASS_MAPPINGS["SaveImage"]()
191
+ imagecrop = NODE_CLASS_MAPPINGS["ImageCrop+"]()
192
+
193
+ #Add all the models that load a safetensors file
194
+ model_loaders = [dualcliploader_357, vaeloader_359, unetloader_358, clipvisionloader_438, stylemodelloader_441, downloadandloaddepthanythingv2model_437]
195
+
196
+ # Check which models are valid and how to best load them
197
+ valid_models = [
198
+ getattr(loader[0], 'patcher', loader[0])
199
+ for loader in model_loaders
200
+ if not isinstance(loader[0], dict) and not isinstance(getattr(loader[0], 'patcher', None), dict)
201
+ ]
202
+
203
+ #Finally loads the models
204
+ model_management.load_models_gpu(valid_models)
205
+
206
+ @spaces.GPU(duration=60)
207
+ def generate_image(prompt, structure_image, style_image, depth_strength, style_strength):
208
+ import_custom_nodes()
209
+ with torch.inference_mode():
210
+
211
+ intconstant_83 = intconstant.get_value(value=1024)
212
+
213
+ intconstant_84 = intconstant.get_value(value=1024)
214
+
215
+ cr_clip_input_switch_319 = cr_clip_input_switch.switch(
216
+ Input=1,
217
+ clip1=get_value_at_index(dualcliploader_357, 0),
218
+ clip2=get_value_at_index(dualcliploader_357, 0),
219
+ )
220
+
221
+ cliptextencode_174 = cliptextencode.encode(
222
+ text=prompt,
223
+ clip=get_value_at_index(cr_clip_input_switch_319, 0),
224
+ )
225
+
226
+ cliptextencode_175 = cliptextencode.encode(
227
+ text="purple", clip=get_value_at_index(cr_clip_input_switch_319, 0)
228
+ )
229
+
230
+ loadimage_429 = loadimage.load_image(image=structure_image)
231
+
232
+ imageresize_72 = imageresize.execute(
233
+ width=get_value_at_index(intconstant_83, 0),
234
+ height=get_value_at_index(intconstant_84, 0),
235
+ interpolation="bicubic",
236
+ method="keep proportion",
237
+ condition="always",
238
+ multiple_of=16,
239
+ image=get_value_at_index(loadimage_429, 0),
240
+ )
241
+
242
+ getimagesizeandcount_360 = getimagesizeandcount.getsize(
243
+ image=get_value_at_index(imageresize_72, 0)
244
+ )
245
+
246
+ vaeencode_197 = vaeencode.encode(
247
+ pixels=get_value_at_index(getimagesizeandcount_360, 0),
248
+ vae=get_value_at_index(vaeloader_359, 0),
249
+ )
250
+
251
+ ksamplerselect_363 = ksamplerselect.get_sampler(sampler_name="euler")
252
+
253
+ randomnoise_365 = randomnoise.get_noise(noise_seed=random.randint(1, 2**64))
254
+
255
+
256
+ fluxguidance_430 = fluxguidance.append(
257
+ guidance=15, conditioning=get_value_at_index(cliptextencode_174, 0)
258
+ )
259
+
260
+ depthanything_v2_436 = depthanything_v2.process(
261
+ da_model=get_value_at_index(downloadandloaddepthanythingv2model_437, 0),
262
+ images=get_value_at_index(getimagesizeandcount_360, 0),
263
+ )
264
+
265
+ instructpixtopixconditioning_431 = instructpixtopixconditioning.encode(
266
+ positive=get_value_at_index(fluxguidance_430, 0),
267
+ negative=get_value_at_index(cliptextencode_175, 0),
268
+ vae=get_value_at_index(vaeloader_359, 0),
269
+ pixels=get_value_at_index(depthanything_v2_436, 0),
270
+ )
271
+
272
+ loadimage_440 = loadimage.load_image(image=style_image)
273
+
274
+ clipvisionencode_439 = clipvisionencode.encode(
275
+ crop="center",
276
+ clip_vision=get_value_at_index(clipvisionloader_438, 0),
277
+ image=get_value_at_index(loadimage_440, 0),
278
+ )
279
+
280
+
281
+ emptylatentimage_10 = emptylatentimage.generate(
282
+ width=get_value_at_index(imageresize_72, 1),
283
+ height=get_value_at_index(imageresize_72, 2),
284
+ batch_size=1,
285
+ )
286
+
287
+ cr_conditioning_input_switch_271 = cr_conditioning_input_switch.switch(
288
+ Input=1,
289
+ conditioning1=get_value_at_index(instructpixtopixconditioning_431, 0),
290
+ conditioning2=get_value_at_index(instructpixtopixconditioning_431, 0),
291
+ )
292
+
293
+ cr_conditioning_input_switch_272 = cr_conditioning_input_switch.switch(
294
+ Input=1,
295
+ conditioning1=get_value_at_index(instructpixtopixconditioning_431, 1),
296
+ conditioning2=get_value_at_index(instructpixtopixconditioning_431, 1),
297
+ )
298
+
299
+ cr_model_input_switch_320 = cr_model_input_switch.switch(
300
+ Input=1,
301
+ model1=get_value_at_index(unetloader_358, 0),
302
+ model2=get_value_at_index(unetloader_358, 0),
303
+ )
304
+
305
+ stylemodelapplyadvanced_442 = stylemodelapplyadvanced.apply_stylemodel(
306
+ strength=style_strength,
307
+ conditioning=get_value_at_index(instructpixtopixconditioning_431, 0),
308
+ style_model=get_value_at_index(stylemodelloader_441, 0),
309
+ clip_vision_output=get_value_at_index(clipvisionencode_439, 0),
310
+ )
311
+
312
+ basicguider_366 = basicguider.get_guider(
313
+ model=get_value_at_index(cr_model_input_switch_320, 0),
314
+ conditioning=get_value_at_index(stylemodelapplyadvanced_442, 0),
315
+ )
316
+
317
+ basicscheduler_364 = basicscheduler.get_sigmas(
318
+ scheduler="simple",
319
+ steps=28,
320
+ denoise=1,
321
+ model=get_value_at_index(cr_model_input_switch_320, 0),
322
+ )
323
+
324
+ samplercustomadvanced_362 = samplercustomadvanced.sample(
325
+ noise=get_value_at_index(randomnoise_365, 0),
326
+ guider=get_value_at_index(basicguider_366, 0),
327
+ sampler=get_value_at_index(ksamplerselect_363, 0),
328
+ sigmas=get_value_at_index(basicscheduler_364, 0),
329
+ latent_image=get_value_at_index(emptylatentimage_10, 0),
330
+ )
331
+
332
+ vaedecode_321 = vaedecode.decode(
333
+ samples=get_value_at_index(samplercustomadvanced_362, 0),
334
+ vae=get_value_at_index(vaeloader_359, 0),
335
+ )
336
+
337
+ saveimage_327 = saveimage.save_images(
338
+ filename_prefix=get_value_at_index(text_multiline_454, 0),
339
+ images=get_value_at_index(vaedecode_321, 0),
340
+ )
341
+
342
+
343
+ fluxguidance_382 = fluxguidance.append(
344
+ guidance=depth_strength,
345
+ conditioning=get_value_at_index(cr_conditioning_input_switch_272, 0),
346
+ )
347
+
348
+ imagecrop_447 = imagecrop.execute(
349
+ width=2000,
350
+ height=2000,
351
+ position="top-center",
352
+ x_offset=0,
353
+ y_offset=0,
354
+ image=get_value_at_index(loadimage_440, 0),
355
+ )
356
+
357
+ saved_path = f"output/{saveimage_327['ui']['images'][0]['filename']}"
358
+ return saved_path
359
+
360
+ if __name__ == "__main__":
361
+ # Comment out the main() call
362
+
363
+ # Start your Gradio app
364
+ with gr.Blocks() as app:
365
+ # Add a title
366
+ gr.Markdown("# FLUX Style Shaping")
367
+
368
+ with gr.Row():
369
+ with gr.Column():
370
+ # Add an input
371
+ prompt_input = gr.Textbox(label="Prompt", placeholder="Enter your prompt here...")
372
+ # Add a `Row` to include the groups side by side
373
+ with gr.Row():
374
+ # First group includes structure image and depth strength
375
+ with gr.Group():
376
+ structure_image = gr.Image(label="Structure Image", type="filepath")
377
+ depth_strength = gr.Slider(minimum=0, maximum=50, value=15, label="Depth Strength")
378
+ # Second group includes style image and style strength
379
+ with gr.Group():
380
+ style_image = gr.Image(label="Style Image", type="filepath")
381
+ style_strength = gr.Slider(minimum=0, maximum=1, value=0.5, label="Style Strength")
382
+
383
+ # The generate button
384
+ generate_btn = gr.Button("Generate")
385
+
386
+ with gr.Column():
387
+ # The output image
388
+ output_image = gr.Image(label="Generated Image")
389
+
390
+ # When clicking the button, it will trigger the `generate_image` function, with the respective inputs
391
+ # and the output an image
392
+ generate_btn.click(
393
+ fn=generate_image,
394
+ inputs=[prompt_input, structure_image, style_image, depth_strength, style_strength],
395
+ outputs=[output_image]
396
+ )
397
+ app.launch(share=True)
app/__init__.py ADDED
File without changes
app/app_settings.py ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ file = self.user_manager.get_request_user_filepath(
13
+ request, "comfy.settings.json")
14
+ if os.path.isfile(file):
15
+ try:
16
+ with open(file) as f:
17
+ return json.load(f)
18
+ except:
19
+ logging.error(f"The user settings file is corrupted: {file}")
20
+ return {}
21
+ else:
22
+ return {}
23
+
24
+ def save_settings(self, request, settings):
25
+ file = self.user_manager.get_request_user_filepath(
26
+ request, "comfy.settings.json")
27
+ with open(file, "w") as f:
28
+ f.write(json.dumps(settings, indent=4))
29
+
30
+ def add_routes(self, routes):
31
+ @routes.get("/settings")
32
+ async def get_settings(request):
33
+ return web.json_response(self.get_settings(request))
34
+
35
+ @routes.get("/settings/{id}")
36
+ async def get_setting(request):
37
+ value = None
38
+ settings = self.get_settings(request)
39
+ setting_id = request.match_info.get("id", None)
40
+ if setting_id and setting_id in settings:
41
+ value = settings[setting_id]
42
+ return web.json_response(value)
43
+
44
+ @routes.post("/settings")
45
+ async def post_settings(request):
46
+ settings = self.get_settings(request)
47
+ new_settings = await request.json()
48
+ self.save_settings(request, {**settings, **new_settings})
49
+ return web.Response(status=200)
50
+
51
+ @routes.post("/settings/{id}")
52
+ async def post_setting(request):
53
+ setting_id = request.match_info.get("id", None)
54
+ if not setting_id:
55
+ return web.Response(status=400)
56
+ settings = self.get_settings(request)
57
+ settings[setting_id] = await request.json()
58
+ self.save_settings(request, settings)
59
+ return web.Response(status=200)
app/custom_node_manager.py ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import os
4
+ import folder_paths
5
+ import glob
6
+ from aiohttp import web
7
+
8
+ class CustomNodeManager:
9
+ """
10
+ Placeholder to refactor the custom node management features from ComfyUI-Manager.
11
+ Currently it only contains the custom workflow templates feature.
12
+ """
13
+ def add_routes(self, routes, webapp, loadedModules):
14
+
15
+ @routes.get("/workflow_templates")
16
+ async def get_workflow_templates(request):
17
+ """Returns a web response that contains the map of custom_nodes names and their associated workflow templates. The ones without templates are omitted."""
18
+ files = [
19
+ file
20
+ for folder in folder_paths.get_folder_paths("custom_nodes")
21
+ for file in glob.glob(os.path.join(folder, '*/example_workflows/*.json'))
22
+ ]
23
+ workflow_templates_dict = {} # custom_nodes folder name -> example workflow names
24
+ for file in files:
25
+ custom_nodes_name = os.path.basename(os.path.dirname(os.path.dirname(file)))
26
+ workflow_name = os.path.splitext(os.path.basename(file))[0]
27
+ workflow_templates_dict.setdefault(custom_nodes_name, []).append(workflow_name)
28
+ return web.json_response(workflow_templates_dict)
29
+
30
+ # Serve workflow templates from custom nodes.
31
+ for module_name, module_dir in loadedModules:
32
+ workflows_dir = os.path.join(module_dir, 'example_workflows')
33
+ if os.path.exists(workflows_dir):
34
+ webapp.add_routes([web.static('/api/workflow_templates/' + module_name, workflows_dir)])
app/frontend_management.py ADDED
@@ -0,0 +1,204 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+ import argparse
3
+ import logging
4
+ import os
5
+ import re
6
+ import tempfile
7
+ import zipfile
8
+ from dataclasses import dataclass
9
+ from functools import cached_property
10
+ from pathlib import Path
11
+ from typing import TypedDict, Optional
12
+
13
+ import requests
14
+ from typing_extensions import NotRequired
15
+ from comfy.cli_args import DEFAULT_VERSION_STRING
16
+
17
+
18
+ REQUEST_TIMEOUT = 10 # seconds
19
+
20
+
21
+ class Asset(TypedDict):
22
+ url: str
23
+
24
+
25
+ class Release(TypedDict):
26
+ id: int
27
+ tag_name: str
28
+ name: str
29
+ prerelease: bool
30
+ created_at: str
31
+ published_at: str
32
+ body: str
33
+ assets: NotRequired[list[Asset]]
34
+
35
+
36
+ @dataclass
37
+ class FrontEndProvider:
38
+ owner: str
39
+ repo: str
40
+
41
+ @property
42
+ def folder_name(self) -> str:
43
+ return f"{self.owner}_{self.repo}"
44
+
45
+ @property
46
+ def release_url(self) -> str:
47
+ return f"https://api.github.com/repos/{self.owner}/{self.repo}/releases"
48
+
49
+ @cached_property
50
+ def all_releases(self) -> list[Release]:
51
+ releases = []
52
+ api_url = self.release_url
53
+ while api_url:
54
+ response = requests.get(api_url, timeout=REQUEST_TIMEOUT)
55
+ response.raise_for_status() # Raises an HTTPError if the response was an error
56
+ releases.extend(response.json())
57
+ # GitHub uses the Link header to provide pagination links. Check if it exists and update api_url accordingly.
58
+ if "next" in response.links:
59
+ api_url = response.links["next"]["url"]
60
+ else:
61
+ api_url = None
62
+ return releases
63
+
64
+ @cached_property
65
+ def latest_release(self) -> Release:
66
+ latest_release_url = f"{self.release_url}/latest"
67
+ response = requests.get(latest_release_url, timeout=REQUEST_TIMEOUT)
68
+ response.raise_for_status() # Raises an HTTPError if the response was an error
69
+ return response.json()
70
+
71
+ def get_release(self, version: str) -> Release:
72
+ if version == "latest":
73
+ return self.latest_release
74
+ else:
75
+ for release in self.all_releases:
76
+ if release["tag_name"] in [version, f"v{version}"]:
77
+ return release
78
+ raise ValueError(f"Version {version} not found in releases")
79
+
80
+
81
+ def download_release_asset_zip(release: Release, destination_path: str) -> None:
82
+ """Download dist.zip from github release."""
83
+ asset_url = None
84
+ for asset in release.get("assets", []):
85
+ if asset["name"] == "dist.zip":
86
+ asset_url = asset["url"]
87
+ break
88
+
89
+ if not asset_url:
90
+ raise ValueError("dist.zip not found in the release assets")
91
+
92
+ # Use a temporary file to download the zip content
93
+ with tempfile.TemporaryFile() as tmp_file:
94
+ headers = {"Accept": "application/octet-stream"}
95
+ response = requests.get(
96
+ asset_url, headers=headers, allow_redirects=True, timeout=REQUEST_TIMEOUT
97
+ )
98
+ response.raise_for_status() # Ensure we got a successful response
99
+
100
+ # Write the content to the temporary file
101
+ tmp_file.write(response.content)
102
+
103
+ # Go back to the beginning of the temporary file
104
+ tmp_file.seek(0)
105
+
106
+ # Extract the zip file content to the destination path
107
+ with zipfile.ZipFile(tmp_file, "r") as zip_ref:
108
+ zip_ref.extractall(destination_path)
109
+
110
+
111
+ class FrontendManager:
112
+ DEFAULT_FRONTEND_PATH = str(Path(__file__).parents[1] / "web")
113
+ CUSTOM_FRONTENDS_ROOT = str(Path(__file__).parents[1] / "web_custom_versions")
114
+
115
+ @classmethod
116
+ def parse_version_string(cls, value: str) -> tuple[str, str, str]:
117
+ """
118
+ Args:
119
+ value (str): The version string to parse.
120
+
121
+ Returns:
122
+ tuple[str, str]: A tuple containing provider name and version.
123
+
124
+ Raises:
125
+ argparse.ArgumentTypeError: If the version string is invalid.
126
+ """
127
+ VERSION_PATTERN = r"^([a-zA-Z0-9][a-zA-Z0-9-]{0,38})/([a-zA-Z0-9_.-]+)@(v?\d+\.\d+\.\d+|latest)$"
128
+ match_result = re.match(VERSION_PATTERN, value)
129
+ if match_result is None:
130
+ raise argparse.ArgumentTypeError(f"Invalid version string: {value}")
131
+
132
+ return match_result.group(1), match_result.group(2), match_result.group(3)
133
+
134
+ @classmethod
135
+ def init_frontend_unsafe(cls, version_string: str, provider: Optional[FrontEndProvider] = None) -> str:
136
+ """
137
+ Initializes the frontend for the specified version.
138
+
139
+ Args:
140
+ version_string (str): The version string.
141
+ provider (FrontEndProvider, optional): The provider to use. Defaults to None.
142
+
143
+ Returns:
144
+ str: The path to the initialized frontend.
145
+
146
+ Raises:
147
+ Exception: If there is an error during the initialization process.
148
+ main error source might be request timeout or invalid URL.
149
+ """
150
+ if version_string == DEFAULT_VERSION_STRING:
151
+ return cls.DEFAULT_FRONTEND_PATH
152
+
153
+ repo_owner, repo_name, version = cls.parse_version_string(version_string)
154
+
155
+ if version.startswith("v"):
156
+ expected_path = str(Path(cls.CUSTOM_FRONTENDS_ROOT) / f"{repo_owner}_{repo_name}" / version.lstrip("v"))
157
+ if os.path.exists(expected_path):
158
+ logging.info(f"Using existing copy of specific frontend version tag: {repo_owner}/{repo_name}@{version}")
159
+ return expected_path
160
+
161
+ logging.info(f"Initializing frontend: {repo_owner}/{repo_name}@{version}, requesting version details from GitHub...")
162
+
163
+ provider = provider or FrontEndProvider(repo_owner, repo_name)
164
+ release = provider.get_release(version)
165
+
166
+ semantic_version = release["tag_name"].lstrip("v")
167
+ web_root = str(
168
+ Path(cls.CUSTOM_FRONTENDS_ROOT) / provider.folder_name / semantic_version
169
+ )
170
+ if not os.path.exists(web_root):
171
+ try:
172
+ os.makedirs(web_root, exist_ok=True)
173
+ logging.info(
174
+ "Downloading frontend(%s) version(%s) to (%s)",
175
+ provider.folder_name,
176
+ semantic_version,
177
+ web_root,
178
+ )
179
+ logging.debug(release)
180
+ download_release_asset_zip(release, destination_path=web_root)
181
+ finally:
182
+ # Clean up the directory if it is empty, i.e. the download failed
183
+ if not os.listdir(web_root):
184
+ os.rmdir(web_root)
185
+
186
+ return web_root
187
+
188
+ @classmethod
189
+ def init_frontend(cls, version_string: str) -> str:
190
+ """
191
+ Initializes the frontend with the specified version string.
192
+
193
+ Args:
194
+ version_string (str): The version string to initialize the frontend with.
195
+
196
+ Returns:
197
+ str: The path of the initialized frontend.
198
+ """
199
+ try:
200
+ return cls.init_frontend_unsafe(version_string)
201
+ except Exception as e:
202
+ logging.error("Failed to initialize frontend: %s", e)
203
+ logging.info("Falling back to the default frontend.")
204
+ return cls.DEFAULT_FRONTEND_PATH
app/logger.py ADDED
@@ -0,0 +1,84 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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)
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,330 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ def get_user_data_path(request, check_exists = False, param = "file"):
201
+ file = request.match_info.get(param, None)
202
+ if not file:
203
+ return web.Response(status=400)
204
+
205
+ path = self.get_request_user_filepath(request, file)
206
+ if not path:
207
+ return web.Response(status=403)
208
+
209
+ if check_exists and not os.path.exists(path):
210
+ return web.Response(status=404)
211
+
212
+ return path
213
+
214
+ @routes.get("/userdata/{file}")
215
+ async def getuserdata(request):
216
+ path = get_user_data_path(request, check_exists=True)
217
+ if not isinstance(path, str):
218
+ return path
219
+
220
+ return web.FileResponse(path)
221
+
222
+ @routes.post("/userdata/{file}")
223
+ async def post_userdata(request):
224
+ """
225
+ Upload or update a user data file.
226
+
227
+ This endpoint handles file uploads to a user's data directory, with options for
228
+ controlling overwrite behavior and response format.
229
+
230
+ Query Parameters:
231
+ - overwrite (optional): If "false", prevents overwriting existing files. Defaults to "true".
232
+ - full_info (optional): If "true", returns detailed file information (path, size, modified time).
233
+ If "false", returns only the relative file path.
234
+
235
+ Path Parameters:
236
+ - file: The target file path (URL encoded if necessary).
237
+
238
+ Returns:
239
+ - 400: If 'file' parameter is missing.
240
+ - 403: If the requested path is not allowed.
241
+ - 409: If overwrite=false and the file already exists.
242
+ - 200: JSON response with either:
243
+ - Full file information (if full_info=true)
244
+ - Relative file path (if full_info=false)
245
+
246
+ The request body should contain the raw file content to be written.
247
+ """
248
+ path = get_user_data_path(request)
249
+ if not isinstance(path, str):
250
+ return path
251
+
252
+ overwrite = request.query.get("overwrite", 'true') != "false"
253
+ full_info = request.query.get('full_info', 'false').lower() == "true"
254
+
255
+ if not overwrite and os.path.exists(path):
256
+ return web.Response(status=409, text="File already exists")
257
+
258
+ body = await request.read()
259
+
260
+ with open(path, "wb") as f:
261
+ f.write(body)
262
+
263
+ user_path = self.get_request_user_filepath(request, None)
264
+ if full_info:
265
+ resp = get_file_info(path, user_path)
266
+ else:
267
+ resp = os.path.relpath(path, user_path)
268
+
269
+ return web.json_response(resp)
270
+
271
+ @routes.delete("/userdata/{file}")
272
+ async def delete_userdata(request):
273
+ path = get_user_data_path(request, check_exists=True)
274
+ if not isinstance(path, str):
275
+ return path
276
+
277
+ os.remove(path)
278
+
279
+ return web.Response(status=204)
280
+
281
+ @routes.post("/userdata/{file}/move/{dest}")
282
+ async def move_userdata(request):
283
+ """
284
+ Move or rename a user data file.
285
+
286
+ This endpoint handles moving or renaming files within a user's data directory, with options for
287
+ controlling overwrite behavior and response format.
288
+
289
+ Path Parameters:
290
+ - file: The source file path (URL encoded if necessary)
291
+ - dest: The destination file path (URL encoded if necessary)
292
+
293
+ Query Parameters:
294
+ - overwrite (optional): If "false", prevents overwriting existing files. Defaults to "true".
295
+ - full_info (optional): If "true", returns detailed file information (path, size, modified time).
296
+ If "false", returns only the relative file path.
297
+
298
+ Returns:
299
+ - 400: If either 'file' or 'dest' parameter is missing
300
+ - 403: If either requested path is not allowed
301
+ - 404: If the source file does not exist
302
+ - 409: If overwrite=false and the destination file already exists
303
+ - 200: JSON response with either:
304
+ - Full file information (if full_info=true)
305
+ - Relative file path (if full_info=false)
306
+ """
307
+ source = get_user_data_path(request, check_exists=True)
308
+ if not isinstance(source, str):
309
+ return source
310
+
311
+ dest = get_user_data_path(request, check_exists=False, param="dest")
312
+ if not isinstance(source, str):
313
+ return dest
314
+
315
+ overwrite = request.query.get("overwrite", 'true') != "false"
316
+ full_info = request.query.get('full_info', 'false').lower() == "true"
317
+
318
+ if not overwrite and os.path.exists(dest):
319
+ return web.Response(status=409, text="File already exists")
320
+
321
+ logging.info(f"moving '{source}' -> '{dest}'")
322
+ shutil.move(source, dest)
323
+
324
+ user_path = self.get_request_user_filepath(request, None)
325
+ if full_info:
326
+ resp = get_file_info(dest, user_path)
327
+ else:
328
+ resp = os.path.relpath(dest, user_path)
329
+
330
+ 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,190 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import enum
3
+ import os
4
+ from typing import Optional
5
+ import comfy.options
6
+
7
+
8
+ class EnumAction(argparse.Action):
9
+ """
10
+ Argparse action for handling Enums
11
+ """
12
+ def __init__(self, **kwargs):
13
+ # Pop off the type value
14
+ enum_type = kwargs.pop("type", None)
15
+
16
+ # Ensure an Enum subclass is provided
17
+ if enum_type is None:
18
+ raise ValueError("type must be assigned an Enum when using EnumAction")
19
+ if not issubclass(enum_type, enum.Enum):
20
+ raise TypeError("type must be an Enum when using EnumAction")
21
+
22
+ # Generate choices from the Enum
23
+ choices = tuple(e.value for e in enum_type)
24
+ kwargs.setdefault("choices", choices)
25
+ kwargs.setdefault("metavar", f"[{','.join(list(choices))}]")
26
+
27
+ super(EnumAction, self).__init__(**kwargs)
28
+
29
+ self._enum = enum_type
30
+
31
+ def __call__(self, parser, namespace, values, option_string=None):
32
+ # Convert value back into an Enum
33
+ value = self._enum(values)
34
+ setattr(namespace, self.dest, value)
35
+
36
+
37
+ parser = argparse.ArgumentParser()
38
+
39
+ 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)")
40
+ parser.add_argument("--port", type=int, default=8188, help="Set the listen port.")
41
+ 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")
42
+ 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")
43
+ 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 '*'.")
44
+ parser.add_argument("--max-upload-size", type=float, default=100, help="Set the maximum upload size in MB.")
45
+
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.")
48
+ parser.add_argument("--temp-directory", type=str, default=None, help="Set the ComfyUI temp directory (default is in the ComfyUI directory).")
49
+ parser.add_argument("--input-directory", type=str, default=None, help="Set the ComfyUI input 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
+
70
+ fpvae_group = parser.add_mutually_exclusive_group()
71
+ fpvae_group.add_argument("--fp16-vae", action="store_true", help="Run the VAE in fp16, might cause black images.")
72
+ fpvae_group.add_argument("--fp32-vae", action="store_true", help="Run the VAE in full precision fp32.")
73
+ fpvae_group.add_argument("--bf16-vae", action="store_true", help="Run the VAE in bf16.")
74
+
75
+ parser.add_argument("--cpu-vae", action="store_true", help="Run the VAE on the CPU.")
76
+
77
+ fpte_group = parser.add_mutually_exclusive_group()
78
+ fpte_group.add_argument("--fp8_e4m3fn-text-enc", action="store_true", help="Store text encoder weights in fp8 (e4m3fn variant).")
79
+ fpte_group.add_argument("--fp8_e5m2-text-enc", action="store_true", help="Store text encoder weights in fp8 (e5m2 variant).")
80
+ fpte_group.add_argument("--fp16-text-enc", action="store_true", help="Store text encoder weights in fp16.")
81
+ fpte_group.add_argument("--fp32-text-enc", action="store_true", help="Store text encoder weights in fp32.")
82
+
83
+ parser.add_argument("--force-channels-last", action="store_true", help="Force channels last format when inferencing the models.")
84
+
85
+ parser.add_argument("--directml", type=int, nargs="?", metavar="DIRECTML_DEVICE", const=-1, help="Use torch-directml.")
86
+
87
+ parser.add_argument("--oneapi-device-selector", type=str, default=None, metavar="SELECTOR_STRING", help="Sets the oneAPI device(s) this instance will use.")
88
+ parser.add_argument("--disable-ipex-optimize", action="store_true", help="Disables ipex.optimize default when loading models with Intel's Extension for Pytorch.")
89
+
90
+ class LatentPreviewMethod(enum.Enum):
91
+ NoPreviews = "none"
92
+ Auto = "auto"
93
+ Latent2RGB = "latent2rgb"
94
+ TAESD = "taesd"
95
+
96
+ parser.add_argument("--preview-method", type=LatentPreviewMethod, default=LatentPreviewMethod.NoPreviews, help="Default preview method for sampler nodes.", action=EnumAction)
97
+
98
+ parser.add_argument("--preview-size", type=int, default=512, help="Sets the maximum preview size for sampler nodes.")
99
+
100
+ cache_group = parser.add_mutually_exclusive_group()
101
+ cache_group.add_argument("--cache-classic", action="store_true", help="Use the old style (aggressive) caching.")
102
+ 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.")
103
+
104
+ attn_group = parser.add_mutually_exclusive_group()
105
+ attn_group.add_argument("--use-split-cross-attention", action="store_true", help="Use the split cross attention optimization. Ignored when xformers is used.")
106
+ attn_group.add_argument("--use-quad-cross-attention", action="store_true", help="Use the sub-quadratic cross attention optimization . Ignored when xformers is used.")
107
+ attn_group.add_argument("--use-pytorch-cross-attention", action="store_true", help="Use the new pytorch 2.0 cross attention function.")
108
+ attn_group.add_argument("--use-sage-attention", action="store_true", help="Use sage attention.")
109
+
110
+ parser.add_argument("--disable-xformers", action="store_true", help="Disable xformers.")
111
+
112
+ upcast = parser.add_mutually_exclusive_group()
113
+ upcast.add_argument("--force-upcast-attention", action="store_true", help="Force enable attention upcasting, please report if it fixes black images.")
114
+ upcast.add_argument("--dont-upcast-attention", action="store_true", help="Disable all upcasting of attention. Should be unnecessary except for debugging.")
115
+
116
+
117
+ vram_group = parser.add_mutually_exclusive_group()
118
+ vram_group.add_argument("--gpu-only", action="store_true", help="Store and run everything (text encoders/CLIP models, etc... on the GPU).")
119
+ 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.")
120
+ vram_group.add_argument("--normalvram", action="store_true", help="Used to force normal vram use if lowvram gets automatically enabled.")
121
+ vram_group.add_argument("--lowvram", action="store_true", help="Split the unet in parts to use less vram.")
122
+ vram_group.add_argument("--novram", action="store_true", help="When lowvram isn't enough.")
123
+ vram_group.add_argument("--cpu", action="store_true", help="To use the CPU for everything (slow).")
124
+
125
+ 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.")
126
+
127
+
128
+ 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.")
129
+
130
+ 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.")
131
+ 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.")
132
+ parser.add_argument("--fast", action="store_true", help="Enable some untested and potentially quality deteriorating optimizations.")
133
+
134
+ parser.add_argument("--dont-print-server", action="store_true", help="Don't print server output.")
135
+ parser.add_argument("--quick-test-for-ci", action="store_true", help="Quick test for CI.")
136
+ 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).")
137
+
138
+ parser.add_argument("--disable-metadata", action="store_true", help="Disable saving prompt metadata in files.")
139
+ parser.add_argument("--disable-all-custom-nodes", action="store_true", help="Disable loading all custom nodes.")
140
+
141
+ parser.add_argument("--multi-user", action="store_true", help="Enables per-user storage.")
142
+
143
+ parser.add_argument("--verbose", default='INFO', const='DEBUG', nargs="?", choices=['DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL'], help='Set the logging level')
144
+ parser.add_argument("--log-stdout", action="store_true", help="Send normal process output to stdout instead of stderr (default).")
145
+
146
+ # The default built-in provider hosted under web/
147
+ DEFAULT_VERSION_STRING = "comfyanonymous/ComfyUI@latest"
148
+
149
+ parser.add_argument(
150
+ "--front-end-version",
151
+ type=str,
152
+ default=DEFAULT_VERSION_STRING,
153
+ help="""
154
+ Specifies the version of the frontend to be used. This command needs internet connectivity to query and
155
+ download available frontend implementations from GitHub releases.
156
+
157
+ The version string should be in the format of:
158
+ [repoOwner]/[repoName]@[version]
159
+ where version is one of: "latest" or a valid version number (e.g. "1.0.0")
160
+ """,
161
+ )
162
+
163
+ def is_valid_directory(path: Optional[str]) -> Optional[str]:
164
+ """Validate if the given path is a directory."""
165
+ if path is None:
166
+ return None
167
+
168
+ if not os.path.isdir(path):
169
+ raise argparse.ArgumentTypeError(f"{path} is not a valid directory.")
170
+ return path
171
+
172
+ parser.add_argument(
173
+ "--front-end-root",
174
+ type=is_valid_directory,
175
+ default=None,
176
+ help="The local filesystem path to the directory where the frontend is located. Overrides --front-end-version.",
177
+ )
178
+
179
+ parser.add_argument("--user-directory", type=is_valid_directory, default=None, help="Set the ComfyUI user directory with an absolute path.")
180
+
181
+ if comfy.options.args_parsing:
182
+ args = parser.parse_args()
183
+ else:
184
+ args = parser.parse_args([])
185
+
186
+ if args.windows_standalone_build:
187
+ args.auto_launch = True
188
+
189
+ if args.disable_auto_launch:
190
+ args.auto_launch = False
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,218 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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, attention_mask=None, intermediate_output=None, final_layer_norm_intermediate=True, dtype=torch.float32):
101
+ x = self.embeddings(input_tokens, dtype=dtype)
102
+ mask = None
103
+ if attention_mask is not None:
104
+ 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])
105
+ mask = mask.masked_fill(mask.to(torch.bool), float("-inf"))
106
+
107
+ causal_mask = torch.empty(x.shape[1], x.shape[1], dtype=x.dtype, device=x.device).fill_(float("-inf")).triu_(1)
108
+ if mask is not None:
109
+ mask += causal_mask
110
+ else:
111
+ mask = causal_mask
112
+
113
+ x, i = self.encoder(x, mask=mask, intermediate_output=intermediate_output)
114
+ x = self.final_layer_norm(x)
115
+ if i is not None and final_layer_norm_intermediate:
116
+ i = self.final_layer_norm(i)
117
+
118
+ 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),]
119
+ return x, i, pooled_output
120
+
121
+ class CLIPTextModel(torch.nn.Module):
122
+ def __init__(self, config_dict, dtype, device, operations):
123
+ super().__init__()
124
+ self.num_layers = config_dict["num_hidden_layers"]
125
+ self.text_model = CLIPTextModel_(config_dict, dtype, device, operations)
126
+ embed_dim = config_dict["hidden_size"]
127
+ self.text_projection = operations.Linear(embed_dim, embed_dim, bias=False, dtype=dtype, device=device)
128
+ self.dtype = dtype
129
+
130
+ def get_input_embeddings(self):
131
+ return self.text_model.embeddings.token_embedding
132
+
133
+ def set_input_embeddings(self, embeddings):
134
+ self.text_model.embeddings.token_embedding = embeddings
135
+
136
+ def forward(self, *args, **kwargs):
137
+ x = self.text_model(*args, **kwargs)
138
+ out = self.text_projection(x[2])
139
+ return (x[0], x[1], out, x[2])
140
+
141
+
142
+ class CLIPVisionEmbeddings(torch.nn.Module):
143
+ def __init__(self, embed_dim, num_channels=3, patch_size=14, image_size=224, model_type="", dtype=None, device=None, operations=None):
144
+ super().__init__()
145
+
146
+ num_patches = (image_size // patch_size) ** 2
147
+ if model_type == "siglip_vision_model":
148
+ self.class_embedding = None
149
+ patch_bias = True
150
+ else:
151
+ num_patches = num_patches + 1
152
+ self.class_embedding = torch.nn.Parameter(torch.empty(embed_dim, dtype=dtype, device=device))
153
+ patch_bias = False
154
+
155
+ self.patch_embedding = operations.Conv2d(
156
+ in_channels=num_channels,
157
+ out_channels=embed_dim,
158
+ kernel_size=patch_size,
159
+ stride=patch_size,
160
+ bias=patch_bias,
161
+ dtype=dtype,
162
+ device=device
163
+ )
164
+
165
+ self.position_embedding = operations.Embedding(num_patches, embed_dim, dtype=dtype, device=device)
166
+
167
+ def forward(self, pixel_values):
168
+ embeds = self.patch_embedding(pixel_values).flatten(2).transpose(1, 2)
169
+ if self.class_embedding is not None:
170
+ embeds = torch.cat([comfy.ops.cast_to_input(self.class_embedding, embeds).expand(pixel_values.shape[0], 1, -1), embeds], dim=1)
171
+ return embeds + comfy.ops.cast_to_input(self.position_embedding.weight, embeds)
172
+
173
+
174
+ class CLIPVision(torch.nn.Module):
175
+ def __init__(self, config_dict, dtype, device, operations):
176
+ super().__init__()
177
+ num_layers = config_dict["num_hidden_layers"]
178
+ embed_dim = config_dict["hidden_size"]
179
+ heads = config_dict["num_attention_heads"]
180
+ intermediate_size = config_dict["intermediate_size"]
181
+ intermediate_activation = config_dict["hidden_act"]
182
+ model_type = config_dict["model_type"]
183
+
184
+ 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)
185
+ if model_type == "siglip_vision_model":
186
+ self.pre_layrnorm = lambda a: a
187
+ self.output_layernorm = True
188
+ else:
189
+ self.pre_layrnorm = operations.LayerNorm(embed_dim)
190
+ self.output_layernorm = False
191
+ self.encoder = CLIPEncoder(num_layers, embed_dim, heads, intermediate_size, intermediate_activation, dtype, device, operations)
192
+ self.post_layernorm = operations.LayerNorm(embed_dim)
193
+
194
+ def forward(self, pixel_values, attention_mask=None, intermediate_output=None):
195
+ x = self.embeddings(pixel_values)
196
+ x = self.pre_layrnorm(x)
197
+ #TODO: attention_mask?
198
+ x, i = self.encoder(x, mask=None, intermediate_output=intermediate_output)
199
+ if self.output_layernorm:
200
+ x = self.post_layernorm(x)
201
+ pooled_output = x
202
+ else:
203
+ pooled_output = self.post_layernorm(x[:, 0, :])
204
+ return x, i, pooled_output
205
+
206
+ class CLIPVisionModelProjection(torch.nn.Module):
207
+ def __init__(self, config_dict, dtype, device, operations):
208
+ super().__init__()
209
+ self.vision_model = CLIPVision(config_dict, dtype, device, operations)
210
+ if "projection_dim" in config_dict:
211
+ self.visual_projection = operations.Linear(config_dict["hidden_size"], config_dict["projection_dim"], bias=False)
212
+ else:
213
+ self.visual_projection = lambda a: a
214
+
215
+ def forward(self, *args, **kwargs):
216
+ x = self.vision_model(*args, **kwargs)
217
+ out = self.visual_projection(x[2])
218
+ return (x[0], x[1], out)
comfy/clip_vision.py ADDED
@@ -0,0 +1,129 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
13
+ class Output:
14
+ def __getitem__(self, key):
15
+ return getattr(self, key)
16
+ def __setitem__(self, key, item):
17
+ setattr(self, key, item)
18
+
19
+ def clip_preprocess(image, size=224, mean=[0.48145466, 0.4578275, 0.40821073], std=[0.26862954, 0.26130258, 0.27577711], crop=True):
20
+ mean = torch.tensor(mean, device=image.device, dtype=image.dtype)
21
+ std = torch.tensor(std, device=image.device, dtype=image.dtype)
22
+ image = image.movedim(-1, 1)
23
+ if not (image.shape[2] == size and image.shape[3] == size):
24
+ if crop:
25
+ scale = (size / min(image.shape[2], image.shape[3]))
26
+ scale_size = (round(scale * image.shape[2]), round(scale * image.shape[3]))
27
+ else:
28
+ scale_size = (size, size)
29
+
30
+ image = torch.nn.functional.interpolate(image, size=scale_size, mode="bicubic", antialias=True)
31
+ h = (image.shape[2] - size)//2
32
+ w = (image.shape[3] - size)//2
33
+ image = image[:,:,h:h+size,w:w+size]
34
+ image = torch.clip((255. * image), 0, 255).round() / 255.0
35
+ return (image - mean.view([3,1,1])) / std.view([3,1,1])
36
+
37
+ class ClipVisionModel():
38
+ def __init__(self, json_config):
39
+ with open(json_config) as f:
40
+ config = json.load(f)
41
+
42
+ self.image_size = config.get("image_size", 224)
43
+ self.image_mean = config.get("image_mean", [0.48145466, 0.4578275, 0.40821073])
44
+ self.image_std = config.get("image_std", [0.26862954, 0.26130258, 0.27577711])
45
+ self.load_device = comfy.model_management.text_encoder_device()
46
+ offload_device = comfy.model_management.text_encoder_offload_device()
47
+ self.dtype = comfy.model_management.text_encoder_dtype(self.load_device)
48
+ self.model = comfy.clip_model.CLIPVisionModelProjection(config, self.dtype, offload_device, comfy.ops.manual_cast)
49
+ self.model.eval()
50
+
51
+ self.patcher = comfy.model_patcher.ModelPatcher(self.model, load_device=self.load_device, offload_device=offload_device)
52
+
53
+ def load_sd(self, sd):
54
+ return self.model.load_state_dict(sd, strict=False)
55
+
56
+ def get_sd(self):
57
+ return self.model.state_dict()
58
+
59
+ def encode_image(self, image, crop=True):
60
+ comfy.model_management.load_model_gpu(self.patcher)
61
+ pixel_values = clip_preprocess(image.to(self.load_device), size=self.image_size, mean=self.image_mean, std=self.image_std, crop=crop).float()
62
+ out = self.model(pixel_values=pixel_values, intermediate_output=-2)
63
+
64
+ outputs = Output()
65
+ outputs["last_hidden_state"] = out[0].to(comfy.model_management.intermediate_device())
66
+ outputs["image_embeds"] = out[2].to(comfy.model_management.intermediate_device())
67
+ outputs["penultimate_hidden_states"] = out[1].to(comfy.model_management.intermediate_device())
68
+ return outputs
69
+
70
+ def convert_to_transformers(sd, prefix):
71
+ sd_k = sd.keys()
72
+ if "{}transformer.resblocks.0.attn.in_proj_weight".format(prefix) in sd_k:
73
+ keys_to_replace = {
74
+ "{}class_embedding".format(prefix): "vision_model.embeddings.class_embedding",
75
+ "{}conv1.weight".format(prefix): "vision_model.embeddings.patch_embedding.weight",
76
+ "{}positional_embedding".format(prefix): "vision_model.embeddings.position_embedding.weight",
77
+ "{}ln_post.bias".format(prefix): "vision_model.post_layernorm.bias",
78
+ "{}ln_post.weight".format(prefix): "vision_model.post_layernorm.weight",
79
+ "{}ln_pre.bias".format(prefix): "vision_model.pre_layrnorm.bias",
80
+ "{}ln_pre.weight".format(prefix): "vision_model.pre_layrnorm.weight",
81
+ }
82
+
83
+ for x in keys_to_replace:
84
+ if x in sd_k:
85
+ sd[keys_to_replace[x]] = sd.pop(x)
86
+
87
+ if "{}proj".format(prefix) in sd_k:
88
+ sd['visual_projection.weight'] = sd.pop("{}proj".format(prefix)).transpose(0, 1)
89
+
90
+ sd = transformers_convert(sd, prefix, "vision_model.", 48)
91
+ else:
92
+ replace_prefix = {prefix: ""}
93
+ sd = state_dict_prefix_replace(sd, replace_prefix)
94
+ return sd
95
+
96
+ def load_clipvision_from_sd(sd, prefix="", convert_keys=False):
97
+ if convert_keys:
98
+ sd = convert_to_transformers(sd, prefix)
99
+ if "vision_model.encoder.layers.47.layer_norm1.weight" in sd:
100
+ json_config = os.path.join(os.path.dirname(os.path.realpath(__file__)), "clip_vision_config_g.json")
101
+ elif "vision_model.encoder.layers.30.layer_norm1.weight" in sd:
102
+ json_config = os.path.join(os.path.dirname(os.path.realpath(__file__)), "clip_vision_config_h.json")
103
+ elif "vision_model.encoder.layers.22.layer_norm1.weight" in sd:
104
+ if sd["vision_model.encoder.layers.0.layer_norm1.weight"].shape[0] == 1152:
105
+ json_config = os.path.join(os.path.dirname(os.path.realpath(__file__)), "clip_vision_siglip_384.json")
106
+ elif sd["vision_model.embeddings.position_embedding.weight"].shape[0] == 577:
107
+ json_config = os.path.join(os.path.dirname(os.path.realpath(__file__)), "clip_vision_config_vitl_336.json")
108
+ else:
109
+ json_config = os.path.join(os.path.dirname(os.path.realpath(__file__)), "clip_vision_config_vitl.json")
110
+ else:
111
+ return None
112
+
113
+ clip = ClipVisionModel(json_config)
114
+ m, u = clip.load_sd(sd)
115
+ if len(m) > 0:
116
+ logging.warning("missing clip vision: {}".format(m))
117
+ u = set(u)
118
+ keys = list(sd.keys())
119
+ for k in keys:
120
+ if k not in u:
121
+ sd.pop(k)
122
+ return clip
123
+
124
+ def load(ckpt_path):
125
+ sd = load_torch_file(ckpt_path)
126
+ if "visual.transformer.resblocks.0.attn.in_proj_weight" in sd:
127
+ return load_clipvision_from_sd(sd, prefix="visual.", convert_keys=True)
128
+ else:
129
+ 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_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/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,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from typing import Callable, Protocol, TypedDict, Optional, List
3
+ from .node_typing import IO, InputTypeDict, ComfyNodeABC, CheckLazyMixin
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
+ ]
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,274 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Comfy-specific type hinting"""
2
+
3
+ from __future__ import annotations
4
+ from typing import Literal, TypedDict
5
+ from abc import ABC, abstractmethod
6
+ from enum import Enum
7
+
8
+
9
+ class StrEnum(str, Enum):
10
+ """Base class for string enums. Python's StrEnum is not available until 3.11."""
11
+
12
+ def __str__(self) -> str:
13
+ return self.value
14
+
15
+
16
+ class IO(StrEnum):
17
+ """Node input/output data types.
18
+
19
+ Includes functionality for ``"*"`` (`ANY`) and ``"MULTI,TYPES"``.
20
+ """
21
+
22
+ STRING = "STRING"
23
+ IMAGE = "IMAGE"
24
+ MASK = "MASK"
25
+ LATENT = "LATENT"
26
+ BOOLEAN = "BOOLEAN"
27
+ INT = "INT"
28
+ FLOAT = "FLOAT"
29
+ CONDITIONING = "CONDITIONING"
30
+ SAMPLER = "SAMPLER"
31
+ SIGMAS = "SIGMAS"
32
+ GUIDER = "GUIDER"
33
+ NOISE = "NOISE"
34
+ CLIP = "CLIP"
35
+ CONTROL_NET = "CONTROL_NET"
36
+ VAE = "VAE"
37
+ MODEL = "MODEL"
38
+ CLIP_VISION = "CLIP_VISION"
39
+ CLIP_VISION_OUTPUT = "CLIP_VISION_OUTPUT"
40
+ STYLE_MODEL = "STYLE_MODEL"
41
+ GLIGEN = "GLIGEN"
42
+ UPSCALE_MODEL = "UPSCALE_MODEL"
43
+ AUDIO = "AUDIO"
44
+ WEBCAM = "WEBCAM"
45
+ POINT = "POINT"
46
+ FACE_ANALYSIS = "FACE_ANALYSIS"
47
+ BBOX = "BBOX"
48
+ SEGS = "SEGS"
49
+
50
+ ANY = "*"
51
+ """Always matches any type, but at a price.
52
+
53
+ Causes some functionality issues (e.g. reroutes, link types), and should be avoided whenever possible.
54
+ """
55
+ NUMBER = "FLOAT,INT"
56
+ """A float or an int - could be either"""
57
+ PRIMITIVE = "STRING,FLOAT,INT,BOOLEAN"
58
+ """Could be any of: string, float, int, or bool"""
59
+
60
+ def __ne__(self, value: object) -> bool:
61
+ if self == "*" or value == "*":
62
+ return False
63
+ if not isinstance(value, str):
64
+ return True
65
+ a = frozenset(self.split(","))
66
+ b = frozenset(value.split(","))
67
+ return not (b.issubset(a) or a.issubset(b))
68
+
69
+
70
+ class InputTypeOptions(TypedDict):
71
+ """Provides type hinting for the return type of the INPUT_TYPES node function.
72
+
73
+ 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`).
74
+
75
+ Comfy Docs: https://docs.comfy.org/essentials/custom_node_datatypes
76
+ """
77
+
78
+ default: bool | str | float | int | list | tuple
79
+ """The default value of the widget"""
80
+ defaultInput: bool
81
+ """Defaults to an input slot rather than a widget"""
82
+ forceInput: bool
83
+ """`defaultInput` and also don't allow converting to a widget"""
84
+ lazy: bool
85
+ """Declares that this input uses lazy evaluation"""
86
+ rawLink: bool
87
+ """When a link exists, rather than receiving the evaluated value, you will receive the link (i.e. `["nodeId", <outputIndex>]`). Designed for node expansion."""
88
+ tooltip: str
89
+ """Tooltip for the input (or widget), shown on pointer hover"""
90
+ # class InputTypeNumber(InputTypeOptions):
91
+ # default: float | int
92
+ min: float
93
+ """The minimum value of a number (``FLOAT`` | ``INT``)"""
94
+ max: float
95
+ """The maximum value of a number (``FLOAT`` | ``INT``)"""
96
+ step: float
97
+ """The amount to increment or decrement a widget by when stepping up/down (``FLOAT`` | ``INT``)"""
98
+ round: float
99
+ """Floats are rounded by this value (``FLOAT``)"""
100
+ # class InputTypeBoolean(InputTypeOptions):
101
+ # default: bool
102
+ label_on: str
103
+ """The label to use in the UI when the bool is True (``BOOLEAN``)"""
104
+ label_on: str
105
+ """The label to use in the UI when the bool is False (``BOOLEAN``)"""
106
+ # class InputTypeString(InputTypeOptions):
107
+ # default: str
108
+ multiline: bool
109
+ """Use a multiline text box (``STRING``)"""
110
+ placeholder: str
111
+ """Placeholder text to display in the UI when empty (``STRING``)"""
112
+ # Deprecated:
113
+ # defaultVal: str
114
+ dynamicPrompts: bool
115
+ """Causes the front-end to evaluate dynamic prompts (``STRING``)"""
116
+
117
+
118
+ class HiddenInputTypeDict(TypedDict):
119
+ """Provides type hinting for the hidden entry of node INPUT_TYPES."""
120
+
121
+ node_id: Literal["UNIQUE_ID"]
122
+ """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)."""
123
+ unique_id: Literal["UNIQUE_ID"]
124
+ """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)."""
125
+ prompt: Literal["PROMPT"]
126
+ """PROMPT is the complete prompt sent by the client to the server. See the prompt object for a full description."""
127
+ extra_pnginfo: Literal["EXTRA_PNGINFO"]
128
+ """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)."""
129
+ dynprompt: Literal["DYNPROMPT"]
130
+ """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."""
131
+
132
+
133
+ class InputTypeDict(TypedDict):
134
+ """Provides type hinting for node INPUT_TYPES.
135
+
136
+ Comfy Docs: https://docs.comfy.org/essentials/custom_node_more_on_inputs
137
+ """
138
+
139
+ required: dict[str, tuple[IO, InputTypeOptions]]
140
+ """Describes all inputs that must be connected for the node to execute."""
141
+ optional: dict[str, tuple[IO, InputTypeOptions]]
142
+ """Describes inputs which do not need to be connected."""
143
+ hidden: HiddenInputTypeDict
144
+ """Offers advanced functionality and server-client communication.
145
+
146
+ Comfy Docs: https://docs.comfy.org/essentials/custom_node_more_on_inputs#hidden-inputs
147
+ """
148
+
149
+
150
+ class ComfyNodeABC(ABC):
151
+ """Abstract base class for Comfy nodes. Includes the names and expected types of attributes.
152
+
153
+ Comfy Docs: https://docs.comfy.org/essentials/custom_node_server_overview
154
+ """
155
+
156
+ DESCRIPTION: str
157
+ """Node description, shown as a tooltip when hovering over the node.
158
+
159
+ Usage::
160
+
161
+ # Explicitly define the description
162
+ DESCRIPTION = "Example description here."
163
+
164
+ # Use the docstring of the node class.
165
+ DESCRIPTION = cleandoc(__doc__)
166
+ """
167
+ CATEGORY: str
168
+ """The category of the node, as per the "Add Node" menu.
169
+
170
+ Comfy Docs: https://docs.comfy.org/essentials/custom_node_server_overview#category
171
+ """
172
+ EXPERIMENTAL: bool
173
+ """Flags a node as experimental, informing users that it may change or not work as expected."""
174
+ DEPRECATED: bool
175
+ """Flags a node as deprecated, indicating to users that they should find alternatives to this node."""
176
+
177
+ @classmethod
178
+ @abstractmethod
179
+ def INPUT_TYPES(s) -> InputTypeDict:
180
+ """Defines node inputs.
181
+
182
+ * Must include the ``required`` key, which describes all inputs that must be connected for the node to execute.
183
+ * The ``optional`` key can be added to describe inputs which do not need to be connected.
184
+ * The ``hidden`` key offers some advanced functionality. More info at: https://docs.comfy.org/essentials/custom_node_more_on_inputs#hidden-inputs
185
+
186
+ Comfy Docs: https://docs.comfy.org/essentials/custom_node_server_overview#input-types
187
+ """
188
+ return {"required": {}}
189
+
190
+ OUTPUT_NODE: bool
191
+ """Flags this node as an output node, causing any inputs it requires to be executed.
192
+
193
+ If a node is not connected to any output nodes, that node will not be executed. Usage::
194
+
195
+ OUTPUT_NODE = True
196
+
197
+ From the docs:
198
+
199
+ By default, a node is not considered an output. Set ``OUTPUT_NODE = True`` to specify that it is.
200
+
201
+ Comfy Docs: https://docs.comfy.org/essentials/custom_node_server_overview#output-node
202
+ """
203
+ INPUT_IS_LIST: bool
204
+ """A flag indicating if this node implements the additional code necessary to deal with OUTPUT_IS_LIST nodes.
205
+
206
+ All inputs of ``type`` will become ``list[type]``, regardless of how many items are passed in. This also affects ``check_lazy_status``.
207
+
208
+ From the docs:
209
+
210
+ 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``.
211
+
212
+ Comfy Docs: https://docs.comfy.org/essentials/custom_node_lists#list-processing
213
+ """
214
+ OUTPUT_IS_LIST: tuple[bool]
215
+ """A tuple indicating which node outputs are lists, but will be connected to nodes that expect individual items.
216
+
217
+ Connected nodes that do not implement `INPUT_IS_LIST` will be executed once for every item in the list.
218
+
219
+ A ``tuple[bool]``, where the items match those in `RETURN_TYPES`::
220
+
221
+ RETURN_TYPES = (IO.INT, IO.INT, IO.STRING)
222
+ OUTPUT_IS_LIST = (True, True, False) # The string output will be handled normally
223
+
224
+ From the docs:
225
+
226
+ In order to tell Comfy that the list being returned should not be wrapped, but treated as a series of data for sequential processing,
227
+ the node should provide a class attribute `OUTPUT_IS_LIST`, which is a ``tuple[bool]``, of the same length as `RETURN_TYPES`,
228
+ specifying which outputs which should be so treated.
229
+
230
+ Comfy Docs: https://docs.comfy.org/essentials/custom_node_lists#list-processing
231
+ """
232
+
233
+ RETURN_TYPES: tuple[IO]
234
+ """A tuple representing the outputs of this node.
235
+
236
+ Usage::
237
+
238
+ RETURN_TYPES = (IO.INT, "INT", "CUSTOM_TYPE")
239
+
240
+ Comfy Docs: https://docs.comfy.org/essentials/custom_node_server_overview#return-types
241
+ """
242
+ RETURN_NAMES: tuple[str]
243
+ """The output slot names for each item in `RETURN_TYPES`, e.g. ``RETURN_NAMES = ("count", "filter_string")``
244
+
245
+ Comfy Docs: https://docs.comfy.org/essentials/custom_node_server_overview#return-names
246
+ """
247
+ OUTPUT_TOOLTIPS: tuple[str]
248
+ """A tuple of strings to use as tooltips for node outputs, one for each item in `RETURN_TYPES`."""
249
+ FUNCTION: str
250
+ """The name of the function to execute as a literal string, e.g. `FUNCTION = "execute"`
251
+
252
+ Comfy Docs: https://docs.comfy.org/essentials/custom_node_server_overview#function
253
+ """
254
+
255
+
256
+ class CheckLazyMixin:
257
+ """Provides a basic check_lazy_status implementation and type hinting for nodes that use lazy inputs."""
258
+
259
+ def check_lazy_status(self, **kwargs) -> list[str]:
260
+ """Returns a list of input names that should be evaluated.
261
+
262
+ This basic mixin impl. requires all inputs.
263
+
264
+ :kwargs: All node inputs will be included here. If the input is ``None``, it should be assumed that it has not yet been evaluated. \
265
+ When using ``INPUT_IS_LIST = True``, unevaluated will instead be ``(None,)``.
266
+
267
+ Params should match the nodes execution ``FUNCTION`` (self, and all inputs by name).
268
+ Will be executed repeatedly until it returns an empty list, or all requested items were already evaluated (and sent as params).
269
+
270
+ Comfy Docs: https://docs.comfy.org/essentials/custom_node_lazy_evaluation#defining-check-lazy-status
271
+ """
272
+
273
+ need = [name for name in kwargs if kwargs[name] is None]
274
+ return need
comfy/conds.py ADDED
@@ -0,0 +1,83 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import math
3
+ import comfy.utils
4
+
5
+
6
+ def lcm(a, b): #TODO: eventually replace by math.lcm (added in python3.9)
7
+ return abs(a*b) // math.gcd(a, b)
8
+
9
+ class CONDRegular:
10
+ def __init__(self, cond):
11
+ self.cond = cond
12
+
13
+ def _copy_with(self, cond):
14
+ return self.__class__(cond)
15
+
16
+ def process_cond(self, batch_size, device, **kwargs):
17
+ return self._copy_with(comfy.utils.repeat_to_batch_size(self.cond, batch_size).to(device))
18
+
19
+ def can_concat(self, other):
20
+ if self.cond.shape != other.cond.shape:
21
+ return False
22
+ return True
23
+
24
+ def concat(self, others):
25
+ conds = [self.cond]
26
+ for x in others:
27
+ conds.append(x.cond)
28
+ return torch.cat(conds)
29
+
30
+ class CONDNoiseShape(CONDRegular):
31
+ def process_cond(self, batch_size, device, area, **kwargs):
32
+ data = self.cond
33
+ if area is not None:
34
+ dims = len(area) // 2
35
+ for i in range(dims):
36
+ data = data.narrow(i + 2, area[i + dims], area[i])
37
+
38
+ return self._copy_with(comfy.utils.repeat_to_batch_size(data, batch_size).to(device))
39
+
40
+
41
+ class CONDCrossAttn(CONDRegular):
42
+ def can_concat(self, other):
43
+ s1 = self.cond.shape
44
+ s2 = other.cond.shape
45
+ if s1 != s2:
46
+ if s1[0] != s2[0] or s1[2] != s2[2]: #these 2 cases should not happen
47
+ return False
48
+
49
+ mult_min = lcm(s1[1], s2[1])
50
+ diff = mult_min // min(s1[1], s2[1])
51
+ if diff > 4: #arbitrary limit on the padding because it's probably going to impact performance negatively if it's too much
52
+ return False
53
+ return True
54
+
55
+ def concat(self, others):
56
+ conds = [self.cond]
57
+ crossattn_max_len = self.cond.shape[1]
58
+ for x in others:
59
+ c = x.cond
60
+ crossattn_max_len = lcm(crossattn_max_len, c.shape[1])
61
+ conds.append(c)
62
+
63
+ out = []
64
+ for c in conds:
65
+ if c.shape[1] < crossattn_max_len:
66
+ c = c.repeat(1, crossattn_max_len // c.shape[1], 1) #padding with repeat doesn't change result
67
+ out.append(c)
68
+ return torch.cat(out)
69
+
70
+ class CONDConstant(CONDRegular):
71
+ def __init__(self, cond):
72
+ self.cond = cond
73
+
74
+ def process_cond(self, batch_size, device, **kwargs):
75
+ return self._copy_with(self.cond)
76
+
77
+ def can_concat(self, other):
78
+ if self.cond != other.cond:
79
+ return False
80
+ return True
81
+
82
+ def concat(self, others):
83
+ return self.cond
comfy/controlnet.py ADDED
@@ -0,0 +1,862 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ if weight_dtype is not None:
422
+ supported_inference_dtypes.append(weight_dtype)
423
+
424
+ unet_dtype = comfy.model_management.unet_dtype(model_params=-1, supported_dtypes=supported_inference_dtypes)
425
+
426
+ load_device = comfy.model_management.get_torch_device()
427
+ manual_cast_dtype = comfy.model_management.unet_manual_cast(unet_dtype, load_device)
428
+
429
+ operations = model_options.get("custom_operations", None)
430
+ if operations is None:
431
+ operations = comfy.ops.pick_operations(unet_dtype, manual_cast_dtype, disable_fast_fp8=True)
432
+
433
+ offload_device = comfy.model_management.unet_offload_device()
434
+ return model_config, operations, load_device, unet_dtype, manual_cast_dtype, offload_device
435
+
436
+ def controlnet_load_state_dict(control_model, sd):
437
+ missing, unexpected = control_model.load_state_dict(sd, strict=False)
438
+
439
+ if len(missing) > 0:
440
+ logging.warning("missing controlnet keys: {}".format(missing))
441
+
442
+ if len(unexpected) > 0:
443
+ logging.debug("unexpected controlnet keys: {}".format(unexpected))
444
+ return control_model
445
+
446
+
447
+ def load_controlnet_mmdit(sd, model_options={}):
448
+ new_sd = comfy.model_detection.convert_diffusers_mmdit(sd, "")
449
+ model_config, operations, load_device, unet_dtype, manual_cast_dtype, offload_device = controlnet_config(new_sd, model_options=model_options)
450
+ num_blocks = comfy.model_detection.count_blocks(new_sd, 'joint_blocks.{}.')
451
+ for k in sd:
452
+ new_sd[k] = sd[k]
453
+
454
+ concat_mask = False
455
+ control_latent_channels = new_sd.get("pos_embed_input.proj.weight").shape[1]
456
+ if control_latent_channels == 17: #inpaint controlnet
457
+ concat_mask = True
458
+
459
+ 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)
460
+ control_model = controlnet_load_state_dict(control_model, new_sd)
461
+
462
+ latent_format = comfy.latent_formats.SD3()
463
+ latent_format.shift_factor = 0 #SD3 controlnet weirdness
464
+ 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)
465
+ return control
466
+
467
+
468
+ class ControlNetSD35(ControlNet):
469
+ def pre_run(self, model, percent_to_timestep_function):
470
+ if self.control_model.double_y_emb:
471
+ missing, unexpected = self.control_model.orig_y_embedder.load_state_dict(model.diffusion_model.y_embedder.state_dict(), strict=False)
472
+ else:
473
+ missing, unexpected = self.control_model.x_embedder.load_state_dict(model.diffusion_model.x_embedder.state_dict(), strict=False)
474
+ super().pre_run(model, percent_to_timestep_function)
475
+
476
+ def copy(self):
477
+ c = ControlNetSD35(None, global_average_pooling=self.global_average_pooling, load_device=self.load_device, manual_cast_dtype=self.manual_cast_dtype)
478
+ c.control_model = self.control_model
479
+ c.control_model_wrapped = self.control_model_wrapped
480
+ self.copy_to(c)
481
+ return c
482
+
483
+ def load_controlnet_sd35(sd, model_options={}):
484
+ control_type = -1
485
+ if "control_type" in sd:
486
+ control_type = round(sd.pop("control_type").item())
487
+
488
+ # blur_cnet = control_type == 0
489
+ canny_cnet = control_type == 1
490
+ depth_cnet = control_type == 2
491
+
492
+ new_sd = {}
493
+ for k in comfy.utils.MMDIT_MAP_BASIC:
494
+ if k[1] in sd:
495
+ new_sd[k[0]] = sd.pop(k[1])
496
+ for k in sd:
497
+ new_sd[k] = sd[k]
498
+ sd = new_sd
499
+
500
+ y_emb_shape = sd["y_embedder.mlp.0.weight"].shape
501
+ depth = y_emb_shape[0] // 64
502
+ hidden_size = 64 * depth
503
+ num_heads = depth
504
+ head_dim = hidden_size // num_heads
505
+ num_blocks = comfy.model_detection.count_blocks(new_sd, 'transformer_blocks.{}.')
506
+
507
+ load_device = comfy.model_management.get_torch_device()
508
+ offload_device = comfy.model_management.unet_offload_device()
509
+ unet_dtype = comfy.model_management.unet_dtype(model_params=-1)
510
+
511
+ manual_cast_dtype = comfy.model_management.unet_manual_cast(unet_dtype, load_device)
512
+
513
+ operations = model_options.get("custom_operations", None)
514
+ if operations is None:
515
+ operations = comfy.ops.pick_operations(unet_dtype, manual_cast_dtype, disable_fast_fp8=True)
516
+
517
+ control_model = comfy.cldm.dit_embedder.ControlNetEmbedder(img_size=None,
518
+ patch_size=2,
519
+ in_chans=16,
520
+ num_layers=num_blocks,
521
+ main_model_double=depth,
522
+ double_y_emb=y_emb_shape[0] == y_emb_shape[1],
523
+ attention_head_dim=head_dim,
524
+ num_attention_heads=num_heads,
525
+ adm_in_channels=2048,
526
+ device=offload_device,
527
+ dtype=unet_dtype,
528
+ operations=operations)
529
+
530
+ control_model = controlnet_load_state_dict(control_model, sd)
531
+
532
+ latent_format = comfy.latent_formats.SD3()
533
+ preprocess_image = lambda a: a
534
+ if canny_cnet:
535
+ preprocess_image = lambda a: (a * 255 * 0.5 + 0.5)
536
+ elif depth_cnet:
537
+ preprocess_image = lambda a: 1.0 - a
538
+
539
+ 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)
540
+ return control
541
+
542
+
543
+
544
+ def load_controlnet_hunyuandit(controlnet_data, model_options={}):
545
+ model_config, operations, load_device, unet_dtype, manual_cast_dtype, offload_device = controlnet_config(controlnet_data, model_options=model_options)
546
+
547
+ control_model = comfy.ldm.hydit.controlnet.HunYuanControlNet(operations=operations, device=offload_device, dtype=unet_dtype)
548
+ control_model = controlnet_load_state_dict(control_model, controlnet_data)
549
+
550
+ latent_format = comfy.latent_formats.SDXL()
551
+ extra_conds = ['text_embedding_mask', 'encoder_hidden_states_t5', 'text_embedding_mask_t5', 'image_meta_size', 'style', 'cos_cis_img', 'sin_cis_img']
552
+ 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)
553
+ return control
554
+
555
+ def load_controlnet_flux_xlabs_mistoline(sd, mistoline=False, model_options={}):
556
+ model_config, operations, load_device, unet_dtype, manual_cast_dtype, offload_device = controlnet_config(sd, model_options=model_options)
557
+ control_model = comfy.ldm.flux.controlnet.ControlNetFlux(mistoline=mistoline, operations=operations, device=offload_device, dtype=unet_dtype, **model_config.unet_config)
558
+ control_model = controlnet_load_state_dict(control_model, sd)
559
+ extra_conds = ['y', 'guidance']
560
+ control = ControlNet(control_model, load_device=load_device, manual_cast_dtype=manual_cast_dtype, extra_conds=extra_conds)
561
+ return control
562
+
563
+ def load_controlnet_flux_instantx(sd, model_options={}):
564
+ new_sd = comfy.model_detection.convert_diffusers_mmdit(sd, "")
565
+ model_config, operations, load_device, unet_dtype, manual_cast_dtype, offload_device = controlnet_config(new_sd, model_options=model_options)
566
+ for k in sd:
567
+ new_sd[k] = sd[k]
568
+
569
+ num_union_modes = 0
570
+ union_cnet = "controlnet_mode_embedder.weight"
571
+ if union_cnet in new_sd:
572
+ num_union_modes = new_sd[union_cnet].shape[0]
573
+
574
+ control_latent_channels = new_sd.get("pos_embed_input.weight").shape[1] // 4
575
+ concat_mask = False
576
+ if control_latent_channels == 17:
577
+ concat_mask = True
578
+
579
+ 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)
580
+ control_model = controlnet_load_state_dict(control_model, new_sd)
581
+
582
+ latent_format = comfy.latent_formats.Flux()
583
+ extra_conds = ['y', 'guidance']
584
+ 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)
585
+ return control
586
+
587
+ def convert_mistoline(sd):
588
+ return comfy.utils.state_dict_prefix_replace(sd, {"single_controlnet_blocks.": "controlnet_single_blocks."})
589
+
590
+
591
+ def load_controlnet_state_dict(state_dict, model=None, model_options={}):
592
+ controlnet_data = state_dict
593
+ if 'after_proj_list.18.bias' in controlnet_data.keys(): #Hunyuan DiT
594
+ return load_controlnet_hunyuandit(controlnet_data, model_options=model_options)
595
+
596
+ if "lora_controlnet" in controlnet_data:
597
+ return ControlLora(controlnet_data, model_options=model_options)
598
+
599
+ controlnet_config = None
600
+ supported_inference_dtypes = None
601
+
602
+ if "controlnet_cond_embedding.conv_in.weight" in controlnet_data: #diffusers format
603
+ controlnet_config = comfy.model_detection.unet_config_from_diffusers_unet(controlnet_data)
604
+ diffusers_keys = comfy.utils.unet_to_diffusers(controlnet_config)
605
+ diffusers_keys["controlnet_mid_block.weight"] = "middle_block_out.0.weight"
606
+ diffusers_keys["controlnet_mid_block.bias"] = "middle_block_out.0.bias"
607
+
608
+ count = 0
609
+ loop = True
610
+ while loop:
611
+ suffix = [".weight", ".bias"]
612
+ for s in suffix:
613
+ k_in = "controlnet_down_blocks.{}{}".format(count, s)
614
+ k_out = "zero_convs.{}.0{}".format(count, s)
615
+ if k_in not in controlnet_data:
616
+ loop = False
617
+ break
618
+ diffusers_keys[k_in] = k_out
619
+ count += 1
620
+
621
+ count = 0
622
+ loop = True
623
+ while loop:
624
+ suffix = [".weight", ".bias"]
625
+ for s in suffix:
626
+ if count == 0:
627
+ k_in = "controlnet_cond_embedding.conv_in{}".format(s)
628
+ else:
629
+ k_in = "controlnet_cond_embedding.blocks.{}{}".format(count - 1, s)
630
+ k_out = "input_hint_block.{}{}".format(count * 2, s)
631
+ if k_in not in controlnet_data:
632
+ k_in = "controlnet_cond_embedding.conv_out{}".format(s)
633
+ loop = False
634
+ diffusers_keys[k_in] = k_out
635
+ count += 1
636
+
637
+ new_sd = {}
638
+ for k in diffusers_keys:
639
+ if k in controlnet_data:
640
+ new_sd[diffusers_keys[k]] = controlnet_data.pop(k)
641
+
642
+ if "control_add_embedding.linear_1.bias" in controlnet_data: #Union Controlnet
643
+ controlnet_config["union_controlnet_num_control_type"] = controlnet_data["task_embedding"].shape[0]
644
+ for k in list(controlnet_data.keys()):
645
+ new_k = k.replace('.attn.in_proj_', '.attn.in_proj.')
646
+ new_sd[new_k] = controlnet_data.pop(k)
647
+
648
+ leftover_keys = controlnet_data.keys()
649
+ if len(leftover_keys) > 0:
650
+ logging.warning("leftover keys: {}".format(leftover_keys))
651
+ controlnet_data = new_sd
652
+ elif "controlnet_blocks.0.weight" in controlnet_data:
653
+ if "double_blocks.0.img_attn.norm.key_norm.scale" in controlnet_data:
654
+ return load_controlnet_flux_xlabs_mistoline(controlnet_data, model_options=model_options)
655
+ elif "pos_embed_input.proj.weight" in controlnet_data:
656
+ if "transformer_blocks.0.adaLN_modulation.1.bias" in controlnet_data:
657
+ return load_controlnet_sd35(controlnet_data, model_options=model_options) #Stability sd3.5 format
658
+ else:
659
+ return load_controlnet_mmdit(controlnet_data, model_options=model_options) #SD3 diffusers controlnet
660
+ elif "controlnet_x_embedder.weight" in controlnet_data:
661
+ return load_controlnet_flux_instantx(controlnet_data, model_options=model_options)
662
+ elif "controlnet_blocks.0.linear.weight" in controlnet_data: #mistoline flux
663
+ return load_controlnet_flux_xlabs_mistoline(convert_mistoline(controlnet_data), mistoline=True, model_options=model_options)
664
+
665
+ pth_key = 'control_model.zero_convs.0.0.weight'
666
+ pth = False
667
+ key = 'zero_convs.0.0.weight'
668
+ if pth_key in controlnet_data:
669
+ pth = True
670
+ key = pth_key
671
+ prefix = "control_model."
672
+ elif key in controlnet_data:
673
+ prefix = ""
674
+ else:
675
+ net = load_t2i_adapter(controlnet_data, model_options=model_options)
676
+ if net is None:
677
+ logging.error("error could not detect control model type.")
678
+ return net
679
+
680
+ if controlnet_config is None:
681
+ model_config = comfy.model_detection.model_config_from_unet(controlnet_data, prefix, True)
682
+ supported_inference_dtypes = list(model_config.supported_inference_dtypes)
683
+ controlnet_config = model_config.unet_config
684
+
685
+ unet_dtype = model_options.get("dtype", None)
686
+ if unet_dtype is None:
687
+ weight_dtype = comfy.utils.weight_dtype(controlnet_data)
688
+
689
+ if supported_inference_dtypes is None:
690
+ supported_inference_dtypes = [comfy.model_management.unet_dtype()]
691
+
692
+ if weight_dtype is not None:
693
+ supported_inference_dtypes.append(weight_dtype)
694
+
695
+ unet_dtype = comfy.model_management.unet_dtype(model_params=-1, supported_dtypes=supported_inference_dtypes)
696
+
697
+ load_device = comfy.model_management.get_torch_device()
698
+
699
+ manual_cast_dtype = comfy.model_management.unet_manual_cast(unet_dtype, load_device)
700
+ operations = model_options.get("custom_operations", None)
701
+ if operations is None:
702
+ operations = comfy.ops.pick_operations(unet_dtype, manual_cast_dtype)
703
+
704
+ controlnet_config["operations"] = operations
705
+ controlnet_config["dtype"] = unet_dtype
706
+ controlnet_config["device"] = comfy.model_management.unet_offload_device()
707
+ controlnet_config.pop("out_channels")
708
+ controlnet_config["hint_channels"] = controlnet_data["{}input_hint_block.0.weight".format(prefix)].shape[1]
709
+ control_model = comfy.cldm.cldm.ControlNet(**controlnet_config)
710
+
711
+ if pth:
712
+ if 'difference' in controlnet_data:
713
+ if model is not None:
714
+ comfy.model_management.load_models_gpu([model])
715
+ model_sd = model.model_state_dict()
716
+ for x in controlnet_data:
717
+ c_m = "control_model."
718
+ if x.startswith(c_m):
719
+ sd_key = "diffusion_model.{}".format(x[len(c_m):])
720
+ if sd_key in model_sd:
721
+ cd = controlnet_data[x]
722
+ cd += model_sd[sd_key].type(cd.dtype).to(cd.device)
723
+ else:
724
+ logging.warning("WARNING: Loaded a diff controlnet without a model. It will very likely not work.")
725
+
726
+ class WeightsLoader(torch.nn.Module):
727
+ pass
728
+ w = WeightsLoader()
729
+ w.control_model = control_model
730
+ missing, unexpected = w.load_state_dict(controlnet_data, strict=False)
731
+ else:
732
+ missing, unexpected = control_model.load_state_dict(controlnet_data, strict=False)
733
+
734
+ if len(missing) > 0:
735
+ logging.warning("missing controlnet keys: {}".format(missing))
736
+
737
+ if len(unexpected) > 0:
738
+ logging.debug("unexpected controlnet keys: {}".format(unexpected))
739
+
740
+ global_average_pooling = model_options.get("global_average_pooling", False)
741
+ control = ControlNet(control_model, global_average_pooling=global_average_pooling, load_device=load_device, manual_cast_dtype=manual_cast_dtype)
742
+ return control
743
+
744
+ def load_controlnet(ckpt_path, model=None, model_options={}):
745
+ if "global_average_pooling" not in model_options:
746
+ filename = os.path.splitext(ckpt_path)[0]
747
+ if filename.endswith("_shuffle") or filename.endswith("_shuffle_fp16"): #TODO: smarter way of enabling global_average_pooling
748
+ model_options["global_average_pooling"] = True
749
+
750
+ cnet = load_controlnet_state_dict(comfy.utils.load_torch_file(ckpt_path, safe_load=True), model=model, model_options=model_options)
751
+ if cnet is None:
752
+ logging.error("error checkpoint does not contain controlnet or t2i adapter data {}".format(ckpt_path))
753
+ return cnet
754
+
755
+ class T2IAdapter(ControlBase):
756
+ def __init__(self, t2i_model, channels_in, compression_ratio, upscale_algorithm, device=None):
757
+ super().__init__()
758
+ self.t2i_model = t2i_model
759
+ self.channels_in = channels_in
760
+ self.control_input = None
761
+ self.compression_ratio = compression_ratio
762
+ self.upscale_algorithm = upscale_algorithm
763
+ if device is None:
764
+ device = comfy.model_management.get_torch_device()
765
+ self.device = device
766
+
767
+ def scale_image_to(self, width, height):
768
+ unshuffle_amount = self.t2i_model.unshuffle_amount
769
+ width = math.ceil(width / unshuffle_amount) * unshuffle_amount
770
+ height = math.ceil(height / unshuffle_amount) * unshuffle_amount
771
+ return width, height
772
+
773
+ def get_control(self, x_noisy, t, cond, batched_number, transformer_options):
774
+ control_prev = None
775
+ if self.previous_controlnet is not None:
776
+ control_prev = self.previous_controlnet.get_control(x_noisy, t, cond, batched_number, transformer_options)
777
+
778
+ if self.timestep_range is not None:
779
+ if t[0] > self.timestep_range[0] or t[0] < self.timestep_range[1]:
780
+ if control_prev is not None:
781
+ return control_prev
782
+ else:
783
+ return None
784
+
785
+ 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]:
786
+ if self.cond_hint is not None:
787
+ del self.cond_hint
788
+ self.control_input = None
789
+ self.cond_hint = None
790
+ width, height = self.scale_image_to(x_noisy.shape[3] * self.compression_ratio, x_noisy.shape[2] * self.compression_ratio)
791
+ self.cond_hint = comfy.utils.common_upscale(self.cond_hint_original, width, height, self.upscale_algorithm, "center").float().to(self.device)
792
+ if self.channels_in == 1 and self.cond_hint.shape[1] > 1:
793
+ self.cond_hint = torch.mean(self.cond_hint, 1, keepdim=True)
794
+ if x_noisy.shape[0] != self.cond_hint.shape[0]:
795
+ self.cond_hint = broadcast_image_to(self.cond_hint, x_noisy.shape[0], batched_number)
796
+ if self.control_input is None:
797
+ self.t2i_model.to(x_noisy.dtype)
798
+ self.t2i_model.to(self.device)
799
+ self.control_input = self.t2i_model(self.cond_hint.to(x_noisy.dtype))
800
+ self.t2i_model.cpu()
801
+
802
+ control_input = {}
803
+ for k in self.control_input:
804
+ control_input[k] = list(map(lambda a: None if a is None else a.clone(), self.control_input[k]))
805
+
806
+ return self.control_merge(control_input, control_prev, x_noisy.dtype)
807
+
808
+ def copy(self):
809
+ c = T2IAdapter(self.t2i_model, self.channels_in, self.compression_ratio, self.upscale_algorithm)
810
+ self.copy_to(c)
811
+ return c
812
+
813
+ def load_t2i_adapter(t2i_data, model_options={}): #TODO: model_options
814
+ compression_ratio = 8
815
+ upscale_algorithm = 'nearest-exact'
816
+
817
+ if 'adapter' in t2i_data:
818
+ t2i_data = t2i_data['adapter']
819
+ if 'adapter.body.0.resnets.0.block1.weight' in t2i_data: #diffusers format
820
+ prefix_replace = {}
821
+ for i in range(4):
822
+ for j in range(2):
823
+ prefix_replace["adapter.body.{}.resnets.{}.".format(i, j)] = "body.{}.".format(i * 2 + j)
824
+ prefix_replace["adapter.body.{}.".format(i, )] = "body.{}.".format(i * 2)
825
+ prefix_replace["adapter."] = ""
826
+ t2i_data = comfy.utils.state_dict_prefix_replace(t2i_data, prefix_replace)
827
+ keys = t2i_data.keys()
828
+
829
+ if "body.0.in_conv.weight" in keys:
830
+ cin = t2i_data['body.0.in_conv.weight'].shape[1]
831
+ model_ad = comfy.t2i_adapter.adapter.Adapter_light(cin=cin, channels=[320, 640, 1280, 1280], nums_rb=4)
832
+ elif 'conv_in.weight' in keys:
833
+ cin = t2i_data['conv_in.weight'].shape[1]
834
+ channel = t2i_data['conv_in.weight'].shape[0]
835
+ ksize = t2i_data['body.0.block2.weight'].shape[2]
836
+ use_conv = False
837
+ down_opts = list(filter(lambda a: a.endswith("down_opt.op.weight"), keys))
838
+ if len(down_opts) > 0:
839
+ use_conv = True
840
+ xl = False
841
+ if cin == 256 or cin == 768:
842
+ xl = True
843
+ 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)
844
+ elif "backbone.0.0.weight" in keys:
845
+ 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])
846
+ compression_ratio = 32
847
+ upscale_algorithm = 'bilinear'
848
+ elif "backbone.10.blocks.0.weight" in keys:
849
+ 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])
850
+ compression_ratio = 1
851
+ upscale_algorithm = 'nearest-exact'
852
+ else:
853
+ return None
854
+
855
+ missing, unexpected = model_ad.load_state_dict(t2i_data)
856
+ if len(missing) > 0:
857
+ logging.warning("t2i missing {}".format(missing))
858
+
859
+ if len(unexpected) > 0:
860
+ logging.debug("t2i unexpected {}".format(unexpected))
861
+
862
+ return T2IAdapter(model_ad, model_ad.input_channels, compression_ratio, upscale_algorithm)
comfy/diffusers_convert.py ADDED
@@ -0,0 +1,288 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ # UNet Conversion #
9
+ # =================#
10
+
11
+ unet_conversion_map = [
12
+ # (stable-diffusion, HF Diffusers)
13
+ ("time_embed.0.weight", "time_embedding.linear_1.weight"),
14
+ ("time_embed.0.bias", "time_embedding.linear_1.bias"),
15
+ ("time_embed.2.weight", "time_embedding.linear_2.weight"),
16
+ ("time_embed.2.bias", "time_embedding.linear_2.bias"),
17
+ ("input_blocks.0.0.weight", "conv_in.weight"),
18
+ ("input_blocks.0.0.bias", "conv_in.bias"),
19
+ ("out.0.weight", "conv_norm_out.weight"),
20
+ ("out.0.bias", "conv_norm_out.bias"),
21
+ ("out.2.weight", "conv_out.weight"),
22
+ ("out.2.bias", "conv_out.bias"),
23
+ ]
24
+
25
+ unet_conversion_map_resnet = [
26
+ # (stable-diffusion, HF Diffusers)
27
+ ("in_layers.0", "norm1"),
28
+ ("in_layers.2", "conv1"),
29
+ ("out_layers.0", "norm2"),
30
+ ("out_layers.3", "conv2"),
31
+ ("emb_layers.1", "time_emb_proj"),
32
+ ("skip_connection", "conv_shortcut"),
33
+ ]
34
+
35
+ unet_conversion_map_layer = []
36
+ # hardcoded number of downblocks and resnets/attentions...
37
+ # would need smarter logic for other networks.
38
+ for i in range(4):
39
+ # loop over downblocks/upblocks
40
+
41
+ for j in range(2):
42
+ # loop over resnets/attentions for downblocks
43
+ hf_down_res_prefix = f"down_blocks.{i}.resnets.{j}."
44
+ sd_down_res_prefix = f"input_blocks.{3 * i + j + 1}.0."
45
+ unet_conversion_map_layer.append((sd_down_res_prefix, hf_down_res_prefix))
46
+
47
+ if i < 3:
48
+ # no attention layers in down_blocks.3
49
+ hf_down_atn_prefix = f"down_blocks.{i}.attentions.{j}."
50
+ sd_down_atn_prefix = f"input_blocks.{3 * i + j + 1}.1."
51
+ unet_conversion_map_layer.append((sd_down_atn_prefix, hf_down_atn_prefix))
52
+
53
+ for j in range(3):
54
+ # loop over resnets/attentions for upblocks
55
+ hf_up_res_prefix = f"up_blocks.{i}.resnets.{j}."
56
+ sd_up_res_prefix = f"output_blocks.{3 * i + j}.0."
57
+ unet_conversion_map_layer.append((sd_up_res_prefix, hf_up_res_prefix))
58
+
59
+ if i > 0:
60
+ # no attention layers in up_blocks.0
61
+ hf_up_atn_prefix = f"up_blocks.{i}.attentions.{j}."
62
+ sd_up_atn_prefix = f"output_blocks.{3 * i + j}.1."
63
+ unet_conversion_map_layer.append((sd_up_atn_prefix, hf_up_atn_prefix))
64
+
65
+ if i < 3:
66
+ # no downsample in down_blocks.3
67
+ hf_downsample_prefix = f"down_blocks.{i}.downsamplers.0.conv."
68
+ sd_downsample_prefix = f"input_blocks.{3 * (i + 1)}.0.op."
69
+ unet_conversion_map_layer.append((sd_downsample_prefix, hf_downsample_prefix))
70
+
71
+ # no upsample in up_blocks.3
72
+ hf_upsample_prefix = f"up_blocks.{i}.upsamplers.0."
73
+ sd_upsample_prefix = f"output_blocks.{3 * i + 2}.{1 if i == 0 else 2}."
74
+ unet_conversion_map_layer.append((sd_upsample_prefix, hf_upsample_prefix))
75
+
76
+ hf_mid_atn_prefix = "mid_block.attentions.0."
77
+ sd_mid_atn_prefix = "middle_block.1."
78
+ unet_conversion_map_layer.append((sd_mid_atn_prefix, hf_mid_atn_prefix))
79
+
80
+ for j in range(2):
81
+ hf_mid_res_prefix = f"mid_block.resnets.{j}."
82
+ sd_mid_res_prefix = f"middle_block.{2 * j}."
83
+ unet_conversion_map_layer.append((sd_mid_res_prefix, hf_mid_res_prefix))
84
+
85
+
86
+ def convert_unet_state_dict(unet_state_dict):
87
+ # buyer beware: this is a *brittle* function,
88
+ # and correct output requires that all of these pieces interact in
89
+ # the exact order in which I have arranged them.
90
+ mapping = {k: k for k in unet_state_dict.keys()}
91
+ for sd_name, hf_name in unet_conversion_map:
92
+ mapping[hf_name] = sd_name
93
+ for k, v in mapping.items():
94
+ if "resnets" in k:
95
+ for sd_part, hf_part in unet_conversion_map_resnet:
96
+ v = v.replace(hf_part, sd_part)
97
+ mapping[k] = v
98
+ for k, v in mapping.items():
99
+ for sd_part, hf_part in unet_conversion_map_layer:
100
+ v = v.replace(hf_part, sd_part)
101
+ mapping[k] = v
102
+ new_state_dict = {v: unet_state_dict[k] for k, v in mapping.items()}
103
+ return new_state_dict
104
+
105
+
106
+ # ================#
107
+ # VAE Conversion #
108
+ # ================#
109
+
110
+ vae_conversion_map = [
111
+ # (stable-diffusion, HF Diffusers)
112
+ ("nin_shortcut", "conv_shortcut"),
113
+ ("norm_out", "conv_norm_out"),
114
+ ("mid.attn_1.", "mid_block.attentions.0."),
115
+ ]
116
+
117
+ for i in range(4):
118
+ # down_blocks have two resnets
119
+ for j in range(2):
120
+ hf_down_prefix = f"encoder.down_blocks.{i}.resnets.{j}."
121
+ sd_down_prefix = f"encoder.down.{i}.block.{j}."
122
+ vae_conversion_map.append((sd_down_prefix, hf_down_prefix))
123
+
124
+ if i < 3:
125
+ hf_downsample_prefix = f"down_blocks.{i}.downsamplers.0."
126
+ sd_downsample_prefix = f"down.{i}.downsample."
127
+ vae_conversion_map.append((sd_downsample_prefix, hf_downsample_prefix))
128
+
129
+ hf_upsample_prefix = f"up_blocks.{i}.upsamplers.0."
130
+ sd_upsample_prefix = f"up.{3 - i}.upsample."
131
+ vae_conversion_map.append((sd_upsample_prefix, hf_upsample_prefix))
132
+
133
+ # up_blocks have three resnets
134
+ # also, up blocks in hf are numbered in reverse from sd
135
+ for j in range(3):
136
+ hf_up_prefix = f"decoder.up_blocks.{i}.resnets.{j}."
137
+ sd_up_prefix = f"decoder.up.{3 - i}.block.{j}."
138
+ vae_conversion_map.append((sd_up_prefix, hf_up_prefix))
139
+
140
+ # this part accounts for mid blocks in both the encoder and the decoder
141
+ for i in range(2):
142
+ hf_mid_res_prefix = f"mid_block.resnets.{i}."
143
+ sd_mid_res_prefix = f"mid.block_{i + 1}."
144
+ vae_conversion_map.append((sd_mid_res_prefix, hf_mid_res_prefix))
145
+
146
+ vae_conversion_map_attn = [
147
+ # (stable-diffusion, HF Diffusers)
148
+ ("norm.", "group_norm."),
149
+ ("q.", "query."),
150
+ ("k.", "key."),
151
+ ("v.", "value."),
152
+ ("q.", "to_q."),
153
+ ("k.", "to_k."),
154
+ ("v.", "to_v."),
155
+ ("proj_out.", "to_out.0."),
156
+ ("proj_out.", "proj_attn."),
157
+ ]
158
+
159
+
160
+ def reshape_weight_for_sd(w, conv3d=False):
161
+ # convert HF linear weights to SD conv2d weights
162
+ if conv3d:
163
+ return w.reshape(*w.shape, 1, 1, 1)
164
+ else:
165
+ return w.reshape(*w.shape, 1, 1)
166
+
167
+
168
+ def convert_vae_state_dict(vae_state_dict):
169
+ mapping = {k: k for k in vae_state_dict.keys()}
170
+ conv3d = False
171
+ for k, v in mapping.items():
172
+ for sd_part, hf_part in vae_conversion_map:
173
+ v = v.replace(hf_part, sd_part)
174
+ if v.endswith(".conv.weight"):
175
+ if not conv3d and vae_state_dict[k].ndim == 5:
176
+ conv3d = True
177
+ mapping[k] = v
178
+ for k, v in mapping.items():
179
+ if "attentions" in k:
180
+ for sd_part, hf_part in vae_conversion_map_attn:
181
+ v = v.replace(hf_part, sd_part)
182
+ mapping[k] = v
183
+ new_state_dict = {v: vae_state_dict[k] for k, v in mapping.items()}
184
+ weights_to_convert = ["q", "k", "v", "proj_out"]
185
+ for k, v in new_state_dict.items():
186
+ for weight_name in weights_to_convert:
187
+ if f"mid.attn_1.{weight_name}.weight" in k:
188
+ logging.debug(f"Reshaping {k} for SD format")
189
+ new_state_dict[k] = reshape_weight_for_sd(v, conv3d=conv3d)
190
+ return new_state_dict
191
+
192
+
193
+ # =========================#
194
+ # Text Encoder Conversion #
195
+ # =========================#
196
+
197
+
198
+ textenc_conversion_lst = [
199
+ # (stable-diffusion, HF Diffusers)
200
+ ("resblocks.", "text_model.encoder.layers."),
201
+ ("ln_1", "layer_norm1"),
202
+ ("ln_2", "layer_norm2"),
203
+ (".c_fc.", ".fc1."),
204
+ (".c_proj.", ".fc2."),
205
+ (".attn", ".self_attn"),
206
+ ("ln_final.", "transformer.text_model.final_layer_norm."),
207
+ ("token_embedding.weight", "transformer.text_model.embeddings.token_embedding.weight"),
208
+ ("positional_embedding", "transformer.text_model.embeddings.position_embedding.weight"),
209
+ ]
210
+ protected = {re.escape(x[1]): x[0] for x in textenc_conversion_lst}
211
+ textenc_pattern = re.compile("|".join(protected.keys()))
212
+
213
+ # Ordering is from https://github.com/pytorch/pytorch/blob/master/test/cpp/api/modules.cpp
214
+ code2idx = {"q": 0, "k": 1, "v": 2}
215
+
216
+ # This function exists because at the time of writing torch.cat can't do fp8 with cuda
217
+ def cat_tensors(tensors):
218
+ x = 0
219
+ for t in tensors:
220
+ x += t.shape[0]
221
+
222
+ shape = [x] + list(tensors[0].shape)[1:]
223
+ out = torch.empty(shape, device=tensors[0].device, dtype=tensors[0].dtype)
224
+
225
+ x = 0
226
+ for t in tensors:
227
+ out[x:x + t.shape[0]] = t
228
+ x += t.shape[0]
229
+
230
+ return out
231
+
232
+ def convert_text_enc_state_dict_v20(text_enc_dict, prefix=""):
233
+ new_state_dict = {}
234
+ capture_qkv_weight = {}
235
+ capture_qkv_bias = {}
236
+ for k, v in text_enc_dict.items():
237
+ if not k.startswith(prefix):
238
+ continue
239
+ if (
240
+ k.endswith(".self_attn.q_proj.weight")
241
+ or k.endswith(".self_attn.k_proj.weight")
242
+ or k.endswith(".self_attn.v_proj.weight")
243
+ ):
244
+ k_pre = k[: -len(".q_proj.weight")]
245
+ k_code = k[-len("q_proj.weight")]
246
+ if k_pre not in capture_qkv_weight:
247
+ capture_qkv_weight[k_pre] = [None, None, None]
248
+ capture_qkv_weight[k_pre][code2idx[k_code]] = v
249
+ continue
250
+
251
+ if (
252
+ k.endswith(".self_attn.q_proj.bias")
253
+ or k.endswith(".self_attn.k_proj.bias")
254
+ or k.endswith(".self_attn.v_proj.bias")
255
+ ):
256
+ k_pre = k[: -len(".q_proj.bias")]
257
+ k_code = k[-len("q_proj.bias")]
258
+ if k_pre not in capture_qkv_bias:
259
+ capture_qkv_bias[k_pre] = [None, None, None]
260
+ capture_qkv_bias[k_pre][code2idx[k_code]] = v
261
+ continue
262
+
263
+ text_proj = "transformer.text_projection.weight"
264
+ if k.endswith(text_proj):
265
+ new_state_dict[k.replace(text_proj, "text_projection")] = v.transpose(0, 1).contiguous()
266
+ else:
267
+ relabelled_key = textenc_pattern.sub(lambda m: protected[re.escape(m.group(0))], k)
268
+ new_state_dict[relabelled_key] = v
269
+
270
+ for k_pre, tensors in capture_qkv_weight.items():
271
+ if None in tensors:
272
+ raise Exception("CORRUPTED MODEL: one of the q-k-v values for the text encoder was missing")
273
+ relabelled_key = textenc_pattern.sub(lambda m: protected[re.escape(m.group(0))], k_pre)
274
+ new_state_dict[relabelled_key + ".in_proj_weight"] = cat_tensors(tensors)
275
+
276
+ for k_pre, tensors in capture_qkv_bias.items():
277
+ if None in tensors:
278
+ raise Exception("CORRUPTED MODEL: one of the q-k-v values for the text encoder was missing")
279
+ relabelled_key = textenc_pattern.sub(lambda m: protected[re.escape(m.group(0))], k_pre)
280
+ new_state_dict[relabelled_key + ".in_proj_bias"] = cat_tensors(tensors)
281
+
282
+ return new_state_dict
283
+
284
+
285
+ def convert_text_enc_state_dict(text_enc_dict):
286
+ return text_enc_dict
287
+
288
+
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.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.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')