Xue-She Wang commited on
Commit
0d95f10
0 Parent(s):
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .DS_Store +0 -0
  2. CODEOWNERS +1 -0
  3. LICENSE +674 -0
  4. README.md +0 -0
  5. app/app_settings.py +54 -0
  6. app/user_manager.py +140 -0
  7. comfy/.DS_Store +0 -0
  8. comfy/checkpoint_pickle.py +13 -0
  9. comfy/cldm/cldm.py +312 -0
  10. comfy/cli_args.py +126 -0
  11. comfy/clip_config_bigg.json +23 -0
  12. comfy/clip_model.py +188 -0
  13. comfy/clip_vision.py +116 -0
  14. comfy/clip_vision_config_g.json +18 -0
  15. comfy/clip_vision_config_h.json +18 -0
  16. comfy/clip_vision_config_vitl.json +18 -0
  17. comfy/conds.py +78 -0
  18. comfy/controlnet.py +516 -0
  19. comfy/diffusers_convert.py +261 -0
  20. comfy/diffusers_load.py +36 -0
  21. comfy/extra_samplers/uni_pc.py +894 -0
  22. comfy/gligen.py +341 -0
  23. comfy/k_diffusion/sampling.py +810 -0
  24. comfy/k_diffusion/utils.py +313 -0
  25. comfy/latent_formats.py +39 -0
  26. comfy/ldm/.DS_Store +0 -0
  27. comfy/ldm/models/autoencoder.py +228 -0
  28. comfy/ldm/modules/attention.py +781 -0
  29. comfy/ldm/modules/diffusionmodules/__init__.py +0 -0
  30. comfy/ldm/modules/diffusionmodules/model.py +650 -0
  31. comfy/ldm/modules/diffusionmodules/openaimodel.py +886 -0
  32. comfy/ldm/modules/diffusionmodules/upscaling.py +85 -0
  33. comfy/ldm/modules/diffusionmodules/util.py +304 -0
  34. comfy/ldm/modules/distributions/__init__.py +0 -0
  35. comfy/ldm/modules/distributions/distributions.py +92 -0
  36. comfy/ldm/modules/ema.py +80 -0
  37. comfy/ldm/modules/encoders/__init__.py +0 -0
  38. comfy/ldm/modules/encoders/noise_aug_modules.py +35 -0
  39. comfy/ldm/modules/sub_quadratic_attention.py +273 -0
  40. comfy/ldm/modules/temporal_ae.py +245 -0
  41. comfy/ldm/util.py +197 -0
  42. comfy/lora.py +224 -0
  43. comfy/model_base.py +425 -0
  44. comfy/model_detection.py +320 -0
  45. comfy/model_management.py +805 -0
  46. comfy/model_patcher.py +357 -0
  47. comfy/model_sampling.py +134 -0
  48. comfy/ops.py +114 -0
  49. comfy/options.py +6 -0
  50. comfy/sample.py +118 -0
.DS_Store ADDED
Binary file (8.2 kB). View file
 
CODEOWNERS ADDED
@@ -0,0 +1 @@
 
 
1
+ * @comfyanonymous
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 ADDED
File without changes
app/app_settings.py ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import json
3
+ from aiohttp import web
4
+
5
+
6
+ class AppSettings():
7
+ def __init__(self, user_manager):
8
+ self.user_manager = user_manager
9
+
10
+ def get_settings(self, request):
11
+ file = self.user_manager.get_request_user_filepath(
12
+ request, "comfy.settings.json")
13
+ if os.path.isfile(file):
14
+ with open(file) as f:
15
+ return json.load(f)
16
+ else:
17
+ return {}
18
+
19
+ def save_settings(self, request, settings):
20
+ file = self.user_manager.get_request_user_filepath(
21
+ request, "comfy.settings.json")
22
+ with open(file, "w") as f:
23
+ f.write(json.dumps(settings, indent=4))
24
+
25
+ def add_routes(self, routes):
26
+ @routes.get("/settings")
27
+ async def get_settings(request):
28
+ return web.json_response(self.get_settings(request))
29
+
30
+ @routes.get("/settings/{id}")
31
+ async def get_setting(request):
32
+ value = None
33
+ settings = self.get_settings(request)
34
+ setting_id = request.match_info.get("id", None)
35
+ if setting_id and setting_id in settings:
36
+ value = settings[setting_id]
37
+ return web.json_response(value)
38
+
39
+ @routes.post("/settings")
40
+ async def post_settings(request):
41
+ settings = self.get_settings(request)
42
+ new_settings = await request.json()
43
+ self.save_settings(request, {**settings, **new_settings})
44
+ return web.Response(status=200)
45
+
46
+ @routes.post("/settings/{id}")
47
+ async def post_setting(request):
48
+ setting_id = request.match_info.get("id", None)
49
+ if not setting_id:
50
+ return web.Response(status=400)
51
+ settings = self.get_settings(request)
52
+ settings[setting_id] = await request.json()
53
+ self.save_settings(request, settings)
54
+ return web.Response(status=200)
app/user_manager.py ADDED
@@ -0,0 +1,140 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import os
3
+ import re
4
+ import uuid
5
+ from aiohttp import web
6
+ from comfy.cli_args import args
7
+ from folder_paths import user_directory
8
+ from .app_settings import AppSettings
9
+
10
+ default_user = "default"
11
+ users_file = os.path.join(user_directory, "users.json")
12
+
13
+
14
+ class UserManager():
15
+ def __init__(self):
16
+ global user_directory
17
+
18
+ self.settings = AppSettings(self)
19
+ if not os.path.exists(user_directory):
20
+ os.mkdir(user_directory)
21
+ if not args.multi_user:
22
+ print("****** User settings have been changed to be stored on the server instead of browser storage. ******")
23
+ print("****** For multi-user setups add the --multi-user CLI argument to enable multiple user profiles. ******")
24
+
25
+ if args.multi_user:
26
+ if os.path.isfile(users_file):
27
+ with open(users_file) as f:
28
+ self.users = json.load(f)
29
+ else:
30
+ self.users = {}
31
+ else:
32
+ self.users = {"default": "default"}
33
+
34
+ def get_request_user_id(self, request):
35
+ user = "default"
36
+ if args.multi_user and "comfy-user" in request.headers:
37
+ user = request.headers["comfy-user"]
38
+
39
+ if user not in self.users:
40
+ raise KeyError("Unknown user: " + user)
41
+
42
+ return user
43
+
44
+ def get_request_user_filepath(self, request, file, type="userdata", create_dir=True):
45
+ global user_directory
46
+
47
+ if type == "userdata":
48
+ root_dir = user_directory
49
+ else:
50
+ raise KeyError("Unknown filepath type:" + type)
51
+
52
+ user = self.get_request_user_id(request)
53
+ path = user_root = os.path.abspath(os.path.join(root_dir, user))
54
+
55
+ # prevent leaving /{type}
56
+ if os.path.commonpath((root_dir, user_root)) != root_dir:
57
+ return None
58
+
59
+ parent = user_root
60
+
61
+ if file is not None:
62
+ # prevent leaving /{type}/{user}
63
+ path = os.path.abspath(os.path.join(user_root, file))
64
+ if os.path.commonpath((user_root, path)) != user_root:
65
+ return None
66
+
67
+ if create_dir and not os.path.exists(parent):
68
+ os.mkdir(parent)
69
+
70
+ return path
71
+
72
+ def add_user(self, name):
73
+ name = name.strip()
74
+ if not name:
75
+ raise ValueError("username not provided")
76
+ user_id = re.sub("[^a-zA-Z0-9-_]+", '-', name)
77
+ user_id = user_id + "_" + str(uuid.uuid4())
78
+
79
+ self.users[user_id] = name
80
+
81
+ global users_file
82
+ with open(users_file, "w") as f:
83
+ json.dump(self.users, f)
84
+
85
+ return user_id
86
+
87
+ def add_routes(self, routes):
88
+ self.settings.add_routes(routes)
89
+
90
+ @routes.get("/users")
91
+ async def get_users(request):
92
+ if args.multi_user:
93
+ return web.json_response({"storage": "server", "users": self.users})
94
+ else:
95
+ user_dir = self.get_request_user_filepath(request, None, create_dir=False)
96
+ return web.json_response({
97
+ "storage": "server",
98
+ "migrated": os.path.exists(user_dir)
99
+ })
100
+
101
+ @routes.post("/users")
102
+ async def post_users(request):
103
+ body = await request.json()
104
+ username = body["username"]
105
+ if username in self.users.values():
106
+ return web.json_response({"error": "Duplicate username."}, status=400)
107
+
108
+ user_id = self.add_user(username)
109
+ return web.json_response(user_id)
110
+
111
+ @routes.get("/userdata/{file}")
112
+ async def getuserdata(request):
113
+ file = request.match_info.get("file", None)
114
+ if not file:
115
+ return web.Response(status=400)
116
+
117
+ path = self.get_request_user_filepath(request, file)
118
+ if not path:
119
+ return web.Response(status=403)
120
+
121
+ if not os.path.exists(path):
122
+ return web.Response(status=404)
123
+
124
+ return web.FileResponse(path)
125
+
126
+ @routes.post("/userdata/{file}")
127
+ async def post_userdata(request):
128
+ file = request.match_info.get("file", None)
129
+ if not file:
130
+ return web.Response(status=400)
131
+
132
+ path = self.get_request_user_filepath(request, file)
133
+ if not path:
134
+ return web.Response(status=403)
135
+
136
+ body = await request.read()
137
+ with open(path, "wb") as f:
138
+ f.write(body)
139
+
140
+ return web.Response(status=200)
comfy/.DS_Store ADDED
Binary file (8.2 kB). View file
 
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,312 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #taken from: https://github.com/lllyasviel/ControlNet
2
+ #and modified
3
+
4
+ import torch
5
+ import torch as th
6
+ import torch.nn as nn
7
+
8
+ from ..ldm.modules.diffusionmodules.util import (
9
+ zero_module,
10
+ timestep_embedding,
11
+ )
12
+
13
+ from ..ldm.modules.attention import SpatialTransformer
14
+ from ..ldm.modules.diffusionmodules.openaimodel import UNetModel, TimestepEmbedSequential, ResBlock, Downsample
15
+ from ..ldm.util import exists
16
+ import comfy.ops
17
+
18
+ class ControlledUnetModel(UNetModel):
19
+ #implemented in the ldm unet
20
+ pass
21
+
22
+ class ControlNet(nn.Module):
23
+ def __init__(
24
+ self,
25
+ image_size,
26
+ in_channels,
27
+ model_channels,
28
+ hint_channels,
29
+ num_res_blocks,
30
+ dropout=0,
31
+ channel_mult=(1, 2, 4, 8),
32
+ conv_resample=True,
33
+ dims=2,
34
+ num_classes=None,
35
+ use_checkpoint=False,
36
+ dtype=torch.float32,
37
+ num_heads=-1,
38
+ num_head_channels=-1,
39
+ num_heads_upsample=-1,
40
+ use_scale_shift_norm=False,
41
+ resblock_updown=False,
42
+ use_new_attention_order=False,
43
+ use_spatial_transformer=False, # custom transformer support
44
+ transformer_depth=1, # custom transformer support
45
+ context_dim=None, # custom transformer support
46
+ n_embed=None, # custom support for prediction of discrete ids into codebook of first stage vq model
47
+ legacy=True,
48
+ disable_self_attentions=None,
49
+ num_attention_blocks=None,
50
+ disable_middle_self_attn=False,
51
+ use_linear_in_transformer=False,
52
+ adm_in_channels=None,
53
+ transformer_depth_middle=None,
54
+ transformer_depth_output=None,
55
+ device=None,
56
+ operations=comfy.ops.disable_weight_init,
57
+ **kwargs,
58
+ ):
59
+ super().__init__()
60
+ assert use_spatial_transformer == True, "use_spatial_transformer has to be true"
61
+ if use_spatial_transformer:
62
+ assert context_dim is not None, 'Fool!! You forgot to include the dimension of your cross-attention conditioning...'
63
+
64
+ if context_dim is not None:
65
+ assert use_spatial_transformer, 'Fool!! You forgot to use the spatial transformer for your cross-attention conditioning...'
66
+ # from omegaconf.listconfig import ListConfig
67
+ # if type(context_dim) == ListConfig:
68
+ # context_dim = list(context_dim)
69
+
70
+ if num_heads_upsample == -1:
71
+ num_heads_upsample = num_heads
72
+
73
+ if num_heads == -1:
74
+ assert num_head_channels != -1, 'Either num_heads or num_head_channels has to be set'
75
+
76
+ if num_head_channels == -1:
77
+ assert num_heads != -1, 'Either num_heads or num_head_channels has to be set'
78
+
79
+ self.dims = dims
80
+ self.image_size = image_size
81
+ self.in_channels = in_channels
82
+ self.model_channels = model_channels
83
+
84
+ if isinstance(num_res_blocks, int):
85
+ self.num_res_blocks = len(channel_mult) * [num_res_blocks]
86
+ else:
87
+ if len(num_res_blocks) != len(channel_mult):
88
+ raise ValueError("provide num_res_blocks either as an int (globally constant) or "
89
+ "as a list/tuple (per-level) with the same length as channel_mult")
90
+ self.num_res_blocks = num_res_blocks
91
+
92
+ if disable_self_attentions is not None:
93
+ # should be a list of booleans, indicating whether to disable self-attention in TransformerBlocks or not
94
+ assert len(disable_self_attentions) == len(channel_mult)
95
+ if num_attention_blocks is not None:
96
+ assert len(num_attention_blocks) == len(self.num_res_blocks)
97
+ assert all(map(lambda i: self.num_res_blocks[i] >= num_attention_blocks[i], range(len(num_attention_blocks))))
98
+
99
+ transformer_depth = transformer_depth[:]
100
+
101
+ self.dropout = dropout
102
+ self.channel_mult = channel_mult
103
+ self.conv_resample = conv_resample
104
+ self.num_classes = num_classes
105
+ self.use_checkpoint = use_checkpoint
106
+ self.dtype = dtype
107
+ self.num_heads = num_heads
108
+ self.num_head_channels = num_head_channels
109
+ self.num_heads_upsample = num_heads_upsample
110
+ self.predict_codebook_ids = n_embed is not None
111
+
112
+ time_embed_dim = model_channels * 4
113
+ self.time_embed = nn.Sequential(
114
+ operations.Linear(model_channels, time_embed_dim, dtype=self.dtype, device=device),
115
+ nn.SiLU(),
116
+ operations.Linear(time_embed_dim, time_embed_dim, dtype=self.dtype, device=device),
117
+ )
118
+
119
+ if self.num_classes is not None:
120
+ if isinstance(self.num_classes, int):
121
+ self.label_emb = nn.Embedding(num_classes, time_embed_dim)
122
+ elif self.num_classes == "continuous":
123
+ print("setting up linear c_adm embedding layer")
124
+ self.label_emb = nn.Linear(1, time_embed_dim)
125
+ elif self.num_classes == "sequential":
126
+ assert adm_in_channels is not None
127
+ self.label_emb = nn.Sequential(
128
+ nn.Sequential(
129
+ operations.Linear(adm_in_channels, time_embed_dim, dtype=self.dtype, device=device),
130
+ nn.SiLU(),
131
+ operations.Linear(time_embed_dim, time_embed_dim, dtype=self.dtype, device=device),
132
+ )
133
+ )
134
+ else:
135
+ raise ValueError()
136
+
137
+ self.input_blocks = nn.ModuleList(
138
+ [
139
+ TimestepEmbedSequential(
140
+ operations.conv_nd(dims, in_channels, model_channels, 3, padding=1, dtype=self.dtype, device=device)
141
+ )
142
+ ]
143
+ )
144
+ self.zero_convs = nn.ModuleList([self.make_zero_conv(model_channels, operations=operations, dtype=self.dtype, device=device)])
145
+
146
+ self.input_hint_block = TimestepEmbedSequential(
147
+ operations.conv_nd(dims, hint_channels, 16, 3, padding=1, dtype=self.dtype, device=device),
148
+ nn.SiLU(),
149
+ operations.conv_nd(dims, 16, 16, 3, padding=1, dtype=self.dtype, device=device),
150
+ nn.SiLU(),
151
+ operations.conv_nd(dims, 16, 32, 3, padding=1, stride=2, dtype=self.dtype, device=device),
152
+ nn.SiLU(),
153
+ operations.conv_nd(dims, 32, 32, 3, padding=1, dtype=self.dtype, device=device),
154
+ nn.SiLU(),
155
+ operations.conv_nd(dims, 32, 96, 3, padding=1, stride=2, dtype=self.dtype, device=device),
156
+ nn.SiLU(),
157
+ operations.conv_nd(dims, 96, 96, 3, padding=1, dtype=self.dtype, device=device),
158
+ nn.SiLU(),
159
+ operations.conv_nd(dims, 96, 256, 3, padding=1, stride=2, dtype=self.dtype, device=device),
160
+ nn.SiLU(),
161
+ operations.conv_nd(dims, 256, model_channels, 3, padding=1, dtype=self.dtype, device=device)
162
+ )
163
+
164
+ self._feature_size = model_channels
165
+ input_block_chans = [model_channels]
166
+ ch = model_channels
167
+ ds = 1
168
+ for level, mult in enumerate(channel_mult):
169
+ for nr in range(self.num_res_blocks[level]):
170
+ layers = [
171
+ ResBlock(
172
+ ch,
173
+ time_embed_dim,
174
+ dropout,
175
+ out_channels=mult * model_channels,
176
+ dims=dims,
177
+ use_checkpoint=use_checkpoint,
178
+ use_scale_shift_norm=use_scale_shift_norm,
179
+ dtype=self.dtype,
180
+ device=device,
181
+ operations=operations,
182
+ )
183
+ ]
184
+ ch = mult * model_channels
185
+ num_transformers = transformer_depth.pop(0)
186
+ if num_transformers > 0:
187
+ if num_head_channels == -1:
188
+ dim_head = ch // num_heads
189
+ else:
190
+ num_heads = ch // num_head_channels
191
+ dim_head = num_head_channels
192
+ if legacy:
193
+ #num_heads = 1
194
+ dim_head = ch // num_heads if use_spatial_transformer else num_head_channels
195
+ if exists(disable_self_attentions):
196
+ disabled_sa = disable_self_attentions[level]
197
+ else:
198
+ disabled_sa = False
199
+
200
+ if not exists(num_attention_blocks) or nr < num_attention_blocks[level]:
201
+ layers.append(
202
+ SpatialTransformer(
203
+ ch, num_heads, dim_head, depth=num_transformers, context_dim=context_dim,
204
+ disable_self_attn=disabled_sa, use_linear=use_linear_in_transformer,
205
+ use_checkpoint=use_checkpoint, dtype=self.dtype, device=device, operations=operations
206
+ )
207
+ )
208
+ self.input_blocks.append(TimestepEmbedSequential(*layers))
209
+ self.zero_convs.append(self.make_zero_conv(ch, operations=operations, dtype=self.dtype, device=device))
210
+ self._feature_size += ch
211
+ input_block_chans.append(ch)
212
+ if level != len(channel_mult) - 1:
213
+ out_ch = ch
214
+ self.input_blocks.append(
215
+ TimestepEmbedSequential(
216
+ ResBlock(
217
+ ch,
218
+ time_embed_dim,
219
+ dropout,
220
+ out_channels=out_ch,
221
+ dims=dims,
222
+ use_checkpoint=use_checkpoint,
223
+ use_scale_shift_norm=use_scale_shift_norm,
224
+ down=True,
225
+ dtype=self.dtype,
226
+ device=device,
227
+ operations=operations
228
+ )
229
+ if resblock_updown
230
+ else Downsample(
231
+ ch, conv_resample, dims=dims, out_channels=out_ch, dtype=self.dtype, device=device, operations=operations
232
+ )
233
+ )
234
+ )
235
+ ch = out_ch
236
+ input_block_chans.append(ch)
237
+ self.zero_convs.append(self.make_zero_conv(ch, operations=operations, dtype=self.dtype, device=device))
238
+ ds *= 2
239
+ self._feature_size += ch
240
+
241
+ if num_head_channels == -1:
242
+ dim_head = ch // num_heads
243
+ else:
244
+ num_heads = ch // num_head_channels
245
+ dim_head = num_head_channels
246
+ if legacy:
247
+ #num_heads = 1
248
+ dim_head = ch // num_heads if use_spatial_transformer else num_head_channels
249
+ mid_block = [
250
+ ResBlock(
251
+ ch,
252
+ time_embed_dim,
253
+ dropout,
254
+ dims=dims,
255
+ use_checkpoint=use_checkpoint,
256
+ use_scale_shift_norm=use_scale_shift_norm,
257
+ dtype=self.dtype,
258
+ device=device,
259
+ operations=operations
260
+ )]
261
+ if transformer_depth_middle >= 0:
262
+ mid_block += [SpatialTransformer( # always uses a self-attn
263
+ ch, num_heads, dim_head, depth=transformer_depth_middle, context_dim=context_dim,
264
+ disable_self_attn=disable_middle_self_attn, use_linear=use_linear_in_transformer,
265
+ use_checkpoint=use_checkpoint, dtype=self.dtype, device=device, operations=operations
266
+ ),
267
+ ResBlock(
268
+ ch,
269
+ time_embed_dim,
270
+ dropout,
271
+ dims=dims,
272
+ use_checkpoint=use_checkpoint,
273
+ use_scale_shift_norm=use_scale_shift_norm,
274
+ dtype=self.dtype,
275
+ device=device,
276
+ operations=operations
277
+ )]
278
+ self.middle_block = TimestepEmbedSequential(*mid_block)
279
+ self.middle_block_out = self.make_zero_conv(ch, operations=operations, dtype=self.dtype, device=device)
280
+ self._feature_size += ch
281
+
282
+ def make_zero_conv(self, channels, operations=None, dtype=None, device=None):
283
+ return TimestepEmbedSequential(operations.conv_nd(self.dims, channels, channels, 1, padding=0, dtype=dtype, device=device))
284
+
285
+ def forward(self, x, hint, timesteps, context, y=None, **kwargs):
286
+ t_emb = timestep_embedding(timesteps, self.model_channels, repeat_only=False).to(x.dtype)
287
+ emb = self.time_embed(t_emb)
288
+
289
+ guided_hint = self.input_hint_block(hint, emb, context)
290
+
291
+ outs = []
292
+
293
+ hs = []
294
+ if self.num_classes is not None:
295
+ assert y.shape[0] == x.shape[0]
296
+ emb = emb + self.label_emb(y)
297
+
298
+ h = x
299
+ for module, zero_conv in zip(self.input_blocks, self.zero_convs):
300
+ if guided_hint is not None:
301
+ h = module(h, emb, context)
302
+ h += guided_hint
303
+ guided_hint = None
304
+ else:
305
+ h = module(h, emb, context)
306
+ outs.append(zero_conv(h, emb, context))
307
+
308
+ h = self.middle_block(h, emb, context)
309
+ outs.append(self.middle_block_out(h, emb, context))
310
+
311
+ return outs
312
+
comfy/cli_args.py ADDED
@@ -0,0 +1,126 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import enum
3
+ import comfy.options
4
+
5
+ class EnumAction(argparse.Action):
6
+ """
7
+ Argparse action for handling Enums
8
+ """
9
+ def __init__(self, **kwargs):
10
+ # Pop off the type value
11
+ enum_type = kwargs.pop("type", None)
12
+
13
+ # Ensure an Enum subclass is provided
14
+ if enum_type is None:
15
+ raise ValueError("type must be assigned an Enum when using EnumAction")
16
+ if not issubclass(enum_type, enum.Enum):
17
+ raise TypeError("type must be an Enum when using EnumAction")
18
+
19
+ # Generate choices from the Enum
20
+ choices = tuple(e.value for e in enum_type)
21
+ kwargs.setdefault("choices", choices)
22
+ kwargs.setdefault("metavar", f"[{','.join(list(choices))}]")
23
+
24
+ super(EnumAction, self).__init__(**kwargs)
25
+
26
+ self._enum = enum_type
27
+
28
+ def __call__(self, parser, namespace, values, option_string=None):
29
+ # Convert value back into an Enum
30
+ value = self._enum(values)
31
+ setattr(namespace, self.dest, value)
32
+
33
+
34
+ parser = argparse.ArgumentParser()
35
+
36
+ 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). If --listen is provided without an argument, it defaults to 0.0.0.0. (listens on all)")
37
+ parser.add_argument("--port", type=int, default=8188, help="Set the listen port.")
38
+ 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 '*'.")
39
+ parser.add_argument("--max-upload-size", type=float, default=100, help="Set the maximum upload size in MB.")
40
+
41
+ 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.")
42
+ parser.add_argument("--output-directory", type=str, default=None, help="Set the ComfyUI output directory.")
43
+ parser.add_argument("--temp-directory", type=str, default=None, help="Set the ComfyUI temp directory (default is in the ComfyUI directory).")
44
+ parser.add_argument("--input-directory", type=str, default=None, help="Set the ComfyUI input directory.")
45
+ parser.add_argument("--auto-launch", action="store_true", help="Automatically launch ComfyUI in the default browser.")
46
+ parser.add_argument("--disable-auto-launch", action="store_true", help="Disable auto launching the browser.")
47
+ parser.add_argument("--cuda-device", type=int, default=None, metavar="DEVICE_ID", help="Set the id of the cuda device this instance will use.")
48
+ cm_group = parser.add_mutually_exclusive_group()
49
+ cm_group.add_argument("--cuda-malloc", action="store_true", help="Enable cudaMallocAsync (enabled by default for torch 2.0 and up).")
50
+ cm_group.add_argument("--disable-cuda-malloc", action="store_true", help="Disable cudaMallocAsync.")
51
+
52
+ parser.add_argument("--dont-upcast-attention", action="store_true", help="Disable upcasting of attention. Can boost speed but increase the chances of black images.")
53
+
54
+ fp_group = parser.add_mutually_exclusive_group()
55
+ fp_group.add_argument("--force-fp32", action="store_true", help="Force fp32 (If this makes your GPU work better please report it).")
56
+ fp_group.add_argument("--force-fp16", action="store_true", help="Force fp16.")
57
+
58
+ fpunet_group = parser.add_mutually_exclusive_group()
59
+ fpunet_group.add_argument("--bf16-unet", action="store_true", help="Run the UNET in bf16. This should only be used for testing stuff.")
60
+ fpunet_group.add_argument("--fp16-unet", action="store_true", help="Store unet weights in fp16.")
61
+ fpunet_group.add_argument("--fp8_e4m3fn-unet", action="store_true", help="Store unet weights in fp8_e4m3fn.")
62
+ fpunet_group.add_argument("--fp8_e5m2-unet", action="store_true", help="Store unet weights in fp8_e5m2.")
63
+
64
+ fpvae_group = parser.add_mutually_exclusive_group()
65
+ fpvae_group.add_argument("--fp16-vae", action="store_true", help="Run the VAE in fp16, might cause black images.")
66
+ fpvae_group.add_argument("--fp32-vae", action="store_true", help="Run the VAE in full precision fp32.")
67
+ fpvae_group.add_argument("--bf16-vae", action="store_true", help="Run the VAE in bf16.")
68
+
69
+ parser.add_argument("--cpu-vae", action="store_true", help="Run the VAE on the CPU.")
70
+
71
+ fpte_group = parser.add_mutually_exclusive_group()
72
+ fpte_group.add_argument("--fp8_e4m3fn-text-enc", action="store_true", help="Store text encoder weights in fp8 (e4m3fn variant).")
73
+ fpte_group.add_argument("--fp8_e5m2-text-enc", action="store_true", help="Store text encoder weights in fp8 (e5m2 variant).")
74
+ fpte_group.add_argument("--fp16-text-enc", action="store_true", help="Store text encoder weights in fp16.")
75
+ fpte_group.add_argument("--fp32-text-enc", action="store_true", help="Store text encoder weights in fp32.")
76
+
77
+
78
+ parser.add_argument("--directml", type=int, nargs="?", metavar="DIRECTML_DEVICE", const=-1, help="Use torch-directml.")
79
+
80
+ parser.add_argument("--disable-ipex-optimize", action="store_true", help="Disables ipex.optimize when loading models with Intel GPUs.")
81
+
82
+ class LatentPreviewMethod(enum.Enum):
83
+ NoPreviews = "none"
84
+ Auto = "auto"
85
+ Latent2RGB = "latent2rgb"
86
+ TAESD = "taesd"
87
+
88
+ parser.add_argument("--preview-method", type=LatentPreviewMethod, default=LatentPreviewMethod.NoPreviews, help="Default preview method for sampler nodes.", action=EnumAction)
89
+
90
+ attn_group = parser.add_mutually_exclusive_group()
91
+ attn_group.add_argument("--use-split-cross-attention", action="store_true", help="Use the split cross attention optimization. Ignored when xformers is used.")
92
+ attn_group.add_argument("--use-quad-cross-attention", action="store_true", help="Use the sub-quadratic cross attention optimization . Ignored when xformers is used.")
93
+ attn_group.add_argument("--use-pytorch-cross-attention", action="store_true", help="Use the new pytorch 2.0 cross attention function.")
94
+
95
+ parser.add_argument("--disable-xformers", action="store_true", help="Disable xformers.")
96
+
97
+ vram_group = parser.add_mutually_exclusive_group()
98
+ vram_group.add_argument("--gpu-only", action="store_true", help="Store and run everything (text encoders/CLIP models, etc... on the GPU).")
99
+ 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.")
100
+ vram_group.add_argument("--normalvram", action="store_true", help="Used to force normal vram use if lowvram gets automatically enabled.")
101
+ vram_group.add_argument("--lowvram", action="store_true", help="Split the unet in parts to use less vram.")
102
+ vram_group.add_argument("--novram", action="store_true", help="When lowvram isn't enough.")
103
+ vram_group.add_argument("--cpu", action="store_true", help="To use the CPU for everything (slow).")
104
+
105
+
106
+ 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.")
107
+ 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.")
108
+
109
+ parser.add_argument("--dont-print-server", action="store_true", help="Don't print server output.")
110
+ parser.add_argument("--quick-test-for-ci", action="store_true", help="Quick test for CI.")
111
+ 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).")
112
+
113
+ parser.add_argument("--disable-metadata", action="store_true", help="Disable saving prompt metadata in files.")
114
+
115
+ parser.add_argument("--multi-user", action="store_true", help="Enables per-user storage.")
116
+
117
+ if comfy.options.args_parsing:
118
+ args = parser.parse_args()
119
+ else:
120
+ args = parser.parse_args([])
121
+
122
+ if args.windows_standalone_build:
123
+ args.auto_launch = True
124
+
125
+ if args.disable_auto_launch:
126
+ 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": 2,
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,188 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from comfy.ldm.modules.attention import optimized_attention_for_device
3
+
4
+ class CLIPAttention(torch.nn.Module):
5
+ def __init__(self, embed_dim, heads, dtype, device, operations):
6
+ super().__init__()
7
+
8
+ self.heads = heads
9
+ self.q_proj = operations.Linear(embed_dim, embed_dim, bias=True, dtype=dtype, device=device)
10
+ self.k_proj = operations.Linear(embed_dim, embed_dim, bias=True, dtype=dtype, device=device)
11
+ self.v_proj = operations.Linear(embed_dim, embed_dim, bias=True, dtype=dtype, device=device)
12
+
13
+ self.out_proj = operations.Linear(embed_dim, embed_dim, bias=True, dtype=dtype, device=device)
14
+
15
+ def forward(self, x, mask=None, optimized_attention=None):
16
+ q = self.q_proj(x)
17
+ k = self.k_proj(x)
18
+ v = self.v_proj(x)
19
+
20
+ out = optimized_attention(q, k, v, self.heads, mask)
21
+ return self.out_proj(out)
22
+
23
+ ACTIVATIONS = {"quick_gelu": lambda a: a * torch.sigmoid(1.702 * a),
24
+ "gelu": torch.nn.functional.gelu,
25
+ }
26
+
27
+ class CLIPMLP(torch.nn.Module):
28
+ def __init__(self, embed_dim, intermediate_size, activation, dtype, device, operations):
29
+ super().__init__()
30
+ self.fc1 = operations.Linear(embed_dim, intermediate_size, bias=True, dtype=dtype, device=device)
31
+ self.activation = ACTIVATIONS[activation]
32
+ self.fc2 = operations.Linear(intermediate_size, embed_dim, bias=True, dtype=dtype, device=device)
33
+
34
+ def forward(self, x):
35
+ x = self.fc1(x)
36
+ x = self.activation(x)
37
+ x = self.fc2(x)
38
+ return x
39
+
40
+ class CLIPLayer(torch.nn.Module):
41
+ def __init__(self, embed_dim, heads, intermediate_size, intermediate_activation, dtype, device, operations):
42
+ super().__init__()
43
+ self.layer_norm1 = operations.LayerNorm(embed_dim, dtype=dtype, device=device)
44
+ self.self_attn = CLIPAttention(embed_dim, heads, dtype, device, operations)
45
+ self.layer_norm2 = operations.LayerNorm(embed_dim, dtype=dtype, device=device)
46
+ self.mlp = CLIPMLP(embed_dim, intermediate_size, intermediate_activation, dtype, device, operations)
47
+
48
+ def forward(self, x, mask=None, optimized_attention=None):
49
+ x += self.self_attn(self.layer_norm1(x), mask, optimized_attention)
50
+ x += self.mlp(self.layer_norm2(x))
51
+ return x
52
+
53
+
54
+ class CLIPEncoder(torch.nn.Module):
55
+ def __init__(self, num_layers, embed_dim, heads, intermediate_size, intermediate_activation, dtype, device, operations):
56
+ super().__init__()
57
+ self.layers = torch.nn.ModuleList([CLIPLayer(embed_dim, heads, intermediate_size, intermediate_activation, dtype, device, operations) for i in range(num_layers)])
58
+
59
+ def forward(self, x, mask=None, intermediate_output=None):
60
+ optimized_attention = optimized_attention_for_device(x.device, mask=mask is not None, small_input=True)
61
+
62
+ if intermediate_output is not None:
63
+ if intermediate_output < 0:
64
+ intermediate_output = len(self.layers) + intermediate_output
65
+
66
+ intermediate = None
67
+ for i, l in enumerate(self.layers):
68
+ x = l(x, mask, optimized_attention)
69
+ if i == intermediate_output:
70
+ intermediate = x.clone()
71
+ return x, intermediate
72
+
73
+ class CLIPEmbeddings(torch.nn.Module):
74
+ def __init__(self, embed_dim, vocab_size=49408, num_positions=77, dtype=None, device=None):
75
+ super().__init__()
76
+ self.token_embedding = torch.nn.Embedding(vocab_size, embed_dim, dtype=dtype, device=device)
77
+ self.position_embedding = torch.nn.Embedding(num_positions, embed_dim, dtype=dtype, device=device)
78
+
79
+ def forward(self, input_tokens):
80
+ return self.token_embedding(input_tokens) + self.position_embedding.weight
81
+
82
+
83
+ class CLIPTextModel_(torch.nn.Module):
84
+ def __init__(self, config_dict, dtype, device, operations):
85
+ num_layers = config_dict["num_hidden_layers"]
86
+ embed_dim = config_dict["hidden_size"]
87
+ heads = config_dict["num_attention_heads"]
88
+ intermediate_size = config_dict["intermediate_size"]
89
+ intermediate_activation = config_dict["hidden_act"]
90
+
91
+ super().__init__()
92
+ self.embeddings = CLIPEmbeddings(embed_dim, dtype=torch.float32, device=device)
93
+ self.encoder = CLIPEncoder(num_layers, embed_dim, heads, intermediate_size, intermediate_activation, dtype, device, operations)
94
+ self.final_layer_norm = operations.LayerNorm(embed_dim, dtype=dtype, device=device)
95
+
96
+ def forward(self, input_tokens, attention_mask=None, intermediate_output=None, final_layer_norm_intermediate=True):
97
+ x = self.embeddings(input_tokens)
98
+ mask = None
99
+ if attention_mask is not None:
100
+ mask = 1.0 - attention_mask.to(x.dtype).unsqueeze(1).unsqueeze(1).expand(attention_mask.shape[0], 1, attention_mask.shape[-1], attention_mask.shape[-1])
101
+ mask = mask.masked_fill(mask.to(torch.bool), float("-inf"))
102
+
103
+ causal_mask = torch.empty(x.shape[1], x.shape[1], dtype=x.dtype, device=x.device).fill_(float("-inf")).triu_(1)
104
+ if mask is not None:
105
+ mask += causal_mask
106
+ else:
107
+ mask = causal_mask
108
+
109
+ x, i = self.encoder(x, mask=mask, intermediate_output=intermediate_output)
110
+ x = self.final_layer_norm(x)
111
+ if i is not None and final_layer_norm_intermediate:
112
+ i = self.final_layer_norm(i)
113
+
114
+ pooled_output = x[torch.arange(x.shape[0], device=x.device), input_tokens.to(dtype=torch.int, device=x.device).argmax(dim=-1),]
115
+ return x, i, pooled_output
116
+
117
+ class CLIPTextModel(torch.nn.Module):
118
+ def __init__(self, config_dict, dtype, device, operations):
119
+ super().__init__()
120
+ self.num_layers = config_dict["num_hidden_layers"]
121
+ self.text_model = CLIPTextModel_(config_dict, dtype, device, operations)
122
+ self.dtype = dtype
123
+
124
+ def get_input_embeddings(self):
125
+ return self.text_model.embeddings.token_embedding
126
+
127
+ def set_input_embeddings(self, embeddings):
128
+ self.text_model.embeddings.token_embedding = embeddings
129
+
130
+ def forward(self, *args, **kwargs):
131
+ return self.text_model(*args, **kwargs)
132
+
133
+ class CLIPVisionEmbeddings(torch.nn.Module):
134
+ def __init__(self, embed_dim, num_channels=3, patch_size=14, image_size=224, dtype=None, device=None, operations=None):
135
+ super().__init__()
136
+ self.class_embedding = torch.nn.Parameter(torch.empty(embed_dim, dtype=dtype, device=device))
137
+
138
+ self.patch_embedding = operations.Conv2d(
139
+ in_channels=num_channels,
140
+ out_channels=embed_dim,
141
+ kernel_size=patch_size,
142
+ stride=patch_size,
143
+ bias=False,
144
+ dtype=dtype,
145
+ device=device
146
+ )
147
+
148
+ num_patches = (image_size // patch_size) ** 2
149
+ num_positions = num_patches + 1
150
+ self.position_embedding = torch.nn.Embedding(num_positions, embed_dim, dtype=dtype, device=device)
151
+
152
+ def forward(self, pixel_values):
153
+ embeds = self.patch_embedding(pixel_values).flatten(2).transpose(1, 2)
154
+ return torch.cat([self.class_embedding.to(embeds.device).expand(pixel_values.shape[0], 1, -1), embeds], dim=1) + self.position_embedding.weight.to(embeds.device)
155
+
156
+
157
+ class CLIPVision(torch.nn.Module):
158
+ def __init__(self, config_dict, dtype, device, operations):
159
+ super().__init__()
160
+ num_layers = config_dict["num_hidden_layers"]
161
+ embed_dim = config_dict["hidden_size"]
162
+ heads = config_dict["num_attention_heads"]
163
+ intermediate_size = config_dict["intermediate_size"]
164
+ intermediate_activation = config_dict["hidden_act"]
165
+
166
+ self.embeddings = CLIPVisionEmbeddings(embed_dim, config_dict["num_channels"], config_dict["patch_size"], config_dict["image_size"], dtype=torch.float32, device=device, operations=operations)
167
+ self.pre_layrnorm = operations.LayerNorm(embed_dim)
168
+ self.encoder = CLIPEncoder(num_layers, embed_dim, heads, intermediate_size, intermediate_activation, dtype, device, operations)
169
+ self.post_layernorm = operations.LayerNorm(embed_dim)
170
+
171
+ def forward(self, pixel_values, attention_mask=None, intermediate_output=None):
172
+ x = self.embeddings(pixel_values)
173
+ x = self.pre_layrnorm(x)
174
+ #TODO: attention_mask?
175
+ x, i = self.encoder(x, mask=None, intermediate_output=intermediate_output)
176
+ pooled_output = self.post_layernorm(x[:, 0, :])
177
+ return x, i, pooled_output
178
+
179
+ class CLIPVisionModelProjection(torch.nn.Module):
180
+ def __init__(self, config_dict, dtype, device, operations):
181
+ super().__init__()
182
+ self.vision_model = CLIPVision(config_dict, dtype, device, operations)
183
+ self.visual_projection = operations.Linear(config_dict["hidden_size"], config_dict["projection_dim"], bias=False)
184
+
185
+ def forward(self, *args, **kwargs):
186
+ x = self.vision_model(*args, **kwargs)
187
+ out = self.visual_projection(x[2])
188
+ return (x[0], x[1], out)
comfy/clip_vision.py ADDED
@@ -0,0 +1,116 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from .utils import load_torch_file, transformers_convert, state_dict_prefix_replace
2
+ import os
3
+ import torch
4
+ import json
5
+
6
+ import comfy.ops
7
+ import comfy.model_patcher
8
+ import comfy.model_management
9
+ import comfy.utils
10
+ import comfy.clip_model
11
+
12
+ class Output:
13
+ def __getitem__(self, key):
14
+ return getattr(self, key)
15
+ def __setitem__(self, key, item):
16
+ setattr(self, key, item)
17
+
18
+ def clip_preprocess(image, size=224):
19
+ mean = torch.tensor([ 0.48145466,0.4578275,0.40821073], device=image.device, dtype=image.dtype)
20
+ std = torch.tensor([0.26862954,0.26130258,0.27577711], device=image.device, dtype=image.dtype)
21
+ image = image.movedim(-1, 1)
22
+ if not (image.shape[2] == size and image.shape[3] == size):
23
+ scale = (size / min(image.shape[2], image.shape[3]))
24
+ image = torch.nn.functional.interpolate(image, size=(round(scale * image.shape[2]), round(scale * image.shape[3])), mode="bicubic", antialias=True)
25
+ h = (image.shape[2] - size)//2
26
+ w = (image.shape[3] - size)//2
27
+ image = image[:,:,h:h+size,w:w+size]
28
+ image = torch.clip((255. * image), 0, 255).round() / 255.0
29
+ return (image - mean.view([3,1,1])) / std.view([3,1,1])
30
+
31
+ class ClipVisionModel():
32
+ def __init__(self, json_config):
33
+ with open(json_config) as f:
34
+ config = json.load(f)
35
+
36
+ self.load_device = comfy.model_management.text_encoder_device()
37
+ offload_device = comfy.model_management.text_encoder_offload_device()
38
+ self.dtype = comfy.model_management.text_encoder_dtype(self.load_device)
39
+ self.model = comfy.clip_model.CLIPVisionModelProjection(config, self.dtype, offload_device, comfy.ops.manual_cast)
40
+ self.model.eval()
41
+
42
+ self.patcher = comfy.model_patcher.ModelPatcher(self.model, load_device=self.load_device, offload_device=offload_device)
43
+
44
+ def load_sd(self, sd):
45
+ return self.model.load_state_dict(sd, strict=False)
46
+
47
+ def get_sd(self):
48
+ return self.model.state_dict()
49
+
50
+ def encode_image(self, image):
51
+ comfy.model_management.load_model_gpu(self.patcher)
52
+ pixel_values = clip_preprocess(image.to(self.load_device)).float()
53
+ out = self.model(pixel_values=pixel_values, intermediate_output=-2)
54
+
55
+ outputs = Output()
56
+ outputs["last_hidden_state"] = out[0].to(comfy.model_management.intermediate_device())
57
+ outputs["image_embeds"] = out[2].to(comfy.model_management.intermediate_device())
58
+ outputs["penultimate_hidden_states"] = out[1].to(comfy.model_management.intermediate_device())
59
+ return outputs
60
+
61
+ def convert_to_transformers(sd, prefix):
62
+ sd_k = sd.keys()
63
+ if "{}transformer.resblocks.0.attn.in_proj_weight".format(prefix) in sd_k:
64
+ keys_to_replace = {
65
+ "{}class_embedding".format(prefix): "vision_model.embeddings.class_embedding",
66
+ "{}conv1.weight".format(prefix): "vision_model.embeddings.patch_embedding.weight",
67
+ "{}positional_embedding".format(prefix): "vision_model.embeddings.position_embedding.weight",
68
+ "{}ln_post.bias".format(prefix): "vision_model.post_layernorm.bias",
69
+ "{}ln_post.weight".format(prefix): "vision_model.post_layernorm.weight",
70
+ "{}ln_pre.bias".format(prefix): "vision_model.pre_layrnorm.bias",
71
+ "{}ln_pre.weight".format(prefix): "vision_model.pre_layrnorm.weight",
72
+ }
73
+
74
+ for x in keys_to_replace:
75
+ if x in sd_k:
76
+ sd[keys_to_replace[x]] = sd.pop(x)
77
+
78
+ if "{}proj".format(prefix) in sd_k:
79
+ sd['visual_projection.weight'] = sd.pop("{}proj".format(prefix)).transpose(0, 1)
80
+
81
+ sd = transformers_convert(sd, prefix, "vision_model.", 48)
82
+ else:
83
+ replace_prefix = {prefix: ""}
84
+ sd = state_dict_prefix_replace(sd, replace_prefix)
85
+ return sd
86
+
87
+ def load_clipvision_from_sd(sd, prefix="", convert_keys=False):
88
+ if convert_keys:
89
+ sd = convert_to_transformers(sd, prefix)
90
+ if "vision_model.encoder.layers.47.layer_norm1.weight" in sd:
91
+ json_config = os.path.join(os.path.dirname(os.path.realpath(__file__)), "clip_vision_config_g.json")
92
+ elif "vision_model.encoder.layers.30.layer_norm1.weight" in sd:
93
+ json_config = os.path.join(os.path.dirname(os.path.realpath(__file__)), "clip_vision_config_h.json")
94
+ elif "vision_model.encoder.layers.22.layer_norm1.weight" in sd:
95
+ json_config = os.path.join(os.path.dirname(os.path.realpath(__file__)), "clip_vision_config_vitl.json")
96
+ else:
97
+ return None
98
+
99
+ clip = ClipVisionModel(json_config)
100
+ m, u = clip.load_sd(sd)
101
+ if len(m) > 0:
102
+ print("missing clip vision:", m)
103
+ u = set(u)
104
+ keys = list(sd.keys())
105
+ for k in keys:
106
+ if k not in u:
107
+ t = sd.pop(k)
108
+ del t
109
+ return clip
110
+
111
+ def load(ckpt_path):
112
+ sd = load_torch_file(ckpt_path)
113
+ if "visual.transformer.resblocks.0.attn.in_proj_weight" in sd:
114
+ return load_clipvision_from_sd(sd, prefix="visual.", convert_keys=True)
115
+ else:
116
+ 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/conds.py ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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[:,:,area[2]:area[0] + area[2],area[3]:area[1] + area[3]]
33
+ return self._copy_with(comfy.utils.repeat_to_batch_size(data, batch_size).to(device))
34
+
35
+
36
+ class CONDCrossAttn(CONDRegular):
37
+ def can_concat(self, other):
38
+ s1 = self.cond.shape
39
+ s2 = other.cond.shape
40
+ if s1 != s2:
41
+ if s1[0] != s2[0] or s1[2] != s2[2]: #these 2 cases should not happen
42
+ return False
43
+
44
+ mult_min = lcm(s1[1], s2[1])
45
+ diff = mult_min // min(s1[1], s2[1])
46
+ if diff > 4: #arbitrary limit on the padding because it's probably going to impact performance negatively if it's too much
47
+ return False
48
+ return True
49
+
50
+ def concat(self, others):
51
+ conds = [self.cond]
52
+ crossattn_max_len = self.cond.shape[1]
53
+ for x in others:
54
+ c = x.cond
55
+ crossattn_max_len = lcm(crossattn_max_len, c.shape[1])
56
+ conds.append(c)
57
+
58
+ out = []
59
+ for c in conds:
60
+ if c.shape[1] < crossattn_max_len:
61
+ c = c.repeat(1, crossattn_max_len // c.shape[1], 1) #padding with repeat doesn't change result
62
+ out.append(c)
63
+ return torch.cat(out)
64
+
65
+ class CONDConstant(CONDRegular):
66
+ def __init__(self, cond):
67
+ self.cond = cond
68
+
69
+ def process_cond(self, batch_size, device, **kwargs):
70
+ return self._copy_with(self.cond)
71
+
72
+ def can_concat(self, other):
73
+ if self.cond != other.cond:
74
+ return False
75
+ return True
76
+
77
+ def concat(self, others):
78
+ return self.cond
comfy/controlnet.py ADDED
@@ -0,0 +1,516 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import math
3
+ import os
4
+ import comfy.utils
5
+ import comfy.model_management
6
+ import comfy.model_detection
7
+ import comfy.model_patcher
8
+ import comfy.ops
9
+
10
+ import comfy.cldm.cldm
11
+ import comfy.t2i_adapter.adapter
12
+
13
+
14
+ def broadcast_image_to(tensor, target_batch_size, batched_number):
15
+ current_batch_size = tensor.shape[0]
16
+ #print(current_batch_size, target_batch_size)
17
+ if current_batch_size == 1:
18
+ return tensor
19
+
20
+ per_batch = target_batch_size // batched_number
21
+ tensor = tensor[:per_batch]
22
+
23
+ if per_batch > tensor.shape[0]:
24
+ tensor = torch.cat([tensor] * (per_batch // tensor.shape[0]) + [tensor[:(per_batch % tensor.shape[0])]], dim=0)
25
+
26
+ current_batch_size = tensor.shape[0]
27
+ if current_batch_size == target_batch_size:
28
+ return tensor
29
+ else:
30
+ return torch.cat([tensor] * batched_number, dim=0)
31
+
32
+ class ControlBase:
33
+ def __init__(self, device=None):
34
+ self.cond_hint_original = None
35
+ self.cond_hint = None
36
+ self.strength = 1.0
37
+ self.timestep_percent_range = (0.0, 1.0)
38
+ self.global_average_pooling = False
39
+ self.timestep_range = None
40
+
41
+ if device is None:
42
+ device = comfy.model_management.get_torch_device()
43
+ self.device = device
44
+ self.previous_controlnet = None
45
+
46
+ def set_cond_hint(self, cond_hint, strength=1.0, timestep_percent_range=(0.0, 1.0)):
47
+ self.cond_hint_original = cond_hint
48
+ self.strength = strength
49
+ self.timestep_percent_range = timestep_percent_range
50
+ return self
51
+
52
+ def pre_run(self, model, percent_to_timestep_function):
53
+ self.timestep_range = (percent_to_timestep_function(self.timestep_percent_range[0]), percent_to_timestep_function(self.timestep_percent_range[1]))
54
+ if self.previous_controlnet is not None:
55
+ self.previous_controlnet.pre_run(model, percent_to_timestep_function)
56
+
57
+ def set_previous_controlnet(self, controlnet):
58
+ self.previous_controlnet = controlnet
59
+ return self
60
+
61
+ def cleanup(self):
62
+ if self.previous_controlnet is not None:
63
+ self.previous_controlnet.cleanup()
64
+ if self.cond_hint is not None:
65
+ del self.cond_hint
66
+ self.cond_hint = None
67
+ self.timestep_range = None
68
+
69
+ def get_models(self):
70
+ out = []
71
+ if self.previous_controlnet is not None:
72
+ out += self.previous_controlnet.get_models()
73
+ return out
74
+
75
+ def copy_to(self, c):
76
+ c.cond_hint_original = self.cond_hint_original
77
+ c.strength = self.strength
78
+ c.timestep_percent_range = self.timestep_percent_range
79
+ c.global_average_pooling = self.global_average_pooling
80
+
81
+ def inference_memory_requirements(self, dtype):
82
+ if self.previous_controlnet is not None:
83
+ return self.previous_controlnet.inference_memory_requirements(dtype)
84
+ return 0
85
+
86
+ def control_merge(self, control_input, control_output, control_prev, output_dtype):
87
+ out = {'input':[], 'middle':[], 'output': []}
88
+
89
+ if control_input is not None:
90
+ for i in range(len(control_input)):
91
+ key = 'input'
92
+ x = control_input[i]
93
+ if x is not None:
94
+ x *= self.strength
95
+ if x.dtype != output_dtype:
96
+ x = x.to(output_dtype)
97
+ out[key].insert(0, x)
98
+
99
+ if control_output is not None:
100
+ for i in range(len(control_output)):
101
+ if i == (len(control_output) - 1):
102
+ key = 'middle'
103
+ index = 0
104
+ else:
105
+ key = 'output'
106
+ index = i
107
+ x = control_output[i]
108
+ if x is not None:
109
+ if self.global_average_pooling:
110
+ x = torch.mean(x, dim=(2, 3), keepdim=True).repeat(1, 1, x.shape[2], x.shape[3])
111
+
112
+ x *= self.strength
113
+ if x.dtype != output_dtype:
114
+ x = x.to(output_dtype)
115
+
116
+ out[key].append(x)
117
+ if control_prev is not None:
118
+ for x in ['input', 'middle', 'output']:
119
+ o = out[x]
120
+ for i in range(len(control_prev[x])):
121
+ prev_val = control_prev[x][i]
122
+ if i >= len(o):
123
+ o.append(prev_val)
124
+ elif prev_val is not None:
125
+ if o[i] is None:
126
+ o[i] = prev_val
127
+ else:
128
+ if o[i].shape[0] < prev_val.shape[0]:
129
+ o[i] = prev_val + o[i]
130
+ else:
131
+ o[i] += prev_val
132
+ return out
133
+
134
+ class ControlNet(ControlBase):
135
+ def __init__(self, control_model, global_average_pooling=False, device=None, load_device=None, manual_cast_dtype=None):
136
+ super().__init__(device)
137
+ self.control_model = control_model
138
+ self.load_device = load_device
139
+ self.control_model_wrapped = comfy.model_patcher.ModelPatcher(self.control_model, load_device=load_device, offload_device=comfy.model_management.unet_offload_device())
140
+ self.global_average_pooling = global_average_pooling
141
+ self.model_sampling_current = None
142
+ self.manual_cast_dtype = manual_cast_dtype
143
+
144
+ def get_control(self, x_noisy, t, cond, batched_number):
145
+ control_prev = None
146
+ if self.previous_controlnet is not None:
147
+ control_prev = self.previous_controlnet.get_control(x_noisy, t, cond, batched_number)
148
+
149
+ if self.timestep_range is not None:
150
+ if t[0] > self.timestep_range[0] or t[0] < self.timestep_range[1]:
151
+ if control_prev is not None:
152
+ return control_prev
153
+ else:
154
+ return None
155
+
156
+ dtype = self.control_model.dtype
157
+ if self.manual_cast_dtype is not None:
158
+ dtype = self.manual_cast_dtype
159
+
160
+ output_dtype = x_noisy.dtype
161
+ if self.cond_hint is None or x_noisy.shape[2] * 8 != self.cond_hint.shape[2] or x_noisy.shape[3] * 8 != self.cond_hint.shape[3]:
162
+ if self.cond_hint is not None:
163
+ del self.cond_hint
164
+ self.cond_hint = None
165
+ self.cond_hint = comfy.utils.common_upscale(self.cond_hint_original, x_noisy.shape[3] * 8, x_noisy.shape[2] * 8, 'nearest-exact', "center").to(dtype).to(self.device)
166
+ if x_noisy.shape[0] != self.cond_hint.shape[0]:
167
+ self.cond_hint = broadcast_image_to(self.cond_hint, x_noisy.shape[0], batched_number)
168
+
169
+ context = cond['c_crossattn']
170
+ y = cond.get('y', None)
171
+ if y is not None:
172
+ y = y.to(dtype)
173
+ timestep = self.model_sampling_current.timestep(t)
174
+ x_noisy = self.model_sampling_current.calculate_input(t, x_noisy)
175
+
176
+ control = self.control_model(x=x_noisy.to(dtype), hint=self.cond_hint, timesteps=timestep.float(), context=context.to(dtype), y=y)
177
+ return self.control_merge(None, control, control_prev, output_dtype)
178
+
179
+ def copy(self):
180
+ c = ControlNet(self.control_model, global_average_pooling=self.global_average_pooling, load_device=self.load_device, manual_cast_dtype=self.manual_cast_dtype)
181
+ self.copy_to(c)
182
+ return c
183
+
184
+ def get_models(self):
185
+ out = super().get_models()
186
+ out.append(self.control_model_wrapped)
187
+ return out
188
+
189
+ def pre_run(self, model, percent_to_timestep_function):
190
+ super().pre_run(model, percent_to_timestep_function)
191
+ self.model_sampling_current = model.model_sampling
192
+
193
+ def cleanup(self):
194
+ self.model_sampling_current = None
195
+ super().cleanup()
196
+
197
+ class ControlLoraOps:
198
+ class Linear(torch.nn.Module):
199
+ def __init__(self, in_features: int, out_features: int, bias: bool = True,
200
+ device=None, dtype=None) -> None:
201
+ factory_kwargs = {'device': device, 'dtype': dtype}
202
+ super().__init__()
203
+ self.in_features = in_features
204
+ self.out_features = out_features
205
+ self.weight = None
206
+ self.up = None
207
+ self.down = None
208
+ self.bias = None
209
+
210
+ def forward(self, input):
211
+ weight, bias = comfy.ops.cast_bias_weight(self, input)
212
+ if self.up is not None:
213
+ 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)
214
+ else:
215
+ return torch.nn.functional.linear(input, weight, bias)
216
+
217
+ class Conv2d(torch.nn.Module):
218
+ def __init__(
219
+ self,
220
+ in_channels,
221
+ out_channels,
222
+ kernel_size,
223
+ stride=1,
224
+ padding=0,
225
+ dilation=1,
226
+ groups=1,
227
+ bias=True,
228
+ padding_mode='zeros',
229
+ device=None,
230
+ dtype=None
231
+ ):
232
+ super().__init__()
233
+ self.in_channels = in_channels
234
+ self.out_channels = out_channels
235
+ self.kernel_size = kernel_size
236
+ self.stride = stride
237
+ self.padding = padding
238
+ self.dilation = dilation
239
+ self.transposed = False
240
+ self.output_padding = 0
241
+ self.groups = groups
242
+ self.padding_mode = padding_mode
243
+
244
+ self.weight = None
245
+ self.bias = None
246
+ self.up = None
247
+ self.down = None
248
+
249
+
250
+ def forward(self, input):
251
+ weight, bias = comfy.ops.cast_bias_weight(self, input)
252
+ if self.up is not None:
253
+ 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)
254
+ else:
255
+ return torch.nn.functional.conv2d(input, weight, bias, self.stride, self.padding, self.dilation, self.groups)
256
+
257
+
258
+ class ControlLora(ControlNet):
259
+ def __init__(self, control_weights, global_average_pooling=False, device=None):
260
+ ControlBase.__init__(self, device)
261
+ self.control_weights = control_weights
262
+ self.global_average_pooling = global_average_pooling
263
+
264
+ def pre_run(self, model, percent_to_timestep_function):
265
+ super().pre_run(model, percent_to_timestep_function)
266
+ controlnet_config = model.model_config.unet_config.copy()
267
+ controlnet_config.pop("out_channels")
268
+ controlnet_config["hint_channels"] = self.control_weights["input_hint_block.0.weight"].shape[1]
269
+ self.manual_cast_dtype = model.manual_cast_dtype
270
+ dtype = model.get_dtype()
271
+ if self.manual_cast_dtype is None:
272
+ class control_lora_ops(ControlLoraOps, comfy.ops.disable_weight_init):
273
+ pass
274
+ else:
275
+ class control_lora_ops(ControlLoraOps, comfy.ops.manual_cast):
276
+ pass
277
+ dtype = self.manual_cast_dtype
278
+
279
+ controlnet_config["operations"] = control_lora_ops
280
+ controlnet_config["dtype"] = dtype
281
+ self.control_model = comfy.cldm.cldm.ControlNet(**controlnet_config)
282
+ self.control_model.to(comfy.model_management.get_torch_device())
283
+ diffusion_model = model.diffusion_model
284
+ sd = diffusion_model.state_dict()
285
+ cm = self.control_model.state_dict()
286
+
287
+ for k in sd:
288
+ weight = sd[k]
289
+ try:
290
+ comfy.utils.set_attr(self.control_model, k, weight)
291
+ except:
292
+ pass
293
+
294
+ for k in self.control_weights:
295
+ if k not in {"lora_controlnet"}:
296
+ comfy.utils.set_attr(self.control_model, k, self.control_weights[k].to(dtype).to(comfy.model_management.get_torch_device()))
297
+
298
+ def copy(self):
299
+ c = ControlLora(self.control_weights, global_average_pooling=self.global_average_pooling)
300
+ self.copy_to(c)
301
+ return c
302
+
303
+ def cleanup(self):
304
+ del self.control_model
305
+ self.control_model = None
306
+ super().cleanup()
307
+
308
+ def get_models(self):
309
+ out = ControlBase.get_models(self)
310
+ return out
311
+
312
+ def inference_memory_requirements(self, dtype):
313
+ return comfy.utils.calculate_parameters(self.control_weights) * comfy.model_management.dtype_size(dtype) + ControlBase.inference_memory_requirements(self, dtype)
314
+
315
+ def load_controlnet(ckpt_path, model=None):
316
+ controlnet_data = comfy.utils.load_torch_file(ckpt_path, safe_load=True)
317
+ if "lora_controlnet" in controlnet_data:
318
+ return ControlLora(controlnet_data)
319
+
320
+ controlnet_config = None
321
+ if "controlnet_cond_embedding.conv_in.weight" in controlnet_data: #diffusers format
322
+ unet_dtype = comfy.model_management.unet_dtype()
323
+ controlnet_config = comfy.model_detection.unet_config_from_diffusers_unet(controlnet_data, unet_dtype)
324
+ diffusers_keys = comfy.utils.unet_to_diffusers(controlnet_config)
325
+ diffusers_keys["controlnet_mid_block.weight"] = "middle_block_out.0.weight"
326
+ diffusers_keys["controlnet_mid_block.bias"] = "middle_block_out.0.bias"
327
+
328
+ count = 0
329
+ loop = True
330
+ while loop:
331
+ suffix = [".weight", ".bias"]
332
+ for s in suffix:
333
+ k_in = "controlnet_down_blocks.{}{}".format(count, s)
334
+ k_out = "zero_convs.{}.0{}".format(count, s)
335
+ if k_in not in controlnet_data:
336
+ loop = False
337
+ break
338
+ diffusers_keys[k_in] = k_out
339
+ count += 1
340
+
341
+ count = 0
342
+ loop = True
343
+ while loop:
344
+ suffix = [".weight", ".bias"]
345
+ for s in suffix:
346
+ if count == 0:
347
+ k_in = "controlnet_cond_embedding.conv_in{}".format(s)
348
+ else:
349
+ k_in = "controlnet_cond_embedding.blocks.{}{}".format(count - 1, s)
350
+ k_out = "input_hint_block.{}{}".format(count * 2, s)
351
+ if k_in not in controlnet_data:
352
+ k_in = "controlnet_cond_embedding.conv_out{}".format(s)
353
+ loop = False
354
+ diffusers_keys[k_in] = k_out
355
+ count += 1
356
+
357
+ new_sd = {}
358
+ for k in diffusers_keys:
359
+ if k in controlnet_data:
360
+ new_sd[diffusers_keys[k]] = controlnet_data.pop(k)
361
+
362
+ leftover_keys = controlnet_data.keys()
363
+ if len(leftover_keys) > 0:
364
+ print("leftover keys:", leftover_keys)
365
+ controlnet_data = new_sd
366
+
367
+ pth_key = 'control_model.zero_convs.0.0.weight'
368
+ pth = False
369
+ key = 'zero_convs.0.0.weight'
370
+ if pth_key in controlnet_data:
371
+ pth = True
372
+ key = pth_key
373
+ prefix = "control_model."
374
+ elif key in controlnet_data:
375
+ prefix = ""
376
+ else:
377
+ net = load_t2i_adapter(controlnet_data)
378
+ if net is None:
379
+ print("error checkpoint does not contain controlnet or t2i adapter data", ckpt_path)
380
+ return net
381
+
382
+ if controlnet_config is None:
383
+ unet_dtype = comfy.model_management.unet_dtype()
384
+ controlnet_config = comfy.model_detection.model_config_from_unet(controlnet_data, prefix, unet_dtype, True).unet_config
385
+ load_device = comfy.model_management.get_torch_device()
386
+ manual_cast_dtype = comfy.model_management.unet_manual_cast(unet_dtype, load_device)
387
+ if manual_cast_dtype is not None:
388
+ controlnet_config["operations"] = comfy.ops.manual_cast
389
+ controlnet_config.pop("out_channels")
390
+ controlnet_config["hint_channels"] = controlnet_data["{}input_hint_block.0.weight".format(prefix)].shape[1]
391
+ control_model = comfy.cldm.cldm.ControlNet(**controlnet_config)
392
+
393
+ if pth:
394
+ if 'difference' in controlnet_data:
395
+ if model is not None:
396
+ comfy.model_management.load_models_gpu([model])
397
+ model_sd = model.model_state_dict()
398
+ for x in controlnet_data:
399
+ c_m = "control_model."
400
+ if x.startswith(c_m):
401
+ sd_key = "diffusion_model.{}".format(x[len(c_m):])
402
+ if sd_key in model_sd:
403
+ cd = controlnet_data[x]
404
+ cd += model_sd[sd_key].type(cd.dtype).to(cd.device)
405
+ else:
406
+ print("WARNING: Loaded a diff controlnet without a model. It will very likely not work.")
407
+
408
+ class WeightsLoader(torch.nn.Module):
409
+ pass
410
+ w = WeightsLoader()
411
+ w.control_model = control_model
412
+ missing, unexpected = w.load_state_dict(controlnet_data, strict=False)
413
+ else:
414
+ missing, unexpected = control_model.load_state_dict(controlnet_data, strict=False)
415
+ print(missing, unexpected)
416
+
417
+ global_average_pooling = False
418
+ filename = os.path.splitext(ckpt_path)[0]
419
+ if filename.endswith("_shuffle") or filename.endswith("_shuffle_fp16"): #TODO: smarter way of enabling global_average_pooling
420
+ global_average_pooling = True
421
+
422
+ control = ControlNet(control_model, global_average_pooling=global_average_pooling, load_device=load_device, manual_cast_dtype=manual_cast_dtype)
423
+ return control
424
+
425
+ class T2IAdapter(ControlBase):
426
+ def __init__(self, t2i_model, channels_in, device=None):
427
+ super().__init__(device)
428
+ self.t2i_model = t2i_model
429
+ self.channels_in = channels_in
430
+ self.control_input = None
431
+
432
+ def scale_image_to(self, width, height):
433
+ unshuffle_amount = self.t2i_model.unshuffle_amount
434
+ width = math.ceil(width / unshuffle_amount) * unshuffle_amount
435
+ height = math.ceil(height / unshuffle_amount) * unshuffle_amount
436
+ return width, height
437
+
438
+ def get_control(self, x_noisy, t, cond, batched_number):
439
+ control_prev = None
440
+ if self.previous_controlnet is not None:
441
+ control_prev = self.previous_controlnet.get_control(x_noisy, t, cond, batched_number)
442
+
443
+ if self.timestep_range is not None:
444
+ if t[0] > self.timestep_range[0] or t[0] < self.timestep_range[1]:
445
+ if control_prev is not None:
446
+ return control_prev
447
+ else:
448
+ return None
449
+
450
+ if self.cond_hint is None or x_noisy.shape[2] * 8 != self.cond_hint.shape[2] or x_noisy.shape[3] * 8 != self.cond_hint.shape[3]:
451
+ if self.cond_hint is not None:
452
+ del self.cond_hint
453
+ self.control_input = None
454
+ self.cond_hint = None
455
+ width, height = self.scale_image_to(x_noisy.shape[3] * 8, x_noisy.shape[2] * 8)
456
+ self.cond_hint = comfy.utils.common_upscale(self.cond_hint_original, width, height, 'nearest-exact', "center").float().to(self.device)
457
+ if self.channels_in == 1 and self.cond_hint.shape[1] > 1:
458
+ self.cond_hint = torch.mean(self.cond_hint, 1, keepdim=True)
459
+ if x_noisy.shape[0] != self.cond_hint.shape[0]:
460
+ self.cond_hint = broadcast_image_to(self.cond_hint, x_noisy.shape[0], batched_number)
461
+ if self.control_input is None:
462
+ self.t2i_model.to(x_noisy.dtype)
463
+ self.t2i_model.to(self.device)
464
+ self.control_input = self.t2i_model(self.cond_hint.to(x_noisy.dtype))
465
+ self.t2i_model.cpu()
466
+
467
+ control_input = list(map(lambda a: None if a is None else a.clone(), self.control_input))
468
+ mid = None
469
+ if self.t2i_model.xl == True:
470
+ mid = control_input[-1:]
471
+ control_input = control_input[:-1]
472
+ return self.control_merge(control_input, mid, control_prev, x_noisy.dtype)
473
+
474
+ def copy(self):
475
+ c = T2IAdapter(self.t2i_model, self.channels_in)
476
+ self.copy_to(c)
477
+ return c
478
+
479
+ def load_t2i_adapter(t2i_data):
480
+ if 'adapter' in t2i_data:
481
+ t2i_data = t2i_data['adapter']
482
+ if 'adapter.body.0.resnets.0.block1.weight' in t2i_data: #diffusers format
483
+ prefix_replace = {}
484
+ for i in range(4):
485
+ for j in range(2):
486
+ prefix_replace["adapter.body.{}.resnets.{}.".format(i, j)] = "body.{}.".format(i * 2 + j)
487
+ prefix_replace["adapter.body.{}.".format(i, j)] = "body.{}.".format(i * 2)
488
+ prefix_replace["adapter."] = ""
489
+ t2i_data = comfy.utils.state_dict_prefix_replace(t2i_data, prefix_replace)
490
+ keys = t2i_data.keys()
491
+
492
+ if "body.0.in_conv.weight" in keys:
493
+ cin = t2i_data['body.0.in_conv.weight'].shape[1]
494
+ model_ad = comfy.t2i_adapter.adapter.Adapter_light(cin=cin, channels=[320, 640, 1280, 1280], nums_rb=4)
495
+ elif 'conv_in.weight' in keys:
496
+ cin = t2i_data['conv_in.weight'].shape[1]
497
+ channel = t2i_data['conv_in.weight'].shape[0]
498
+ ksize = t2i_data['body.0.block2.weight'].shape[2]
499
+ use_conv = False
500
+ down_opts = list(filter(lambda a: a.endswith("down_opt.op.weight"), keys))
501
+ if len(down_opts) > 0:
502
+ use_conv = True
503
+ xl = False
504
+ if cin == 256 or cin == 768:
505
+ xl = True
506
+ 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)
507
+ else:
508
+ return None
509
+ missing, unexpected = model_ad.load_state_dict(t2i_data)
510
+ if len(missing) > 0:
511
+ print("t2i missing", missing)
512
+
513
+ if len(unexpected) > 0:
514
+ print("t2i unexpected", unexpected)
515
+
516
+ return T2IAdapter(model_ad, model_ad.input_channels)
comfy/diffusers_convert.py ADDED
@@ -0,0 +1,261 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import re
2
+ import torch
3
+
4
+ # conversion code from https://github.com/huggingface/diffusers/blob/main/scripts/convert_diffusers_to_original_stable_diffusion.py
5
+
6
+ # =================#
7
+ # UNet Conversion #
8
+ # =================#
9
+
10
+ unet_conversion_map = [
11
+ # (stable-diffusion, HF Diffusers)
12
+ ("time_embed.0.weight", "time_embedding.linear_1.weight"),
13
+ ("time_embed.0.bias", "time_embedding.linear_1.bias"),
14
+ ("time_embed.2.weight", "time_embedding.linear_2.weight"),
15
+ ("time_embed.2.bias", "time_embedding.linear_2.bias"),
16
+ ("input_blocks.0.0.weight", "conv_in.weight"),
17
+ ("input_blocks.0.0.bias", "conv_in.bias"),
18
+ ("out.0.weight", "conv_norm_out.weight"),
19
+ ("out.0.bias", "conv_norm_out.bias"),
20
+ ("out.2.weight", "conv_out.weight"),
21
+ ("out.2.bias", "conv_out.bias"),
22
+ ]
23
+
24
+ unet_conversion_map_resnet = [
25
+ # (stable-diffusion, HF Diffusers)
26
+ ("in_layers.0", "norm1"),
27
+ ("in_layers.2", "conv1"),
28
+ ("out_layers.0", "norm2"),
29
+ ("out_layers.3", "conv2"),
30
+ ("emb_layers.1", "time_emb_proj"),
31
+ ("skip_connection", "conv_shortcut"),
32
+ ]
33
+
34
+ unet_conversion_map_layer = []
35
+ # hardcoded number of downblocks and resnets/attentions...
36
+ # would need smarter logic for other networks.
37
+ for i in range(4):
38
+ # loop over downblocks/upblocks
39
+
40
+ for j in range(2):
41
+ # loop over resnets/attentions for downblocks
42
+ hf_down_res_prefix = f"down_blocks.{i}.resnets.{j}."
43
+ sd_down_res_prefix = f"input_blocks.{3 * i + j + 1}.0."
44
+ unet_conversion_map_layer.append((sd_down_res_prefix, hf_down_res_prefix))
45
+
46
+ if i < 3:
47
+ # no attention layers in down_blocks.3
48
+ hf_down_atn_prefix = f"down_blocks.{i}.attentions.{j}."
49
+ sd_down_atn_prefix = f"input_blocks.{3 * i + j + 1}.1."
50
+ unet_conversion_map_layer.append((sd_down_atn_prefix, hf_down_atn_prefix))
51
+
52
+ for j in range(3):
53
+ # loop over resnets/attentions for upblocks
54
+ hf_up_res_prefix = f"up_blocks.{i}.resnets.{j}."
55
+ sd_up_res_prefix = f"output_blocks.{3 * i + j}.0."
56
+ unet_conversion_map_layer.append((sd_up_res_prefix, hf_up_res_prefix))
57
+
58
+ if i > 0:
59
+ # no attention layers in up_blocks.0
60
+ hf_up_atn_prefix = f"up_blocks.{i}.attentions.{j}."
61
+ sd_up_atn_prefix = f"output_blocks.{3 * i + j}.1."
62
+ unet_conversion_map_layer.append((sd_up_atn_prefix, hf_up_atn_prefix))
63
+
64
+ if i < 3:
65
+ # no downsample in down_blocks.3
66
+ hf_downsample_prefix = f"down_blocks.{i}.downsamplers.0.conv."
67
+ sd_downsample_prefix = f"input_blocks.{3 * (i + 1)}.0.op."
68
+ unet_conversion_map_layer.append((sd_downsample_prefix, hf_downsample_prefix))
69
+
70
+ # no upsample in up_blocks.3
71
+ hf_upsample_prefix = f"up_blocks.{i}.upsamplers.0."
72
+ sd_upsample_prefix = f"output_blocks.{3 * i + 2}.{1 if i == 0 else 2}."
73
+ unet_conversion_map_layer.append((sd_upsample_prefix, hf_upsample_prefix))
74
+
75
+ hf_mid_atn_prefix = "mid_block.attentions.0."
76
+ sd_mid_atn_prefix = "middle_block.1."
77
+ unet_conversion_map_layer.append((sd_mid_atn_prefix, hf_mid_atn_prefix))
78
+
79
+ for j in range(2):
80
+ hf_mid_res_prefix = f"mid_block.resnets.{j}."
81
+ sd_mid_res_prefix = f"middle_block.{2 * j}."
82
+ unet_conversion_map_layer.append((sd_mid_res_prefix, hf_mid_res_prefix))
83
+
84
+
85
+ def convert_unet_state_dict(unet_state_dict):
86
+ # buyer beware: this is a *brittle* function,
87
+ # and correct output requires that all of these pieces interact in
88
+ # the exact order in which I have arranged them.
89
+ mapping = {k: k for k in unet_state_dict.keys()}
90
+ for sd_name, hf_name in unet_conversion_map:
91
+ mapping[hf_name] = sd_name
92
+ for k, v in mapping.items():
93
+ if "resnets" in k:
94
+ for sd_part, hf_part in unet_conversion_map_resnet:
95
+ v = v.replace(hf_part, sd_part)
96
+ mapping[k] = v
97
+ for k, v in mapping.items():
98
+ for sd_part, hf_part in unet_conversion_map_layer:
99
+ v = v.replace(hf_part, sd_part)
100
+ mapping[k] = v
101
+ new_state_dict = {v: unet_state_dict[k] for k, v in mapping.items()}
102
+ return new_state_dict
103
+
104
+
105
+ # ================#
106
+ # VAE Conversion #
107
+ # ================#
108
+
109
+ vae_conversion_map = [
110
+ # (stable-diffusion, HF Diffusers)
111
+ ("nin_shortcut", "conv_shortcut"),
112
+ ("norm_out", "conv_norm_out"),
113
+ ("mid.attn_1.", "mid_block.attentions.0."),
114
+ ]
115
+
116
+ for i in range(4):
117
+ # down_blocks have two resnets
118
+ for j in range(2):
119
+ hf_down_prefix = f"encoder.down_blocks.{i}.resnets.{j}."
120
+ sd_down_prefix = f"encoder.down.{i}.block.{j}."
121
+ vae_conversion_map.append((sd_down_prefix, hf_down_prefix))
122
+
123
+ if i < 3:
124
+ hf_downsample_prefix = f"down_blocks.{i}.downsamplers.0."
125
+ sd_downsample_prefix = f"down.{i}.downsample."
126
+ vae_conversion_map.append((sd_downsample_prefix, hf_downsample_prefix))
127
+
128
+ hf_upsample_prefix = f"up_blocks.{i}.upsamplers.0."
129
+ sd_upsample_prefix = f"up.{3 - i}.upsample."
130
+ vae_conversion_map.append((sd_upsample_prefix, hf_upsample_prefix))
131
+
132
+ # up_blocks have three resnets
133
+ # also, up blocks in hf are numbered in reverse from sd
134
+ for j in range(3):
135
+ hf_up_prefix = f"decoder.up_blocks.{i}.resnets.{j}."
136
+ sd_up_prefix = f"decoder.up.{3 - i}.block.{j}."
137
+ vae_conversion_map.append((sd_up_prefix, hf_up_prefix))
138
+
139
+ # this part accounts for mid blocks in both the encoder and the decoder
140
+ for i in range(2):
141
+ hf_mid_res_prefix = f"mid_block.resnets.{i}."
142
+ sd_mid_res_prefix = f"mid.block_{i + 1}."
143
+ vae_conversion_map.append((sd_mid_res_prefix, hf_mid_res_prefix))
144
+
145
+ vae_conversion_map_attn = [
146
+ # (stable-diffusion, HF Diffusers)
147
+ ("norm.", "group_norm."),
148
+ ("q.", "query."),
149
+ ("k.", "key."),
150
+ ("v.", "value."),
151
+ ("q.", "to_q."),
152
+ ("k.", "to_k."),
153
+ ("v.", "to_v."),
154
+ ("proj_out.", "to_out.0."),
155
+ ("proj_out.", "proj_attn."),
156
+ ]
157
+
158
+
159
+ def reshape_weight_for_sd(w):
160
+ # convert HF linear weights to SD conv2d weights
161
+ return w.reshape(*w.shape, 1, 1)
162
+
163
+
164
+ def convert_vae_state_dict(vae_state_dict):
165
+ mapping = {k: k for k in vae_state_dict.keys()}
166
+ for k, v in mapping.items():
167
+ for sd_part, hf_part in vae_conversion_map:
168
+ v = v.replace(hf_part, sd_part)
169
+ mapping[k] = v
170
+ for k, v in mapping.items():
171
+ if "attentions" in k:
172
+ for sd_part, hf_part in vae_conversion_map_attn:
173
+ v = v.replace(hf_part, sd_part)
174
+ mapping[k] = v
175
+ new_state_dict = {v: vae_state_dict[k] for k, v in mapping.items()}
176
+ weights_to_convert = ["q", "k", "v", "proj_out"]
177
+ for k, v in new_state_dict.items():
178
+ for weight_name in weights_to_convert:
179
+ if f"mid.attn_1.{weight_name}.weight" in k:
180
+ print(f"Reshaping {k} for SD format")
181
+ new_state_dict[k] = reshape_weight_for_sd(v)
182
+ return new_state_dict
183
+
184
+
185
+ # =========================#
186
+ # Text Encoder Conversion #
187
+ # =========================#
188
+
189
+
190
+ textenc_conversion_lst = [
191
+ # (stable-diffusion, HF Diffusers)
192
+ ("resblocks.", "text_model.encoder.layers."),
193
+ ("ln_1", "layer_norm1"),
194
+ ("ln_2", "layer_norm2"),
195
+ (".c_fc.", ".fc1."),
196
+ (".c_proj.", ".fc2."),
197
+ (".attn", ".self_attn"),
198
+ ("ln_final.", "transformer.text_model.final_layer_norm."),
199
+ ("token_embedding.weight", "transformer.text_model.embeddings.token_embedding.weight"),
200
+ ("positional_embedding", "transformer.text_model.embeddings.position_embedding.weight"),
201
+ ]
202
+ protected = {re.escape(x[1]): x[0] for x in textenc_conversion_lst}
203
+ textenc_pattern = re.compile("|".join(protected.keys()))
204
+
205
+ # Ordering is from https://github.com/pytorch/pytorch/blob/master/test/cpp/api/modules.cpp
206
+ code2idx = {"q": 0, "k": 1, "v": 2}
207
+
208
+
209
+ def convert_text_enc_state_dict_v20(text_enc_dict, prefix=""):
210
+ new_state_dict = {}
211
+ capture_qkv_weight = {}
212
+ capture_qkv_bias = {}
213
+ for k, v in text_enc_dict.items():
214
+ if not k.startswith(prefix):
215
+ continue
216
+ if (
217
+ k.endswith(".self_attn.q_proj.weight")
218
+ or k.endswith(".self_attn.k_proj.weight")
219
+ or k.endswith(".self_attn.v_proj.weight")
220
+ ):
221
+ k_pre = k[: -len(".q_proj.weight")]
222
+ k_code = k[-len("q_proj.weight")]
223
+ if k_pre not in capture_qkv_weight:
224
+ capture_qkv_weight[k_pre] = [None, None, None]
225
+ capture_qkv_weight[k_pre][code2idx[k_code]] = v
226
+ continue
227
+
228
+ if (
229
+ k.endswith(".self_attn.q_proj.bias")
230
+ or k.endswith(".self_attn.k_proj.bias")
231
+ or k.endswith(".self_attn.v_proj.bias")
232
+ ):
233
+ k_pre = k[: -len(".q_proj.bias")]
234
+ k_code = k[-len("q_proj.bias")]
235
+ if k_pre not in capture_qkv_bias:
236
+ capture_qkv_bias[k_pre] = [None, None, None]
237
+ capture_qkv_bias[k_pre][code2idx[k_code]] = v
238
+ continue
239
+
240
+ relabelled_key = textenc_pattern.sub(lambda m: protected[re.escape(m.group(0))], k)
241
+ new_state_dict[relabelled_key] = v
242
+
243
+ for k_pre, tensors in capture_qkv_weight.items():
244
+ if None in tensors:
245
+ raise Exception("CORRUPTED MODEL: one of the q-k-v values for the text encoder was missing")
246
+ relabelled_key = textenc_pattern.sub(lambda m: protected[re.escape(m.group(0))], k_pre)
247
+ new_state_dict[relabelled_key + ".in_proj_weight"] = torch.cat(tensors)
248
+
249
+ for k_pre, tensors in capture_qkv_bias.items():
250
+ if None in tensors:
251
+ raise Exception("CORRUPTED MODEL: one of the q-k-v values for the text encoder was missing")
252
+ relabelled_key = textenc_pattern.sub(lambda m: protected[re.escape(m.group(0))], k_pre)
253
+ new_state_dict[relabelled_key + ".in_proj_bias"] = torch.cat(tensors)
254
+
255
+ return new_state_dict
256
+
257
+
258
+ def convert_text_enc_state_dict(text_enc_dict):
259
+ return text_enc_dict
260
+
261
+
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_unet(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,894 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #code taken from: https://github.com/wl-zhao/UniPC and modified
2
+
3
+ import torch
4
+ import torch.nn.functional as F
5
+ import math
6
+
7
+ from tqdm.auto import trange, tqdm
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
+ """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
+ noise_mask=None,
362
+ masked_image=None,
363
+ noise=None,
364
+ ):
365
+ """Construct a UniPC.
366
+
367
+ We support both data_prediction and noise_prediction.
368
+ """
369
+ self.model = model_fn
370
+ self.noise_schedule = noise_schedule
371
+ self.variant = variant
372
+ self.predict_x0 = predict_x0
373
+ self.thresholding = thresholding
374
+ self.max_val = max_val
375
+ self.noise_mask = noise_mask
376
+ self.masked_image = masked_image
377
+ self.noise = noise
378
+
379
+ def dynamic_thresholding_fn(self, x0, t=None):
380
+ """
381
+ The dynamic thresholding method.
382
+ """
383
+ dims = x0.dim()
384
+ p = self.dynamic_thresholding_ratio
385
+ s = torch.quantile(torch.abs(x0).reshape((x0.shape[0], -1)), p, dim=1)
386
+ s = expand_dims(torch.maximum(s, self.thresholding_max_val * torch.ones_like(s).to(s.device)), dims)
387
+ x0 = torch.clamp(x0, -s, s) / s
388
+ return x0
389
+
390
+ def noise_prediction_fn(self, x, t):
391
+ """
392
+ Return the noise prediction model.
393
+ """
394
+ if self.noise_mask is not None:
395
+ return self.model(x, t) * self.noise_mask
396
+ else:
397
+ return self.model(x, t)
398
+
399
+ def data_prediction_fn(self, x, t):
400
+ """
401
+ Return the data prediction model (with thresholding).
402
+ """
403
+ noise = self.noise_prediction_fn(x, t)
404
+ dims = x.dim()
405
+ alpha_t, sigma_t = self.noise_schedule.marginal_alpha(t), self.noise_schedule.marginal_std(t)
406
+ x0 = (x - expand_dims(sigma_t, dims) * noise) / expand_dims(alpha_t, dims)
407
+ if self.thresholding:
408
+ p = 0.995 # A hyperparameter in the paper of "Imagen" [1].
409
+ s = torch.quantile(torch.abs(x0).reshape((x0.shape[0], -1)), p, dim=1)
410
+ s = expand_dims(torch.maximum(s, self.max_val * torch.ones_like(s).to(s.device)), dims)
411
+ x0 = torch.clamp(x0, -s, s) / s
412
+ if self.noise_mask is not None:
413
+ x0 = x0 * self.noise_mask + (1. - self.noise_mask) * self.masked_image
414
+ return x0
415
+
416
+ def model_fn(self, x, t):
417
+ """
418
+ Convert the model to the noise prediction model or the data prediction model.
419
+ """
420
+ if self.predict_x0:
421
+ return self.data_prediction_fn(x, t)
422
+ else:
423
+ return self.noise_prediction_fn(x, t)
424
+
425
+ def get_time_steps(self, skip_type, t_T, t_0, N, device):
426
+ """Compute the intermediate time steps for sampling.
427
+ """
428
+ if skip_type == 'logSNR':
429
+ lambda_T = self.noise_schedule.marginal_lambda(torch.tensor(t_T).to(device))
430
+ lambda_0 = self.noise_schedule.marginal_lambda(torch.tensor(t_0).to(device))
431
+ logSNR_steps = torch.linspace(lambda_T.cpu().item(), lambda_0.cpu().item(), N + 1).to(device)
432
+ return self.noise_schedule.inverse_lambda(logSNR_steps)
433
+ elif skip_type == 'time_uniform':
434
+ return torch.linspace(t_T, t_0, N + 1).to(device)
435
+ elif skip_type == 'time_quadratic':
436
+ t_order = 2
437
+ t = torch.linspace(t_T**(1. / t_order), t_0**(1. / t_order), N + 1).pow(t_order).to(device)
438
+ return t
439
+ else:
440
+ raise ValueError("Unsupported skip_type {}, need to be 'logSNR' or 'time_uniform' or 'time_quadratic'".format(skip_type))
441
+
442
+ def get_orders_and_timesteps_for_singlestep_solver(self, steps, order, skip_type, t_T, t_0, device):
443
+ """
444
+ Get the order of each step for sampling by the singlestep DPM-Solver.
445
+ """
446
+ if order == 3:
447
+ K = steps // 3 + 1
448
+ if steps % 3 == 0:
449
+ orders = [3,] * (K - 2) + [2, 1]
450
+ elif steps % 3 == 1:
451
+ orders = [3,] * (K - 1) + [1]
452
+ else:
453
+ orders = [3,] * (K - 1) + [2]
454
+ elif order == 2:
455
+ if steps % 2 == 0:
456
+ K = steps // 2
457
+ orders = [2,] * K
458
+ else:
459
+ K = steps // 2 + 1
460
+ orders = [2,] * (K - 1) + [1]
461
+ elif order == 1:
462
+ K = steps
463
+ orders = [1,] * steps
464
+ else:
465
+ raise ValueError("'order' must be '1' or '2' or '3'.")
466
+ if skip_type == 'logSNR':
467
+ # To reproduce the results in DPM-Solver paper
468
+ timesteps_outer = self.get_time_steps(skip_type, t_T, t_0, K, device)
469
+ else:
470
+ timesteps_outer = self.get_time_steps(skip_type, t_T, t_0, steps, device)[torch.cumsum(torch.tensor([0,] + orders), 0).to(device)]
471
+ return timesteps_outer, orders
472
+
473
+ def denoise_to_zero_fn(self, x, s):
474
+ """
475
+ Denoise at the final step, which is equivalent to solve the ODE from lambda_s to infty by first-order discretization.
476
+ """
477
+ return self.data_prediction_fn(x, s)
478
+
479
+ def multistep_uni_pc_update(self, x, model_prev_list, t_prev_list, t, order, **kwargs):
480
+ if len(t.shape) == 0:
481
+ t = t.view(-1)
482
+ if 'bh' in self.variant:
483
+ return self.multistep_uni_pc_bh_update(x, model_prev_list, t_prev_list, t, order, **kwargs)
484
+ else:
485
+ assert self.variant == 'vary_coeff'
486
+ return self.multistep_uni_pc_vary_update(x, model_prev_list, t_prev_list, t, order, **kwargs)
487
+
488
+ def multistep_uni_pc_vary_update(self, x, model_prev_list, t_prev_list, t, order, use_corrector=True):
489
+ print(f'using unified predictor-corrector with order {order} (solver type: vary coeff)')
490
+ ns = self.noise_schedule
491
+ assert order <= len(model_prev_list)
492
+
493
+ # first compute rks
494
+ t_prev_0 = t_prev_list[-1]
495
+ lambda_prev_0 = ns.marginal_lambda(t_prev_0)
496
+ lambda_t = ns.marginal_lambda(t)
497
+ model_prev_0 = model_prev_list[-1]
498
+ sigma_prev_0, sigma_t = ns.marginal_std(t_prev_0), ns.marginal_std(t)
499
+ log_alpha_t = ns.marginal_log_mean_coeff(t)
500
+ alpha_t = torch.exp(log_alpha_t)
501
+
502
+ h = lambda_t - lambda_prev_0
503
+
504
+ rks = []
505
+ D1s = []
506
+ for i in range(1, order):
507
+ t_prev_i = t_prev_list[-(i + 1)]
508
+ model_prev_i = model_prev_list[-(i + 1)]
509
+ lambda_prev_i = ns.marginal_lambda(t_prev_i)
510
+ rk = (lambda_prev_i - lambda_prev_0) / h
511
+ rks.append(rk)
512
+ D1s.append((model_prev_i - model_prev_0) / rk)
513
+
514
+ rks.append(1.)
515
+ rks = torch.tensor(rks, device=x.device)
516
+
517
+ K = len(rks)
518
+ # build C matrix
519
+ C = []
520
+
521
+ col = torch.ones_like(rks)
522
+ for k in range(1, K + 1):
523
+ C.append(col)
524
+ col = col * rks / (k + 1)
525
+ C = torch.stack(C, dim=1)
526
+
527
+ if len(D1s) > 0:
528
+ D1s = torch.stack(D1s, dim=1) # (B, K)
529
+ C_inv_p = torch.linalg.inv(C[:-1, :-1])
530
+ A_p = C_inv_p
531
+
532
+ if use_corrector:
533
+ print('using corrector')
534
+ C_inv = torch.linalg.inv(C)
535
+ A_c = C_inv
536
+
537
+ hh = -h if self.predict_x0 else h
538
+ h_phi_1 = torch.expm1(hh)
539
+ h_phi_ks = []
540
+ factorial_k = 1
541
+ h_phi_k = h_phi_1
542
+ for k in range(1, K + 2):
543
+ h_phi_ks.append(h_phi_k)
544
+ h_phi_k = h_phi_k / hh - 1 / factorial_k
545
+ factorial_k *= (k + 1)
546
+
547
+ model_t = None
548
+ if self.predict_x0:
549
+ x_t_ = (
550
+ sigma_t / sigma_prev_0 * x
551
+ - alpha_t * h_phi_1 * model_prev_0
552
+ )
553
+ # now predictor
554
+ x_t = x_t_
555
+ if len(D1s) > 0:
556
+ # compute the residuals for predictor
557
+ for k in range(K - 1):
558
+ x_t = x_t - alpha_t * h_phi_ks[k + 1] * torch.einsum('bkchw,k->bchw', D1s, A_p[k])
559
+ # now corrector
560
+ if use_corrector:
561
+ model_t = self.model_fn(x_t, t)
562
+ D1_t = (model_t - model_prev_0)
563
+ x_t = x_t_
564
+ k = 0
565
+ for k in range(K - 1):
566
+ x_t = x_t - alpha_t * h_phi_ks[k + 1] * torch.einsum('bkchw,k->bchw', D1s, A_c[k][:-1])
567
+ x_t = x_t - alpha_t * h_phi_ks[K] * (D1_t * A_c[k][-1])
568
+ else:
569
+ log_alpha_prev_0, log_alpha_t = ns.marginal_log_mean_coeff(t_prev_0), ns.marginal_log_mean_coeff(t)
570
+ x_t_ = (
571
+ (torch.exp(log_alpha_t - log_alpha_prev_0)) * x
572
+ - (sigma_t * h_phi_1) * model_prev_0
573
+ )
574
+ # now predictor
575
+ x_t = x_t_
576
+ if len(D1s) > 0:
577
+ # compute the residuals for predictor
578
+ for k in range(K - 1):
579
+ x_t = x_t - sigma_t * h_phi_ks[k + 1] * torch.einsum('bkchw,k->bchw', D1s, A_p[k])
580
+ # now corrector
581
+ if use_corrector:
582
+ model_t = self.model_fn(x_t, t)
583
+ D1_t = (model_t - model_prev_0)
584
+ x_t = x_t_
585
+ k = 0
586
+ for k in range(K - 1):
587
+ x_t = x_t - sigma_t * h_phi_ks[k + 1] * torch.einsum('bkchw,k->bchw', D1s, A_c[k][:-1])
588
+ x_t = x_t - sigma_t * h_phi_ks[K] * (D1_t * A_c[k][-1])
589
+ return x_t, model_t
590
+
591
+ def multistep_uni_pc_bh_update(self, x, model_prev_list, t_prev_list, t, order, x_t=None, use_corrector=True):
592
+ # print(f'using unified predictor-corrector with order {order} (solver type: B(h))')
593
+ ns = self.noise_schedule
594
+ assert order <= len(model_prev_list)
595
+ dims = x.dim()
596
+
597
+ # first compute rks
598
+ t_prev_0 = t_prev_list[-1]
599
+ lambda_prev_0 = ns.marginal_lambda(t_prev_0)
600
+ lambda_t = ns.marginal_lambda(t)
601
+ model_prev_0 = model_prev_list[-1]
602
+ sigma_prev_0, sigma_t = ns.marginal_std(t_prev_0), ns.marginal_std(t)
603
+ log_alpha_prev_0, log_alpha_t = ns.marginal_log_mean_coeff(t_prev_0), ns.marginal_log_mean_coeff(t)
604
+ alpha_t = torch.exp(log_alpha_t)
605
+
606
+ h = lambda_t - lambda_prev_0
607
+
608
+ rks = []
609
+ D1s = []
610
+ for i in range(1, order):
611
+ t_prev_i = t_prev_list[-(i + 1)]
612
+ model_prev_i = model_prev_list[-(i + 1)]
613
+ lambda_prev_i = ns.marginal_lambda(t_prev_i)
614
+ rk = ((lambda_prev_i - lambda_prev_0) / h)[0]
615
+ rks.append(rk)
616
+ D1s.append((model_prev_i - model_prev_0) / rk)
617
+
618
+ rks.append(1.)
619
+ rks = torch.tensor(rks, device=x.device)
620
+
621
+ R = []
622
+ b = []
623
+
624
+ hh = -h[0] if self.predict_x0 else h[0]
625
+ h_phi_1 = torch.expm1(hh) # h\phi_1(h) = e^h - 1
626
+ h_phi_k = h_phi_1 / hh - 1
627
+
628
+ factorial_i = 1
629
+
630
+ if self.variant == 'bh1':
631
+ B_h = hh
632
+ elif self.variant == 'bh2':
633
+ B_h = torch.expm1(hh)
634
+ else:
635
+ raise NotImplementedError()
636
+
637
+ for i in range(1, order + 1):
638
+ R.append(torch.pow(rks, i - 1))
639
+ b.append(h_phi_k * factorial_i / B_h)
640
+ factorial_i *= (i + 1)
641
+ h_phi_k = h_phi_k / hh - 1 / factorial_i
642
+
643
+ R = torch.stack(R)
644
+ b = torch.tensor(b, device=x.device)
645
+
646
+ # now predictor
647
+ use_predictor = len(D1s) > 0 and x_t is None
648
+ if len(D1s) > 0:
649
+ D1s = torch.stack(D1s, dim=1) # (B, K)
650
+ if x_t is None:
651
+ # for order 2, we use a simplified version
652
+ if order == 2:
653
+ rhos_p = torch.tensor([0.5], device=b.device)
654
+ else:
655
+ rhos_p = torch.linalg.solve(R[:-1, :-1], b[:-1])
656
+ else:
657
+ D1s = None
658
+
659
+ if use_corrector:
660
+ # print('using corrector')
661
+ # for order 1, we use a simplified version
662
+ if order == 1:
663
+ rhos_c = torch.tensor([0.5], device=b.device)
664
+ else:
665
+ rhos_c = torch.linalg.solve(R, b)
666
+
667
+ model_t = None
668
+ if self.predict_x0:
669
+ x_t_ = (
670
+ expand_dims(sigma_t / sigma_prev_0, dims) * x
671
+ - expand_dims(alpha_t * h_phi_1, dims)* model_prev_0
672
+ )
673
+
674
+ if x_t is None:
675
+ if use_predictor:
676
+ pred_res = torch.einsum('k,bkchw->bchw', rhos_p, D1s)
677
+ else:
678
+ pred_res = 0
679
+ x_t = x_t_ - expand_dims(alpha_t * B_h, dims) * pred_res
680
+
681
+ if use_corrector:
682
+ model_t = self.model_fn(x_t, t)
683
+ if D1s is not None:
684
+ corr_res = torch.einsum('k,bkchw->bchw', rhos_c[:-1], D1s)
685
+ else:
686
+ corr_res = 0
687
+ D1_t = (model_t - model_prev_0)
688
+ x_t = x_t_ - expand_dims(alpha_t * B_h, dims) * (corr_res + rhos_c[-1] * D1_t)
689
+ else:
690
+ x_t_ = (
691
+ expand_dims(torch.exp(log_alpha_t - log_alpha_prev_0), dims) * x
692
+ - expand_dims(sigma_t * h_phi_1, dims) * model_prev_0
693
+ )
694
+ if x_t is None:
695
+ if use_predictor:
696
+ pred_res = torch.einsum('k,bkchw->bchw', rhos_p, D1s)
697
+ else:
698
+ pred_res = 0
699
+ x_t = x_t_ - expand_dims(sigma_t * B_h, dims) * pred_res
700
+
701
+ if use_corrector:
702
+ model_t = self.model_fn(x_t, t)
703
+ if D1s is not None:
704
+ corr_res = torch.einsum('k,bkchw->bchw', rhos_c[:-1], D1s)
705
+ else:
706
+ corr_res = 0
707
+ D1_t = (model_t - model_prev_0)
708
+ x_t = x_t_ - expand_dims(sigma_t * B_h, dims) * (corr_res + rhos_c[-1] * D1_t)
709
+ return x_t, model_t
710
+
711
+
712
+ def sample(self, x, timesteps, t_start=None, t_end=None, order=3, skip_type='time_uniform',
713
+ method='singlestep', lower_order_final=True, denoise_to_zero=False, solver_type='dpm_solver',
714
+ atol=0.0078, rtol=0.05, corrector=False, callback=None, disable_pbar=False
715
+ ):
716
+ # t_0 = 1. / self.noise_schedule.total_N if t_end is None else t_end
717
+ # t_T = self.noise_schedule.T if t_start is None else t_start
718
+ device = x.device
719
+ steps = len(timesteps) - 1
720
+ if method == 'multistep':
721
+ assert steps >= order
722
+ # timesteps = self.get_time_steps(skip_type=skip_type, t_T=t_T, t_0=t_0, N=steps, device=device)
723
+ assert timesteps.shape[0] - 1 == steps
724
+ # with torch.no_grad():
725
+ for step_index in trange(steps, disable=disable_pbar):
726
+ if self.noise_mask is not None:
727
+ x = x * self.noise_mask + (1. - self.noise_mask) * (self.masked_image * self.noise_schedule.marginal_alpha(timesteps[step_index]) + self.noise * self.noise_schedule.marginal_std(timesteps[step_index]))
728
+ if step_index == 0:
729
+ vec_t = timesteps[0].expand((x.shape[0]))
730
+ model_prev_list = [self.model_fn(x, vec_t)]
731
+ t_prev_list = [vec_t]
732
+ elif step_index < order:
733
+ init_order = step_index
734
+ # Init the first `order` values by lower order multistep DPM-Solver.
735
+ # for init_order in range(1, order):
736
+ vec_t = timesteps[init_order].expand(x.shape[0])
737
+ x, model_x = self.multistep_uni_pc_update(x, model_prev_list, t_prev_list, vec_t, init_order, use_corrector=True)
738
+ if model_x is None:
739
+ model_x = self.model_fn(x, vec_t)
740
+ model_prev_list.append(model_x)
741
+ t_prev_list.append(vec_t)
742
+ else:
743
+ extra_final_step = 0
744
+ if step_index == (steps - 1):
745
+ extra_final_step = 1
746
+ for step in range(step_index, step_index + 1 + extra_final_step):
747
+ vec_t = timesteps[step].expand(x.shape[0])
748
+ if lower_order_final:
749
+ step_order = min(order, steps + 1 - step)
750
+ else:
751
+ step_order = order
752
+ # print('this step order:', step_order)
753
+ if step == steps:
754
+ # print('do not run corrector at the last step')
755
+ use_corrector = False
756
+ else:
757
+ use_corrector = True
758
+ x, model_x = self.multistep_uni_pc_update(x, model_prev_list, t_prev_list, vec_t, step_order, use_corrector=use_corrector)
759
+ for i in range(order - 1):
760
+ t_prev_list[i] = t_prev_list[i + 1]
761
+ model_prev_list[i] = model_prev_list[i + 1]
762
+ t_prev_list[-1] = vec_t
763
+ # We do not need to evaluate the final model value.
764
+ if step < steps:
765
+ if model_x is None:
766
+ model_x = self.model_fn(x, vec_t)
767
+ model_prev_list[-1] = model_x
768
+ if callback is not None:
769
+ callback(step_index, model_prev_list[-1], x, steps)
770
+ else:
771
+ raise NotImplementedError()
772
+ # if denoise_to_zero:
773
+ # x = self.denoise_to_zero_fn(x, torch.ones((x.shape[0],)).to(device) * t_0)
774
+ return x
775
+
776
+
777
+ #############################################################
778
+ # other utility functions
779
+ #############################################################
780
+
781
+ def interpolate_fn(x, xp, yp):
782
+ """
783
+ A piecewise linear function y = f(x), using xp and yp as keypoints.
784
+ We implement f(x) in a differentiable way (i.e. applicable for autograd).
785
+ 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.)
786
+
787
+ Args:
788
+ 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).
789
+ xp: PyTorch tensor with shape [C, K], where K is the number of keypoints.
790
+ yp: PyTorch tensor with shape [C, K].
791
+ Returns:
792
+ The function values f(x), with shape [N, C].
793
+ """
794
+ N, K = x.shape[0], xp.shape[1]
795
+ all_x = torch.cat([x.unsqueeze(2), xp.unsqueeze(0).repeat((N, 1, 1))], dim=2)
796
+ sorted_all_x, x_indices = torch.sort(all_x, dim=2)
797
+ x_idx = torch.argmin(x_indices, dim=2)
798
+ cand_start_idx = x_idx - 1
799
+ start_idx = torch.where(
800
+ torch.eq(x_idx, 0),
801
+ torch.tensor(1, device=x.device),
802
+ torch.where(
803
+ torch.eq(x_idx, K), torch.tensor(K - 2, device=x.device), cand_start_idx,
804
+ ),
805
+ )
806
+ end_idx = torch.where(torch.eq(start_idx, cand_start_idx), start_idx + 2, start_idx + 1)
807
+ start_x = torch.gather(sorted_all_x, dim=2, index=start_idx.unsqueeze(2)).squeeze(2)
808
+ end_x = torch.gather(sorted_all_x, dim=2, index=end_idx.unsqueeze(2)).squeeze(2)
809
+ start_idx2 = torch.where(
810
+ torch.eq(x_idx, 0),
811
+ torch.tensor(0, device=x.device),
812
+ torch.where(
813
+ torch.eq(x_idx, K), torch.tensor(K - 2, device=x.device), cand_start_idx,
814
+ ),
815
+ )
816
+ y_positions_expanded = yp.unsqueeze(0).expand(N, -1, -1)
817
+ start_y = torch.gather(y_positions_expanded, dim=2, index=start_idx2.unsqueeze(2)).squeeze(2)
818
+ end_y = torch.gather(y_positions_expanded, dim=2, index=(start_idx2 + 1).unsqueeze(2)).squeeze(2)
819
+ cand = start_y + (x - start_x) * (end_y - start_y) / (end_x - start_x)
820
+ return cand
821
+
822
+
823
+ def expand_dims(v, dims):
824
+ """
825
+ Expand the tensor `v` to the dim `dims`.
826
+
827
+ Args:
828
+ `v`: a PyTorch tensor with shape [N].
829
+ `dim`: a `int`.
830
+ Returns:
831
+ a PyTorch tensor with shape [N, 1, 1, ..., 1] and the total dimension is `dims`.
832
+ """
833
+ return v[(...,) + (None,)*(dims - 1)]
834
+
835
+
836
+ class SigmaConvert:
837
+ schedule = ""
838
+ def marginal_log_mean_coeff(self, sigma):
839
+ return 0.5 * torch.log(1 / ((sigma * sigma) + 1))
840
+
841
+ def marginal_alpha(self, t):
842
+ return torch.exp(self.marginal_log_mean_coeff(t))
843
+
844
+ def marginal_std(self, t):
845
+ return torch.sqrt(1. - torch.exp(2. * self.marginal_log_mean_coeff(t)))
846
+
847
+ def marginal_lambda(self, t):
848
+ """
849
+ Compute lambda_t = log(alpha_t) - log(sigma_t) of a given continuous-time label t in [0, T].
850
+ """
851
+ log_mean_coeff = self.marginal_log_mean_coeff(t)
852
+ log_std = 0.5 * torch.log(1. - torch.exp(2. * log_mean_coeff))
853
+ return log_mean_coeff - log_std
854
+
855
+ def predict_eps_sigma(model, input, sigma_in, **kwargs):
856
+ sigma = sigma_in.view(sigma_in.shape[:1] + (1,) * (input.ndim - 1))
857
+ input = input * ((sigma ** 2 + 1.0) ** 0.5)
858
+ return (input - model(input, sigma_in, **kwargs)) / sigma
859
+
860
+
861
+ def sample_unipc(model, noise, image, sigmas, max_denoise, extra_args=None, callback=None, disable=False, noise_mask=None, variant='bh1'):
862
+ timesteps = sigmas.clone()
863
+ if sigmas[-1] == 0:
864
+ timesteps = sigmas[:]
865
+ timesteps[-1] = 0.001
866
+ else:
867
+ timesteps = sigmas.clone()
868
+ ns = SigmaConvert()
869
+
870
+ if image is not None:
871
+ img = image * ns.marginal_alpha(timesteps[0])
872
+ if max_denoise:
873
+ noise_mult = 1.0
874
+ else:
875
+ noise_mult = ns.marginal_std(timesteps[0])
876
+ img += noise * noise_mult
877
+ else:
878
+ img = noise
879
+
880
+ model_type = "noise"
881
+
882
+ model_fn = model_wrapper(
883
+ lambda input, sigma, **kwargs: predict_eps_sigma(model, input, sigma, **kwargs),
884
+ ns,
885
+ model_type=model_type,
886
+ guidance_type="uncond",
887
+ model_kwargs=extra_args,
888
+ )
889
+
890
+ order = min(3, len(timesteps) - 2)
891
+ uni_pc = UniPC(model_fn, ns, predict_x0=True, thresholding=False, noise_mask=noise_mask, masked_image=image, noise=noise, variant=variant)
892
+ x = uni_pc.sample(img, timesteps=timesteps, skip_type="time_uniform", method="multistep", order=order, lower_order_final=True, callback=callback, disable_pbar=disable)
893
+ x /= ns.marginal_alpha(timesteps[-1])
894
+ return x
comfy/gligen.py ADDED
@@ -0,0 +1,341 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from torch import nn
3
+ from .ldm.modules.attention import CrossAttention
4
+ from inspect import isfunction
5
+
6
+
7
+ def exists(val):
8
+ return val is not None
9
+
10
+
11
+ def uniq(arr):
12
+ return{el: True for el in arr}.keys()
13
+
14
+
15
+ def default(val, d):
16
+ if exists(val):
17
+ return val
18
+ return d() if isfunction(d) else d
19
+
20
+
21
+ # feedforward
22
+ class GEGLU(nn.Module):
23
+ def __init__(self, dim_in, dim_out):
24
+ super().__init__()
25
+ self.proj = nn.Linear(dim_in, dim_out * 2)
26
+
27
+ def forward(self, x):
28
+ x, gate = self.proj(x).chunk(2, dim=-1)
29
+ return x * torch.nn.functional.gelu(gate)
30
+
31
+
32
+ class FeedForward(nn.Module):
33
+ def __init__(self, dim, dim_out=None, mult=4, glu=False, dropout=0.):
34
+ super().__init__()
35
+ inner_dim = int(dim * mult)
36
+ dim_out = default(dim_out, dim)
37
+ project_in = nn.Sequential(
38
+ nn.Linear(dim, inner_dim),
39
+ nn.GELU()
40
+ ) if not glu else GEGLU(dim, inner_dim)
41
+
42
+ self.net = nn.Sequential(
43
+ project_in,
44
+ nn.Dropout(dropout),
45
+ nn.Linear(inner_dim, dim_out)
46
+ )
47
+
48
+ def forward(self, x):
49
+ return self.net(x)
50
+
51
+
52
+ class GatedCrossAttentionDense(nn.Module):
53
+ def __init__(self, query_dim, context_dim, n_heads, d_head):
54
+ super().__init__()
55
+
56
+ self.attn = CrossAttention(
57
+ query_dim=query_dim,
58
+ context_dim=context_dim,
59
+ heads=n_heads,
60
+ dim_head=d_head)
61
+ self.ff = FeedForward(query_dim, glu=True)
62
+
63
+ self.norm1 = nn.LayerNorm(query_dim)
64
+ self.norm2 = nn.LayerNorm(query_dim)
65
+
66
+ self.register_parameter('alpha_attn', nn.Parameter(torch.tensor(0.)))
67
+ self.register_parameter('alpha_dense', nn.Parameter(torch.tensor(0.)))
68
+
69
+ # this can be useful: we can externally change magnitude of tanh(alpha)
70
+ # for example, when it is set to 0, then the entire model is same as
71
+ # original one
72
+ self.scale = 1
73
+
74
+ def forward(self, x, objs):
75
+
76
+ x = x + self.scale * \
77
+ torch.tanh(self.alpha_attn) * self.attn(self.norm1(x), objs, objs)
78
+ x = x + self.scale * \
79
+ torch.tanh(self.alpha_dense) * self.ff(self.norm2(x))
80
+
81
+ return x
82
+
83
+
84
+ class GatedSelfAttentionDense(nn.Module):
85
+ def __init__(self, query_dim, context_dim, n_heads, d_head):
86
+ super().__init__()
87
+
88
+ # we need a linear projection since we need cat visual feature and obj
89
+ # feature
90
+ self.linear = nn.Linear(context_dim, query_dim)
91
+
92
+ self.attn = CrossAttention(
93
+ query_dim=query_dim,
94
+ context_dim=query_dim,
95
+ heads=n_heads,
96
+ dim_head=d_head)
97
+ self.ff = FeedForward(query_dim, glu=True)
98
+
99
+ self.norm1 = nn.LayerNorm(query_dim)
100
+ self.norm2 = nn.LayerNorm(query_dim)
101
+
102
+ self.register_parameter('alpha_attn', nn.Parameter(torch.tensor(0.)))
103
+ self.register_parameter('alpha_dense', nn.Parameter(torch.tensor(0.)))
104
+
105
+ # this can be useful: we can externally change magnitude of tanh(alpha)
106
+ # for example, when it is set to 0, then the entire model is same as
107
+ # original one
108
+ self.scale = 1
109
+
110
+ def forward(self, x, objs):
111
+
112
+ N_visual = x.shape[1]
113
+ objs = self.linear(objs)
114
+
115
+ x = x + self.scale * torch.tanh(self.alpha_attn) * self.attn(
116
+ self.norm1(torch.cat([x, objs], dim=1)))[:, 0:N_visual, :]
117
+ x = x + self.scale * \
118
+ torch.tanh(self.alpha_dense) * self.ff(self.norm2(x))
119
+
120
+ return x
121
+
122
+
123
+ class GatedSelfAttentionDense2(nn.Module):
124
+ def __init__(self, query_dim, context_dim, n_heads, d_head):
125
+ super().__init__()
126
+
127
+ # we need a linear projection since we need cat visual feature and obj
128
+ # feature
129
+ self.linear = nn.Linear(context_dim, query_dim)
130
+
131
+ self.attn = CrossAttention(
132
+ query_dim=query_dim, context_dim=query_dim, dim_head=d_head)
133
+ self.ff = FeedForward(query_dim, glu=True)
134
+
135
+ self.norm1 = nn.LayerNorm(query_dim)
136
+ self.norm2 = nn.LayerNorm(query_dim)
137
+
138
+ self.register_parameter('alpha_attn', nn.Parameter(torch.tensor(0.)))
139
+ self.register_parameter('alpha_dense', nn.Parameter(torch.tensor(0.)))
140
+
141
+ # this can be useful: we can externally change magnitude of tanh(alpha)
142
+ # for example, when it is set to 0, then the entire model is same as
143
+ # original one
144
+ self.scale = 1
145
+
146
+ def forward(self, x, objs):
147
+
148
+ B, N_visual, _ = x.shape
149
+ B, N_ground, _ = objs.shape
150
+
151
+ objs = self.linear(objs)
152
+
153
+ # sanity check
154
+ size_v = math.sqrt(N_visual)
155
+ size_g = math.sqrt(N_ground)
156
+ assert int(size_v) == size_v, "Visual tokens must be square rootable"
157
+ assert int(size_g) == size_g, "Grounding tokens must be square rootable"
158
+ size_v = int(size_v)
159
+ size_g = int(size_g)
160
+
161
+ # select grounding token and resize it to visual token size as residual
162
+ out = self.attn(self.norm1(torch.cat([x, objs], dim=1)))[
163
+ :, N_visual:, :]
164
+ out = out.permute(0, 2, 1).reshape(B, -1, size_g, size_g)
165
+ out = torch.nn.functional.interpolate(
166
+ out, (size_v, size_v), mode='bicubic')
167
+ residual = out.reshape(B, -1, N_visual).permute(0, 2, 1)
168
+
169
+ # add residual to visual feature
170
+ x = x + self.scale * torch.tanh(self.alpha_attn) * residual
171
+ x = x + self.scale * \
172
+ torch.tanh(self.alpha_dense) * self.ff(self.norm2(x))
173
+
174
+ return x
175
+
176
+
177
+ class FourierEmbedder():
178
+ def __init__(self, num_freqs=64, temperature=100):
179
+
180
+ self.num_freqs = num_freqs
181
+ self.temperature = temperature
182
+ self.freq_bands = temperature ** (torch.arange(num_freqs) / num_freqs)
183
+
184
+ @torch.no_grad()
185
+ def __call__(self, x, cat_dim=-1):
186
+ "x: arbitrary shape of tensor. dim: cat dim"
187
+ out = []
188
+ for freq in self.freq_bands:
189
+ out.append(torch.sin(freq * x))
190
+ out.append(torch.cos(freq * x))
191
+ return torch.cat(out, cat_dim)
192
+
193
+
194
+ class PositionNet(nn.Module):
195
+ def __init__(self, in_dim, out_dim, fourier_freqs=8):
196
+ super().__init__()
197
+ self.in_dim = in_dim
198
+ self.out_dim = out_dim
199
+
200
+ self.fourier_embedder = FourierEmbedder(num_freqs=fourier_freqs)
201
+ self.position_dim = fourier_freqs * 2 * 4 # 2 is sin&cos, 4 is xyxy
202
+
203
+ self.linears = nn.Sequential(
204
+ nn.Linear(self.in_dim + self.position_dim, 512),
205
+ nn.SiLU(),
206
+ nn.Linear(512, 512),
207
+ nn.SiLU(),
208
+ nn.Linear(512, out_dim),
209
+ )
210
+
211
+ self.null_positive_feature = torch.nn.Parameter(
212
+ torch.zeros([self.in_dim]))
213
+ self.null_position_feature = torch.nn.Parameter(
214
+ torch.zeros([self.position_dim]))
215
+
216
+ def forward(self, boxes, masks, positive_embeddings):
217
+ B, N, _ = boxes.shape
218
+ dtype = self.linears[0].weight.dtype
219
+ masks = masks.unsqueeze(-1).to(dtype)
220
+ positive_embeddings = positive_embeddings.to(dtype)
221
+
222
+ # embedding position (it may includes padding as placeholder)
223
+ xyxy_embedding = self.fourier_embedder(boxes.to(dtype)) # B*N*4 --> B*N*C
224
+
225
+ # learnable null embedding
226
+ positive_null = self.null_positive_feature.view(1, 1, -1)
227
+ xyxy_null = self.null_position_feature.view(1, 1, -1)
228
+
229
+ # replace padding with learnable null embedding
230
+ positive_embeddings = positive_embeddings * \
231
+ masks + (1 - masks) * positive_null
232
+ xyxy_embedding = xyxy_embedding * masks + (1 - masks) * xyxy_null
233
+
234
+ objs = self.linears(
235
+ torch.cat([positive_embeddings, xyxy_embedding], dim=-1))
236
+ assert objs.shape == torch.Size([B, N, self.out_dim])
237
+ return objs
238
+
239
+
240
+ class Gligen(nn.Module):
241
+ def __init__(self, modules, position_net, key_dim):
242
+ super().__init__()
243
+ self.module_list = nn.ModuleList(modules)
244
+ self.position_net = position_net
245
+ self.key_dim = key_dim
246
+ self.max_objs = 30
247
+ self.current_device = torch.device("cpu")
248
+
249
+ def _set_position(self, boxes, masks, positive_embeddings):
250
+ objs = self.position_net(boxes, masks, positive_embeddings)
251
+ def func(x, extra_options):
252
+ key = extra_options["transformer_index"]
253
+ module = self.module_list[key]
254
+ return module(x, objs)
255
+ return func
256
+
257
+ def set_position(self, latent_image_shape, position_params, device):
258
+ batch, c, h, w = latent_image_shape
259
+ masks = torch.zeros([self.max_objs], device="cpu")
260
+ boxes = []
261
+ positive_embeddings = []
262
+ for p in position_params:
263
+ x1 = (p[4]) / w
264
+ y1 = (p[3]) / h
265
+ x2 = (p[4] + p[2]) / w
266
+ y2 = (p[3] + p[1]) / h
267
+ masks[len(boxes)] = 1.0
268
+ boxes += [torch.tensor((x1, y1, x2, y2)).unsqueeze(0)]
269
+ positive_embeddings += [p[0]]
270
+ append_boxes = []
271
+ append_conds = []
272
+ if len(boxes) < self.max_objs:
273
+ append_boxes = [torch.zeros(
274
+ [self.max_objs - len(boxes), 4], device="cpu")]
275
+ append_conds = [torch.zeros(
276
+ [self.max_objs - len(boxes), self.key_dim], device="cpu")]
277
+
278
+ box_out = torch.cat(
279
+ boxes + append_boxes).unsqueeze(0).repeat(batch, 1, 1)
280
+ masks = masks.unsqueeze(0).repeat(batch, 1)
281
+ conds = torch.cat(positive_embeddings +
282
+ append_conds).unsqueeze(0).repeat(batch, 1, 1)
283
+ return self._set_position(
284
+ box_out.to(device),
285
+ masks.to(device),
286
+ conds.to(device))
287
+
288
+ def set_empty(self, latent_image_shape, device):
289
+ batch, c, h, w = latent_image_shape
290
+ masks = torch.zeros([self.max_objs], device="cpu").repeat(batch, 1)
291
+ box_out = torch.zeros([self.max_objs, 4],
292
+ device="cpu").repeat(batch, 1, 1)
293
+ conds = torch.zeros([self.max_objs, self.key_dim],
294
+ device="cpu").repeat(batch, 1, 1)
295
+ return self._set_position(
296
+ box_out.to(device),
297
+ masks.to(device),
298
+ conds.to(device))
299
+
300
+
301
+ def load_gligen(sd):
302
+ sd_k = sd.keys()
303
+ output_list = []
304
+ key_dim = 768
305
+ for a in ["input_blocks", "middle_block", "output_blocks"]:
306
+ for b in range(20):
307
+ k_temp = filter(lambda k: "{}.{}.".format(a, b)
308
+ in k and ".fuser." in k, sd_k)
309
+ k_temp = map(lambda k: (k, k.split(".fuser.")[-1]), k_temp)
310
+
311
+ n_sd = {}
312
+ for k in k_temp:
313
+ n_sd[k[1]] = sd[k[0]]
314
+ if len(n_sd) > 0:
315
+ query_dim = n_sd["linear.weight"].shape[0]
316
+ key_dim = n_sd["linear.weight"].shape[1]
317
+
318
+ if key_dim == 768: # SD1.x
319
+ n_heads = 8
320
+ d_head = query_dim // n_heads
321
+ else:
322
+ d_head = 64
323
+ n_heads = query_dim // d_head
324
+
325
+ gated = GatedSelfAttentionDense(
326
+ query_dim, key_dim, n_heads, d_head)
327
+ gated.load_state_dict(n_sd, strict=False)
328
+ output_list.append(gated)
329
+
330
+ if "position_net.null_positive_feature" in sd_k:
331
+ in_dim = sd["position_net.null_positive_feature"].shape[0]
332
+ out_dim = sd["position_net.linears.4.weight"].shape[0]
333
+
334
+ class WeightsLoader(torch.nn.Module):
335
+ pass
336
+ w = WeightsLoader()
337
+ w.position_net = PositionNet(in_dim, out_dim)
338
+ w.load_state_dict(sd, strict=False)
339
+
340
+ gligen = Gligen(output_list, w.position_net, key_dim)
341
+ return gligen
comfy/k_diffusion/sampling.py ADDED
@@ -0,0 +1,810 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+
3
+ from scipy import integrate
4
+ import torch
5
+ from torch import nn
6
+ import torchsde
7
+ from tqdm.auto import trange, tqdm
8
+
9
+ from . import utils
10
+
11
+
12
+ def append_zero(x):
13
+ return torch.cat([x, x.new_zeros([1])])
14
+
15
+
16
+ def get_sigmas_karras(n, sigma_min, sigma_max, rho=7., device='cpu'):
17
+ """Constructs the noise schedule of Karras et al. (2022)."""
18
+ ramp = torch.linspace(0, 1, n, device=device)
19
+ min_inv_rho = sigma_min ** (1 / rho)
20
+ max_inv_rho = sigma_max ** (1 / rho)
21
+ sigmas = (max_inv_rho + ramp * (min_inv_rho - max_inv_rho)) ** rho
22
+ return append_zero(sigmas).to(device)
23
+
24
+
25
+ def get_sigmas_exponential(n, sigma_min, sigma_max, device='cpu'):
26
+ """Constructs an exponential noise schedule."""
27
+ sigmas = torch.linspace(math.log(sigma_max), math.log(sigma_min), n, device=device).exp()
28
+ return append_zero(sigmas)
29
+
30
+
31
+ def get_sigmas_polyexponential(n, sigma_min, sigma_max, rho=1., device='cpu'):
32
+ """Constructs an polynomial in log sigma noise schedule."""
33
+ ramp = torch.linspace(1, 0, n, device=device) ** rho
34
+ sigmas = torch.exp(ramp * (math.log(sigma_max) - math.log(sigma_min)) + math.log(sigma_min))
35
+ return append_zero(sigmas)
36
+
37
+
38
+ def get_sigmas_vp(n, beta_d=19.9, beta_min=0.1, eps_s=1e-3, device='cpu'):
39
+ """Constructs a continuous VP noise schedule."""
40
+ t = torch.linspace(1, eps_s, n, device=device)
41
+ sigmas = torch.sqrt(torch.exp(beta_d * t ** 2 / 2 + beta_min * t) - 1)
42
+ return append_zero(sigmas)
43
+
44
+
45
+ def to_d(x, sigma, denoised):
46
+ """Converts a denoiser output to a Karras ODE derivative."""
47
+ return (x - denoised) / utils.append_dims(sigma, x.ndim)
48
+
49
+
50
+ def get_ancestral_step(sigma_from, sigma_to, eta=1.):
51
+ """Calculates the noise level (sigma_down) to step down to and the amount
52
+ of noise to add (sigma_up) when doing an ancestral sampling step."""
53
+ if not eta:
54
+ return sigma_to, 0.
55
+ sigma_up = min(sigma_to, eta * (sigma_to ** 2 * (sigma_from ** 2 - sigma_to ** 2) / sigma_from ** 2) ** 0.5)
56
+ sigma_down = (sigma_to ** 2 - sigma_up ** 2) ** 0.5
57
+ return sigma_down, sigma_up
58
+
59
+
60
+ def default_noise_sampler(x):
61
+ return lambda sigma, sigma_next: torch.randn_like(x)
62
+
63
+
64
+ class BatchedBrownianTree:
65
+ """A wrapper around torchsde.BrownianTree that enables batches of entropy."""
66
+
67
+ def __init__(self, x, t0, t1, seed=None, **kwargs):
68
+ self.cpu_tree = True
69
+ if "cpu" in kwargs:
70
+ self.cpu_tree = kwargs.pop("cpu")
71
+ t0, t1, self.sign = self.sort(t0, t1)
72
+ w0 = kwargs.get('w0', torch.zeros_like(x))
73
+ if seed is None:
74
+ seed = torch.randint(0, 2 ** 63 - 1, []).item()
75
+ self.batched = True
76
+ try:
77
+ assert len(seed) == x.shape[0]
78
+ w0 = w0[0]
79
+ except TypeError:
80
+ seed = [seed]
81
+ self.batched = False
82
+ if self.cpu_tree:
83
+ self.trees = [torchsde.BrownianTree(t0.cpu(), w0.cpu(), t1.cpu(), entropy=s, **kwargs) for s in seed]
84
+ else:
85
+ self.trees = [torchsde.BrownianTree(t0, w0, t1, entropy=s, **kwargs) for s in seed]
86
+
87
+ @staticmethod
88
+ def sort(a, b):
89
+ return (a, b, 1) if a < b else (b, a, -1)
90
+
91
+ def __call__(self, t0, t1):
92
+ t0, t1, sign = self.sort(t0, t1)
93
+ if self.cpu_tree:
94
+ w = torch.stack([tree(t0.cpu().float(), t1.cpu().float()).to(t0.dtype).to(t0.device) for tree in self.trees]) * (self.sign * sign)
95
+ else:
96
+ w = torch.stack([tree(t0, t1) for tree in self.trees]) * (self.sign * sign)
97
+
98
+ return w if self.batched else w[0]
99
+
100
+
101
+ class BrownianTreeNoiseSampler:
102
+ """A noise sampler backed by a torchsde.BrownianTree.
103
+
104
+ Args:
105
+ x (Tensor): The tensor whose shape, device and dtype to use to generate
106
+ random samples.
107
+ sigma_min (float): The low end of the valid interval.
108
+ sigma_max (float): The high end of the valid interval.
109
+ seed (int or List[int]): The random seed. If a list of seeds is
110
+ supplied instead of a single integer, then the noise sampler will
111
+ use one BrownianTree per batch item, each with its own seed.
112
+ transform (callable): A function that maps sigma to the sampler's
113
+ internal timestep.
114
+ """
115
+
116
+ def __init__(self, x, sigma_min, sigma_max, seed=None, transform=lambda x: x, cpu=False):
117
+ self.transform = transform
118
+ t0, t1 = self.transform(torch.as_tensor(sigma_min)), self.transform(torch.as_tensor(sigma_max))
119
+ self.tree = BatchedBrownianTree(x, t0, t1, seed, cpu=cpu)
120
+
121
+ def __call__(self, sigma, sigma_next):
122
+ t0, t1 = self.transform(torch.as_tensor(sigma)), self.transform(torch.as_tensor(sigma_next))
123
+ return self.tree(t0, t1) / (t1 - t0).abs().sqrt()
124
+
125
+
126
+ @torch.no_grad()
127
+ def sample_euler(model, x, sigmas, extra_args=None, callback=None, disable=None, s_churn=0., s_tmin=0., s_tmax=float('inf'), s_noise=1.):
128
+ """Implements Algorithm 2 (Euler steps) from Karras et al. (2022)."""
129
+ extra_args = {} if extra_args is None else extra_args
130
+ s_in = x.new_ones([x.shape[0]])
131
+ for i in trange(len(sigmas) - 1, disable=disable):
132
+ gamma = min(s_churn / (len(sigmas) - 1), 2 ** 0.5 - 1) if s_tmin <= sigmas[i] <= s_tmax else 0.
133
+ sigma_hat = sigmas[i] * (gamma + 1)
134
+ if gamma > 0:
135
+ eps = torch.randn_like(x) * s_noise
136
+ x = x + eps * (sigma_hat ** 2 - sigmas[i] ** 2) ** 0.5
137
+ denoised = model(x, sigma_hat * s_in, **extra_args)
138
+ d = to_d(x, sigma_hat, denoised)
139
+ if callback is not None:
140
+ callback({'x': x, 'i': i, 'sigma': sigmas[i], 'sigma_hat': sigma_hat, 'denoised': denoised})
141
+ dt = sigmas[i + 1] - sigma_hat
142
+ # Euler method
143
+ x = x + d * dt
144
+ return x
145
+
146
+
147
+ @torch.no_grad()
148
+ def sample_euler_ancestral(model, x, sigmas, extra_args=None, callback=None, disable=None, eta=1., s_noise=1., noise_sampler=None):
149
+ """Ancestral sampling with Euler method steps."""
150
+ extra_args = {} if extra_args is None else extra_args
151
+ noise_sampler = default_noise_sampler(x) if noise_sampler is None else noise_sampler
152
+ s_in = x.new_ones([x.shape[0]])
153
+ for i in trange(len(sigmas) - 1, disable=disable):
154
+ denoised = model(x, sigmas[i] * s_in, **extra_args)
155
+ sigma_down, sigma_up = get_ancestral_step(sigmas[i], sigmas[i + 1], eta=eta)
156
+ if callback is not None:
157
+ callback({'x': x, 'i': i, 'sigma': sigmas[i], 'sigma_hat': sigmas[i], 'denoised': denoised})
158
+ d = to_d(x, sigmas[i], denoised)
159
+ # Euler method
160
+ dt = sigma_down - sigmas[i]
161
+ x = x + d * dt
162
+ if sigmas[i + 1] > 0:
163
+ x = x + noise_sampler(sigmas[i], sigmas[i + 1]) * s_noise * sigma_up
164
+ return x
165
+
166
+
167
+ @torch.no_grad()
168
+ def sample_heun(model, x, sigmas, extra_args=None, callback=None, disable=None, s_churn=0., s_tmin=0., s_tmax=float('inf'), s_noise=1.):
169
+ """Implements Algorithm 2 (Heun steps) from Karras et al. (2022)."""
170
+ extra_args = {} if extra_args is None else extra_args
171
+ s_in = x.new_ones([x.shape[0]])
172
+ for i in trange(len(sigmas) - 1, disable=disable):
173
+ gamma = min(s_churn / (len(sigmas) - 1), 2 ** 0.5 - 1) if s_tmin <= sigmas[i] <= s_tmax else 0.
174
+ sigma_hat = sigmas[i] * (gamma + 1)
175
+ if gamma > 0:
176
+ eps = torch.randn_like(x) * s_noise
177
+ x = x + eps * (sigma_hat ** 2 - sigmas[i] ** 2) ** 0.5
178
+ denoised = model(x, sigma_hat * s_in, **extra_args)
179
+ d = to_d(x, sigma_hat, denoised)
180
+ if callback is not None:
181
+ callback({'x': x, 'i': i, 'sigma': sigmas[i], 'sigma_hat': sigma_hat, 'denoised': denoised})
182
+ dt = sigmas[i + 1] - sigma_hat
183
+ if sigmas[i + 1] == 0:
184
+ # Euler method
185
+ x = x + d * dt
186
+ else:
187
+ # Heun's method
188
+ x_2 = x + d * dt
189
+ denoised_2 = model(x_2, sigmas[i + 1] * s_in, **extra_args)
190
+ d_2 = to_d(x_2, sigmas[i + 1], denoised_2)
191
+ d_prime = (d + d_2) / 2
192
+ x = x + d_prime * dt
193
+ return x
194
+
195
+
196
+ @torch.no_grad()
197
+ def sample_dpm_2(model, x, sigmas, extra_args=None, callback=None, disable=None, s_churn=0., s_tmin=0., s_tmax=float('inf'), s_noise=1.):
198
+ """A sampler inspired by DPM-Solver-2 and Algorithm 2 from Karras et al. (2022)."""
199
+ extra_args = {} if extra_args is None else extra_args
200
+ s_in = x.new_ones([x.shape[0]])
201
+ for i in trange(len(sigmas) - 1, disable=disable):
202
+ gamma = min(s_churn / (len(sigmas) - 1), 2 ** 0.5 - 1) if s_tmin <= sigmas[i] <= s_tmax else 0.
203
+ sigma_hat = sigmas[i] * (gamma + 1)
204
+ if gamma > 0:
205
+ eps = torch.randn_like(x) * s_noise
206
+ x = x + eps * (sigma_hat ** 2 - sigmas[i] ** 2) ** 0.5
207
+ denoised = model(x, sigma_hat * s_in, **extra_args)
208
+ d = to_d(x, sigma_hat, denoised)
209
+ if callback is not None:
210
+ callback({'x': x, 'i': i, 'sigma': sigmas[i], 'sigma_hat': sigma_hat, 'denoised': denoised})
211
+ if sigmas[i + 1] == 0:
212
+ # Euler method
213
+ dt = sigmas[i + 1] - sigma_hat
214
+ x = x + d * dt
215
+ else:
216
+ # DPM-Solver-2
217
+ sigma_mid = sigma_hat.log().lerp(sigmas[i + 1].log(), 0.5).exp()
218
+ dt_1 = sigma_mid - sigma_hat
219
+ dt_2 = sigmas[i + 1] - sigma_hat
220
+ x_2 = x + d * dt_1
221
+ denoised_2 = model(x_2, sigma_mid * s_in, **extra_args)
222
+ d_2 = to_d(x_2, sigma_mid, denoised_2)
223
+ x = x + d_2 * dt_2
224
+ return x
225
+
226
+
227
+ @torch.no_grad()
228
+ def sample_dpm_2_ancestral(model, x, sigmas, extra_args=None, callback=None, disable=None, eta=1., s_noise=1., noise_sampler=None):
229
+ """Ancestral sampling with DPM-Solver second-order steps."""
230
+ extra_args = {} if extra_args is None else extra_args
231
+ noise_sampler = default_noise_sampler(x) if noise_sampler is None else noise_sampler
232
+ s_in = x.new_ones([x.shape[0]])
233
+ for i in trange(len(sigmas) - 1, disable=disable):
234
+ denoised = model(x, sigmas[i] * s_in, **extra_args)
235
+ sigma_down, sigma_up = get_ancestral_step(sigmas[i], sigmas[i + 1], eta=eta)
236
+ if callback is not None:
237
+ callback({'x': x, 'i': i, 'sigma': sigmas[i], 'sigma_hat': sigmas[i], 'denoised': denoised})
238
+ d = to_d(x, sigmas[i], denoised)
239
+ if sigma_down == 0:
240
+ # Euler method
241
+ dt = sigma_down - sigmas[i]
242
+ x = x + d * dt
243
+ else:
244
+ # DPM-Solver-2
245
+ sigma_mid = sigmas[i].log().lerp(sigma_down.log(), 0.5).exp()
246
+ dt_1 = sigma_mid - sigmas[i]
247
+ dt_2 = sigma_down - sigmas[i]
248
+ x_2 = x + d * dt_1
249
+ denoised_2 = model(x_2, sigma_mid * s_in, **extra_args)
250
+ d_2 = to_d(x_2, sigma_mid, denoised_2)
251
+ x = x + d_2 * dt_2
252
+ x = x + noise_sampler(sigmas[i], sigmas[i + 1]) * s_noise * sigma_up
253
+ return x
254
+
255
+
256
+ def linear_multistep_coeff(order, t, i, j):
257
+ if order - 1 > i:
258
+ raise ValueError(f'Order {order} too high for step {i}')
259
+ def fn(tau):
260
+ prod = 1.
261
+ for k in range(order):
262
+ if j == k:
263
+ continue
264
+ prod *= (tau - t[i - k]) / (t[i - j] - t[i - k])
265
+ return prod
266
+ return integrate.quad(fn, t[i], t[i + 1], epsrel=1e-4)[0]
267
+
268
+
269
+ @torch.no_grad()
270
+ def sample_lms(model, x, sigmas, extra_args=None, callback=None, disable=None, order=4):
271
+ extra_args = {} if extra_args is None else extra_args
272
+ s_in = x.new_ones([x.shape[0]])
273
+ sigmas_cpu = sigmas.detach().cpu().numpy()
274
+ ds = []
275
+ for i in trange(len(sigmas) - 1, disable=disable):
276
+ denoised = model(x, sigmas[i] * s_in, **extra_args)
277
+ d = to_d(x, sigmas[i], denoised)
278
+ ds.append(d)
279
+ if len(ds) > order:
280
+ ds.pop(0)
281
+ if callback is not None:
282
+ callback({'x': x, 'i': i, 'sigma': sigmas[i], 'sigma_hat': sigmas[i], 'denoised': denoised})
283
+ cur_order = min(i + 1, order)
284
+ coeffs = [linear_multistep_coeff(cur_order, sigmas_cpu, i, j) for j in range(cur_order)]
285
+ x = x + sum(coeff * d for coeff, d in zip(coeffs, reversed(ds)))
286
+ return x
287
+
288
+
289
+ class PIDStepSizeController:
290
+ """A PID controller for ODE adaptive step size control."""
291
+ def __init__(self, h, pcoeff, icoeff, dcoeff, order=1, accept_safety=0.81, eps=1e-8):
292
+ self.h = h
293
+ self.b1 = (pcoeff + icoeff + dcoeff) / order
294
+ self.b2 = -(pcoeff + 2 * dcoeff) / order
295
+ self.b3 = dcoeff / order
296
+ self.accept_safety = accept_safety
297
+ self.eps = eps
298
+ self.errs = []
299
+
300
+ def limiter(self, x):
301
+ return 1 + math.atan(x - 1)
302
+
303
+ def propose_step(self, error):
304
+ inv_error = 1 / (float(error) + self.eps)
305
+ if not self.errs:
306
+ self.errs = [inv_error, inv_error, inv_error]
307
+ self.errs[0] = inv_error
308
+ factor = self.errs[0] ** self.b1 * self.errs[1] ** self.b2 * self.errs[2] ** self.b3
309
+ factor = self.limiter(factor)
310
+ accept = factor >= self.accept_safety
311
+ if accept:
312
+ self.errs[2] = self.errs[1]
313
+ self.errs[1] = self.errs[0]
314
+ self.h *= factor
315
+ return accept
316
+
317
+
318
+ class DPMSolver(nn.Module):
319
+ """DPM-Solver. See https://arxiv.org/abs/2206.00927."""
320
+
321
+ def __init__(self, model, extra_args=None, eps_callback=None, info_callback=None):
322
+ super().__init__()
323
+ self.model = model
324
+ self.extra_args = {} if extra_args is None else extra_args
325
+ self.eps_callback = eps_callback
326
+ self.info_callback = info_callback
327
+
328
+ def t(self, sigma):
329
+ return -sigma.log()
330
+
331
+ def sigma(self, t):
332
+ return t.neg().exp()
333
+
334
+ def eps(self, eps_cache, key, x, t, *args, **kwargs):
335
+ if key in eps_cache:
336
+ return eps_cache[key], eps_cache
337
+ sigma = self.sigma(t) * x.new_ones([x.shape[0]])
338
+ eps = (x - self.model(x, sigma, *args, **self.extra_args, **kwargs)) / self.sigma(t)
339
+ if self.eps_callback is not None:
340
+ self.eps_callback()
341
+ return eps, {key: eps, **eps_cache}
342
+
343
+ def dpm_solver_1_step(self, x, t, t_next, eps_cache=None):
344
+ eps_cache = {} if eps_cache is None else eps_cache
345
+ h = t_next - t
346
+ eps, eps_cache = self.eps(eps_cache, 'eps', x, t)
347
+ x_1 = x - self.sigma(t_next) * h.expm1() * eps
348
+ return x_1, eps_cache
349
+
350
+ def dpm_solver_2_step(self, x, t, t_next, r1=1 / 2, eps_cache=None):
351
+ eps_cache = {} if eps_cache is None else eps_cache
352
+ h = t_next - t
353
+ eps, eps_cache = self.eps(eps_cache, 'eps', x, t)
354
+ s1 = t + r1 * h
355
+ u1 = x - self.sigma(s1) * (r1 * h).expm1() * eps
356
+ eps_r1, eps_cache = self.eps(eps_cache, 'eps_r1', u1, s1)
357
+ x_2 = x - self.sigma(t_next) * h.expm1() * eps - self.sigma(t_next) / (2 * r1) * h.expm1() * (eps_r1 - eps)
358
+ return x_2, eps_cache
359
+
360
+ def dpm_solver_3_step(self, x, t, t_next, r1=1 / 3, r2=2 / 3, eps_cache=None):
361
+ eps_cache = {} if eps_cache is None else eps_cache
362
+ h = t_next - t
363
+ eps, eps_cache = self.eps(eps_cache, 'eps', x, t)
364
+ s1 = t + r1 * h
365
+ s2 = t + r2 * h
366
+ u1 = x - self.sigma(s1) * (r1 * h).expm1() * eps
367
+ eps_r1, eps_cache = self.eps(eps_cache, 'eps_r1', u1, s1)
368
+ u2 = x - self.sigma(s2) * (r2 * h).expm1() * eps - self.sigma(s2) * (r2 / r1) * ((r2 * h).expm1() / (r2 * h) - 1) * (eps_r1 - eps)
369
+ eps_r2, eps_cache = self.eps(eps_cache, 'eps_r2', u2, s2)
370
+ x_3 = x - self.sigma(t_next) * h.expm1() * eps - self.sigma(t_next) / r2 * (h.expm1() / h - 1) * (eps_r2 - eps)
371
+ return x_3, eps_cache
372
+
373
+ def dpm_solver_fast(self, x, t_start, t_end, nfe, eta=0., s_noise=1., noise_sampler=None):
374
+ noise_sampler = default_noise_sampler(x) if noise_sampler is None else noise_sampler
375
+ if not t_end > t_start and eta:
376
+ raise ValueError('eta must be 0 for reverse sampling')
377
+
378
+ m = math.floor(nfe / 3) + 1
379
+ ts = torch.linspace(t_start, t_end, m + 1, device=x.device)
380
+
381
+ if nfe % 3 == 0:
382
+ orders = [3] * (m - 2) + [2, 1]
383
+ else:
384
+ orders = [3] * (m - 1) + [nfe % 3]
385
+
386
+ for i in range(len(orders)):
387
+ eps_cache = {}
388
+ t, t_next = ts[i], ts[i + 1]
389
+ if eta:
390
+ sd, su = get_ancestral_step(self.sigma(t), self.sigma(t_next), eta)
391
+ t_next_ = torch.minimum(t_end, self.t(sd))
392
+ su = (self.sigma(t_next) ** 2 - self.sigma(t_next_) ** 2) ** 0.5
393
+ else:
394
+ t_next_, su = t_next, 0.
395
+
396
+ eps, eps_cache = self.eps(eps_cache, 'eps', x, t)
397
+ denoised = x - self.sigma(t) * eps
398
+ if self.info_callback is not None:
399
+ self.info_callback({'x': x, 'i': i, 't': ts[i], 't_up': t, 'denoised': denoised})
400
+
401
+ if orders[i] == 1:
402
+ x, eps_cache = self.dpm_solver_1_step(x, t, t_next_, eps_cache=eps_cache)
403
+ elif orders[i] == 2:
404
+ x, eps_cache = self.dpm_solver_2_step(x, t, t_next_, eps_cache=eps_cache)
405
+ else:
406
+ x, eps_cache = self.dpm_solver_3_step(x, t, t_next_, eps_cache=eps_cache)
407
+
408
+ x = x + su * s_noise * noise_sampler(self.sigma(t), self.sigma(t_next))
409
+
410
+ return x
411
+
412
+ def dpm_solver_adaptive(self, x, t_start, t_end, order=3, rtol=0.05, atol=0.0078, h_init=0.05, pcoeff=0., icoeff=1., dcoeff=0., accept_safety=0.81, eta=0., s_noise=1., noise_sampler=None):
413
+ noise_sampler = default_noise_sampler(x) if noise_sampler is None else noise_sampler
414
+ if order not in {2, 3}:
415
+ raise ValueError('order should be 2 or 3')
416
+ forward = t_end > t_start
417
+ if not forward and eta:
418
+ raise ValueError('eta must be 0 for reverse sampling')
419
+ h_init = abs(h_init) * (1 if forward else -1)
420
+ atol = torch.tensor(atol)
421
+ rtol = torch.tensor(rtol)
422
+ s = t_start
423
+ x_prev = x
424
+ accept = True
425
+ pid = PIDStepSizeController(h_init, pcoeff, icoeff, dcoeff, 1.5 if eta else order, accept_safety)
426
+ info = {'steps': 0, 'nfe': 0, 'n_accept': 0, 'n_reject': 0}
427
+
428
+ while s < t_end - 1e-5 if forward else s > t_end + 1e-5:
429
+ eps_cache = {}
430
+ t = torch.minimum(t_end, s + pid.h) if forward else torch.maximum(t_end, s + pid.h)
431
+ if eta:
432
+ sd, su = get_ancestral_step(self.sigma(s), self.sigma(t), eta)
433
+ t_ = torch.minimum(t_end, self.t(sd))
434
+ su = (self.sigma(t) ** 2 - self.sigma(t_) ** 2) ** 0.5
435
+ else:
436
+ t_, su = t, 0.
437
+
438
+ eps, eps_cache = self.eps(eps_cache, 'eps', x, s)
439
+ denoised = x - self.sigma(s) * eps
440
+
441
+ if order == 2:
442
+ x_low, eps_cache = self.dpm_solver_1_step(x, s, t_, eps_cache=eps_cache)
443
+ x_high, eps_cache = self.dpm_solver_2_step(x, s, t_, eps_cache=eps_cache)
444
+ else:
445
+ x_low, eps_cache = self.dpm_solver_2_step(x, s, t_, r1=1 / 3, eps_cache=eps_cache)
446
+ x_high, eps_cache = self.dpm_solver_3_step(x, s, t_, eps_cache=eps_cache)
447
+ delta = torch.maximum(atol, rtol * torch.maximum(x_low.abs(), x_prev.abs()))
448
+ error = torch.linalg.norm((x_low - x_high) / delta) / x.numel() ** 0.5
449
+ accept = pid.propose_step(error)
450
+ if accept:
451
+ x_prev = x_low
452
+ x = x_high + su * s_noise * noise_sampler(self.sigma(s), self.sigma(t))
453
+ s = t
454
+ info['n_accept'] += 1
455
+ else:
456
+ info['n_reject'] += 1
457
+ info['nfe'] += order
458
+ info['steps'] += 1
459
+
460
+ if self.info_callback is not None:
461
+ self.info_callback({'x': x, 'i': info['steps'] - 1, 't': s, 't_up': s, 'denoised': denoised, 'error': error, 'h': pid.h, **info})
462
+
463
+ return x, info
464
+
465
+
466
+ @torch.no_grad()
467
+ def sample_dpm_fast(model, x, sigma_min, sigma_max, n, extra_args=None, callback=None, disable=None, eta=0., s_noise=1., noise_sampler=None):
468
+ """DPM-Solver-Fast (fixed step size). See https://arxiv.org/abs/2206.00927."""
469
+ if sigma_min <= 0 or sigma_max <= 0:
470
+ raise ValueError('sigma_min and sigma_max must not be 0')
471
+ with tqdm(total=n, disable=disable) as pbar:
472
+ dpm_solver = DPMSolver(model, extra_args, eps_callback=pbar.update)
473
+ if callback is not None:
474
+ dpm_solver.info_callback = lambda info: callback({'sigma': dpm_solver.sigma(info['t']), 'sigma_hat': dpm_solver.sigma(info['t_up']), **info})
475
+ return dpm_solver.dpm_solver_fast(x, dpm_solver.t(torch.tensor(sigma_max)), dpm_solver.t(torch.tensor(sigma_min)), n, eta, s_noise, noise_sampler)
476
+
477
+
478
+ @torch.no_grad()
479
+ def sample_dpm_adaptive(model, x, sigma_min, sigma_max, extra_args=None, callback=None, disable=None, order=3, rtol=0.05, atol=0.0078, h_init=0.05, pcoeff=0., icoeff=1., dcoeff=0., accept_safety=0.81, eta=0., s_noise=1., noise_sampler=None, return_info=False):
480
+ """DPM-Solver-12 and 23 (adaptive step size). See https://arxiv.org/abs/2206.00927."""
481
+ if sigma_min <= 0 or sigma_max <= 0:
482
+ raise ValueError('sigma_min and sigma_max must not be 0')
483
+ with tqdm(disable=disable) as pbar:
484
+ dpm_solver = DPMSolver(model, extra_args, eps_callback=pbar.update)
485
+ if callback is not None:
486
+ dpm_solver.info_callback = lambda info: callback({'sigma': dpm_solver.sigma(info['t']), 'sigma_hat': dpm_solver.sigma(info['t_up']), **info})
487
+ x, info = dpm_solver.dpm_solver_adaptive(x, dpm_solver.t(torch.tensor(sigma_max)), dpm_solver.t(torch.tensor(sigma_min)), order, rtol, atol, h_init, pcoeff, icoeff, dcoeff, accept_safety, eta, s_noise, noise_sampler)
488
+ if return_info:
489
+ return x, info
490
+ return x
491
+
492
+
493
+ @torch.no_grad()
494
+ def sample_dpmpp_2s_ancestral(model, x, sigmas, extra_args=None, callback=None, disable=None, eta=1., s_noise=1., noise_sampler=None):
495
+ """Ancestral sampling with DPM-Solver++(2S) second-order steps."""
496
+ extra_args = {} if extra_args is None else extra_args
497
+ noise_sampler = default_noise_sampler(x) if noise_sampler is None else noise_sampler
498
+ s_in = x.new_ones([x.shape[0]])
499
+ sigma_fn = lambda t: t.neg().exp()
500
+ t_fn = lambda sigma: sigma.log().neg()
501
+
502
+ for i in trange(len(sigmas) - 1, disable=disable):
503
+ denoised = model(x, sigmas[i] * s_in, **extra_args)
504
+ sigma_down, sigma_up = get_ancestral_step(sigmas[i], sigmas[i + 1], eta=eta)
505
+ if callback is not None:
506
+ callback({'x': x, 'i': i, 'sigma': sigmas[i], 'sigma_hat': sigmas[i], 'denoised': denoised})
507
+ if sigma_down == 0:
508
+ # Euler method
509
+ d = to_d(x, sigmas[i], denoised)
510
+ dt = sigma_down - sigmas[i]
511
+ x = x + d * dt
512
+ else:
513
+ # DPM-Solver++(2S)
514
+ t, t_next = t_fn(sigmas[i]), t_fn(sigma_down)
515
+ r = 1 / 2
516
+ h = t_next - t
517
+ s = t + r * h
518
+ x_2 = (sigma_fn(s) / sigma_fn(t)) * x - (-h * r).expm1() * denoised
519
+ denoised_2 = model(x_2, sigma_fn(s) * s_in, **extra_args)
520
+ x = (sigma_fn(t_next) / sigma_fn(t)) * x - (-h).expm1() * denoised_2
521
+ # Noise addition
522
+ if sigmas[i + 1] > 0:
523
+ x = x + noise_sampler(sigmas[i], sigmas[i + 1]) * s_noise * sigma_up
524
+ return x
525
+
526
+
527
+ @torch.no_grad()
528
+ def sample_dpmpp_sde(model, x, sigmas, extra_args=None, callback=None, disable=None, eta=1., s_noise=1., noise_sampler=None, r=1 / 2):
529
+ """DPM-Solver++ (stochastic)."""
530
+ sigma_min, sigma_max = sigmas[sigmas > 0].min(), sigmas.max()
531
+ seed = extra_args.get("seed", None)
532
+ noise_sampler = BrownianTreeNoiseSampler(x, sigma_min, sigma_max, seed=seed, cpu=True) if noise_sampler is None else noise_sampler
533
+ extra_args = {} if extra_args is None else extra_args
534
+ s_in = x.new_ones([x.shape[0]])
535
+ sigma_fn = lambda t: t.neg().exp()
536
+ t_fn = lambda sigma: sigma.log().neg()
537
+
538
+ for i in trange(len(sigmas) - 1, disable=disable):
539
+ denoised = model(x, sigmas[i] * s_in, **extra_args)
540
+ if callback is not None:
541
+ callback({'x': x, 'i': i, 'sigma': sigmas[i], 'sigma_hat': sigmas[i], 'denoised': denoised})
542
+ if sigmas[i + 1] == 0:
543
+ # Euler method
544
+ d = to_d(x, sigmas[i], denoised)
545
+ dt = sigmas[i + 1] - sigmas[i]
546
+ x = x + d * dt
547
+ else:
548
+ # DPM-Solver++
549
+ t, t_next = t_fn(sigmas[i]), t_fn(sigmas[i + 1])
550
+ h = t_next - t
551
+ s = t + h * r
552
+ fac = 1 / (2 * r)
553
+
554
+ # Step 1
555
+ sd, su = get_ancestral_step(sigma_fn(t), sigma_fn(s), eta)
556
+ s_ = t_fn(sd)
557
+ x_2 = (sigma_fn(s_) / sigma_fn(t)) * x - (t - s_).expm1() * denoised
558
+ x_2 = x_2 + noise_sampler(sigma_fn(t), sigma_fn(s)) * s_noise * su
559
+ denoised_2 = model(x_2, sigma_fn(s) * s_in, **extra_args)
560
+
561
+ # Step 2
562
+ sd, su = get_ancestral_step(sigma_fn(t), sigma_fn(t_next), eta)
563
+ t_next_ = t_fn(sd)
564
+ denoised_d = (1 - fac) * denoised + fac * denoised_2
565
+ x = (sigma_fn(t_next_) / sigma_fn(t)) * x - (t - t_next_).expm1() * denoised_d
566
+ x = x + noise_sampler(sigma_fn(t), sigma_fn(t_next)) * s_noise * su
567
+ return x
568
+
569
+
570
+ @torch.no_grad()
571
+ def sample_dpmpp_2m(model, x, sigmas, extra_args=None, callback=None, disable=None):
572
+ """DPM-Solver++(2M)."""
573
+ extra_args = {} if extra_args is None else extra_args
574
+ s_in = x.new_ones([x.shape[0]])
575
+ sigma_fn = lambda t: t.neg().exp()
576
+ t_fn = lambda sigma: sigma.log().neg()
577
+ old_denoised = None
578
+
579
+ for i in trange(len(sigmas) - 1, disable=disable):
580
+ denoised = model(x, sigmas[i] * s_in, **extra_args)
581
+ if callback is not None:
582
+ callback({'x': x, 'i': i, 'sigma': sigmas[i], 'sigma_hat': sigmas[i], 'denoised': denoised})
583
+ t, t_next = t_fn(sigmas[i]), t_fn(sigmas[i + 1])
584
+ h = t_next - t
585
+ if old_denoised is None or sigmas[i + 1] == 0:
586
+ x = (sigma_fn(t_next) / sigma_fn(t)) * x - (-h).expm1() * denoised
587
+ else:
588
+ h_last = t - t_fn(sigmas[i - 1])
589
+ r = h_last / h
590
+ denoised_d = (1 + 1 / (2 * r)) * denoised - (1 / (2 * r)) * old_denoised
591
+ x = (sigma_fn(t_next) / sigma_fn(t)) * x - (-h).expm1() * denoised_d
592
+ old_denoised = denoised
593
+ return x
594
+
595
+ @torch.no_grad()
596
+ def sample_dpmpp_2m_sde(model, x, sigmas, extra_args=None, callback=None, disable=None, eta=1., s_noise=1., noise_sampler=None, solver_type='midpoint'):
597
+ """DPM-Solver++(2M) SDE."""
598
+
599
+ if solver_type not in {'heun', 'midpoint'}:
600
+ raise ValueError('solver_type must be \'heun\' or \'midpoint\'')
601
+
602
+ seed = extra_args.get("seed", None)
603
+ sigma_min, sigma_max = sigmas[sigmas > 0].min(), sigmas.max()
604
+ noise_sampler = BrownianTreeNoiseSampler(x, sigma_min, sigma_max, seed=seed, cpu=True) if noise_sampler is None else noise_sampler
605
+ extra_args = {} if extra_args is None else extra_args
606
+ s_in = x.new_ones([x.shape[0]])
607
+
608
+ old_denoised = None
609
+ h_last = None
610
+ h = None
611
+
612
+ for i in trange(len(sigmas) - 1, disable=disable):
613
+ denoised = model(x, sigmas[i] * s_in, **extra_args)
614
+ if callback is not None:
615
+ callback({'x': x, 'i': i, 'sigma': sigmas[i], 'sigma_hat': sigmas[i], 'denoised': denoised})
616
+ if sigmas[i + 1] == 0:
617
+ # Denoising step
618
+ x = denoised
619
+ else:
620
+ # DPM-Solver++(2M) SDE
621
+ t, s = -sigmas[i].log(), -sigmas[i + 1].log()
622
+ h = s - t
623
+ eta_h = eta * h
624
+
625
+ x = sigmas[i + 1] / sigmas[i] * (-eta_h).exp() * x + (-h - eta_h).expm1().neg() * denoised
626
+
627
+ if old_denoised is not None:
628
+ r = h_last / h
629
+ if solver_type == 'heun':
630
+ x = x + ((-h - eta_h).expm1().neg() / (-h - eta_h) + 1) * (1 / r) * (denoised - old_denoised)
631
+ elif solver_type == 'midpoint':
632
+ x = x + 0.5 * (-h - eta_h).expm1().neg() * (1 / r) * (denoised - old_denoised)
633
+
634
+ if eta:
635
+ x = x + noise_sampler(sigmas[i], sigmas[i + 1]) * sigmas[i + 1] * (-2 * eta_h).expm1().neg().sqrt() * s_noise
636
+
637
+ old_denoised = denoised
638
+ h_last = h
639
+ return x
640
+
641
+ @torch.no_grad()
642
+ def sample_dpmpp_3m_sde(model, x, sigmas, extra_args=None, callback=None, disable=None, eta=1., s_noise=1., noise_sampler=None):
643
+ """DPM-Solver++(3M) SDE."""
644
+
645
+ seed = extra_args.get("seed", None)
646
+ sigma_min, sigma_max = sigmas[sigmas > 0].min(), sigmas.max()
647
+ noise_sampler = BrownianTreeNoiseSampler(x, sigma_min, sigma_max, seed=seed, cpu=True) if noise_sampler is None else noise_sampler
648
+ extra_args = {} if extra_args is None else extra_args
649
+ s_in = x.new_ones([x.shape[0]])
650
+
651
+ denoised_1, denoised_2 = None, None
652
+ h, h_1, h_2 = None, None, None
653
+
654
+ for i in trange(len(sigmas) - 1, disable=disable):
655
+ denoised = model(x, sigmas[i] * s_in, **extra_args)
656
+ if callback is not None:
657
+ callback({'x': x, 'i': i, 'sigma': sigmas[i], 'sigma_hat': sigmas[i], 'denoised': denoised})
658
+ if sigmas[i + 1] == 0:
659
+ # Denoising step
660
+ x = denoised
661
+ else:
662
+ t, s = -sigmas[i].log(), -sigmas[i + 1].log()
663
+ h = s - t
664
+ h_eta = h * (eta + 1)
665
+
666
+ x = torch.exp(-h_eta) * x + (-h_eta).expm1().neg() * denoised
667
+
668
+ if h_2 is not None:
669
+ r0 = h_1 / h
670
+ r1 = h_2 / h
671
+ d1_0 = (denoised - denoised_1) / r0
672
+ d1_1 = (denoised_1 - denoised_2) / r1
673
+ d1 = d1_0 + (d1_0 - d1_1) * r0 / (r0 + r1)
674
+ d2 = (d1_0 - d1_1) / (r0 + r1)
675
+ phi_2 = h_eta.neg().expm1() / h_eta + 1
676
+ phi_3 = phi_2 / h_eta - 0.5
677
+ x = x + phi_2 * d1 - phi_3 * d2
678
+ elif h_1 is not None:
679
+ r = h_1 / h
680
+ d = (denoised - denoised_1) / r
681
+ phi_2 = h_eta.neg().expm1() / h_eta + 1
682
+ x = x + phi_2 * d
683
+
684
+ if eta:
685
+ x = x + noise_sampler(sigmas[i], sigmas[i + 1]) * sigmas[i + 1] * (-2 * h * eta).expm1().neg().sqrt() * s_noise
686
+
687
+ denoised_1, denoised_2 = denoised, denoised_1
688
+ h_1, h_2 = h, h_1
689
+ return x
690
+
691
+ @torch.no_grad()
692
+ def sample_dpmpp_3m_sde_gpu(model, x, sigmas, extra_args=None, callback=None, disable=None, eta=1., s_noise=1., noise_sampler=None):
693
+ sigma_min, sigma_max = sigmas[sigmas > 0].min(), sigmas.max()
694
+ noise_sampler = BrownianTreeNoiseSampler(x, sigma_min, sigma_max, seed=extra_args.get("seed", None), cpu=False) if noise_sampler is None else noise_sampler
695
+ return sample_dpmpp_3m_sde(model, x, sigmas, extra_args=extra_args, callback=callback, disable=disable, eta=eta, s_noise=s_noise, noise_sampler=noise_sampler)
696
+
697
+ @torch.no_grad()
698
+ def sample_dpmpp_2m_sde_gpu(model, x, sigmas, extra_args=None, callback=None, disable=None, eta=1., s_noise=1., noise_sampler=None, solver_type='midpoint'):
699
+ sigma_min, sigma_max = sigmas[sigmas > 0].min(), sigmas.max()
700
+ noise_sampler = BrownianTreeNoiseSampler(x, sigma_min, sigma_max, seed=extra_args.get("seed", None), cpu=False) if noise_sampler is None else noise_sampler
701
+ return sample_dpmpp_2m_sde(model, x, sigmas, extra_args=extra_args, callback=callback, disable=disable, eta=eta, s_noise=s_noise, noise_sampler=noise_sampler, solver_type=solver_type)
702
+
703
+ @torch.no_grad()
704
+ def sample_dpmpp_sde_gpu(model, x, sigmas, extra_args=None, callback=None, disable=None, eta=1., s_noise=1., noise_sampler=None, r=1 / 2):
705
+ sigma_min, sigma_max = sigmas[sigmas > 0].min(), sigmas.max()
706
+ noise_sampler = BrownianTreeNoiseSampler(x, sigma_min, sigma_max, seed=extra_args.get("seed", None), cpu=False) if noise_sampler is None else noise_sampler
707
+ return sample_dpmpp_sde(model, x, sigmas, extra_args=extra_args, callback=callback, disable=disable, eta=eta, s_noise=s_noise, noise_sampler=noise_sampler, r=r)
708
+
709
+
710
+ def DDPMSampler_step(x, sigma, sigma_prev, noise, noise_sampler):
711
+ alpha_cumprod = 1 / ((sigma * sigma) + 1)
712
+ alpha_cumprod_prev = 1 / ((sigma_prev * sigma_prev) + 1)
713
+ alpha = (alpha_cumprod / alpha_cumprod_prev)
714
+
715
+ mu = (1.0 / alpha).sqrt() * (x - (1 - alpha) * noise / (1 - alpha_cumprod).sqrt())
716
+ if sigma_prev > 0:
717
+ mu += ((1 - alpha) * (1. - alpha_cumprod_prev) / (1. - alpha_cumprod)).sqrt() * noise_sampler(sigma, sigma_prev)
718
+ return mu
719
+
720
+ def generic_step_sampler(model, x, sigmas, extra_args=None, callback=None, disable=None, noise_sampler=None, step_function=None):
721
+ extra_args = {} if extra_args is None else extra_args
722
+ noise_sampler = default_noise_sampler(x) if noise_sampler is None else noise_sampler
723
+ s_in = x.new_ones([x.shape[0]])
724
+
725
+ for i in trange(len(sigmas) - 1, disable=disable):
726
+ denoised = model(x, sigmas[i] * s_in, **extra_args)
727
+ if callback is not None:
728
+ callback({'x': x, 'i': i, 'sigma': sigmas[i], 'sigma_hat': sigmas[i], 'denoised': denoised})
729
+ x = step_function(x / torch.sqrt(1.0 + sigmas[i] ** 2.0), sigmas[i], sigmas[i + 1], (x - denoised) / sigmas[i], noise_sampler)
730
+ if sigmas[i + 1] != 0:
731
+ x *= torch.sqrt(1.0 + sigmas[i + 1] ** 2.0)
732
+ return x
733
+
734
+
735
+ @torch.no_grad()
736
+ def sample_ddpm(model, x, sigmas, extra_args=None, callback=None, disable=None, noise_sampler=None):
737
+ return generic_step_sampler(model, x, sigmas, extra_args, callback, disable, noise_sampler, DDPMSampler_step)
738
+
739
+ @torch.no_grad()
740
+ def sample_lcm(model, x, sigmas, extra_args=None, callback=None, disable=None, noise_sampler=None):
741
+ extra_args = {} if extra_args is None else extra_args
742
+ noise_sampler = default_noise_sampler(x) if noise_sampler is None else noise_sampler
743
+ s_in = x.new_ones([x.shape[0]])
744
+ for i in trange(len(sigmas) - 1, disable=disable):
745
+ denoised = model(x, sigmas[i] * s_in, **extra_args)
746
+ if callback is not None:
747
+ callback({'x': x, 'i': i, 'sigma': sigmas[i], 'sigma_hat': sigmas[i], 'denoised': denoised})
748
+
749
+ x = denoised
750
+ if sigmas[i + 1] > 0:
751
+ x += sigmas[i + 1] * noise_sampler(sigmas[i], sigmas[i + 1])
752
+ return x
753
+
754
+
755
+
756
+ @torch.no_grad()
757
+ def sample_heunpp2(model, x, sigmas, extra_args=None, callback=None, disable=None, s_churn=0., s_tmin=0., s_tmax=float('inf'), s_noise=1.):
758
+ # From MIT licensed: https://github.com/Carzit/sd-webui-samplers-scheduler/
759
+ extra_args = {} if extra_args is None else extra_args
760
+ s_in = x.new_ones([x.shape[0]])
761
+ s_end = sigmas[-1]
762
+ for i in trange(len(sigmas) - 1, disable=disable):
763
+ gamma = min(s_churn / (len(sigmas) - 1), 2 ** 0.5 - 1) if s_tmin <= sigmas[i] <= s_tmax else 0.
764
+ eps = torch.randn_like(x) * s_noise
765
+ sigma_hat = sigmas[i] * (gamma + 1)
766
+ if gamma > 0:
767
+ x = x + eps * (sigma_hat ** 2 - sigmas[i] ** 2) ** 0.5
768
+ denoised = model(x, sigma_hat * s_in, **extra_args)
769
+ d = to_d(x, sigma_hat, denoised)
770
+ if callback is not None:
771
+ callback({'x': x, 'i': i, 'sigma': sigmas[i], 'sigma_hat': sigma_hat, 'denoised': denoised})
772
+ dt = sigmas[i + 1] - sigma_hat
773
+ if sigmas[i + 1] == s_end:
774
+ # Euler method
775
+ x = x + d * dt
776
+ elif sigmas[i + 2] == s_end:
777
+
778
+ # Heun's method
779
+ x_2 = x + d * dt
780
+ denoised_2 = model(x_2, sigmas[i + 1] * s_in, **extra_args)
781
+ d_2 = to_d(x_2, sigmas[i + 1], denoised_2)
782
+
783
+ w = 2 * sigmas[0]
784
+ w2 = sigmas[i+1]/w
785
+ w1 = 1 - w2
786
+
787
+ d_prime = d * w1 + d_2 * w2
788
+
789
+
790
+ x = x + d_prime * dt
791
+
792
+ else:
793
+ # Heun++
794
+ x_2 = x + d * dt
795
+ denoised_2 = model(x_2, sigmas[i + 1] * s_in, **extra_args)
796
+ d_2 = to_d(x_2, sigmas[i + 1], denoised_2)
797
+ dt_2 = sigmas[i + 2] - sigmas[i + 1]
798
+
799
+ x_3 = x_2 + d_2 * dt_2
800
+ denoised_3 = model(x_3, sigmas[i + 2] * s_in, **extra_args)
801
+ d_3 = to_d(x_3, sigmas[i + 2], denoised_3)
802
+
803
+ w = 3 * sigmas[0]
804
+ w2 = sigmas[i + 1] / w
805
+ w3 = sigmas[i + 2] / w
806
+ w1 = 1 - w2 - w3
807
+
808
+ d_prime = w1 * d + w2 * d_2 + w3 * d_3
809
+ x = x + d_prime * dt
810
+ return x
comfy/k_diffusion/utils.py ADDED
@@ -0,0 +1,313 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from contextlib import contextmanager
2
+ import hashlib
3
+ import math
4
+ from pathlib import Path
5
+ import shutil
6
+ import urllib
7
+ import warnings
8
+
9
+ from PIL import Image
10
+ import torch
11
+ from torch import nn, optim
12
+ from torch.utils import data
13
+
14
+
15
+ def hf_datasets_augs_helper(examples, transform, image_key, mode='RGB'):
16
+ """Apply passed in transforms for HuggingFace Datasets."""
17
+ images = [transform(image.convert(mode)) for image in examples[image_key]]
18
+ return {image_key: images}
19
+
20
+
21
+ def append_dims(x, target_dims):
22
+ """Appends dimensions to the end of a tensor until it has target_dims dimensions."""
23
+ dims_to_append = target_dims - x.ndim
24
+ if dims_to_append < 0:
25
+ raise ValueError(f'input has {x.ndim} dims but target_dims is {target_dims}, which is less')
26
+ expanded = x[(...,) + (None,) * dims_to_append]
27
+ # MPS will get inf values if it tries to index into the new axes, but detaching fixes this.
28
+ # https://github.com/pytorch/pytorch/issues/84364
29
+ return expanded.detach().clone() if expanded.device.type == 'mps' else expanded
30
+
31
+
32
+ def n_params(module):
33
+ """Returns the number of trainable parameters in a module."""
34
+ return sum(p.numel() for p in module.parameters())
35
+
36
+
37
+ def download_file(path, url, digest=None):
38
+ """Downloads a file if it does not exist, optionally checking its SHA-256 hash."""
39
+ path = Path(path)
40
+ path.parent.mkdir(parents=True, exist_ok=True)
41
+ if not path.exists():
42
+ with urllib.request.urlopen(url) as response, open(path, 'wb') as f:
43
+ shutil.copyfileobj(response, f)
44
+ if digest is not None:
45
+ file_digest = hashlib.sha256(open(path, 'rb').read()).hexdigest()
46
+ if digest != file_digest:
47
+ raise OSError(f'hash of {path} (url: {url}) failed to validate')
48
+ return path
49
+
50
+
51
+ @contextmanager
52
+ def train_mode(model, mode=True):
53
+ """A context manager that places a model into training mode and restores
54
+ the previous mode on exit."""
55
+ modes = [module.training for module in model.modules()]
56
+ try:
57
+ yield model.train(mode)
58
+ finally:
59
+ for i, module in enumerate(model.modules()):
60
+ module.training = modes[i]
61
+
62
+
63
+ def eval_mode(model):
64
+ """A context manager that places a model into evaluation mode and restores
65
+ the previous mode on exit."""
66
+ return train_mode(model, False)
67
+
68
+
69
+ @torch.no_grad()
70
+ def ema_update(model, averaged_model, decay):
71
+ """Incorporates updated model parameters into an exponential moving averaged
72
+ version of a model. It should be called after each optimizer step."""
73
+ model_params = dict(model.named_parameters())
74
+ averaged_params = dict(averaged_model.named_parameters())
75
+ assert model_params.keys() == averaged_params.keys()
76
+
77
+ for name, param in model_params.items():
78
+ averaged_params[name].mul_(decay).add_(param, alpha=1 - decay)
79
+
80
+ model_buffers = dict(model.named_buffers())
81
+ averaged_buffers = dict(averaged_model.named_buffers())
82
+ assert model_buffers.keys() == averaged_buffers.keys()
83
+
84
+ for name, buf in model_buffers.items():
85
+ averaged_buffers[name].copy_(buf)
86
+
87
+
88
+ class EMAWarmup:
89
+ """Implements an EMA warmup using an inverse decay schedule.
90
+ If inv_gamma=1 and power=1, implements a simple average. inv_gamma=1, power=2/3 are
91
+ good values for models you plan to train for a million or more steps (reaches decay
92
+ factor 0.999 at 31.6K steps, 0.9999 at 1M steps), inv_gamma=1, power=3/4 for models
93
+ you plan to train for less (reaches decay factor 0.999 at 10K steps, 0.9999 at
94
+ 215.4k steps).
95
+ Args:
96
+ inv_gamma (float): Inverse multiplicative factor of EMA warmup. Default: 1.
97
+ power (float): Exponential factor of EMA warmup. Default: 1.
98
+ min_value (float): The minimum EMA decay rate. Default: 0.
99
+ max_value (float): The maximum EMA decay rate. Default: 1.
100
+ start_at (int): The epoch to start averaging at. Default: 0.
101
+ last_epoch (int): The index of last epoch. Default: 0.
102
+ """
103
+
104
+ def __init__(self, inv_gamma=1., power=1., min_value=0., max_value=1., start_at=0,
105
+ last_epoch=0):
106
+ self.inv_gamma = inv_gamma
107
+ self.power = power
108
+ self.min_value = min_value
109
+ self.max_value = max_value
110
+ self.start_at = start_at
111
+ self.last_epoch = last_epoch
112
+
113
+ def state_dict(self):
114
+ """Returns the state of the class as a :class:`dict`."""
115
+ return dict(self.__dict__.items())
116
+
117
+ def load_state_dict(self, state_dict):
118
+ """Loads the class's state.
119
+ Args:
120
+ state_dict (dict): scaler state. Should be an object returned
121
+ from a call to :meth:`state_dict`.
122
+ """
123
+ self.__dict__.update(state_dict)
124
+
125
+ def get_value(self):
126
+ """Gets the current EMA decay rate."""
127
+ epoch = max(0, self.last_epoch - self.start_at)
128
+ value = 1 - (1 + epoch / self.inv_gamma) ** -self.power
129
+ return 0. if epoch < 0 else min(self.max_value, max(self.min_value, value))
130
+
131
+ def step(self):
132
+ """Updates the step count."""
133
+ self.last_epoch += 1
134
+
135
+
136
+ class InverseLR(optim.lr_scheduler._LRScheduler):
137
+ """Implements an inverse decay learning rate schedule with an optional exponential
138
+ warmup. When last_epoch=-1, sets initial lr as lr.
139
+ inv_gamma is the number of steps/epochs required for the learning rate to decay to
140
+ (1 / 2)**power of its original value.
141
+ Args:
142
+ optimizer (Optimizer): Wrapped optimizer.
143
+ inv_gamma (float): Inverse multiplicative factor of learning rate decay. Default: 1.
144
+ power (float): Exponential factor of learning rate decay. Default: 1.
145
+ warmup (float): Exponential warmup factor (0 <= warmup < 1, 0 to disable)
146
+ Default: 0.
147
+ min_lr (float): The minimum learning rate. Default: 0.
148
+ last_epoch (int): The index of last epoch. Default: -1.
149
+ verbose (bool): If ``True``, prints a message to stdout for
150
+ each update. Default: ``False``.
151
+ """
152
+
153
+ def __init__(self, optimizer, inv_gamma=1., power=1., warmup=0., min_lr=0.,
154
+ last_epoch=-1, verbose=False):
155
+ self.inv_gamma = inv_gamma
156
+ self.power = power
157
+ if not 0. <= warmup < 1:
158
+ raise ValueError('Invalid value for warmup')
159
+ self.warmup = warmup
160
+ self.min_lr = min_lr
161
+ super().__init__(optimizer, last_epoch, verbose)
162
+
163
+ def get_lr(self):
164
+ if not self._get_lr_called_within_step:
165
+ warnings.warn("To get the last learning rate computed by the scheduler, "
166
+ "please use `get_last_lr()`.")
167
+
168
+ return self._get_closed_form_lr()
169
+
170
+ def _get_closed_form_lr(self):
171
+ warmup = 1 - self.warmup ** (self.last_epoch + 1)
172
+ lr_mult = (1 + self.last_epoch / self.inv_gamma) ** -self.power
173
+ return [warmup * max(self.min_lr, base_lr * lr_mult)
174
+ for base_lr in self.base_lrs]
175
+
176
+
177
+ class ExponentialLR(optim.lr_scheduler._LRScheduler):
178
+ """Implements an exponential learning rate schedule with an optional exponential
179
+ warmup. When last_epoch=-1, sets initial lr as lr. Decays the learning rate
180
+ continuously by decay (default 0.5) every num_steps steps.
181
+ Args:
182
+ optimizer (Optimizer): Wrapped optimizer.
183
+ num_steps (float): The number of steps to decay the learning rate by decay in.
184
+ decay (float): The factor by which to decay the learning rate every num_steps
185
+ steps. Default: 0.5.
186
+ warmup (float): Exponential warmup factor (0 <= warmup < 1, 0 to disable)
187
+ Default: 0.
188
+ min_lr (float): The minimum learning rate. Default: 0.
189
+ last_epoch (int): The index of last epoch. Default: -1.
190
+ verbose (bool): If ``True``, prints a message to stdout for
191
+ each update. Default: ``False``.
192
+ """
193
+
194
+ def __init__(self, optimizer, num_steps, decay=0.5, warmup=0., min_lr=0.,
195
+ last_epoch=-1, verbose=False):
196
+ self.num_steps = num_steps
197
+ self.decay = decay
198
+ if not 0. <= warmup < 1:
199
+ raise ValueError('Invalid value for warmup')
200
+ self.warmup = warmup
201
+ self.min_lr = min_lr
202
+ super().__init__(optimizer, last_epoch, verbose)
203
+
204
+ def get_lr(self):
205
+ if not self._get_lr_called_within_step:
206
+ warnings.warn("To get the last learning rate computed by the scheduler, "
207
+ "please use `get_last_lr()`.")
208
+
209
+ return self._get_closed_form_lr()
210
+
211
+ def _get_closed_form_lr(self):
212
+ warmup = 1 - self.warmup ** (self.last_epoch + 1)
213
+ lr_mult = (self.decay ** (1 / self.num_steps)) ** self.last_epoch
214
+ return [warmup * max(self.min_lr, base_lr * lr_mult)
215
+ for base_lr in self.base_lrs]
216
+
217
+
218
+ def rand_log_normal(shape, loc=0., scale=1., device='cpu', dtype=torch.float32):
219
+ """Draws samples from an lognormal distribution."""
220
+ return (torch.randn(shape, device=device, dtype=dtype) * scale + loc).exp()
221
+
222
+
223
+ def rand_log_logistic(shape, loc=0., scale=1., min_value=0., max_value=float('inf'), device='cpu', dtype=torch.float32):
224
+ """Draws samples from an optionally truncated log-logistic distribution."""
225
+ min_value = torch.as_tensor(min_value, device=device, dtype=torch.float64)
226
+ max_value = torch.as_tensor(max_value, device=device, dtype=torch.float64)
227
+ min_cdf = min_value.log().sub(loc).div(scale).sigmoid()
228
+ max_cdf = max_value.log().sub(loc).div(scale).sigmoid()
229
+ u = torch.rand(shape, device=device, dtype=torch.float64) * (max_cdf - min_cdf) + min_cdf
230
+ return u.logit().mul(scale).add(loc).exp().to(dtype)
231
+
232
+
233
+ def rand_log_uniform(shape, min_value, max_value, device='cpu', dtype=torch.float32):
234
+ """Draws samples from an log-uniform distribution."""
235
+ min_value = math.log(min_value)
236
+ max_value = math.log(max_value)
237
+ return (torch.rand(shape, device=device, dtype=dtype) * (max_value - min_value) + min_value).exp()
238
+
239
+
240
+ def rand_v_diffusion(shape, sigma_data=1., min_value=0., max_value=float('inf'), device='cpu', dtype=torch.float32):
241
+ """Draws samples from a truncated v-diffusion training timestep distribution."""
242
+ min_cdf = math.atan(min_value / sigma_data) * 2 / math.pi
243
+ max_cdf = math.atan(max_value / sigma_data) * 2 / math.pi
244
+ u = torch.rand(shape, device=device, dtype=dtype) * (max_cdf - min_cdf) + min_cdf
245
+ return torch.tan(u * math.pi / 2) * sigma_data
246
+
247
+
248
+ def rand_split_log_normal(shape, loc, scale_1, scale_2, device='cpu', dtype=torch.float32):
249
+ """Draws samples from a split lognormal distribution."""
250
+ n = torch.randn(shape, device=device, dtype=dtype).abs()
251
+ u = torch.rand(shape, device=device, dtype=dtype)
252
+ n_left = n * -scale_1 + loc
253
+ n_right = n * scale_2 + loc
254
+ ratio = scale_1 / (scale_1 + scale_2)
255
+ return torch.where(u < ratio, n_left, n_right).exp()
256
+
257
+
258
+ class FolderOfImages(data.Dataset):
259
+ """Recursively finds all images in a directory. It does not support
260
+ classes/targets."""
261
+
262
+ IMG_EXTENSIONS = {'.jpg', '.jpeg', '.png', '.ppm', '.bmp', '.pgm', '.tif', '.tiff', '.webp'}
263
+
264
+ def __init__(self, root, transform=None):
265
+ super().__init__()
266
+ self.root = Path(root)
267
+ self.transform = nn.Identity() if transform is None else transform
268
+ self.paths = sorted(path for path in self.root.rglob('*') if path.suffix.lower() in self.IMG_EXTENSIONS)
269
+
270
+ def __repr__(self):
271
+ return f'FolderOfImages(root="{self.root}", len: {len(self)})'
272
+
273
+ def __len__(self):
274
+ return len(self.paths)
275
+
276
+ def __getitem__(self, key):
277
+ path = self.paths[key]
278
+ with open(path, 'rb') as f:
279
+ image = Image.open(f).convert('RGB')
280
+ image = self.transform(image)
281
+ return image,
282
+
283
+
284
+ class CSVLogger:
285
+ def __init__(self, filename, columns):
286
+ self.filename = Path(filename)
287
+ self.columns = columns
288
+ if self.filename.exists():
289
+ self.file = open(self.filename, 'a')
290
+ else:
291
+ self.file = open(self.filename, 'w')
292
+ self.write(*self.columns)
293
+
294
+ def write(self, *args):
295
+ print(*args, sep=',', file=self.file, flush=True)
296
+
297
+
298
+ @contextmanager
299
+ def tf32_mode(cudnn=None, matmul=None):
300
+ """A context manager that sets whether TF32 is allowed on cuDNN or matmul."""
301
+ cudnn_old = torch.backends.cudnn.allow_tf32
302
+ matmul_old = torch.backends.cuda.matmul.allow_tf32
303
+ try:
304
+ if cudnn is not None:
305
+ torch.backends.cudnn.allow_tf32 = cudnn
306
+ if matmul is not None:
307
+ torch.backends.cuda.matmul.allow_tf32 = matmul
308
+ yield
309
+ finally:
310
+ if cudnn is not None:
311
+ torch.backends.cudnn.allow_tf32 = cudnn_old
312
+ if matmul is not None:
313
+ torch.backends.cuda.matmul.allow_tf32 = matmul_old
comfy/latent_formats.py ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ class LatentFormat:
3
+ scale_factor = 1.0
4
+ latent_rgb_factors = None
5
+ taesd_decoder_name = None
6
+
7
+ def process_in(self, latent):
8
+ return latent * self.scale_factor
9
+
10
+ def process_out(self, latent):
11
+ return latent / self.scale_factor
12
+
13
+ class SD15(LatentFormat):
14
+ def __init__(self, scale_factor=0.18215):
15
+ self.scale_factor = scale_factor
16
+ self.latent_rgb_factors = [
17
+ # R G B
18
+ [ 0.3512, 0.2297, 0.3227],
19
+ [ 0.3250, 0.4974, 0.2350],
20
+ [-0.2829, 0.1762, 0.2721],
21
+ [-0.2120, -0.2616, -0.7177]
22
+ ]
23
+ self.taesd_decoder_name = "taesd_decoder"
24
+
25
+ class SDXL(LatentFormat):
26
+ def __init__(self):
27
+ self.scale_factor = 0.13025
28
+ self.latent_rgb_factors = [
29
+ # R G B
30
+ [ 0.3920, 0.4054, 0.4549],
31
+ [-0.2634, -0.0196, 0.0653],
32
+ [ 0.0568, 0.1687, -0.0755],
33
+ [-0.3112, -0.2359, -0.2076]
34
+ ]
35
+ self.taesd_decoder_name = "taesdxl_decoder"
36
+
37
+ class SD_X4(LatentFormat):
38
+ def __init__(self):
39
+ self.scale_factor = 0.08333
comfy/ldm/.DS_Store ADDED
Binary file (6.15 kB). View file
 
comfy/ldm/models/autoencoder.py ADDED
@@ -0,0 +1,228 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ # import pytorch_lightning as pl
3
+ import torch.nn.functional as F
4
+ from contextlib import contextmanager
5
+ from typing import Any, Dict, List, Optional, Tuple, Union
6
+
7
+ from comfy.ldm.modules.distributions.distributions import DiagonalGaussianDistribution
8
+
9
+ from comfy.ldm.util import instantiate_from_config
10
+ from comfy.ldm.modules.ema import LitEma
11
+ import comfy.ops
12
+
13
+ class DiagonalGaussianRegularizer(torch.nn.Module):
14
+ def __init__(self, sample: bool = True):
15
+ super().__init__()
16
+ self.sample = sample
17
+
18
+ def get_trainable_parameters(self) -> Any:
19
+ yield from ()
20
+
21
+ def forward(self, z: torch.Tensor) -> Tuple[torch.Tensor, dict]:
22
+ log = dict()
23
+ posterior = DiagonalGaussianDistribution(z)
24
+ if self.sample:
25
+ z = posterior.sample()
26
+ else:
27
+ z = posterior.mode()
28
+ kl_loss = posterior.kl()
29
+ kl_loss = torch.sum(kl_loss) / kl_loss.shape[0]
30
+ log["kl_loss"] = kl_loss
31
+ return z, log
32
+
33
+
34
+ class AbstractAutoencoder(torch.nn.Module):
35
+ """
36
+ This is the base class for all autoencoders, including image autoencoders, image autoencoders with discriminators,
37
+ unCLIP models, etc. Hence, it is fairly general, and specific features
38
+ (e.g. discriminator training, encoding, decoding) must be implemented in subclasses.
39
+ """
40
+
41
+ def __init__(
42
+ self,
43
+ ema_decay: Union[None, float] = None,
44
+ monitor: Union[None, str] = None,
45
+ input_key: str = "jpg",
46
+ **kwargs,
47
+ ):
48
+ super().__init__()
49
+
50
+ self.input_key = input_key
51
+ self.use_ema = ema_decay is not None
52
+ if monitor is not None:
53
+ self.monitor = monitor
54
+
55
+ if self.use_ema:
56
+ self.model_ema = LitEma(self, decay=ema_decay)
57
+ logpy.info(f"Keeping EMAs of {len(list(self.model_ema.buffers()))}.")
58
+
59
+ def get_input(self, batch) -> Any:
60
+ raise NotImplementedError()
61
+
62
+ def on_train_batch_end(self, *args, **kwargs):
63
+ # for EMA computation
64
+ if self.use_ema:
65
+ self.model_ema(self)
66
+
67
+ @contextmanager
68
+ def ema_scope(self, context=None):
69
+ if self.use_ema:
70
+ self.model_ema.store(self.parameters())
71
+ self.model_ema.copy_to(self)
72
+ if context is not None:
73
+ logpy.info(f"{context}: Switched to EMA weights")
74
+ try:
75
+ yield None
76
+ finally:
77
+ if self.use_ema:
78
+ self.model_ema.restore(self.parameters())
79
+ if context is not None:
80
+ logpy.info(f"{context}: Restored training weights")
81
+
82
+ def encode(self, *args, **kwargs) -> torch.Tensor:
83
+ raise NotImplementedError("encode()-method of abstract base class called")
84
+
85
+ def decode(self, *args, **kwargs) -> torch.Tensor:
86
+ raise NotImplementedError("decode()-method of abstract base class called")
87
+
88
+ def instantiate_optimizer_from_config(self, params, lr, cfg):
89
+ logpy.info(f"loading >>> {cfg['target']} <<< optimizer from config")
90
+ return get_obj_from_str(cfg["target"])(
91
+ params, lr=lr, **cfg.get("params", dict())
92
+ )
93
+
94
+ def configure_optimizers(self) -> Any:
95
+ raise NotImplementedError()
96
+
97
+
98
+ class AutoencodingEngine(AbstractAutoencoder):
99
+ """
100
+ Base class for all image autoencoders that we train, like VQGAN or AutoencoderKL
101
+ (we also restore them explicitly as special cases for legacy reasons).
102
+ Regularizations such as KL or VQ are moved to the regularizer class.
103
+ """
104
+
105
+ def __init__(
106
+ self,
107
+ *args,
108
+ encoder_config: Dict,
109
+ decoder_config: Dict,
110
+ regularizer_config: Dict,
111
+ **kwargs,
112
+ ):
113
+ super().__init__(*args, **kwargs)
114
+
115
+ self.encoder: torch.nn.Module = instantiate_from_config(encoder_config)
116
+ self.decoder: torch.nn.Module = instantiate_from_config(decoder_config)
117
+ self.regularization: AbstractRegularizer = instantiate_from_config(
118
+ regularizer_config
119
+ )
120
+
121
+ def get_last_layer(self):
122
+ return self.decoder.get_last_layer()
123
+
124
+ def encode(
125
+ self,
126
+ x: torch.Tensor,
127
+ return_reg_log: bool = False,
128
+ unregularized: bool = False,
129
+ ) -> Union[torch.Tensor, Tuple[torch.Tensor, dict]]:
130
+ z = self.encoder(x)
131
+ if unregularized:
132
+ return z, dict()
133
+ z, reg_log = self.regularization(z)
134
+ if return_reg_log:
135
+ return z, reg_log
136
+ return z
137
+
138
+ def decode(self, z: torch.Tensor, **kwargs) -> torch.Tensor:
139
+ x = self.decoder(z, **kwargs)
140
+ return x
141
+
142
+ def forward(
143
+ self, x: torch.Tensor, **additional_decode_kwargs
144
+ ) -> Tuple[torch.Tensor, torch.Tensor, dict]:
145
+ z, reg_log = self.encode(x, return_reg_log=True)
146
+ dec = self.decode(z, **additional_decode_kwargs)
147
+ return z, dec, reg_log
148
+
149
+
150
+ class AutoencodingEngineLegacy(AutoencodingEngine):
151
+ def __init__(self, embed_dim: int, **kwargs):
152
+ self.max_batch_size = kwargs.pop("max_batch_size", None)
153
+ ddconfig = kwargs.pop("ddconfig")
154
+ super().__init__(
155
+ encoder_config={
156
+ "target": "comfy.ldm.modules.diffusionmodules.model.Encoder",
157
+ "params": ddconfig,
158
+ },
159
+ decoder_config={
160
+ "target": "comfy.ldm.modules.diffusionmodules.model.Decoder",
161
+ "params": ddconfig,
162
+ },
163
+ **kwargs,
164
+ )
165
+ self.quant_conv = comfy.ops.disable_weight_init.Conv2d(
166
+ (1 + ddconfig["double_z"]) * ddconfig["z_channels"],
167
+ (1 + ddconfig["double_z"]) * embed_dim,
168
+ 1,
169
+ )
170
+ self.post_quant_conv = comfy.ops.disable_weight_init.Conv2d(embed_dim, ddconfig["z_channels"], 1)
171
+ self.embed_dim = embed_dim
172
+
173
+ def get_autoencoder_params(self) -> list:
174
+ params = super().get_autoencoder_params()
175
+ return params
176
+
177
+ def encode(
178
+ self, x: torch.Tensor, return_reg_log: bool = False
179
+ ) -> Union[torch.Tensor, Tuple[torch.Tensor, dict]]:
180
+ if self.max_batch_size is None:
181
+ z = self.encoder(x)
182
+ z = self.quant_conv(z)
183
+ else:
184
+ N = x.shape[0]
185
+ bs = self.max_batch_size
186
+ n_batches = int(math.ceil(N / bs))
187
+ z = list()
188
+ for i_batch in range(n_batches):
189
+ z_batch = self.encoder(x[i_batch * bs : (i_batch + 1) * bs])
190
+ z_batch = self.quant_conv(z_batch)
191
+ z.append(z_batch)
192
+ z = torch.cat(z, 0)
193
+
194
+ z, reg_log = self.regularization(z)
195
+ if return_reg_log:
196
+ return z, reg_log
197
+ return z
198
+
199
+ def decode(self, z: torch.Tensor, **decoder_kwargs) -> torch.Tensor:
200
+ if self.max_batch_size is None:
201
+ dec = self.post_quant_conv(z)
202
+ dec = self.decoder(dec, **decoder_kwargs)
203
+ else:
204
+ N = z.shape[0]
205
+ bs = self.max_batch_size
206
+ n_batches = int(math.ceil(N / bs))
207
+ dec = list()
208
+ for i_batch in range(n_batches):
209
+ dec_batch = self.post_quant_conv(z[i_batch * bs : (i_batch + 1) * bs])
210
+ dec_batch = self.decoder(dec_batch, **decoder_kwargs)
211
+ dec.append(dec_batch)
212
+ dec = torch.cat(dec, 0)
213
+
214
+ return dec
215
+
216
+
217
+ class AutoencoderKL(AutoencodingEngineLegacy):
218
+ def __init__(self, **kwargs):
219
+ if "lossconfig" in kwargs:
220
+ kwargs["loss_config"] = kwargs.pop("lossconfig")
221
+ super().__init__(
222
+ regularizer_config={
223
+ "target": (
224
+ "comfy.ldm.models.autoencoder.DiagonalGaussianRegularizer"
225
+ )
226
+ },
227
+ **kwargs,
228
+ )
comfy/ldm/modules/attention.py ADDED
@@ -0,0 +1,781 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ import torch
3
+ import torch.nn.functional as F
4
+ from torch import nn, einsum
5
+ from einops import rearrange, repeat
6
+ from typing import Optional, Any
7
+
8
+ from .diffusionmodules.util import checkpoint, AlphaBlender, timestep_embedding
9
+ from .sub_quadratic_attention import efficient_dot_product_attention
10
+
11
+ from comfy import model_management
12
+
13
+ if model_management.xformers_enabled():
14
+ import xformers
15
+ import xformers.ops
16
+
17
+ from comfy.cli_args import args
18
+ import comfy.ops
19
+ ops = comfy.ops.disable_weight_init
20
+
21
+ # CrossAttn precision handling
22
+ if args.dont_upcast_attention:
23
+ print("disabling upcasting of attention")
24
+ _ATTN_PRECISION = "fp16"
25
+ else:
26
+ _ATTN_PRECISION = "fp32"
27
+
28
+
29
+ def exists(val):
30
+ return val is not None
31
+
32
+
33
+ def uniq(arr):
34
+ return{el: True for el in arr}.keys()
35
+
36
+
37
+ def default(val, d):
38
+ if exists(val):
39
+ return val
40
+ return d
41
+
42
+
43
+ def max_neg_value(t):
44
+ return -torch.finfo(t.dtype).max
45
+
46
+
47
+ def init_(tensor):
48
+ dim = tensor.shape[-1]
49
+ std = 1 / math.sqrt(dim)
50
+ tensor.uniform_(-std, std)
51
+ return tensor
52
+
53
+
54
+ # feedforward
55
+ class GEGLU(nn.Module):
56
+ def __init__(self, dim_in, dim_out, dtype=None, device=None, operations=ops):
57
+ super().__init__()
58
+ self.proj = operations.Linear(dim_in, dim_out * 2, dtype=dtype, device=device)
59
+
60
+ def forward(self, x):
61
+ x, gate = self.proj(x).chunk(2, dim=-1)
62
+ return x * F.gelu(gate)
63
+
64
+
65
+ class FeedForward(nn.Module):
66
+ def __init__(self, dim, dim_out=None, mult=4, glu=False, dropout=0., dtype=None, device=None, operations=ops):
67
+ super().__init__()
68
+ inner_dim = int(dim * mult)
69
+ dim_out = default(dim_out, dim)
70
+ project_in = nn.Sequential(
71
+ operations.Linear(dim, inner_dim, dtype=dtype, device=device),
72
+ nn.GELU()
73
+ ) if not glu else GEGLU(dim, inner_dim, dtype=dtype, device=device, operations=operations)
74
+
75
+ self.net = nn.Sequential(
76
+ project_in,
77
+ nn.Dropout(dropout),
78
+ operations.Linear(inner_dim, dim_out, dtype=dtype, device=device)
79
+ )
80
+
81
+ def forward(self, x):
82
+ return self.net(x)
83
+
84
+ def Normalize(in_channels, dtype=None, device=None):
85
+ return torch.nn.GroupNorm(num_groups=32, num_channels=in_channels, eps=1e-6, affine=True, dtype=dtype, device=device)
86
+
87
+ def attention_basic(q, k, v, heads, mask=None):
88
+ b, _, dim_head = q.shape
89
+ dim_head //= heads
90
+ scale = dim_head ** -0.5
91
+
92
+ h = heads
93
+ q, k, v = map(
94
+ lambda t: t.unsqueeze(3)
95
+ .reshape(b, -1, heads, dim_head)
96
+ .permute(0, 2, 1, 3)
97
+ .reshape(b * heads, -1, dim_head)
98
+ .contiguous(),
99
+ (q, k, v),
100
+ )
101
+
102
+ # force cast to fp32 to avoid overflowing
103
+ if _ATTN_PRECISION =="fp32":
104
+ sim = einsum('b i d, b j d -> b i j', q.float(), k.float()) * scale
105
+ else:
106
+ sim = einsum('b i d, b j d -> b i j', q, k) * scale
107
+
108
+ del q, k
109
+
110
+ if exists(mask):
111
+ if mask.dtype == torch.bool:
112
+ mask = rearrange(mask, 'b ... -> b (...)') #TODO: check if this bool part matches pytorch attention
113
+ max_neg_value = -torch.finfo(sim.dtype).max
114
+ mask = repeat(mask, 'b j -> (b h) () j', h=h)
115
+ sim.masked_fill_(~mask, max_neg_value)
116
+ else:
117
+ sim += mask
118
+
119
+ # attention, what we cannot get enough of
120
+ sim = sim.softmax(dim=-1)
121
+
122
+ out = einsum('b i j, b j d -> b i d', sim.to(v.dtype), v)
123
+ out = (
124
+ out.unsqueeze(0)
125
+ .reshape(b, heads, -1, dim_head)
126
+ .permute(0, 2, 1, 3)
127
+ .reshape(b, -1, heads * dim_head)
128
+ )
129
+ return out
130
+
131
+
132
+ def attention_sub_quad(query, key, value, heads, mask=None):
133
+ b, _, dim_head = query.shape
134
+ dim_head //= heads
135
+
136
+ scale = dim_head ** -0.5
137
+ query = query.unsqueeze(3).reshape(b, -1, heads, dim_head).permute(0, 2, 1, 3).reshape(b * heads, -1, dim_head)
138
+ value = value.unsqueeze(3).reshape(b, -1, heads, dim_head).permute(0, 2, 1, 3).reshape(b * heads, -1, dim_head)
139
+
140
+ key = key.unsqueeze(3).reshape(b, -1, heads, dim_head).permute(0, 2, 3, 1).reshape(b * heads, dim_head, -1)
141
+
142
+ dtype = query.dtype
143
+ upcast_attention = _ATTN_PRECISION =="fp32" and query.dtype != torch.float32
144
+ if upcast_attention:
145
+ bytes_per_token = torch.finfo(torch.float32).bits//8
146
+ else:
147
+ bytes_per_token = torch.finfo(query.dtype).bits//8
148
+ batch_x_heads, q_tokens, _ = query.shape
149
+ _, _, k_tokens = key.shape
150
+ qk_matmul_size_bytes = batch_x_heads * bytes_per_token * q_tokens * k_tokens
151
+
152
+ mem_free_total, mem_free_torch = model_management.get_free_memory(query.device, True)
153
+
154
+ kv_chunk_size_min = None
155
+ kv_chunk_size = None
156
+ query_chunk_size = None
157
+
158
+ for x in [4096, 2048, 1024, 512, 256]:
159
+ count = mem_free_total / (batch_x_heads * bytes_per_token * x * 4.0)
160
+ if count >= k_tokens:
161
+ kv_chunk_size = k_tokens
162
+ query_chunk_size = x
163
+ break
164
+
165
+ if query_chunk_size is None:
166
+ query_chunk_size = 512
167
+
168
+ hidden_states = efficient_dot_product_attention(
169
+ query,
170
+ key,
171
+ value,
172
+ query_chunk_size=query_chunk_size,
173
+ kv_chunk_size=kv_chunk_size,
174
+ kv_chunk_size_min=kv_chunk_size_min,
175
+ use_checkpoint=False,
176
+ upcast_attention=upcast_attention,
177
+ mask=mask,
178
+ )
179
+
180
+ hidden_states = hidden_states.to(dtype)
181
+
182
+ hidden_states = hidden_states.unflatten(0, (-1, heads)).transpose(1,2).flatten(start_dim=2)
183
+ return hidden_states
184
+
185
+ def attention_split(q, k, v, heads, mask=None):
186
+ b, _, dim_head = q.shape
187
+ dim_head //= heads
188
+ scale = dim_head ** -0.5
189
+
190
+ h = heads
191
+ q, k, v = map(
192
+ lambda t: t.unsqueeze(3)
193
+ .reshape(b, -1, heads, dim_head)
194
+ .permute(0, 2, 1, 3)
195
+ .reshape(b * heads, -1, dim_head)
196
+ .contiguous(),
197
+ (q, k, v),
198
+ )
199
+
200
+ r1 = torch.zeros(q.shape[0], q.shape[1], v.shape[2], device=q.device, dtype=q.dtype)
201
+
202
+ mem_free_total = model_management.get_free_memory(q.device)
203
+
204
+ if _ATTN_PRECISION =="fp32":
205
+ element_size = 4
206
+ else:
207
+ element_size = q.element_size()
208
+
209
+ gb = 1024 ** 3
210
+ tensor_size = q.shape[0] * q.shape[1] * k.shape[1] * element_size
211
+ modifier = 3
212
+ mem_required = tensor_size * modifier
213
+ steps = 1
214
+
215
+
216
+ if mem_required > mem_free_total:
217
+ steps = 2**(math.ceil(math.log(mem_required / mem_free_total, 2)))
218
+ # print(f"Expected tensor size:{tensor_size/gb:0.1f}GB, cuda free:{mem_free_cuda/gb:0.1f}GB "
219
+ # f"torch free:{mem_free_torch/gb:0.1f} total:{mem_free_total/gb:0.1f} steps:{steps}")
220
+
221
+ if steps > 64:
222
+ max_res = math.floor(math.sqrt(math.sqrt(mem_free_total / 2.5)) / 8) * 64
223
+ raise RuntimeError(f'Not enough memory, use lower resolution (max approx. {max_res}x{max_res}). '
224
+ f'Need: {mem_required/64/gb:0.1f}GB free, Have:{mem_free_total/gb:0.1f}GB free')
225
+
226
+ # print("steps", steps, mem_required, mem_free_total, modifier, q.element_size(), tensor_size)
227
+ first_op_done = False
228
+ cleared_cache = False
229
+ while True:
230
+ try:
231
+ slice_size = q.shape[1] // steps if (q.shape[1] % steps) == 0 else q.shape[1]
232
+ for i in range(0, q.shape[1], slice_size):
233
+ end = i + slice_size
234
+ if _ATTN_PRECISION =="fp32":
235
+ with torch.autocast(enabled=False, device_type = 'cuda'):
236
+ s1 = einsum('b i d, b j d -> b i j', q[:, i:end].float(), k.float()) * scale
237
+ else:
238
+ s1 = einsum('b i d, b j d -> b i j', q[:, i:end], k) * scale
239
+
240
+ if mask is not None:
241
+ if len(mask.shape) == 2:
242
+ s1 += mask[i:end]
243
+ else:
244
+ s1 += mask[:, i:end]
245
+
246
+ s2 = s1.softmax(dim=-1).to(v.dtype)
247
+ del s1
248
+ first_op_done = True
249
+
250
+ r1[:, i:end] = einsum('b i j, b j d -> b i d', s2, v)
251
+ del s2
252
+ break
253
+ except model_management.OOM_EXCEPTION as e:
254
+ if first_op_done == False:
255
+ model_management.soft_empty_cache(True)
256
+ if cleared_cache == False:
257
+ cleared_cache = True
258
+ print("out of memory error, emptying cache and trying again")
259
+ continue
260
+ steps *= 2
261
+ if steps > 64:
262
+ raise e
263
+ print("out of memory error, increasing steps and trying again", steps)
264
+ else:
265
+ raise e
266
+
267
+ del q, k, v
268
+
269
+ r1 = (
270
+ r1.unsqueeze(0)
271
+ .reshape(b, heads, -1, dim_head)
272
+ .permute(0, 2, 1, 3)
273
+ .reshape(b, -1, heads * dim_head)
274
+ )
275
+ return r1
276
+
277
+ BROKEN_XFORMERS = False
278
+ try:
279
+ x_vers = xformers.__version__
280
+ #I think 0.0.23 is also broken (q with bs bigger than 65535 gives CUDA error)
281
+ BROKEN_XFORMERS = x_vers.startswith("0.0.21") or x_vers.startswith("0.0.22") or x_vers.startswith("0.0.23")
282
+ except:
283
+ pass
284
+
285
+ def attention_xformers(q, k, v, heads, mask=None):
286
+ b, _, dim_head = q.shape
287
+ dim_head //= heads
288
+ if BROKEN_XFORMERS:
289
+ if b * heads > 65535:
290
+ return attention_pytorch(q, k, v, heads, mask)
291
+
292
+ q, k, v = map(
293
+ lambda t: t.unsqueeze(3)
294
+ .reshape(b, -1, heads, dim_head)
295
+ .permute(0, 2, 1, 3)
296
+ .reshape(b * heads, -1, dim_head)
297
+ .contiguous(),
298
+ (q, k, v),
299
+ )
300
+
301
+ if mask is not None:
302
+ pad = 8 - q.shape[1] % 8
303
+ mask_out = torch.empty([q.shape[0], q.shape[1], q.shape[1] + pad], dtype=q.dtype, device=q.device)
304
+ mask_out[:, :, :mask.shape[-1]] = mask
305
+ mask = mask_out[:, :, :mask.shape[-1]]
306
+
307
+ out = xformers.ops.memory_efficient_attention(q, k, v, attn_bias=mask)
308
+
309
+ out = (
310
+ out.unsqueeze(0)
311
+ .reshape(b, heads, -1, dim_head)
312
+ .permute(0, 2, 1, 3)
313
+ .reshape(b, -1, heads * dim_head)
314
+ )
315
+ return out
316
+
317
+ def attention_pytorch(q, k, v, heads, mask=None):
318
+ b, _, dim_head = q.shape
319
+ dim_head //= heads
320
+ q, k, v = map(
321
+ lambda t: t.view(b, -1, heads, dim_head).transpose(1, 2),
322
+ (q, k, v),
323
+ )
324
+
325
+ out = torch.nn.functional.scaled_dot_product_attention(q, k, v, attn_mask=mask, dropout_p=0.0, is_causal=False)
326
+ out = (
327
+ out.transpose(1, 2).reshape(b, -1, heads * dim_head)
328
+ )
329
+ return out
330
+
331
+
332
+ optimized_attention = attention_basic
333
+
334
+ if model_management.xformers_enabled():
335
+ print("Using xformers cross attention")
336
+ optimized_attention = attention_xformers
337
+ elif model_management.pytorch_attention_enabled():
338
+ print("Using pytorch cross attention")
339
+ optimized_attention = attention_pytorch
340
+ else:
341
+ if args.use_split_cross_attention:
342
+ print("Using split optimization for cross attention")
343
+ optimized_attention = attention_split
344
+ else:
345
+ print("Using sub quadratic optimization for cross attention, if you have memory or speed issues try using: --use-split-cross-attention")
346
+ optimized_attention = attention_sub_quad
347
+
348
+ optimized_attention_masked = optimized_attention
349
+
350
+ def optimized_attention_for_device(device, mask=False, small_input=False):
351
+ if small_input:
352
+ if model_management.pytorch_attention_enabled():
353
+ return attention_pytorch #TODO: need to confirm but this is probably slightly faster for small inputs in all cases
354
+ else:
355
+ return attention_basic
356
+
357
+ if device == torch.device("cpu"):
358
+ return attention_sub_quad
359
+
360
+ if mask:
361
+ return optimized_attention_masked
362
+
363
+ return optimized_attention
364
+
365
+
366
+ class CrossAttention(nn.Module):
367
+ def __init__(self, query_dim, context_dim=None, heads=8, dim_head=64, dropout=0., dtype=None, device=None, operations=ops):
368
+ super().__init__()
369
+ inner_dim = dim_head * heads
370
+ context_dim = default(context_dim, query_dim)
371
+
372
+ self.heads = heads
373
+ self.dim_head = dim_head
374
+
375
+ self.to_q = operations.Linear(query_dim, inner_dim, bias=False, dtype=dtype, device=device)
376
+ self.to_k = operations.Linear(context_dim, inner_dim, bias=False, dtype=dtype, device=device)
377
+ self.to_v = operations.Linear(context_dim, inner_dim, bias=False, dtype=dtype, device=device)
378
+
379
+ self.to_out = nn.Sequential(operations.Linear(inner_dim, query_dim, dtype=dtype, device=device), nn.Dropout(dropout))
380
+
381
+ def forward(self, x, context=None, value=None, mask=None):
382
+ q = self.to_q(x)
383
+ context = default(context, x)
384
+ k = self.to_k(context)
385
+ if value is not None:
386
+ v = self.to_v(value)
387
+ del value
388
+ else:
389
+ v = self.to_v(context)
390
+
391
+ if mask is None:
392
+ out = optimized_attention(q, k, v, self.heads)
393
+ else:
394
+ out = optimized_attention_masked(q, k, v, self.heads, mask)
395
+ return self.to_out(out)
396
+
397
+
398
+ class BasicTransformerBlock(nn.Module):
399
+ def __init__(self, dim, n_heads, d_head, dropout=0., context_dim=None, gated_ff=True, checkpoint=True, ff_in=False, inner_dim=None,
400
+ disable_self_attn=False, disable_temporal_crossattention=False, switch_temporal_ca_to_sa=False, dtype=None, device=None, operations=ops):
401
+ super().__init__()
402
+
403
+ self.ff_in = ff_in or inner_dim is not None
404
+ if inner_dim is None:
405
+ inner_dim = dim
406
+
407
+ self.is_res = inner_dim == dim
408
+
409
+ if self.ff_in:
410
+ self.norm_in = operations.LayerNorm(dim, dtype=dtype, device=device)
411
+ self.ff_in = FeedForward(dim, dim_out=inner_dim, dropout=dropout, glu=gated_ff, dtype=dtype, device=device, operations=operations)
412
+
413
+ self.disable_self_attn = disable_self_attn
414
+ self.attn1 = CrossAttention(query_dim=inner_dim, heads=n_heads, dim_head=d_head, dropout=dropout,
415
+ context_dim=context_dim if self.disable_self_attn else None, dtype=dtype, device=device, operations=operations) # is a self-attention if not self.disable_self_attn
416
+ self.ff = FeedForward(inner_dim, dim_out=dim, dropout=dropout, glu=gated_ff, dtype=dtype, device=device, operations=operations)
417
+
418
+ if disable_temporal_crossattention:
419
+ if switch_temporal_ca_to_sa:
420
+ raise ValueError
421
+ else:
422
+ self.attn2 = None
423
+ else:
424
+ context_dim_attn2 = None
425
+ if not switch_temporal_ca_to_sa:
426
+ context_dim_attn2 = context_dim
427
+
428
+ self.attn2 = CrossAttention(query_dim=inner_dim, context_dim=context_dim_attn2,
429
+ heads=n_heads, dim_head=d_head, dropout=dropout, dtype=dtype, device=device, operations=operations) # is self-attn if context is none
430
+ self.norm2 = operations.LayerNorm(inner_dim, dtype=dtype, device=device)
431
+
432
+ self.norm1 = operations.LayerNorm(inner_dim, dtype=dtype, device=device)
433
+ self.norm3 = operations.LayerNorm(inner_dim, dtype=dtype, device=device)
434
+ self.checkpoint = checkpoint
435
+ self.n_heads = n_heads
436
+ self.d_head = d_head
437
+ self.switch_temporal_ca_to_sa = switch_temporal_ca_to_sa
438
+
439
+ def forward(self, x, context=None, transformer_options={}):
440
+ return checkpoint(self._forward, (x, context, transformer_options), self.parameters(), self.checkpoint)
441
+
442
+ def _forward(self, x, context=None, transformer_options={}):
443
+ extra_options = {}
444
+ block = transformer_options.get("block", None)
445
+ block_index = transformer_options.get("block_index", 0)
446
+ transformer_patches = {}
447
+ transformer_patches_replace = {}
448
+
449
+ for k in transformer_options:
450
+ if k == "patches":
451
+ transformer_patches = transformer_options[k]
452
+ elif k == "patches_replace":
453
+ transformer_patches_replace = transformer_options[k]
454
+ else:
455
+ extra_options[k] = transformer_options[k]
456
+
457
+ extra_options["n_heads"] = self.n_heads
458
+ extra_options["dim_head"] = self.d_head
459
+
460
+ if self.ff_in:
461
+ x_skip = x
462
+ x = self.ff_in(self.norm_in(x))
463
+ if self.is_res:
464
+ x += x_skip
465
+
466
+ n = self.norm1(x)
467
+ if self.disable_self_attn:
468
+ context_attn1 = context
469
+ else:
470
+ context_attn1 = None
471
+ value_attn1 = None
472
+
473
+ if "attn1_patch" in transformer_patches:
474
+ patch = transformer_patches["attn1_patch"]
475
+ if context_attn1 is None:
476
+ context_attn1 = n
477
+ value_attn1 = context_attn1
478
+ for p in patch:
479
+ n, context_attn1, value_attn1 = p(n, context_attn1, value_attn1, extra_options)
480
+
481
+ if block is not None:
482
+ transformer_block = (block[0], block[1], block_index)
483
+ else:
484
+ transformer_block = None
485
+ attn1_replace_patch = transformer_patches_replace.get("attn1", {})
486
+ block_attn1 = transformer_block
487
+ if block_attn1 not in attn1_replace_patch:
488
+ block_attn1 = block
489
+
490
+ if block_attn1 in attn1_replace_patch:
491
+ if context_attn1 is None:
492
+ context_attn1 = n
493
+ value_attn1 = n
494
+ n = self.attn1.to_q(n)
495
+ context_attn1 = self.attn1.to_k(context_attn1)
496
+ value_attn1 = self.attn1.to_v(value_attn1)
497
+ n = attn1_replace_patch[block_attn1](n, context_attn1, value_attn1, extra_options)
498
+ n = self.attn1.to_out(n)
499
+ else:
500
+ n = self.attn1(n, context=context_attn1, value=value_attn1)
501
+
502
+ if "attn1_output_patch" in transformer_patches:
503
+ patch = transformer_patches["attn1_output_patch"]
504
+ for p in patch:
505
+ n = p(n, extra_options)
506
+
507
+ x += n
508
+ if "middle_patch" in transformer_patches:
509
+ patch = transformer_patches["middle_patch"]
510
+ for p in patch:
511
+ x = p(x, extra_options)
512
+
513
+ if self.attn2 is not None:
514
+ n = self.norm2(x)
515
+ if self.switch_temporal_ca_to_sa:
516
+ context_attn2 = n
517
+ else:
518
+ context_attn2 = context
519
+ value_attn2 = None
520
+ if "attn2_patch" in transformer_patches:
521
+ patch = transformer_patches["attn2_patch"]
522
+ value_attn2 = context_attn2
523
+ for p in patch:
524
+ n, context_attn2, value_attn2 = p(n, context_attn2, value_attn2, extra_options)
525
+
526
+ attn2_replace_patch = transformer_patches_replace.get("attn2", {})
527
+ block_attn2 = transformer_block
528
+ if block_attn2 not in attn2_replace_patch:
529
+ block_attn2 = block
530
+
531
+ if block_attn2 in attn2_replace_patch:
532
+ if value_attn2 is None:
533
+ value_attn2 = context_attn2
534
+ n = self.attn2.to_q(n)
535
+ context_attn2 = self.attn2.to_k(context_attn2)
536
+ value_attn2 = self.attn2.to_v(value_attn2)
537
+ n = attn2_replace_patch[block_attn2](n, context_attn2, value_attn2, extra_options)
538
+ n = self.attn2.to_out(n)
539
+ else:
540
+ n = self.attn2(n, context=context_attn2, value=value_attn2)
541
+
542
+ if "attn2_output_patch" in transformer_patches:
543
+ patch = transformer_patches["attn2_output_patch"]
544
+ for p in patch:
545
+ n = p(n, extra_options)
546
+
547
+ x += n
548
+ if self.is_res:
549
+ x_skip = x
550
+ x = self.ff(self.norm3(x))
551
+ if self.is_res:
552
+ x += x_skip
553
+
554
+ return x
555
+
556
+
557
+ class SpatialTransformer(nn.Module):
558
+ """
559
+ Transformer block for image-like data.
560
+ First, project the input (aka embedding)
561
+ and reshape to b, t, d.
562
+ Then apply standard transformer action.
563
+ Finally, reshape to image
564
+ NEW: use_linear for more efficiency instead of the 1x1 convs
565
+ """
566
+ def __init__(self, in_channels, n_heads, d_head,
567
+ depth=1, dropout=0., context_dim=None,
568
+ disable_self_attn=False, use_linear=False,
569
+ use_checkpoint=True, dtype=None, device=None, operations=ops):
570
+ super().__init__()
571
+ if exists(context_dim) and not isinstance(context_dim, list):
572
+ context_dim = [context_dim] * depth
573
+ self.in_channels = in_channels
574
+ inner_dim = n_heads * d_head
575
+ self.norm = operations.GroupNorm(num_groups=32, num_channels=in_channels, eps=1e-6, affine=True, dtype=dtype, device=device)
576
+ if not use_linear:
577
+ self.proj_in = operations.Conv2d(in_channels,
578
+ inner_dim,
579
+ kernel_size=1,
580
+ stride=1,
581
+ padding=0, dtype=dtype, device=device)
582
+ else:
583
+ self.proj_in = operations.Linear(in_channels, inner_dim, dtype=dtype, device=device)
584
+
585
+ self.transformer_blocks = nn.ModuleList(
586
+ [BasicTransformerBlock(inner_dim, n_heads, d_head, dropout=dropout, context_dim=context_dim[d],
587
+ disable_self_attn=disable_self_attn, checkpoint=use_checkpoint, dtype=dtype, device=device, operations=operations)
588
+ for d in range(depth)]
589
+ )
590
+ if not use_linear:
591
+ self.proj_out = operations.Conv2d(inner_dim,in_channels,
592
+ kernel_size=1,
593
+ stride=1,
594
+ padding=0, dtype=dtype, device=device)
595
+ else:
596
+ self.proj_out = operations.Linear(in_channels, inner_dim, dtype=dtype, device=device)
597
+ self.use_linear = use_linear
598
+
599
+ def forward(self, x, context=None, transformer_options={}):
600
+ # note: if no context is given, cross-attention defaults to self-attention
601
+ if not isinstance(context, list):
602
+ context = [context] * len(self.transformer_blocks)
603
+ b, c, h, w = x.shape
604
+ x_in = x
605
+ x = self.norm(x)
606
+ if not self.use_linear:
607
+ x = self.proj_in(x)
608
+ x = rearrange(x, 'b c h w -> b (h w) c').contiguous()
609
+ if self.use_linear:
610
+ x = self.proj_in(x)
611
+ for i, block in enumerate(self.transformer_blocks):
612
+ transformer_options["block_index"] = i
613
+ x = block(x, context=context[i], transformer_options=transformer_options)
614
+ if self.use_linear:
615
+ x = self.proj_out(x)
616
+ x = rearrange(x, 'b (h w) c -> b c h w', h=h, w=w).contiguous()
617
+ if not self.use_linear:
618
+ x = self.proj_out(x)
619
+ return x + x_in
620
+
621
+
622
+ class SpatialVideoTransformer(SpatialTransformer):
623
+ def __init__(
624
+ self,
625
+ in_channels,
626
+ n_heads,
627
+ d_head,
628
+ depth=1,
629
+ dropout=0.0,
630
+ use_linear=False,
631
+ context_dim=None,
632
+ use_spatial_context=False,
633
+ timesteps=None,
634
+ merge_strategy: str = "fixed",
635
+ merge_factor: float = 0.5,
636
+ time_context_dim=None,
637
+ ff_in=False,
638
+ checkpoint=False,
639
+ time_depth=1,
640
+ disable_self_attn=False,
641
+ disable_temporal_crossattention=False,
642
+ max_time_embed_period: int = 10000,
643
+ dtype=None, device=None, operations=ops
644
+ ):
645
+ super().__init__(
646
+ in_channels,
647
+ n_heads,
648
+ d_head,
649
+ depth=depth,
650
+ dropout=dropout,
651
+ use_checkpoint=checkpoint,
652
+ context_dim=context_dim,
653
+ use_linear=use_linear,
654
+ disable_self_attn=disable_self_attn,
655
+ dtype=dtype, device=device, operations=operations
656
+ )
657
+ self.time_depth = time_depth
658
+ self.depth = depth
659
+ self.max_time_embed_period = max_time_embed_period
660
+
661
+ time_mix_d_head = d_head
662
+ n_time_mix_heads = n_heads
663
+
664
+ time_mix_inner_dim = int(time_mix_d_head * n_time_mix_heads)
665
+
666
+ inner_dim = n_heads * d_head
667
+ if use_spatial_context:
668
+ time_context_dim = context_dim
669
+
670
+ self.time_stack = nn.ModuleList(
671
+ [
672
+ BasicTransformerBlock(
673
+ inner_dim,
674
+ n_time_mix_heads,
675
+ time_mix_d_head,
676
+ dropout=dropout,
677
+ context_dim=time_context_dim,
678
+ # timesteps=timesteps,
679
+ checkpoint=checkpoint,
680
+ ff_in=ff_in,
681
+ inner_dim=time_mix_inner_dim,
682
+ disable_self_attn=disable_self_attn,
683
+ disable_temporal_crossattention=disable_temporal_crossattention,
684
+ dtype=dtype, device=device, operations=operations
685
+ )
686
+ for _ in range(self.depth)
687
+ ]
688
+ )
689
+
690
+ assert len(self.time_stack) == len(self.transformer_blocks)
691
+
692
+ self.use_spatial_context = use_spatial_context
693
+ self.in_channels = in_channels
694
+
695
+ time_embed_dim = self.in_channels * 4
696
+ self.time_pos_embed = nn.Sequential(
697
+ operations.Linear(self.in_channels, time_embed_dim, dtype=dtype, device=device),
698
+ nn.SiLU(),
699
+ operations.Linear(time_embed_dim, self.in_channels, dtype=dtype, device=device),
700
+ )
701
+
702
+ self.time_mixer = AlphaBlender(
703
+ alpha=merge_factor, merge_strategy=merge_strategy
704
+ )
705
+
706
+ def forward(
707
+ self,
708
+ x: torch.Tensor,
709
+ context: Optional[torch.Tensor] = None,
710
+ time_context: Optional[torch.Tensor] = None,
711
+ timesteps: Optional[int] = None,
712
+ image_only_indicator: Optional[torch.Tensor] = None,
713
+ transformer_options={}
714
+ ) -> torch.Tensor:
715
+ _, _, h, w = x.shape
716
+ x_in = x
717
+ spatial_context = None
718
+ if exists(context):
719
+ spatial_context = context
720
+
721
+ if self.use_spatial_context:
722
+ assert (
723
+ context.ndim == 3
724
+ ), f"n dims of spatial context should be 3 but are {context.ndim}"
725
+
726
+ if time_context is None:
727
+ time_context = context
728
+ time_context_first_timestep = time_context[::timesteps]
729
+ time_context = repeat(
730
+ time_context_first_timestep, "b ... -> (b n) ...", n=h * w
731
+ )
732
+ elif time_context is not None and not self.use_spatial_context:
733
+ time_context = repeat(time_context, "b ... -> (b n) ...", n=h * w)
734
+ if time_context.ndim == 2:
735
+ time_context = rearrange(time_context, "b c -> b 1 c")
736
+
737
+ x = self.norm(x)
738
+ if not self.use_linear:
739
+ x = self.proj_in(x)
740
+ x = rearrange(x, "b c h w -> b (h w) c")
741
+ if self.use_linear:
742
+ x = self.proj_in(x)
743
+
744
+ num_frames = torch.arange(timesteps, device=x.device)
745
+ num_frames = repeat(num_frames, "t -> b t", b=x.shape[0] // timesteps)
746
+ num_frames = rearrange(num_frames, "b t -> (b t)")
747
+ t_emb = timestep_embedding(num_frames, self.in_channels, repeat_only=False, max_period=self.max_time_embed_period).to(x.dtype)
748
+ emb = self.time_pos_embed(t_emb)
749
+ emb = emb[:, None, :]
750
+
751
+ for it_, (block, mix_block) in enumerate(
752
+ zip(self.transformer_blocks, self.time_stack)
753
+ ):
754
+ transformer_options["block_index"] = it_
755
+ x = block(
756
+ x,
757
+ context=spatial_context,
758
+ transformer_options=transformer_options,
759
+ )
760
+
761
+ x_mix = x
762
+ x_mix = x_mix + emb
763
+
764
+ B, S, C = x_mix.shape
765
+ x_mix = rearrange(x_mix, "(b t) s c -> (b s) t c", t=timesteps)
766
+ x_mix = mix_block(x_mix, context=time_context) #TODO: transformer_options
767
+ x_mix = rearrange(
768
+ x_mix, "(b s) t c -> (b t) s c", s=S, b=B // timesteps, c=C, t=timesteps
769
+ )
770
+
771
+ x = self.time_mixer(x_spatial=x, x_temporal=x_mix, image_only_indicator=image_only_indicator)
772
+
773
+ if self.use_linear:
774
+ x = self.proj_out(x)
775
+ x = rearrange(x, "b (h w) c -> b c h w", h=h, w=w)
776
+ if not self.use_linear:
777
+ x = self.proj_out(x)
778
+ out = x + x_in
779
+ return out
780
+
781
+
comfy/ldm/modules/diffusionmodules/__init__.py ADDED
File without changes
comfy/ldm/modules/diffusionmodules/model.py ADDED
@@ -0,0 +1,650 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # pytorch_diffusion + derived encoder decoder
2
+ import math
3
+ import torch
4
+ import torch.nn as nn
5
+ import numpy as np
6
+ from einops import rearrange
7
+ from typing import Optional, Any
8
+
9
+ from comfy import model_management
10
+ import comfy.ops
11
+ ops = comfy.ops.disable_weight_init
12
+
13
+ if model_management.xformers_enabled_vae():
14
+ import xformers
15
+ import xformers.ops
16
+
17
+ def get_timestep_embedding(timesteps, embedding_dim):
18
+ """
19
+ This matches the implementation in Denoising Diffusion Probabilistic Models:
20
+ From Fairseq.
21
+ Build sinusoidal embeddings.
22
+ This matches the implementation in tensor2tensor, but differs slightly
23
+ from the description in Section 3.5 of "Attention Is All You Need".
24
+ """
25
+ assert len(timesteps.shape) == 1
26
+
27
+ half_dim = embedding_dim // 2
28
+ emb = math.log(10000) / (half_dim - 1)
29
+ emb = torch.exp(torch.arange(half_dim, dtype=torch.float32) * -emb)
30
+ emb = emb.to(device=timesteps.device)
31
+ emb = timesteps.float()[:, None] * emb[None, :]
32
+ emb = torch.cat([torch.sin(emb), torch.cos(emb)], dim=1)
33
+ if embedding_dim % 2 == 1: # zero pad
34
+ emb = torch.nn.functional.pad(emb, (0,1,0,0))
35
+ return emb
36
+
37
+
38
+ def nonlinearity(x):
39
+ # swish
40
+ return x*torch.sigmoid(x)
41
+
42
+
43
+ def Normalize(in_channels, num_groups=32):
44
+ return ops.GroupNorm(num_groups=num_groups, num_channels=in_channels, eps=1e-6, affine=True)
45
+
46
+
47
+ class Upsample(nn.Module):
48
+ def __init__(self, in_channels, with_conv):
49
+ super().__init__()
50
+ self.with_conv = with_conv
51
+ if self.with_conv:
52
+ self.conv = ops.Conv2d(in_channels,
53
+ in_channels,
54
+ kernel_size=3,
55
+ stride=1,
56
+ padding=1)
57
+
58
+ def forward(self, x):
59
+ try:
60
+ x = torch.nn.functional.interpolate(x, scale_factor=2.0, mode="nearest")
61
+ except: #operation not implemented for bf16
62
+ b, c, h, w = x.shape
63
+ out = torch.empty((b, c, h*2, w*2), dtype=x.dtype, layout=x.layout, device=x.device)
64
+ split = 8
65
+ l = out.shape[1] // split
66
+ for i in range(0, out.shape[1], l):
67
+ out[:,i:i+l] = torch.nn.functional.interpolate(x[:,i:i+l].to(torch.float32), scale_factor=2.0, mode="nearest").to(x.dtype)
68
+ del x
69
+ x = out
70
+
71
+ if self.with_conv:
72
+ x = self.conv(x)
73
+ return x
74
+
75
+
76
+ class Downsample(nn.Module):
77
+ def __init__(self, in_channels, with_conv):
78
+ super().__init__()
79
+ self.with_conv = with_conv
80
+ if self.with_conv:
81
+ # no asymmetric padding in torch conv, must do it ourselves
82
+ self.conv = ops.Conv2d(in_channels,
83
+ in_channels,
84
+ kernel_size=3,
85
+ stride=2,
86
+ padding=0)
87
+
88
+ def forward(self, x):
89
+ if self.with_conv:
90
+ pad = (0,1,0,1)
91
+ x = torch.nn.functional.pad(x, pad, mode="constant", value=0)
92
+ x = self.conv(x)
93
+ else:
94
+ x = torch.nn.functional.avg_pool2d(x, kernel_size=2, stride=2)
95
+ return x
96
+
97
+
98
+ class ResnetBlock(nn.Module):
99
+ def __init__(self, *, in_channels, out_channels=None, conv_shortcut=False,
100
+ dropout, temb_channels=512):
101
+ super().__init__()
102
+ self.in_channels = in_channels
103
+ out_channels = in_channels if out_channels is None else out_channels
104
+ self.out_channels = out_channels
105
+ self.use_conv_shortcut = conv_shortcut
106
+
107
+ self.swish = torch.nn.SiLU(inplace=True)
108
+ self.norm1 = Normalize(in_channels)
109
+ self.conv1 = ops.Conv2d(in_channels,
110
+ out_channels,
111
+ kernel_size=3,
112
+ stride=1,
113
+ padding=1)
114
+ if temb_channels > 0:
115
+ self.temb_proj = ops.Linear(temb_channels,
116
+ out_channels)
117
+ self.norm2 = Normalize(out_channels)
118
+ self.dropout = torch.nn.Dropout(dropout, inplace=True)
119
+ self.conv2 = ops.Conv2d(out_channels,
120
+ out_channels,
121
+ kernel_size=3,
122
+ stride=1,
123
+ padding=1)
124
+ if self.in_channels != self.out_channels:
125
+ if self.use_conv_shortcut:
126
+ self.conv_shortcut = ops.Conv2d(in_channels,
127
+ out_channels,
128
+ kernel_size=3,
129
+ stride=1,
130
+ padding=1)
131
+ else:
132
+ self.nin_shortcut = ops.Conv2d(in_channels,
133
+ out_channels,
134
+ kernel_size=1,
135
+ stride=1,
136
+ padding=0)
137
+
138
+ def forward(self, x, temb):
139
+ h = x
140
+ h = self.norm1(h)
141
+ h = self.swish(h)
142
+ h = self.conv1(h)
143
+
144
+ if temb is not None:
145
+ h = h + self.temb_proj(self.swish(temb))[:,:,None,None]
146
+
147
+ h = self.norm2(h)
148
+ h = self.swish(h)
149
+ h = self.dropout(h)
150
+ h = self.conv2(h)
151
+
152
+ if self.in_channels != self.out_channels:
153
+ if self.use_conv_shortcut:
154
+ x = self.conv_shortcut(x)
155
+ else:
156
+ x = self.nin_shortcut(x)
157
+
158
+ return x+h
159
+
160
+ def slice_attention(q, k, v):
161
+ r1 = torch.zeros_like(k, device=q.device)
162
+ scale = (int(q.shape[-1])**(-0.5))
163
+
164
+ mem_free_total = model_management.get_free_memory(q.device)
165
+
166
+ gb = 1024 ** 3
167
+ tensor_size = q.shape[0] * q.shape[1] * k.shape[2] * q.element_size()
168
+ modifier = 3 if q.element_size() == 2 else 2.5
169
+ mem_required = tensor_size * modifier
170
+ steps = 1
171
+
172
+ if mem_required > mem_free_total:
173
+ steps = 2**(math.ceil(math.log(mem_required / mem_free_total, 2)))
174
+
175
+ while True:
176
+ try:
177
+ slice_size = q.shape[1] // steps if (q.shape[1] % steps) == 0 else q.shape[1]
178
+ for i in range(0, q.shape[1], slice_size):
179
+ end = i + slice_size
180
+ s1 = torch.bmm(q[:, i:end], k) * scale
181
+
182
+ s2 = torch.nn.functional.softmax(s1, dim=2).permute(0,2,1)
183
+ del s1
184
+
185
+ r1[:, :, i:end] = torch.bmm(v, s2)
186
+ del s2
187
+ break
188
+ except model_management.OOM_EXCEPTION as e:
189
+ model_management.soft_empty_cache(True)
190
+ steps *= 2
191
+ if steps > 128:
192
+ raise e
193
+ print("out of memory error, increasing steps and trying again", steps)
194
+
195
+ return r1
196
+
197
+ def normal_attention(q, k, v):
198
+ # compute attention
199
+ b,c,h,w = q.shape
200
+
201
+ q = q.reshape(b,c,h*w)
202
+ q = q.permute(0,2,1) # b,hw,c
203
+ k = k.reshape(b,c,h*w) # b,c,hw
204
+ v = v.reshape(b,c,h*w)
205
+
206
+ r1 = slice_attention(q, k, v)
207
+ h_ = r1.reshape(b,c,h,w)
208
+ del r1
209
+ return h_
210
+
211
+ def xformers_attention(q, k, v):
212
+ # compute attention
213
+ B, C, H, W = q.shape
214
+ q, k, v = map(
215
+ lambda t: t.view(B, C, -1).transpose(1, 2).contiguous(),
216
+ (q, k, v),
217
+ )
218
+
219
+ try:
220
+ out = xformers.ops.memory_efficient_attention(q, k, v, attn_bias=None)
221
+ out = out.transpose(1, 2).reshape(B, C, H, W)
222
+ except NotImplementedError as e:
223
+ out = slice_attention(q.view(B, -1, C), k.view(B, -1, C).transpose(1, 2), v.view(B, -1, C).transpose(1, 2)).reshape(B, C, H, W)
224
+ return out
225
+
226
+ def pytorch_attention(q, k, v):
227
+ # compute attention
228
+ B, C, H, W = q.shape
229
+ q, k, v = map(
230
+ lambda t: t.view(B, 1, C, -1).transpose(2, 3).contiguous(),
231
+ (q, k, v),
232
+ )
233
+
234
+ try:
235
+ out = torch.nn.functional.scaled_dot_product_attention(q, k, v, attn_mask=None, dropout_p=0.0, is_causal=False)
236
+ out = out.transpose(2, 3).reshape(B, C, H, W)
237
+ except model_management.OOM_EXCEPTION as e:
238
+ print("scaled_dot_product_attention OOMed: switched to slice attention")
239
+ out = slice_attention(q.view(B, -1, C), k.view(B, -1, C).transpose(1, 2), v.view(B, -1, C).transpose(1, 2)).reshape(B, C, H, W)
240
+ return out
241
+
242
+
243
+ class AttnBlock(nn.Module):
244
+ def __init__(self, in_channels):
245
+ super().__init__()
246
+ self.in_channels = in_channels
247
+
248
+ self.norm = Normalize(in_channels)
249
+ self.q = ops.Conv2d(in_channels,
250
+ in_channels,
251
+ kernel_size=1,
252
+ stride=1,
253
+ padding=0)
254
+ self.k = ops.Conv2d(in_channels,
255
+ in_channels,
256
+ kernel_size=1,
257
+ stride=1,
258
+ padding=0)
259
+ self.v = ops.Conv2d(in_channels,
260
+ in_channels,
261
+ kernel_size=1,
262
+ stride=1,
263
+ padding=0)
264
+ self.proj_out = ops.Conv2d(in_channels,
265
+ in_channels,
266
+ kernel_size=1,
267
+ stride=1,
268
+ padding=0)
269
+
270
+ if model_management.xformers_enabled_vae():
271
+ print("Using xformers attention in VAE")
272
+ self.optimized_attention = xformers_attention
273
+ elif model_management.pytorch_attention_enabled():
274
+ print("Using pytorch attention in VAE")
275
+ self.optimized_attention = pytorch_attention
276
+ else:
277
+ print("Using split attention in VAE")
278
+ self.optimized_attention = normal_attention
279
+
280
+ def forward(self, x):
281
+ h_ = x
282
+ h_ = self.norm(h_)
283
+ q = self.q(h_)
284
+ k = self.k(h_)
285
+ v = self.v(h_)
286
+
287
+ h_ = self.optimized_attention(q, k, v)
288
+
289
+ h_ = self.proj_out(h_)
290
+
291
+ return x+h_
292
+
293
+
294
+ def make_attn(in_channels, attn_type="vanilla", attn_kwargs=None):
295
+ return AttnBlock(in_channels)
296
+
297
+
298
+ class Model(nn.Module):
299
+ def __init__(self, *, ch, out_ch, ch_mult=(1,2,4,8), num_res_blocks,
300
+ attn_resolutions, dropout=0.0, resamp_with_conv=True, in_channels,
301
+ resolution, use_timestep=True, use_linear_attn=False, attn_type="vanilla"):
302
+ super().__init__()
303
+ if use_linear_attn: attn_type = "linear"
304
+ self.ch = ch
305
+ self.temb_ch = self.ch*4
306
+ self.num_resolutions = len(ch_mult)
307
+ self.num_res_blocks = num_res_blocks
308
+ self.resolution = resolution
309
+ self.in_channels = in_channels
310
+
311
+ self.use_timestep = use_timestep
312
+ if self.use_timestep:
313
+ # timestep embedding
314
+ self.temb = nn.Module()
315
+ self.temb.dense = nn.ModuleList([
316
+ ops.Linear(self.ch,
317
+ self.temb_ch),
318
+ ops.Linear(self.temb_ch,
319
+ self.temb_ch),
320
+ ])
321
+
322
+ # downsampling
323
+ self.conv_in = ops.Conv2d(in_channels,
324
+ self.ch,
325
+ kernel_size=3,
326
+ stride=1,
327
+ padding=1)
328
+
329
+ curr_res = resolution
330
+ in_ch_mult = (1,)+tuple(ch_mult)
331
+ self.down = nn.ModuleList()
332
+ for i_level in range(self.num_resolutions):
333
+ block = nn.ModuleList()
334
+ attn = nn.ModuleList()
335
+ block_in = ch*in_ch_mult[i_level]
336
+ block_out = ch*ch_mult[i_level]
337
+ for i_block in range(self.num_res_blocks):
338
+ block.append(ResnetBlock(in_channels=block_in,
339
+ out_channels=block_out,
340
+ temb_channels=self.temb_ch,
341
+ dropout=dropout))
342
+ block_in = block_out
343
+ if curr_res in attn_resolutions:
344
+ attn.append(make_attn(block_in, attn_type=attn_type))
345
+ down = nn.Module()
346
+ down.block = block
347
+ down.attn = attn
348
+ if i_level != self.num_resolutions-1:
349
+ down.downsample = Downsample(block_in, resamp_with_conv)
350
+ curr_res = curr_res // 2
351
+ self.down.append(down)
352
+
353
+ # middle
354
+ self.mid = nn.Module()
355
+ self.mid.block_1 = ResnetBlock(in_channels=block_in,
356
+ out_channels=block_in,
357
+ temb_channels=self.temb_ch,
358
+ dropout=dropout)
359
+ self.mid.attn_1 = make_attn(block_in, attn_type=attn_type)
360
+ self.mid.block_2 = ResnetBlock(in_channels=block_in,
361
+ out_channels=block_in,
362
+ temb_channels=self.temb_ch,
363
+ dropout=dropout)
364
+
365
+ # upsampling
366
+ self.up = nn.ModuleList()
367
+ for i_level in reversed(range(self.num_resolutions)):
368
+ block = nn.ModuleList()
369
+ attn = nn.ModuleList()
370
+ block_out = ch*ch_mult[i_level]
371
+ skip_in = ch*ch_mult[i_level]
372
+ for i_block in range(self.num_res_blocks+1):
373
+ if i_block == self.num_res_blocks:
374
+ skip_in = ch*in_ch_mult[i_level]
375
+ block.append(ResnetBlock(in_channels=block_in+skip_in,
376
+ out_channels=block_out,
377
+ temb_channels=self.temb_ch,
378
+ dropout=dropout))
379
+ block_in = block_out
380
+ if curr_res in attn_resolutions:
381
+ attn.append(make_attn(block_in, attn_type=attn_type))
382
+ up = nn.Module()
383
+ up.block = block
384
+ up.attn = attn
385
+ if i_level != 0:
386
+ up.upsample = Upsample(block_in, resamp_with_conv)
387
+ curr_res = curr_res * 2
388
+ self.up.insert(0, up) # prepend to get consistent order
389
+
390
+ # end
391
+ self.norm_out = Normalize(block_in)
392
+ self.conv_out = ops.Conv2d(block_in,
393
+ out_ch,
394
+ kernel_size=3,
395
+ stride=1,
396
+ padding=1)
397
+
398
+ def forward(self, x, t=None, context=None):
399
+ #assert x.shape[2] == x.shape[3] == self.resolution
400
+ if context is not None:
401
+ # assume aligned context, cat along channel axis
402
+ x = torch.cat((x, context), dim=1)
403
+ if self.use_timestep:
404
+ # timestep embedding
405
+ assert t is not None
406
+ temb = get_timestep_embedding(t, self.ch)
407
+ temb = self.temb.dense[0](temb)
408
+ temb = nonlinearity(temb)
409
+ temb = self.temb.dense[1](temb)
410
+ else:
411
+ temb = None
412
+
413
+ # downsampling
414
+ hs = [self.conv_in(x)]
415
+ for i_level in range(self.num_resolutions):
416
+ for i_block in range(self.num_res_blocks):
417
+ h = self.down[i_level].block[i_block](hs[-1], temb)
418
+ if len(self.down[i_level].attn) > 0:
419
+ h = self.down[i_level].attn[i_block](h)
420
+ hs.append(h)
421
+ if i_level != self.num_resolutions-1:
422
+ hs.append(self.down[i_level].downsample(hs[-1]))
423
+
424
+ # middle
425
+ h = hs[-1]
426
+ h = self.mid.block_1(h, temb)
427
+ h = self.mid.attn_1(h)
428
+ h = self.mid.block_2(h, temb)
429
+
430
+ # upsampling
431
+ for i_level in reversed(range(self.num_resolutions)):
432
+ for i_block in range(self.num_res_blocks+1):
433
+ h = self.up[i_level].block[i_block](
434
+ torch.cat([h, hs.pop()], dim=1), temb)
435
+ if len(self.up[i_level].attn) > 0:
436
+ h = self.up[i_level].attn[i_block](h)
437
+ if i_level != 0:
438
+ h = self.up[i_level].upsample(h)
439
+
440
+ # end
441
+ h = self.norm_out(h)
442
+ h = nonlinearity(h)
443
+ h = self.conv_out(h)
444
+ return h
445
+
446
+ def get_last_layer(self):
447
+ return self.conv_out.weight
448
+
449
+
450
+ class Encoder(nn.Module):
451
+ def __init__(self, *, ch, out_ch, ch_mult=(1,2,4,8), num_res_blocks,
452
+ attn_resolutions, dropout=0.0, resamp_with_conv=True, in_channels,
453
+ resolution, z_channels, double_z=True, use_linear_attn=False, attn_type="vanilla",
454
+ **ignore_kwargs):
455
+ super().__init__()
456
+ if use_linear_attn: attn_type = "linear"
457
+ self.ch = ch
458
+ self.temb_ch = 0
459
+ self.num_resolutions = len(ch_mult)
460
+ self.num_res_blocks = num_res_blocks
461
+ self.resolution = resolution
462
+ self.in_channels = in_channels
463
+
464
+ # downsampling
465
+ self.conv_in = ops.Conv2d(in_channels,
466
+ self.ch,
467
+ kernel_size=3,
468
+ stride=1,
469
+ padding=1)
470
+
471
+ curr_res = resolution
472
+ in_ch_mult = (1,)+tuple(ch_mult)
473
+ self.in_ch_mult = in_ch_mult
474
+ self.down = nn.ModuleList()
475
+ for i_level in range(self.num_resolutions):
476
+ block = nn.ModuleList()
477
+ attn = nn.ModuleList()
478
+ block_in = ch*in_ch_mult[i_level]
479
+ block_out = ch*ch_mult[i_level]
480
+ for i_block in range(self.num_res_blocks):
481
+ block.append(ResnetBlock(in_channels=block_in,
482
+ out_channels=block_out,
483
+ temb_channels=self.temb_ch,
484
+ dropout=dropout))
485
+ block_in = block_out
486
+ if curr_res in attn_resolutions:
487
+ attn.append(make_attn(block_in, attn_type=attn_type))
488
+ down = nn.Module()
489
+ down.block = block
490
+ down.attn = attn
491
+ if i_level != self.num_resolutions-1:
492
+ down.downsample = Downsample(block_in, resamp_with_conv)
493
+ curr_res = curr_res // 2
494
+ self.down.append(down)
495
+
496
+ # middle
497
+ self.mid = nn.Module()
498
+ self.mid.block_1 = ResnetBlock(in_channels=block_in,
499
+ out_channels=block_in,
500
+ temb_channels=self.temb_ch,
501
+ dropout=dropout)
502
+ self.mid.attn_1 = make_attn(block_in, attn_type=attn_type)
503
+ self.mid.block_2 = ResnetBlock(in_channels=block_in,
504
+ out_channels=block_in,
505
+ temb_channels=self.temb_ch,
506
+ dropout=dropout)
507
+
508
+ # end
509
+ self.norm_out = Normalize(block_in)
510
+ self.conv_out = ops.Conv2d(block_in,
511
+ 2*z_channels if double_z else z_channels,
512
+ kernel_size=3,
513
+ stride=1,
514
+ padding=1)
515
+
516
+ def forward(self, x):
517
+ # timestep embedding
518
+ temb = None
519
+ # downsampling
520
+ h = self.conv_in(x)
521
+ for i_level in range(self.num_resolutions):
522
+ for i_block in range(self.num_res_blocks):
523
+ h = self.down[i_level].block[i_block](h, temb)
524
+ if len(self.down[i_level].attn) > 0:
525
+ h = self.down[i_level].attn[i_block](h)
526
+ if i_level != self.num_resolutions-1:
527
+ h = self.down[i_level].downsample(h)
528
+
529
+ # middle
530
+ h = self.mid.block_1(h, temb)
531
+ h = self.mid.attn_1(h)
532
+ h = self.mid.block_2(h, temb)
533
+
534
+ # end
535
+ h = self.norm_out(h)
536
+ h = nonlinearity(h)
537
+ h = self.conv_out(h)
538
+ return h
539
+
540
+
541
+ class Decoder(nn.Module):
542
+ def __init__(self, *, ch, out_ch, ch_mult=(1,2,4,8), num_res_blocks,
543
+ attn_resolutions, dropout=0.0, resamp_with_conv=True, in_channels,
544
+ resolution, z_channels, give_pre_end=False, tanh_out=False, use_linear_attn=False,
545
+ conv_out_op=ops.Conv2d,
546
+ resnet_op=ResnetBlock,
547
+ attn_op=AttnBlock,
548
+ **ignorekwargs):
549
+ super().__init__()
550
+ if use_linear_attn: attn_type = "linear"
551
+ self.ch = ch
552
+ self.temb_ch = 0
553
+ self.num_resolutions = len(ch_mult)
554
+ self.num_res_blocks = num_res_blocks
555
+ self.resolution = resolution
556
+ self.in_channels = in_channels
557
+ self.give_pre_end = give_pre_end
558
+ self.tanh_out = tanh_out
559
+
560
+ # compute in_ch_mult, block_in and curr_res at lowest res
561
+ in_ch_mult = (1,)+tuple(ch_mult)
562
+ block_in = ch*ch_mult[self.num_resolutions-1]
563
+ curr_res = resolution // 2**(self.num_resolutions-1)
564
+ self.z_shape = (1,z_channels,curr_res,curr_res)
565
+ print("Working with z of shape {} = {} dimensions.".format(
566
+ self.z_shape, np.prod(self.z_shape)))
567
+
568
+ # z to block_in
569
+ self.conv_in = ops.Conv2d(z_channels,
570
+ block_in,
571
+ kernel_size=3,
572
+ stride=1,
573
+ padding=1)
574
+
575
+ # middle
576
+ self.mid = nn.Module()
577
+ self.mid.block_1 = resnet_op(in_channels=block_in,
578
+ out_channels=block_in,
579
+ temb_channels=self.temb_ch,
580
+ dropout=dropout)
581
+ self.mid.attn_1 = attn_op(block_in)
582
+ self.mid.block_2 = resnet_op(in_channels=block_in,
583
+ out_channels=block_in,
584
+ temb_channels=self.temb_ch,
585
+ dropout=dropout)
586
+
587
+ # upsampling
588
+ self.up = nn.ModuleList()
589
+ for i_level in reversed(range(self.num_resolutions)):
590
+ block = nn.ModuleList()
591
+ attn = nn.ModuleList()
592
+ block_out = ch*ch_mult[i_level]
593
+ for i_block in range(self.num_res_blocks+1):
594
+ block.append(resnet_op(in_channels=block_in,
595
+ out_channels=block_out,
596
+ temb_channels=self.temb_ch,
597
+ dropout=dropout))
598
+ block_in = block_out
599
+ if curr_res in attn_resolutions:
600
+ attn.append(attn_op(block_in))
601
+ up = nn.Module()
602
+ up.block = block
603
+ up.attn = attn
604
+ if i_level != 0:
605
+ up.upsample = Upsample(block_in, resamp_with_conv)
606
+ curr_res = curr_res * 2
607
+ self.up.insert(0, up) # prepend to get consistent order
608
+
609
+ # end
610
+ self.norm_out = Normalize(block_in)
611
+ self.conv_out = conv_out_op(block_in,
612
+ out_ch,
613
+ kernel_size=3,
614
+ stride=1,
615
+ padding=1)
616
+
617
+ def forward(self, z, **kwargs):
618
+ #assert z.shape[1:] == self.z_shape[1:]
619
+ self.last_z_shape = z.shape
620
+
621
+ # timestep embedding
622
+ temb = None
623
+
624
+ # z to block_in
625
+ h = self.conv_in(z)
626
+
627
+ # middle
628
+ h = self.mid.block_1(h, temb, **kwargs)
629
+ h = self.mid.attn_1(h, **kwargs)
630
+ h = self.mid.block_2(h, temb, **kwargs)
631
+
632
+ # upsampling
633
+ for i_level in reversed(range(self.num_resolutions)):
634
+ for i_block in range(self.num_res_blocks+1):
635
+ h = self.up[i_level].block[i_block](h, temb, **kwargs)
636
+ if len(self.up[i_level].attn) > 0:
637
+ h = self.up[i_level].attn[i_block](h, **kwargs)
638
+ if i_level != 0:
639
+ h = self.up[i_level].upsample(h)
640
+
641
+ # end
642
+ if self.give_pre_end:
643
+ return h
644
+
645
+ h = self.norm_out(h)
646
+ h = nonlinearity(h)
647
+ h = self.conv_out(h, **kwargs)
648
+ if self.tanh_out:
649
+ h = torch.tanh(h)
650
+ return h
comfy/ldm/modules/diffusionmodules/openaimodel.py ADDED
@@ -0,0 +1,886 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from abc import abstractmethod
2
+
3
+ import torch as th
4
+ import torch.nn as nn
5
+ import torch.nn.functional as F
6
+ from einops import rearrange
7
+
8
+ from .util import (
9
+ checkpoint,
10
+ avg_pool_nd,
11
+ zero_module,
12
+ timestep_embedding,
13
+ AlphaBlender,
14
+ )
15
+ from ..attention import SpatialTransformer, SpatialVideoTransformer, default
16
+ from comfy.ldm.util import exists
17
+ import comfy.ops
18
+ ops = comfy.ops.disable_weight_init
19
+
20
+ class TimestepBlock(nn.Module):
21
+ """
22
+ Any module where forward() takes timestep embeddings as a second argument.
23
+ """
24
+
25
+ @abstractmethod
26
+ def forward(self, x, emb):
27
+ """
28
+ Apply the module to `x` given `emb` timestep embeddings.
29
+ """
30
+
31
+ #This is needed because accelerate makes a copy of transformer_options which breaks "transformer_index"
32
+ def forward_timestep_embed(ts, x, emb, context=None, transformer_options={}, output_shape=None, time_context=None, num_video_frames=None, image_only_indicator=None):
33
+ for layer in ts:
34
+ if isinstance(layer, VideoResBlock):
35
+ x = layer(x, emb, num_video_frames, image_only_indicator)
36
+ elif isinstance(layer, TimestepBlock):
37
+ x = layer(x, emb)
38
+ elif isinstance(layer, SpatialVideoTransformer):
39
+ x = layer(x, context, time_context, num_video_frames, image_only_indicator, transformer_options)
40
+ if "transformer_index" in transformer_options:
41
+ transformer_options["transformer_index"] += 1
42
+ elif isinstance(layer, SpatialTransformer):
43
+ x = layer(x, context, transformer_options)
44
+ if "transformer_index" in transformer_options:
45
+ transformer_options["transformer_index"] += 1
46
+ elif isinstance(layer, Upsample):
47
+ x = layer(x, output_shape=output_shape)
48
+ else:
49
+ x = layer(x)
50
+ return x
51
+
52
+ class TimestepEmbedSequential(nn.Sequential, TimestepBlock):
53
+ """
54
+ A sequential module that passes timestep embeddings to the children that
55
+ support it as an extra input.
56
+ """
57
+
58
+ def forward(self, *args, **kwargs):
59
+ return forward_timestep_embed(self, *args, **kwargs)
60
+
61
+ class Upsample(nn.Module):
62
+ """
63
+ An upsampling layer with an optional convolution.
64
+ :param channels: channels in the inputs and outputs.
65
+ :param use_conv: a bool determining if a convolution is applied.
66
+ :param dims: determines if the signal is 1D, 2D, or 3D. If 3D, then
67
+ upsampling occurs in the inner-two dimensions.
68
+ """
69
+
70
+ def __init__(self, channels, use_conv, dims=2, out_channels=None, padding=1, dtype=None, device=None, operations=ops):
71
+ super().__init__()
72
+ self.channels = channels
73
+ self.out_channels = out_channels or channels
74
+ self.use_conv = use_conv
75
+ self.dims = dims
76
+ if use_conv:
77
+ self.conv = operations.conv_nd(dims, self.channels, self.out_channels, 3, padding=padding, dtype=dtype, device=device)
78
+
79
+ def forward(self, x, output_shape=None):
80
+ assert x.shape[1] == self.channels
81
+ if self.dims == 3:
82
+ shape = [x.shape[2], x.shape[3] * 2, x.shape[4] * 2]
83
+ if output_shape is not None:
84
+ shape[1] = output_shape[3]
85
+ shape[2] = output_shape[4]
86
+ else:
87
+ shape = [x.shape[2] * 2, x.shape[3] * 2]
88
+ if output_shape is not None:
89
+ shape[0] = output_shape[2]
90
+ shape[1] = output_shape[3]
91
+
92
+ x = F.interpolate(x, size=shape, mode="nearest")
93
+ if self.use_conv:
94
+ x = self.conv(x)
95
+ return x
96
+
97
+ class Downsample(nn.Module):
98
+ """
99
+ A downsampling layer with an optional convolution.
100
+ :param channels: channels in the inputs and outputs.
101
+ :param use_conv: a bool determining if a convolution is applied.
102
+ :param dims: determines if the signal is 1D, 2D, or 3D. If 3D, then
103
+ downsampling occurs in the inner-two dimensions.
104
+ """
105
+
106
+ def __init__(self, channels, use_conv, dims=2, out_channels=None, padding=1, dtype=None, device=None, operations=ops):
107
+ super().__init__()
108
+ self.channels = channels
109
+ self.out_channels = out_channels or channels
110
+ self.use_conv = use_conv
111
+ self.dims = dims
112
+ stride = 2 if dims != 3 else (1, 2, 2)
113
+ if use_conv:
114
+ self.op = operations.conv_nd(
115
+ dims, self.channels, self.out_channels, 3, stride=stride, padding=padding, dtype=dtype, device=device
116
+ )
117
+ else:
118
+ assert self.channels == self.out_channels
119
+ self.op = avg_pool_nd(dims, kernel_size=stride, stride=stride)
120
+
121
+ def forward(self, x):
122
+ assert x.shape[1] == self.channels
123
+ return self.op(x)
124
+
125
+
126
+ class ResBlock(TimestepBlock):
127
+ """
128
+ A residual block that can optionally change the number of channels.
129
+ :param channels: the number of input channels.
130
+ :param emb_channels: the number of timestep embedding channels.
131
+ :param dropout: the rate of dropout.
132
+ :param out_channels: if specified, the number of out channels.
133
+ :param use_conv: if True and out_channels is specified, use a spatial
134
+ convolution instead of a smaller 1x1 convolution to change the
135
+ channels in the skip connection.
136
+ :param dims: determines if the signal is 1D, 2D, or 3D.
137
+ :param use_checkpoint: if True, use gradient checkpointing on this module.
138
+ :param up: if True, use this block for upsampling.
139
+ :param down: if True, use this block for downsampling.
140
+ """
141
+
142
+ def __init__(
143
+ self,
144
+ channels,
145
+ emb_channels,
146
+ dropout,
147
+ out_channels=None,
148
+ use_conv=False,
149
+ use_scale_shift_norm=False,
150
+ dims=2,
151
+ use_checkpoint=False,
152
+ up=False,
153
+ down=False,
154
+ kernel_size=3,
155
+ exchange_temb_dims=False,
156
+ skip_t_emb=False,
157
+ dtype=None,
158
+ device=None,
159
+ operations=ops
160
+ ):
161
+ super().__init__()
162
+ self.channels = channels
163
+ self.emb_channels = emb_channels
164
+ self.dropout = dropout
165
+ self.out_channels = out_channels or channels
166
+ self.use_conv = use_conv
167
+ self.use_checkpoint = use_checkpoint
168
+ self.use_scale_shift_norm = use_scale_shift_norm
169
+ self.exchange_temb_dims = exchange_temb_dims
170
+
171
+ if isinstance(kernel_size, list):
172
+ padding = [k // 2 for k in kernel_size]
173
+ else:
174
+ padding = kernel_size // 2
175
+
176
+ self.in_layers = nn.Sequential(
177
+ operations.GroupNorm(32, channels, dtype=dtype, device=device),
178
+ nn.SiLU(),
179
+ operations.conv_nd(dims, channels, self.out_channels, kernel_size, padding=padding, dtype=dtype, device=device),
180
+ )
181
+
182
+ self.updown = up or down
183
+
184
+ if up:
185
+ self.h_upd = Upsample(channels, False, dims, dtype=dtype, device=device)
186
+ self.x_upd = Upsample(channels, False, dims, dtype=dtype, device=device)
187
+ elif down:
188
+ self.h_upd = Downsample(channels, False, dims, dtype=dtype, device=device)
189
+ self.x_upd = Downsample(channels, False, dims, dtype=dtype, device=device)
190
+ else:
191
+ self.h_upd = self.x_upd = nn.Identity()
192
+
193
+ self.skip_t_emb = skip_t_emb
194
+ if self.skip_t_emb:
195
+ self.emb_layers = None
196
+ self.exchange_temb_dims = False
197
+ else:
198
+ self.emb_layers = nn.Sequential(
199
+ nn.SiLU(),
200
+ operations.Linear(
201
+ emb_channels,
202
+ 2 * self.out_channels if use_scale_shift_norm else self.out_channels, dtype=dtype, device=device
203
+ ),
204
+ )
205
+ self.out_layers = nn.Sequential(
206
+ operations.GroupNorm(32, self.out_channels, dtype=dtype, device=device),
207
+ nn.SiLU(),
208
+ nn.Dropout(p=dropout),
209
+ operations.conv_nd(dims, self.out_channels, self.out_channels, kernel_size, padding=padding, dtype=dtype, device=device)
210
+ ,
211
+ )
212
+
213
+ if self.out_channels == channels:
214
+ self.skip_connection = nn.Identity()
215
+ elif use_conv:
216
+ self.skip_connection = operations.conv_nd(
217
+ dims, channels, self.out_channels, kernel_size, padding=padding, dtype=dtype, device=device
218
+ )
219
+ else:
220
+ self.skip_connection = operations.conv_nd(dims, channels, self.out_channels, 1, dtype=dtype, device=device)
221
+
222
+ def forward(self, x, emb):
223
+ """
224
+ Apply the block to a Tensor, conditioned on a timestep embedding.
225
+ :param x: an [N x C x ...] Tensor of features.
226
+ :param emb: an [N x emb_channels] Tensor of timestep embeddings.
227
+ :return: an [N x C x ...] Tensor of outputs.
228
+ """
229
+ return checkpoint(
230
+ self._forward, (x, emb), self.parameters(), self.use_checkpoint
231
+ )
232
+
233
+
234
+ def _forward(self, x, emb):
235
+ if self.updown:
236
+ in_rest, in_conv = self.in_layers[:-1], self.in_layers[-1]
237
+ h = in_rest(x)
238
+ h = self.h_upd(h)
239
+ x = self.x_upd(x)
240
+ h = in_conv(h)
241
+ else:
242
+ h = self.in_layers(x)
243
+
244
+ emb_out = None
245
+ if not self.skip_t_emb:
246
+ emb_out = self.emb_layers(emb).type(h.dtype)
247
+ while len(emb_out.shape) < len(h.shape):
248
+ emb_out = emb_out[..., None]
249
+ if self.use_scale_shift_norm:
250
+ out_norm, out_rest = self.out_layers[0], self.out_layers[1:]
251
+ h = out_norm(h)
252
+ if emb_out is not None:
253
+ scale, shift = th.chunk(emb_out, 2, dim=1)
254
+ h *= (1 + scale)
255
+ h += shift
256
+ h = out_rest(h)
257
+ else:
258
+ if emb_out is not None:
259
+ if self.exchange_temb_dims:
260
+ emb_out = rearrange(emb_out, "b t c ... -> b c t ...")
261
+ h = h + emb_out
262
+ h = self.out_layers(h)
263
+ return self.skip_connection(x) + h
264
+
265
+
266
+ class VideoResBlock(ResBlock):
267
+ def __init__(
268
+ self,
269
+ channels: int,
270
+ emb_channels: int,
271
+ dropout: float,
272
+ video_kernel_size=3,
273
+ merge_strategy: str = "fixed",
274
+ merge_factor: float = 0.5,
275
+ out_channels=None,
276
+ use_conv: bool = False,
277
+ use_scale_shift_norm: bool = False,
278
+ dims: int = 2,
279
+ use_checkpoint: bool = False,
280
+ up: bool = False,
281
+ down: bool = False,
282
+ dtype=None,
283
+ device=None,
284
+ operations=ops
285
+ ):
286
+ super().__init__(
287
+ channels,
288
+ emb_channels,
289
+ dropout,
290
+ out_channels=out_channels,
291
+ use_conv=use_conv,
292
+ use_scale_shift_norm=use_scale_shift_norm,
293
+ dims=dims,
294
+ use_checkpoint=use_checkpoint,
295
+ up=up,
296
+ down=down,
297
+ dtype=dtype,
298
+ device=device,
299
+ operations=operations
300
+ )
301
+
302
+ self.time_stack = ResBlock(
303
+ default(out_channels, channels),
304
+ emb_channels,
305
+ dropout=dropout,
306
+ dims=3,
307
+ out_channels=default(out_channels, channels),
308
+ use_scale_shift_norm=False,
309
+ use_conv=False,
310
+ up=False,
311
+ down=False,
312
+ kernel_size=video_kernel_size,
313
+ use_checkpoint=use_checkpoint,
314
+ exchange_temb_dims=True,
315
+ dtype=dtype,
316
+ device=device,
317
+ operations=operations
318
+ )
319
+ self.time_mixer = AlphaBlender(
320
+ alpha=merge_factor,
321
+ merge_strategy=merge_strategy,
322
+ rearrange_pattern="b t -> b 1 t 1 1",
323
+ )
324
+
325
+ def forward(
326
+ self,
327
+ x: th.Tensor,
328
+ emb: th.Tensor,
329
+ num_video_frames: int,
330
+ image_only_indicator = None,
331
+ ) -> th.Tensor:
332
+ x = super().forward(x, emb)
333
+
334
+ x_mix = rearrange(x, "(b t) c h w -> b c t h w", t=num_video_frames)
335
+ x = rearrange(x, "(b t) c h w -> b c t h w", t=num_video_frames)
336
+
337
+ x = self.time_stack(
338
+ x, rearrange(emb, "(b t) ... -> b t ...", t=num_video_frames)
339
+ )
340
+ x = self.time_mixer(
341
+ x_spatial=x_mix, x_temporal=x, image_only_indicator=image_only_indicator
342
+ )
343
+ x = rearrange(x, "b c t h w -> (b t) c h w")
344
+ return x
345
+
346
+
347
+ class Timestep(nn.Module):
348
+ def __init__(self, dim):
349
+ super().__init__()
350
+ self.dim = dim
351
+
352
+ def forward(self, t):
353
+ return timestep_embedding(t, self.dim)
354
+
355
+ def apply_control(h, control, name):
356
+ if control is not None and name in control and len(control[name]) > 0:
357
+ ctrl = control[name].pop()
358
+ if ctrl is not None:
359
+ try:
360
+ h += ctrl
361
+ except:
362
+ print("warning control could not be applied", h.shape, ctrl.shape)
363
+ return h
364
+
365
+ class UNetModel(nn.Module):
366
+ """
367
+ The full UNet model with attention and timestep embedding.
368
+ :param in_channels: channels in the input Tensor.
369
+ :param model_channels: base channel count for the model.
370
+ :param out_channels: channels in the output Tensor.
371
+ :param num_res_blocks: number of residual blocks per downsample.
372
+ :param dropout: the dropout probability.
373
+ :param channel_mult: channel multiplier for each level of the UNet.
374
+ :param conv_resample: if True, use learned convolutions for upsampling and
375
+ downsampling.
376
+ :param dims: determines if the signal is 1D, 2D, or 3D.
377
+ :param num_classes: if specified (as an int), then this model will be
378
+ class-conditional with `num_classes` classes.
379
+ :param use_checkpoint: use gradient checkpointing to reduce memory usage.
380
+ :param num_heads: the number of attention heads in each attention layer.
381
+ :param num_heads_channels: if specified, ignore num_heads and instead use
382
+ a fixed channel width per attention head.
383
+ :param num_heads_upsample: works with num_heads to set a different number
384
+ of heads for upsampling. Deprecated.
385
+ :param use_scale_shift_norm: use a FiLM-like conditioning mechanism.
386
+ :param resblock_updown: use residual blocks for up/downsampling.
387
+ :param use_new_attention_order: use a different attention pattern for potentially
388
+ increased efficiency.
389
+ """
390
+
391
+ def __init__(
392
+ self,
393
+ image_size,
394
+ in_channels,
395
+ model_channels,
396
+ out_channels,
397
+ num_res_blocks,
398
+ dropout=0,
399
+ channel_mult=(1, 2, 4, 8),
400
+ conv_resample=True,
401
+ dims=2,
402
+ num_classes=None,
403
+ use_checkpoint=False,
404
+ dtype=th.float32,
405
+ num_heads=-1,
406
+ num_head_channels=-1,
407
+ num_heads_upsample=-1,
408
+ use_scale_shift_norm=False,
409
+ resblock_updown=False,
410
+ use_new_attention_order=False,
411
+ use_spatial_transformer=False, # custom transformer support
412
+ transformer_depth=1, # custom transformer support
413
+ context_dim=None, # custom transformer support
414
+ n_embed=None, # custom support for prediction of discrete ids into codebook of first stage vq model
415
+ legacy=True,
416
+ disable_self_attentions=None,
417
+ num_attention_blocks=None,
418
+ disable_middle_self_attn=False,
419
+ use_linear_in_transformer=False,
420
+ adm_in_channels=None,
421
+ transformer_depth_middle=None,
422
+ transformer_depth_output=None,
423
+ use_temporal_resblock=False,
424
+ use_temporal_attention=False,
425
+ time_context_dim=None,
426
+ extra_ff_mix_layer=False,
427
+ use_spatial_context=False,
428
+ merge_strategy=None,
429
+ merge_factor=0.0,
430
+ video_kernel_size=None,
431
+ disable_temporal_crossattention=False,
432
+ max_ddpm_temb_period=10000,
433
+ device=None,
434
+ operations=ops,
435
+ ):
436
+ super().__init__()
437
+
438
+ if context_dim is not None:
439
+ assert use_spatial_transformer, 'Fool!! You forgot to use the spatial transformer for your cross-attention conditioning...'
440
+ # from omegaconf.listconfig import ListConfig
441
+ # if type(context_dim) == ListConfig:
442
+ # context_dim = list(context_dim)
443
+
444
+ if num_heads_upsample == -1:
445
+ num_heads_upsample = num_heads
446
+
447
+ if num_heads == -1:
448
+ assert num_head_channels != -1, 'Either num_heads or num_head_channels has to be set'
449
+
450
+ if num_head_channels == -1:
451
+ assert num_heads != -1, 'Either num_heads or num_head_channels has to be set'
452
+
453
+ self.in_channels = in_channels
454
+ self.model_channels = model_channels
455
+ self.out_channels = out_channels
456
+
457
+ if isinstance(num_res_blocks, int):
458
+ self.num_res_blocks = len(channel_mult) * [num_res_blocks]
459
+ else:
460
+ if len(num_res_blocks) != len(channel_mult):
461
+ raise ValueError("provide num_res_blocks either as an int (globally constant) or "
462
+ "as a list/tuple (per-level) with the same length as channel_mult")
463
+ self.num_res_blocks = num_res_blocks
464
+
465
+ if disable_self_attentions is not None:
466
+ # should be a list of booleans, indicating whether to disable self-attention in TransformerBlocks or not
467
+ assert len(disable_self_attentions) == len(channel_mult)
468
+ if num_attention_blocks is not None:
469
+ assert len(num_attention_blocks) == len(self.num_res_blocks)
470
+
471
+ transformer_depth = transformer_depth[:]
472
+ transformer_depth_output = transformer_depth_output[:]
473
+
474
+ self.dropout = dropout
475
+ self.channel_mult = channel_mult
476
+ self.conv_resample = conv_resample
477
+ self.num_classes = num_classes
478
+ self.use_checkpoint = use_checkpoint
479
+ self.dtype = dtype
480
+ self.num_heads = num_heads
481
+ self.num_head_channels = num_head_channels
482
+ self.num_heads_upsample = num_heads_upsample
483
+ self.use_temporal_resblocks = use_temporal_resblock
484
+ self.predict_codebook_ids = n_embed is not None
485
+
486
+ self.default_num_video_frames = None
487
+ self.default_image_only_indicator = None
488
+
489
+ time_embed_dim = model_channels * 4
490
+ self.time_embed = nn.Sequential(
491
+ operations.Linear(model_channels, time_embed_dim, dtype=self.dtype, device=device),
492
+ nn.SiLU(),
493
+ operations.Linear(time_embed_dim, time_embed_dim, dtype=self.dtype, device=device),
494
+ )
495
+
496
+ if self.num_classes is not None:
497
+ if isinstance(self.num_classes, int):
498
+ self.label_emb = nn.Embedding(num_classes, time_embed_dim, dtype=self.dtype, device=device)
499
+ elif self.num_classes == "continuous":
500
+ print("setting up linear c_adm embedding layer")
501
+ self.label_emb = nn.Linear(1, time_embed_dim)
502
+ elif self.num_classes == "sequential":
503
+ assert adm_in_channels is not None
504
+ self.label_emb = nn.Sequential(
505
+ nn.Sequential(
506
+ operations.Linear(adm_in_channels, time_embed_dim, dtype=self.dtype, device=device),
507
+ nn.SiLU(),
508
+ operations.Linear(time_embed_dim, time_embed_dim, dtype=self.dtype, device=device),
509
+ )
510
+ )
511
+ else:
512
+ raise ValueError()
513
+
514
+ self.input_blocks = nn.ModuleList(
515
+ [
516
+ TimestepEmbedSequential(
517
+ operations.conv_nd(dims, in_channels, model_channels, 3, padding=1, dtype=self.dtype, device=device)
518
+ )
519
+ ]
520
+ )
521
+ self._feature_size = model_channels
522
+ input_block_chans = [model_channels]
523
+ ch = model_channels
524
+ ds = 1
525
+
526
+ def get_attention_layer(
527
+ ch,
528
+ num_heads,
529
+ dim_head,
530
+ depth=1,
531
+ context_dim=None,
532
+ use_checkpoint=False,
533
+ disable_self_attn=False,
534
+ ):
535
+ if use_temporal_attention:
536
+ return SpatialVideoTransformer(
537
+ ch,
538
+ num_heads,
539
+ dim_head,
540
+ depth=depth,
541
+ context_dim=context_dim,
542
+ time_context_dim=time_context_dim,
543
+ dropout=dropout,
544
+ ff_in=extra_ff_mix_layer,
545
+ use_spatial_context=use_spatial_context,
546
+ merge_strategy=merge_strategy,
547
+ merge_factor=merge_factor,
548
+ checkpoint=use_checkpoint,
549
+ use_linear=use_linear_in_transformer,
550
+ disable_self_attn=disable_self_attn,
551
+ disable_temporal_crossattention=disable_temporal_crossattention,
552
+ max_time_embed_period=max_ddpm_temb_period,
553
+ dtype=self.dtype, device=device, operations=operations
554
+ )
555
+ else:
556
+ return SpatialTransformer(
557
+ ch, num_heads, dim_head, depth=depth, context_dim=context_dim,
558
+ disable_self_attn=disable_self_attn, use_linear=use_linear_in_transformer,
559
+ use_checkpoint=use_checkpoint, dtype=self.dtype, device=device, operations=operations
560
+ )
561
+
562
+ def get_resblock(
563
+ merge_factor,
564
+ merge_strategy,
565
+ video_kernel_size,
566
+ ch,
567
+ time_embed_dim,
568
+ dropout,
569
+ out_channels,
570
+ dims,
571
+ use_checkpoint,
572
+ use_scale_shift_norm,
573
+ down=False,
574
+ up=False,
575
+ dtype=None,
576
+ device=None,
577
+ operations=ops
578
+ ):
579
+ if self.use_temporal_resblocks:
580
+ return VideoResBlock(
581
+ merge_factor=merge_factor,
582
+ merge_strategy=merge_strategy,
583
+ video_kernel_size=video_kernel_size,
584
+ channels=ch,
585
+ emb_channels=time_embed_dim,
586
+ dropout=dropout,
587
+ out_channels=out_channels,
588
+ dims=dims,
589
+ use_checkpoint=use_checkpoint,
590
+ use_scale_shift_norm=use_scale_shift_norm,
591
+ down=down,
592
+ up=up,
593
+ dtype=dtype,
594
+ device=device,
595
+ operations=operations
596
+ )
597
+ else:
598
+ return ResBlock(
599
+ channels=ch,
600
+ emb_channels=time_embed_dim,
601
+ dropout=dropout,
602
+ out_channels=out_channels,
603
+ use_checkpoint=use_checkpoint,
604
+ dims=dims,
605
+ use_scale_shift_norm=use_scale_shift_norm,
606
+ down=down,
607
+ up=up,
608
+ dtype=dtype,
609
+ device=device,
610
+ operations=operations
611
+ )
612
+
613
+ for level, mult in enumerate(channel_mult):
614
+ for nr in range(self.num_res_blocks[level]):
615
+ layers = [
616
+ get_resblock(
617
+ merge_factor=merge_factor,
618
+ merge_strategy=merge_strategy,
619
+ video_kernel_size=video_kernel_size,
620
+ ch=ch,
621
+ time_embed_dim=time_embed_dim,
622
+ dropout=dropout,
623
+ out_channels=mult * model_channels,
624
+ dims=dims,
625
+ use_checkpoint=use_checkpoint,
626
+ use_scale_shift_norm=use_scale_shift_norm,
627
+ dtype=self.dtype,
628
+ device=device,
629
+ operations=operations,
630
+ )
631
+ ]
632
+ ch = mult * model_channels
633
+ num_transformers = transformer_depth.pop(0)
634
+ if num_transformers > 0:
635
+ if num_head_channels == -1:
636
+ dim_head = ch // num_heads
637
+ else:
638
+ num_heads = ch // num_head_channels
639
+ dim_head = num_head_channels
640
+ if legacy:
641
+ #num_heads = 1
642
+ dim_head = ch // num_heads if use_spatial_transformer else num_head_channels
643
+ if exists(disable_self_attentions):
644
+ disabled_sa = disable_self_attentions[level]
645
+ else:
646
+ disabled_sa = False
647
+
648
+ if not exists(num_attention_blocks) or nr < num_attention_blocks[level]:
649
+ layers.append(get_attention_layer(
650
+ ch, num_heads, dim_head, depth=num_transformers, context_dim=context_dim,
651
+ disable_self_attn=disabled_sa, use_checkpoint=use_checkpoint)
652
+ )
653
+ self.input_blocks.append(TimestepEmbedSequential(*layers))
654
+ self._feature_size += ch
655
+ input_block_chans.append(ch)
656
+ if level != len(channel_mult) - 1:
657
+ out_ch = ch
658
+ self.input_blocks.append(
659
+ TimestepEmbedSequential(
660
+ get_resblock(
661
+ merge_factor=merge_factor,
662
+ merge_strategy=merge_strategy,
663
+ video_kernel_size=video_kernel_size,
664
+ ch=ch,
665
+ time_embed_dim=time_embed_dim,
666
+ dropout=dropout,
667
+ out_channels=out_ch,
668
+ dims=dims,
669
+ use_checkpoint=use_checkpoint,
670
+ use_scale_shift_norm=use_scale_shift_norm,
671
+ down=True,
672
+ dtype=self.dtype,
673
+ device=device,
674
+ operations=operations
675
+ )
676
+ if resblock_updown
677
+ else Downsample(
678
+ ch, conv_resample, dims=dims, out_channels=out_ch, dtype=self.dtype, device=device, operations=operations
679
+ )
680
+ )
681
+ )
682
+ ch = out_ch
683
+ input_block_chans.append(ch)
684
+ ds *= 2
685
+ self._feature_size += ch
686
+
687
+ if num_head_channels == -1:
688
+ dim_head = ch // num_heads
689
+ else:
690
+ num_heads = ch // num_head_channels
691
+ dim_head = num_head_channels
692
+ if legacy:
693
+ #num_heads = 1
694
+ dim_head = ch // num_heads if use_spatial_transformer else num_head_channels
695
+ mid_block = [
696
+ get_resblock(
697
+ merge_factor=merge_factor,
698
+ merge_strategy=merge_strategy,
699
+ video_kernel_size=video_kernel_size,
700
+ ch=ch,
701
+ time_embed_dim=time_embed_dim,
702
+ dropout=dropout,
703
+ out_channels=None,
704
+ dims=dims,
705
+ use_checkpoint=use_checkpoint,
706
+ use_scale_shift_norm=use_scale_shift_norm,
707
+ dtype=self.dtype,
708
+ device=device,
709
+ operations=operations
710
+ )]
711
+ if transformer_depth_middle >= 0:
712
+ mid_block += [get_attention_layer( # always uses a self-attn
713
+ ch, num_heads, dim_head, depth=transformer_depth_middle, context_dim=context_dim,
714
+ disable_self_attn=disable_middle_self_attn, use_checkpoint=use_checkpoint
715
+ ),
716
+ get_resblock(
717
+ merge_factor=merge_factor,
718
+ merge_strategy=merge_strategy,
719
+ video_kernel_size=video_kernel_size,
720
+ ch=ch,
721
+ time_embed_dim=time_embed_dim,
722
+ dropout=dropout,
723
+ out_channels=None,
724
+ dims=dims,
725
+ use_checkpoint=use_checkpoint,
726
+ use_scale_shift_norm=use_scale_shift_norm,
727
+ dtype=self.dtype,
728
+ device=device,
729
+ operations=operations
730
+ )]
731
+ self.middle_block = TimestepEmbedSequential(*mid_block)
732
+ self._feature_size += ch
733
+
734
+ self.output_blocks = nn.ModuleList([])
735
+ for level, mult in list(enumerate(channel_mult))[::-1]:
736
+ for i in range(self.num_res_blocks[level] + 1):
737
+ ich = input_block_chans.pop()
738
+ layers = [
739
+ get_resblock(
740
+ merge_factor=merge_factor,
741
+ merge_strategy=merge_strategy,
742
+ video_kernel_size=video_kernel_size,
743
+ ch=ch + ich,
744
+ time_embed_dim=time_embed_dim,
745
+ dropout=dropout,
746
+ out_channels=model_channels * mult,
747
+ dims=dims,
748
+ use_checkpoint=use_checkpoint,
749
+ use_scale_shift_norm=use_scale_shift_norm,
750
+ dtype=self.dtype,
751
+ device=device,
752
+ operations=operations
753
+ )
754
+ ]
755
+ ch = model_channels * mult
756
+ num_transformers = transformer_depth_output.pop()
757
+ if num_transformers > 0:
758
+ if num_head_channels == -1:
759
+ dim_head = ch // num_heads
760
+ else:
761
+ num_heads = ch // num_head_channels
762
+ dim_head = num_head_channels
763
+ if legacy:
764
+ #num_heads = 1
765
+ dim_head = ch // num_heads if use_spatial_transformer else num_head_channels
766
+ if exists(disable_self_attentions):
767
+ disabled_sa = disable_self_attentions[level]
768
+ else:
769
+ disabled_sa = False
770
+
771
+ if not exists(num_attention_blocks) or i < num_attention_blocks[level]:
772
+ layers.append(
773
+ get_attention_layer(
774
+ ch, num_heads, dim_head, depth=num_transformers, context_dim=context_dim,
775
+ disable_self_attn=disabled_sa, use_checkpoint=use_checkpoint
776
+ )
777
+ )
778
+ if level and i == self.num_res_blocks[level]:
779
+ out_ch = ch
780
+ layers.append(
781
+ get_resblock(
782
+ merge_factor=merge_factor,
783
+ merge_strategy=merge_strategy,
784
+ video_kernel_size=video_kernel_size,
785
+ ch=ch,
786
+ time_embed_dim=time_embed_dim,
787
+ dropout=dropout,
788
+ out_channels=out_ch,
789
+ dims=dims,
790
+ use_checkpoint=use_checkpoint,
791
+ use_scale_shift_norm=use_scale_shift_norm,
792
+ up=True,
793
+ dtype=self.dtype,
794
+ device=device,
795
+ operations=operations
796
+ )
797
+ if resblock_updown
798
+ else Upsample(ch, conv_resample, dims=dims, out_channels=out_ch, dtype=self.dtype, device=device, operations=operations)
799
+ )
800
+ ds //= 2
801
+ self.output_blocks.append(TimestepEmbedSequential(*layers))
802
+ self._feature_size += ch
803
+
804
+ self.out = nn.Sequential(
805
+ operations.GroupNorm(32, ch, dtype=self.dtype, device=device),
806
+ nn.SiLU(),
807
+ zero_module(operations.conv_nd(dims, model_channels, out_channels, 3, padding=1, dtype=self.dtype, device=device)),
808
+ )
809
+ if self.predict_codebook_ids:
810
+ self.id_predictor = nn.Sequential(
811
+ operations.GroupNorm(32, ch, dtype=self.dtype, device=device),
812
+ operations.conv_nd(dims, model_channels, n_embed, 1, dtype=self.dtype, device=device),
813
+ #nn.LogSoftmax(dim=1) # change to cross_entropy and produce non-normalized logits
814
+ )
815
+
816
+ def forward(self, x, timesteps=None, context=None, y=None, control=None, transformer_options={}, **kwargs):
817
+ """
818
+ Apply the model to an input batch.
819
+ :param x: an [N x C x ...] Tensor of inputs.
820
+ :param timesteps: a 1-D batch of timesteps.
821
+ :param context: conditioning plugged in via crossattn
822
+ :param y: an [N] Tensor of labels, if class-conditional.
823
+ :return: an [N x C x ...] Tensor of outputs.
824
+ """
825
+ transformer_options["original_shape"] = list(x.shape)
826
+ transformer_options["transformer_index"] = 0
827
+ transformer_patches = transformer_options.get("patches", {})
828
+
829
+ num_video_frames = kwargs.get("num_video_frames", self.default_num_video_frames)
830
+ image_only_indicator = kwargs.get("image_only_indicator", self.default_image_only_indicator)
831
+ time_context = kwargs.get("time_context", None)
832
+
833
+ assert (y is not None) == (
834
+ self.num_classes is not None
835
+ ), "must specify y if and only if the model is class-conditional"
836
+ hs = []
837
+ t_emb = timestep_embedding(timesteps, self.model_channels, repeat_only=False).to(x.dtype)
838
+ emb = self.time_embed(t_emb)
839
+
840
+ if self.num_classes is not None:
841
+ assert y.shape[0] == x.shape[0]
842
+ emb = emb + self.label_emb(y)
843
+
844
+ h = x
845
+ for id, module in enumerate(self.input_blocks):
846
+ transformer_options["block"] = ("input", id)
847
+ h = forward_timestep_embed(module, h, emb, context, transformer_options, time_context=time_context, num_video_frames=num_video_frames, image_only_indicator=image_only_indicator)
848
+ h = apply_control(h, control, 'input')
849
+ if "input_block_patch" in transformer_patches:
850
+ patch = transformer_patches["input_block_patch"]
851
+ for p in patch:
852
+ h = p(h, transformer_options)
853
+
854
+ hs.append(h)
855
+ if "input_block_patch_after_skip" in transformer_patches:
856
+ patch = transformer_patches["input_block_patch_after_skip"]
857
+ for p in patch:
858
+ h = p(h, transformer_options)
859
+
860
+ transformer_options["block"] = ("middle", 0)
861
+ h = forward_timestep_embed(self.middle_block, h, emb, context, transformer_options, time_context=time_context, num_video_frames=num_video_frames, image_only_indicator=image_only_indicator)
862
+ h = apply_control(h, control, 'middle')
863
+
864
+
865
+ for id, module in enumerate(self.output_blocks):
866
+ transformer_options["block"] = ("output", id)
867
+ hsp = hs.pop()
868
+ hsp = apply_control(hsp, control, 'output')
869
+
870
+ if "output_block_patch" in transformer_patches:
871
+ patch = transformer_patches["output_block_patch"]
872
+ for p in patch:
873
+ h, hsp = p(h, hsp, transformer_options)
874
+
875
+ h = th.cat([h, hsp], dim=1)
876
+ del hsp
877
+ if len(hs) > 0:
878
+ output_shape = hs[-1].shape
879
+ else:
880
+ output_shape = None
881
+ h = forward_timestep_embed(module, h, emb, context, transformer_options, output_shape, time_context=time_context, num_video_frames=num_video_frames, image_only_indicator=image_only_indicator)
882
+ h = h.type(x.dtype)
883
+ if self.predict_codebook_ids:
884
+ return self.id_predictor(h)
885
+ else:
886
+ return self.out(h)
comfy/ldm/modules/diffusionmodules/upscaling.py ADDED
@@ -0,0 +1,85 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ import numpy as np
4
+ from functools import partial
5
+
6
+ from .util import extract_into_tensor, make_beta_schedule
7
+ from comfy.ldm.util import default
8
+
9
+
10
+ class AbstractLowScaleModel(nn.Module):
11
+ # for concatenating a downsampled image to the latent representation
12
+ def __init__(self, noise_schedule_config=None):
13
+ super(AbstractLowScaleModel, self).__init__()
14
+ if noise_schedule_config is not None:
15
+ self.register_schedule(**noise_schedule_config)
16
+
17
+ def register_schedule(self, beta_schedule="linear", timesteps=1000,
18
+ linear_start=1e-4, linear_end=2e-2, cosine_s=8e-3):
19
+ betas = make_beta_schedule(beta_schedule, timesteps, linear_start=linear_start, linear_end=linear_end,
20
+ cosine_s=cosine_s)
21
+ alphas = 1. - betas
22
+ alphas_cumprod = np.cumprod(alphas, axis=0)
23
+ alphas_cumprod_prev = np.append(1., alphas_cumprod[:-1])
24
+
25
+ timesteps, = betas.shape
26
+ self.num_timesteps = int(timesteps)
27
+ self.linear_start = linear_start
28
+ self.linear_end = linear_end
29
+ assert alphas_cumprod.shape[0] == self.num_timesteps, 'alphas have to be defined for each timestep'
30
+
31
+ to_torch = partial(torch.tensor, dtype=torch.float32)
32
+
33
+ self.register_buffer('betas', to_torch(betas))
34
+ self.register_buffer('alphas_cumprod', to_torch(alphas_cumprod))
35
+ self.register_buffer('alphas_cumprod_prev', to_torch(alphas_cumprod_prev))
36
+
37
+ # calculations for diffusion q(x_t | x_{t-1}) and others
38
+ self.register_buffer('sqrt_alphas_cumprod', to_torch(np.sqrt(alphas_cumprod)))
39
+ self.register_buffer('sqrt_one_minus_alphas_cumprod', to_torch(np.sqrt(1. - alphas_cumprod)))
40
+ self.register_buffer('log_one_minus_alphas_cumprod', to_torch(np.log(1. - alphas_cumprod)))
41
+ self.register_buffer('sqrt_recip_alphas_cumprod', to_torch(np.sqrt(1. / alphas_cumprod)))
42
+ self.register_buffer('sqrt_recipm1_alphas_cumprod', to_torch(np.sqrt(1. / alphas_cumprod - 1)))
43
+
44
+ def q_sample(self, x_start, t, noise=None, seed=None):
45
+ if noise is None:
46
+ if seed is None:
47
+ noise = torch.randn_like(x_start)
48
+ else:
49
+ noise = torch.randn(x_start.size(), dtype=x_start.dtype, layout=x_start.layout, generator=torch.manual_seed(seed)).to(x_start.device)
50
+ return (extract_into_tensor(self.sqrt_alphas_cumprod.to(x_start.device), t, x_start.shape) * x_start +
51
+ extract_into_tensor(self.sqrt_one_minus_alphas_cumprod.to(x_start.device), t, x_start.shape) * noise)
52
+
53
+ def forward(self, x):
54
+ return x, None
55
+
56
+ def decode(self, x):
57
+ return x
58
+
59
+
60
+ class SimpleImageConcat(AbstractLowScaleModel):
61
+ # no noise level conditioning
62
+ def __init__(self):
63
+ super(SimpleImageConcat, self).__init__(noise_schedule_config=None)
64
+ self.max_noise_level = 0
65
+
66
+ def forward(self, x):
67
+ # fix to constant noise level
68
+ return x, torch.zeros(x.shape[0], device=x.device).long()
69
+
70
+
71
+ class ImageConcatWithNoiseAugmentation(AbstractLowScaleModel):
72
+ def __init__(self, noise_schedule_config, max_noise_level=1000, to_cuda=False):
73
+ super().__init__(noise_schedule_config=noise_schedule_config)
74
+ self.max_noise_level = max_noise_level
75
+
76
+ def forward(self, x, noise_level=None, seed=None):
77
+ if noise_level is None:
78
+ noise_level = torch.randint(0, self.max_noise_level, (x.shape[0],), device=x.device).long()
79
+ else:
80
+ assert isinstance(noise_level, torch.Tensor)
81
+ z = self.q_sample(x, noise_level, seed=seed)
82
+ return z, noise_level
83
+
84
+
85
+
comfy/ldm/modules/diffusionmodules/util.py ADDED
@@ -0,0 +1,304 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # adopted from
2
+ # https://github.com/openai/improved-diffusion/blob/main/improved_diffusion/gaussian_diffusion.py
3
+ # and
4
+ # https://github.com/lucidrains/denoising-diffusion-pytorch/blob/7706bdfc6f527f58d33f84b7b522e61e6e3164b3/denoising_diffusion_pytorch/denoising_diffusion_pytorch.py
5
+ # and
6
+ # https://github.com/openai/guided-diffusion/blob/0ba878e517b276c45d1195eb29f6f5f72659a05b/guided_diffusion/nn.py
7
+ #
8
+ # thanks!
9
+
10
+
11
+ import os
12
+ import math
13
+ import torch
14
+ import torch.nn as nn
15
+ import numpy as np
16
+ from einops import repeat, rearrange
17
+
18
+ from comfy.ldm.util import instantiate_from_config
19
+
20
+ class AlphaBlender(nn.Module):
21
+ strategies = ["learned", "fixed", "learned_with_images"]
22
+
23
+ def __init__(
24
+ self,
25
+ alpha: float,
26
+ merge_strategy: str = "learned_with_images",
27
+ rearrange_pattern: str = "b t -> (b t) 1 1",
28
+ ):
29
+ super().__init__()
30
+ self.merge_strategy = merge_strategy
31
+ self.rearrange_pattern = rearrange_pattern
32
+
33
+ assert (
34
+ merge_strategy in self.strategies
35
+ ), f"merge_strategy needs to be in {self.strategies}"
36
+
37
+ if self.merge_strategy == "fixed":
38
+ self.register_buffer("mix_factor", torch.Tensor([alpha]))
39
+ elif (
40
+ self.merge_strategy == "learned"
41
+ or self.merge_strategy == "learned_with_images"
42
+ ):
43
+ self.register_parameter(
44
+ "mix_factor", torch.nn.Parameter(torch.Tensor([alpha]))
45
+ )
46
+ else:
47
+ raise ValueError(f"unknown merge strategy {self.merge_strategy}")
48
+
49
+ def get_alpha(self, image_only_indicator: torch.Tensor) -> torch.Tensor:
50
+ # skip_time_mix = rearrange(repeat(skip_time_mix, 'b -> (b t) () () ()', t=t), '(b t) 1 ... -> b 1 t ...', t=t)
51
+ if self.merge_strategy == "fixed":
52
+ # make shape compatible
53
+ # alpha = repeat(self.mix_factor, '1 -> b () t () ()', t=t, b=bs)
54
+ alpha = self.mix_factor.to(image_only_indicator.device)
55
+ elif self.merge_strategy == "learned":
56
+ alpha = torch.sigmoid(self.mix_factor.to(image_only_indicator.device))
57
+ # make shape compatible
58
+ # alpha = repeat(alpha, '1 -> s () ()', s = t * bs)
59
+ elif self.merge_strategy == "learned_with_images":
60
+ assert image_only_indicator is not None, "need image_only_indicator ..."
61
+ alpha = torch.where(
62
+ image_only_indicator.bool(),
63
+ torch.ones(1, 1, device=image_only_indicator.device),
64
+ rearrange(torch.sigmoid(self.mix_factor.to(image_only_indicator.device)), "... -> ... 1"),
65
+ )
66
+ alpha = rearrange(alpha, self.rearrange_pattern)
67
+ # make shape compatible
68
+ # alpha = repeat(alpha, '1 -> s () ()', s = t * bs)
69
+ else:
70
+ raise NotImplementedError()
71
+ return alpha
72
+
73
+ def forward(
74
+ self,
75
+ x_spatial,
76
+ x_temporal,
77
+ image_only_indicator=None,
78
+ ) -> torch.Tensor:
79
+ alpha = self.get_alpha(image_only_indicator)
80
+ x = (
81
+ alpha.to(x_spatial.dtype) * x_spatial
82
+ + (1.0 - alpha).to(x_spatial.dtype) * x_temporal
83
+ )
84
+ return x
85
+
86
+
87
+ def make_beta_schedule(schedule, n_timestep, linear_start=1e-4, linear_end=2e-2, cosine_s=8e-3):
88
+ if schedule == "linear":
89
+ betas = (
90
+ torch.linspace(linear_start ** 0.5, linear_end ** 0.5, n_timestep, dtype=torch.float64) ** 2
91
+ )
92
+
93
+ elif schedule == "cosine":
94
+ timesteps = (
95
+ torch.arange(n_timestep + 1, dtype=torch.float64) / n_timestep + cosine_s
96
+ )
97
+ alphas = timesteps / (1 + cosine_s) * np.pi / 2
98
+ alphas = torch.cos(alphas).pow(2)
99
+ alphas = alphas / alphas[0]
100
+ betas = 1 - alphas[1:] / alphas[:-1]
101
+ betas = torch.clamp(betas, min=0, max=0.999)
102
+
103
+ elif schedule == "squaredcos_cap_v2": # used for karlo prior
104
+ # return early
105
+ return betas_for_alpha_bar(
106
+ n_timestep,
107
+ lambda t: math.cos((t + 0.008) / 1.008 * math.pi / 2) ** 2,
108
+ )
109
+
110
+ elif schedule == "sqrt_linear":
111
+ betas = torch.linspace(linear_start, linear_end, n_timestep, dtype=torch.float64)
112
+ elif schedule == "sqrt":
113
+ betas = torch.linspace(linear_start, linear_end, n_timestep, dtype=torch.float64) ** 0.5
114
+ else:
115
+ raise ValueError(f"schedule '{schedule}' unknown.")
116
+ return betas
117
+
118
+
119
+ def make_ddim_timesteps(ddim_discr_method, num_ddim_timesteps, num_ddpm_timesteps, verbose=True):
120
+ if ddim_discr_method == 'uniform':
121
+ c = num_ddpm_timesteps // num_ddim_timesteps
122
+ ddim_timesteps = np.asarray(list(range(0, num_ddpm_timesteps, c)))
123
+ elif ddim_discr_method == 'quad':
124
+ ddim_timesteps = ((np.linspace(0, np.sqrt(num_ddpm_timesteps * .8), num_ddim_timesteps)) ** 2).astype(int)
125
+ else:
126
+ raise NotImplementedError(f'There is no ddim discretization method called "{ddim_discr_method}"')
127
+
128
+ # assert ddim_timesteps.shape[0] == num_ddim_timesteps
129
+ # add one to get the final alpha values right (the ones from first scale to data during sampling)
130
+ steps_out = ddim_timesteps + 1
131
+ if verbose:
132
+ print(f'Selected timesteps for ddim sampler: {steps_out}')
133
+ return steps_out
134
+
135
+
136
+ def make_ddim_sampling_parameters(alphacums, ddim_timesteps, eta, verbose=True):
137
+ # select alphas for computing the variance schedule
138
+ alphas = alphacums[ddim_timesteps]
139
+ alphas_prev = np.asarray([alphacums[0]] + alphacums[ddim_timesteps[:-1]].tolist())
140
+
141
+ # according the the formula provided in https://arxiv.org/abs/2010.02502
142
+ sigmas = eta * np.sqrt((1 - alphas_prev) / (1 - alphas) * (1 - alphas / alphas_prev))
143
+ if verbose:
144
+ print(f'Selected alphas for ddim sampler: a_t: {alphas}; a_(t-1): {alphas_prev}')
145
+ print(f'For the chosen value of eta, which is {eta}, '
146
+ f'this results in the following sigma_t schedule for ddim sampler {sigmas}')
147
+ return sigmas, alphas, alphas_prev
148
+
149
+
150
+ def betas_for_alpha_bar(num_diffusion_timesteps, alpha_bar, max_beta=0.999):
151
+ """
152
+ Create a beta schedule that discretizes the given alpha_t_bar function,
153
+ which defines the cumulative product of (1-beta) over time from t = [0,1].
154
+ :param num_diffusion_timesteps: the number of betas to produce.
155
+ :param alpha_bar: a lambda that takes an argument t from 0 to 1 and
156
+ produces the cumulative product of (1-beta) up to that
157
+ part of the diffusion process.
158
+ :param max_beta: the maximum beta to use; use values lower than 1 to
159
+ prevent singularities.
160
+ """
161
+ betas = []
162
+ for i in range(num_diffusion_timesteps):
163
+ t1 = i / num_diffusion_timesteps
164
+ t2 = (i + 1) / num_diffusion_timesteps
165
+ betas.append(min(1 - alpha_bar(t2) / alpha_bar(t1), max_beta))
166
+ return np.array(betas)
167
+
168
+
169
+ def extract_into_tensor(a, t, x_shape):
170
+ b, *_ = t.shape
171
+ out = a.gather(-1, t)
172
+ return out.reshape(b, *((1,) * (len(x_shape) - 1)))
173
+
174
+
175
+ def checkpoint(func, inputs, params, flag):
176
+ """
177
+ Evaluate a function without caching intermediate activations, allowing for
178
+ reduced memory at the expense of extra compute in the backward pass.
179
+ :param func: the function to evaluate.
180
+ :param inputs: the argument sequence to pass to `func`.
181
+ :param params: a sequence of parameters `func` depends on but does not
182
+ explicitly take as arguments.
183
+ :param flag: if False, disable gradient checkpointing.
184
+ """
185
+ if flag:
186
+ args = tuple(inputs) + tuple(params)
187
+ return CheckpointFunction.apply(func, len(inputs), *args)
188
+ else:
189
+ return func(*inputs)
190
+
191
+
192
+ class CheckpointFunction(torch.autograd.Function):
193
+ @staticmethod
194
+ def forward(ctx, run_function, length, *args):
195
+ ctx.run_function = run_function
196
+ ctx.input_tensors = list(args[:length])
197
+ ctx.input_params = list(args[length:])
198
+ ctx.gpu_autocast_kwargs = {"enabled": torch.is_autocast_enabled(),
199
+ "dtype": torch.get_autocast_gpu_dtype(),
200
+ "cache_enabled": torch.is_autocast_cache_enabled()}
201
+ with torch.no_grad():
202
+ output_tensors = ctx.run_function(*ctx.input_tensors)
203
+ return output_tensors
204
+
205
+ @staticmethod
206
+ def backward(ctx, *output_grads):
207
+ ctx.input_tensors = [x.detach().requires_grad_(True) for x in ctx.input_tensors]
208
+ with torch.enable_grad(), \
209
+ torch.cuda.amp.autocast(**ctx.gpu_autocast_kwargs):
210
+ # Fixes a bug where the first op in run_function modifies the
211
+ # Tensor storage in place, which is not allowed for detach()'d
212
+ # Tensors.
213
+ shallow_copies = [x.view_as(x) for x in ctx.input_tensors]
214
+ output_tensors = ctx.run_function(*shallow_copies)
215
+ input_grads = torch.autograd.grad(
216
+ output_tensors,
217
+ ctx.input_tensors + ctx.input_params,
218
+ output_grads,
219
+ allow_unused=True,
220
+ )
221
+ del ctx.input_tensors
222
+ del ctx.input_params
223
+ del output_tensors
224
+ return (None, None) + input_grads
225
+
226
+
227
+ def timestep_embedding(timesteps, dim, max_period=10000, repeat_only=False):
228
+ """
229
+ Create sinusoidal timestep embeddings.
230
+ :param timesteps: a 1-D Tensor of N indices, one per batch element.
231
+ These may be fractional.
232
+ :param dim: the dimension of the output.
233
+ :param max_period: controls the minimum frequency of the embeddings.
234
+ :return: an [N x dim] Tensor of positional embeddings.
235
+ """
236
+ if not repeat_only:
237
+ half = dim // 2
238
+ freqs = torch.exp(
239
+ -math.log(max_period) * torch.arange(start=0, end=half, dtype=torch.float32, device=timesteps.device) / half
240
+ )
241
+ args = timesteps[:, None].float() * freqs[None]
242
+ embedding = torch.cat([torch.cos(args), torch.sin(args)], dim=-1)
243
+ if dim % 2:
244
+ embedding = torch.cat([embedding, torch.zeros_like(embedding[:, :1])], dim=-1)
245
+ else:
246
+ embedding = repeat(timesteps, 'b -> b d', d=dim)
247
+ return embedding
248
+
249
+
250
+ def zero_module(module):
251
+ """
252
+ Zero out the parameters of a module and return it.
253
+ """
254
+ for p in module.parameters():
255
+ p.detach().zero_()
256
+ return module
257
+
258
+
259
+ def scale_module(module, scale):
260
+ """
261
+ Scale the parameters of a module and return it.
262
+ """
263
+ for p in module.parameters():
264
+ p.detach().mul_(scale)
265
+ return module
266
+
267
+
268
+ def mean_flat(tensor):
269
+ """
270
+ Take the mean over all non-batch dimensions.
271
+ """
272
+ return tensor.mean(dim=list(range(1, len(tensor.shape))))
273
+
274
+
275
+ def avg_pool_nd(dims, *args, **kwargs):
276
+ """
277
+ Create a 1D, 2D, or 3D average pooling module.
278
+ """
279
+ if dims == 1:
280
+ return nn.AvgPool1d(*args, **kwargs)
281
+ elif dims == 2:
282
+ return nn.AvgPool2d(*args, **kwargs)
283
+ elif dims == 3:
284
+ return nn.AvgPool3d(*args, **kwargs)
285
+ raise ValueError(f"unsupported dimensions: {dims}")
286
+
287
+
288
+ class HybridConditioner(nn.Module):
289
+
290
+ def __init__(self, c_concat_config, c_crossattn_config):
291
+ super().__init__()
292
+ self.concat_conditioner = instantiate_from_config(c_concat_config)
293
+ self.crossattn_conditioner = instantiate_from_config(c_crossattn_config)
294
+
295
+ def forward(self, c_concat, c_crossattn):
296
+ c_concat = self.concat_conditioner(c_concat)
297
+ c_crossattn = self.crossattn_conditioner(c_crossattn)
298
+ return {'c_concat': [c_concat], 'c_crossattn': [c_crossattn]}
299
+
300
+
301
+ def noise_like(shape, device, repeat=False):
302
+ repeat_noise = lambda: torch.randn((1, *shape[1:]), device=device).repeat(shape[0], *((1,) * (len(shape) - 1)))
303
+ noise = lambda: torch.randn(shape, device=device)
304
+ return repeat_noise() if repeat else noise()
comfy/ldm/modules/distributions/__init__.py ADDED
File without changes
comfy/ldm/modules/distributions/distributions.py ADDED
@@ -0,0 +1,92 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import numpy as np
3
+
4
+
5
+ class AbstractDistribution:
6
+ def sample(self):
7
+ raise NotImplementedError()
8
+
9
+ def mode(self):
10
+ raise NotImplementedError()
11
+
12
+
13
+ class DiracDistribution(AbstractDistribution):
14
+ def __init__(self, value):
15
+ self.value = value
16
+
17
+ def sample(self):
18
+ return self.value
19
+
20
+ def mode(self):
21
+ return self.value
22
+
23
+
24
+ class DiagonalGaussianDistribution(object):
25
+ def __init__(self, parameters, deterministic=False):
26
+ self.parameters = parameters
27
+ self.mean, self.logvar = torch.chunk(parameters, 2, dim=1)
28
+ self.logvar = torch.clamp(self.logvar, -30.0, 20.0)
29
+ self.deterministic = deterministic
30
+ self.std = torch.exp(0.5 * self.logvar)
31
+ self.var = torch.exp(self.logvar)
32
+ if self.deterministic:
33
+ self.var = self.std = torch.zeros_like(self.mean).to(device=self.parameters.device)
34
+
35
+ def sample(self):
36
+ x = self.mean + self.std * torch.randn(self.mean.shape).to(device=self.parameters.device)
37
+ return x
38
+
39
+ def kl(self, other=None):
40
+ if self.deterministic:
41
+ return torch.Tensor([0.])
42
+ else:
43
+ if other is None:
44
+ return 0.5 * torch.sum(torch.pow(self.mean, 2)
45
+ + self.var - 1.0 - self.logvar,
46
+ dim=[1, 2, 3])
47
+ else:
48
+ return 0.5 * torch.sum(
49
+ torch.pow(self.mean - other.mean, 2) / other.var
50
+ + self.var / other.var - 1.0 - self.logvar + other.logvar,
51
+ dim=[1, 2, 3])
52
+
53
+ def nll(self, sample, dims=[1,2,3]):
54
+ if self.deterministic:
55
+ return torch.Tensor([0.])
56
+ logtwopi = np.log(2.0 * np.pi)
57
+ return 0.5 * torch.sum(
58
+ logtwopi + self.logvar + torch.pow(sample - self.mean, 2) / self.var,
59
+ dim=dims)
60
+
61
+ def mode(self):
62
+ return self.mean
63
+
64
+
65
+ def normal_kl(mean1, logvar1, mean2, logvar2):
66
+ """
67
+ source: https://github.com/openai/guided-diffusion/blob/27c20a8fab9cb472df5d6bdd6c8d11c8f430b924/guided_diffusion/losses.py#L12
68
+ Compute the KL divergence between two gaussians.
69
+ Shapes are automatically broadcasted, so batches can be compared to
70
+ scalars, among other use cases.
71
+ """
72
+ tensor = None
73
+ for obj in (mean1, logvar1, mean2, logvar2):
74
+ if isinstance(obj, torch.Tensor):
75
+ tensor = obj
76
+ break
77
+ assert tensor is not None, "at least one argument must be a Tensor"
78
+
79
+ # Force variances to be Tensors. Broadcasting helps convert scalars to
80
+ # Tensors, but it does not work for torch.exp().
81
+ logvar1, logvar2 = [
82
+ x if isinstance(x, torch.Tensor) else torch.tensor(x).to(tensor)
83
+ for x in (logvar1, logvar2)
84
+ ]
85
+
86
+ return 0.5 * (
87
+ -1.0
88
+ + logvar2
89
+ - logvar1
90
+ + torch.exp(logvar1 - logvar2)
91
+ + ((mean1 - mean2) ** 2) * torch.exp(-logvar2)
92
+ )
comfy/ldm/modules/ema.py ADDED
@@ -0,0 +1,80 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from torch import nn
3
+
4
+
5
+ class LitEma(nn.Module):
6
+ def __init__(self, model, decay=0.9999, use_num_upates=True):
7
+ super().__init__()
8
+ if decay < 0.0 or decay > 1.0:
9
+ raise ValueError('Decay must be between 0 and 1')
10
+
11
+ self.m_name2s_name = {}
12
+ self.register_buffer('decay', torch.tensor(decay, dtype=torch.float32))
13
+ self.register_buffer('num_updates', torch.tensor(0, dtype=torch.int) if use_num_upates
14
+ else torch.tensor(-1, dtype=torch.int))
15
+
16
+ for name, p in model.named_parameters():
17
+ if p.requires_grad:
18
+ # remove as '.'-character is not allowed in buffers
19
+ s_name = name.replace('.', '')
20
+ self.m_name2s_name.update({name: s_name})
21
+ self.register_buffer(s_name, p.clone().detach().data)
22
+
23
+ self.collected_params = []
24
+
25
+ def reset_num_updates(self):
26
+ del self.num_updates
27
+ self.register_buffer('num_updates', torch.tensor(0, dtype=torch.int))
28
+
29
+ def forward(self, model):
30
+ decay = self.decay
31
+
32
+ if self.num_updates >= 0:
33
+ self.num_updates += 1
34
+ decay = min(self.decay, (1 + self.num_updates) / (10 + self.num_updates))
35
+
36
+ one_minus_decay = 1.0 - decay
37
+
38
+ with torch.no_grad():
39
+ m_param = dict(model.named_parameters())
40
+ shadow_params = dict(self.named_buffers())
41
+
42
+ for key in m_param:
43
+ if m_param[key].requires_grad:
44
+ sname = self.m_name2s_name[key]
45
+ shadow_params[sname] = shadow_params[sname].type_as(m_param[key])
46
+ shadow_params[sname].sub_(one_minus_decay * (shadow_params[sname] - m_param[key]))
47
+ else:
48
+ assert not key in self.m_name2s_name
49
+
50
+ def copy_to(self, model):
51
+ m_param = dict(model.named_parameters())
52
+ shadow_params = dict(self.named_buffers())
53
+ for key in m_param:
54
+ if m_param[key].requires_grad:
55
+ m_param[key].data.copy_(shadow_params[self.m_name2s_name[key]].data)
56
+ else:
57
+ assert not key in self.m_name2s_name
58
+
59
+ def store(self, parameters):
60
+ """
61
+ Save the current parameters for restoring later.
62
+ Args:
63
+ parameters: Iterable of `torch.nn.Parameter`; the parameters to be
64
+ temporarily stored.
65
+ """
66
+ self.collected_params = [param.clone() for param in parameters]
67
+
68
+ def restore(self, parameters):
69
+ """
70
+ Restore the parameters stored with the `store` method.
71
+ Useful to validate the model with EMA parameters without affecting the
72
+ original optimization process. Store the parameters before the
73
+ `copy_to` method. After validation (or model saving), use this to
74
+ restore the former parameters.
75
+ Args:
76
+ parameters: Iterable of `torch.nn.Parameter`; the parameters to be
77
+ updated with the stored parameters.
78
+ """
79
+ for c_param, param in zip(self.collected_params, parameters):
80
+ param.data.copy_(c_param.data)
comfy/ldm/modules/encoders/__init__.py ADDED
File without changes
comfy/ldm/modules/encoders/noise_aug_modules.py ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from ..diffusionmodules.upscaling import ImageConcatWithNoiseAugmentation
2
+ from ..diffusionmodules.openaimodel import Timestep
3
+ import torch
4
+
5
+ class CLIPEmbeddingNoiseAugmentation(ImageConcatWithNoiseAugmentation):
6
+ def __init__(self, *args, clip_stats_path=None, timestep_dim=256, **kwargs):
7
+ super().__init__(*args, **kwargs)
8
+ if clip_stats_path is None:
9
+ clip_mean, clip_std = torch.zeros(timestep_dim), torch.ones(timestep_dim)
10
+ else:
11
+ clip_mean, clip_std = torch.load(clip_stats_path, map_location="cpu")
12
+ self.register_buffer("data_mean", clip_mean[None, :], persistent=False)
13
+ self.register_buffer("data_std", clip_std[None, :], persistent=False)
14
+ self.time_embed = Timestep(timestep_dim)
15
+
16
+ def scale(self, x):
17
+ # re-normalize to centered mean and unit variance
18
+ x = (x - self.data_mean.to(x.device)) * 1. / self.data_std.to(x.device)
19
+ return x
20
+
21
+ def unscale(self, x):
22
+ # back to original data stats
23
+ x = (x * self.data_std.to(x.device)) + self.data_mean.to(x.device)
24
+ return x
25
+
26
+ def forward(self, x, noise_level=None, seed=None):
27
+ if noise_level is None:
28
+ noise_level = torch.randint(0, self.max_noise_level, (x.shape[0],), device=x.device).long()
29
+ else:
30
+ assert isinstance(noise_level, torch.Tensor)
31
+ x = self.scale(x)
32
+ z = self.q_sample(x, noise_level, seed=seed)
33
+ z = self.unscale(z)
34
+ noise_level = self.time_embed(noise_level)
35
+ return z, noise_level
comfy/ldm/modules/sub_quadratic_attention.py ADDED
@@ -0,0 +1,273 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # original source:
2
+ # https://github.com/AminRezaei0x443/memory-efficient-attention/blob/1bc0d9e6ac5f82ea43a375135c4e1d3896ee1694/memory_efficient_attention/attention_torch.py
3
+ # license:
4
+ # MIT
5
+ # credit:
6
+ # Amin Rezaei (original author)
7
+ # Alex Birch (optimized algorithm for 3D tensors, at the expense of removing bias, masking and callbacks)
8
+ # implementation of:
9
+ # Self-attention Does Not Need O(n2) Memory":
10
+ # https://arxiv.org/abs/2112.05682v2
11
+
12
+ from functools import partial
13
+ import torch
14
+ from torch import Tensor
15
+ from torch.utils.checkpoint import checkpoint
16
+ import math
17
+
18
+ try:
19
+ from typing import Optional, NamedTuple, List, Protocol
20
+ except ImportError:
21
+ from typing import Optional, NamedTuple, List
22
+ from typing_extensions import Protocol
23
+
24
+ from torch import Tensor
25
+ from typing import List
26
+
27
+ from comfy import model_management
28
+
29
+ def dynamic_slice(
30
+ x: Tensor,
31
+ starts: List[int],
32
+ sizes: List[int],
33
+ ) -> Tensor:
34
+ slicing = [slice(start, start + size) for start, size in zip(starts, sizes)]
35
+ return x[slicing]
36
+
37
+ class AttnChunk(NamedTuple):
38
+ exp_values: Tensor
39
+ exp_weights_sum: Tensor
40
+ max_score: Tensor
41
+
42
+ class SummarizeChunk(Protocol):
43
+ @staticmethod
44
+ def __call__(
45
+ query: Tensor,
46
+ key_t: Tensor,
47
+ value: Tensor,
48
+ ) -> AttnChunk: ...
49
+
50
+ class ComputeQueryChunkAttn(Protocol):
51
+ @staticmethod
52
+ def __call__(
53
+ query: Tensor,
54
+ key_t: Tensor,
55
+ value: Tensor,
56
+ ) -> Tensor: ...
57
+
58
+ def _summarize_chunk(
59
+ query: Tensor,
60
+ key_t: Tensor,
61
+ value: Tensor,
62
+ scale: float,
63
+ upcast_attention: bool,
64
+ mask,
65
+ ) -> AttnChunk:
66
+ if upcast_attention:
67
+ with torch.autocast(enabled=False, device_type = 'cuda'):
68
+ query = query.float()
69
+ key_t = key_t.float()
70
+ attn_weights = torch.baddbmm(
71
+ torch.empty(1, 1, 1, device=query.device, dtype=query.dtype),
72
+ query,
73
+ key_t,
74
+ alpha=scale,
75
+ beta=0,
76
+ )
77
+ else:
78
+ attn_weights = torch.baddbmm(
79
+ torch.empty(1, 1, 1, device=query.device, dtype=query.dtype),
80
+ query,
81
+ key_t,
82
+ alpha=scale,
83
+ beta=0,
84
+ )
85
+ max_score, _ = torch.max(attn_weights, -1, keepdim=True)
86
+ max_score = max_score.detach()
87
+ attn_weights -= max_score
88
+ if mask is not None:
89
+ attn_weights += mask
90
+ torch.exp(attn_weights, out=attn_weights)
91
+ exp_weights = attn_weights.to(value.dtype)
92
+ exp_values = torch.bmm(exp_weights, value)
93
+ max_score = max_score.squeeze(-1)
94
+ return AttnChunk(exp_values, exp_weights.sum(dim=-1), max_score)
95
+
96
+ def _query_chunk_attention(
97
+ query: Tensor,
98
+ key_t: Tensor,
99
+ value: Tensor,
100
+ summarize_chunk: SummarizeChunk,
101
+ kv_chunk_size: int,
102
+ mask,
103
+ ) -> Tensor:
104
+ batch_x_heads, k_channels_per_head, k_tokens = key_t.shape
105
+ _, _, v_channels_per_head = value.shape
106
+
107
+ def chunk_scanner(chunk_idx: int, mask) -> AttnChunk:
108
+ key_chunk = dynamic_slice(
109
+ key_t,
110
+ (0, 0, chunk_idx),
111
+ (batch_x_heads, k_channels_per_head, kv_chunk_size)
112
+ )
113
+ value_chunk = dynamic_slice(
114
+ value,
115
+ (0, chunk_idx, 0),
116
+ (batch_x_heads, kv_chunk_size, v_channels_per_head)
117
+ )
118
+ if mask is not None:
119
+ mask = mask[:,:,chunk_idx:chunk_idx + kv_chunk_size]
120
+
121
+ return summarize_chunk(query, key_chunk, value_chunk, mask=mask)
122
+
123
+ chunks: List[AttnChunk] = [
124
+ chunk_scanner(chunk, mask) for chunk in torch.arange(0, k_tokens, kv_chunk_size)
125
+ ]
126
+ acc_chunk = AttnChunk(*map(torch.stack, zip(*chunks)))
127
+ chunk_values, chunk_weights, chunk_max = acc_chunk
128
+
129
+ global_max, _ = torch.max(chunk_max, 0, keepdim=True)
130
+ max_diffs = torch.exp(chunk_max - global_max)
131
+ chunk_values *= torch.unsqueeze(max_diffs, -1)
132
+ chunk_weights *= max_diffs
133
+
134
+ all_values = chunk_values.sum(dim=0)
135
+ all_weights = torch.unsqueeze(chunk_weights, -1).sum(dim=0)
136
+ return all_values / all_weights
137
+
138
+ # TODO: refactor CrossAttention#get_attention_scores to share code with this
139
+ def _get_attention_scores_no_kv_chunking(
140
+ query: Tensor,
141
+ key_t: Tensor,
142
+ value: Tensor,
143
+ scale: float,
144
+ upcast_attention: bool,
145
+ mask,
146
+ ) -> Tensor:
147
+ if upcast_attention:
148
+ with torch.autocast(enabled=False, device_type = 'cuda'):
149
+ query = query.float()
150
+ key_t = key_t.float()
151
+ attn_scores = torch.baddbmm(
152
+ torch.empty(1, 1, 1, device=query.device, dtype=query.dtype),
153
+ query,
154
+ key_t,
155
+ alpha=scale,
156
+ beta=0,
157
+ )
158
+ else:
159
+ attn_scores = torch.baddbmm(
160
+ torch.empty(1, 1, 1, device=query.device, dtype=query.dtype),
161
+ query,
162
+ key_t,
163
+ alpha=scale,
164
+ beta=0,
165
+ )
166
+
167
+ if mask is not None:
168
+ attn_scores += mask
169
+ try:
170
+ attn_probs = attn_scores.softmax(dim=-1)
171
+ del attn_scores
172
+ except model_management.OOM_EXCEPTION:
173
+ print("ran out of memory while running softmax in _get_attention_scores_no_kv_chunking, trying slower in place softmax instead")
174
+ attn_scores -= attn_scores.max(dim=-1, keepdim=True).values
175
+ torch.exp(attn_scores, out=attn_scores)
176
+ summed = torch.sum(attn_scores, dim=-1, keepdim=True)
177
+ attn_scores /= summed
178
+ attn_probs = attn_scores
179
+
180
+ hidden_states_slice = torch.bmm(attn_probs.to(value.dtype), value)
181
+ return hidden_states_slice
182
+
183
+ class ScannedChunk(NamedTuple):
184
+ chunk_idx: int
185
+ attn_chunk: AttnChunk
186
+
187
+ def efficient_dot_product_attention(
188
+ query: Tensor,
189
+ key_t: Tensor,
190
+ value: Tensor,
191
+ query_chunk_size=1024,
192
+ kv_chunk_size: Optional[int] = None,
193
+ kv_chunk_size_min: Optional[int] = None,
194
+ use_checkpoint=True,
195
+ upcast_attention=False,
196
+ mask = None,
197
+ ):
198
+ """Computes efficient dot-product attention given query, transposed key, and value.
199
+ This is efficient version of attention presented in
200
+ https://arxiv.org/abs/2112.05682v2 which comes with O(sqrt(n)) memory requirements.
201
+ Args:
202
+ query: queries for calculating attention with shape of
203
+ `[batch * num_heads, tokens, channels_per_head]`.
204
+ key_t: keys for calculating attention with shape of
205
+ `[batch * num_heads, channels_per_head, tokens]`.
206
+ value: values to be used in attention with shape of
207
+ `[batch * num_heads, tokens, channels_per_head]`.
208
+ query_chunk_size: int: query chunks size
209
+ kv_chunk_size: Optional[int]: key/value chunks size. if None: defaults to sqrt(key_tokens)
210
+ kv_chunk_size_min: Optional[int]: key/value minimum chunk size. only considered when kv_chunk_size is None. changes `sqrt(key_tokens)` into `max(sqrt(key_tokens), kv_chunk_size_min)`, to ensure our chunk sizes don't get too small (smaller chunks = more chunks = less concurrent work done).
211
+ use_checkpoint: bool: whether to use checkpointing (recommended True for training, False for inference)
212
+ Returns:
213
+ Output of shape `[batch * num_heads, query_tokens, channels_per_head]`.
214
+ """
215
+ batch_x_heads, q_tokens, q_channels_per_head = query.shape
216
+ _, _, k_tokens = key_t.shape
217
+ scale = q_channels_per_head ** -0.5
218
+
219
+ kv_chunk_size = min(kv_chunk_size or int(math.sqrt(k_tokens)), k_tokens)
220
+ if kv_chunk_size_min is not None:
221
+ kv_chunk_size = max(kv_chunk_size, kv_chunk_size_min)
222
+
223
+ if mask is not None and len(mask.shape) == 2:
224
+ mask = mask.unsqueeze(0)
225
+
226
+ def get_query_chunk(chunk_idx: int) -> Tensor:
227
+ return dynamic_slice(
228
+ query,
229
+ (0, chunk_idx, 0),
230
+ (batch_x_heads, min(query_chunk_size, q_tokens), q_channels_per_head)
231
+ )
232
+
233
+ def get_mask_chunk(chunk_idx: int) -> Tensor:
234
+ if mask is None:
235
+ return None
236
+ chunk = min(query_chunk_size, q_tokens)
237
+ return mask[:,chunk_idx:chunk_idx + chunk]
238
+
239
+ summarize_chunk: SummarizeChunk = partial(_summarize_chunk, scale=scale, upcast_attention=upcast_attention)
240
+ summarize_chunk: SummarizeChunk = partial(checkpoint, summarize_chunk) if use_checkpoint else summarize_chunk
241
+ compute_query_chunk_attn: ComputeQueryChunkAttn = partial(
242
+ _get_attention_scores_no_kv_chunking,
243
+ scale=scale,
244
+ upcast_attention=upcast_attention
245
+ ) if k_tokens <= kv_chunk_size else (
246
+ # fast-path for when there's just 1 key-value chunk per query chunk (this is just sliced attention btw)
247
+ partial(
248
+ _query_chunk_attention,
249
+ kv_chunk_size=kv_chunk_size,
250
+ summarize_chunk=summarize_chunk,
251
+ )
252
+ )
253
+
254
+ if q_tokens <= query_chunk_size:
255
+ # fast-path for when there's just 1 query chunk
256
+ return compute_query_chunk_attn(
257
+ query=query,
258
+ key_t=key_t,
259
+ value=value,
260
+ mask=mask,
261
+ )
262
+
263
+ # TODO: maybe we should use torch.empty_like(query) to allocate storage in-advance,
264
+ # and pass slices to be mutated, instead of torch.cat()ing the returned slices
265
+ res = torch.cat([
266
+ compute_query_chunk_attn(
267
+ query=get_query_chunk(i * query_chunk_size),
268
+ key_t=key_t,
269
+ value=value,
270
+ mask=get_mask_chunk(i * query_chunk_size)
271
+ ) for i in range(math.ceil(q_tokens / query_chunk_size))
272
+ ], dim=1)
273
+ return res
comfy/ldm/modules/temporal_ae.py ADDED
@@ -0,0 +1,245 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import functools
2
+ from typing import Callable, Iterable, Union
3
+
4
+ import torch
5
+ from einops import rearrange, repeat
6
+
7
+ import comfy.ops
8
+ ops = comfy.ops.disable_weight_init
9
+
10
+ from .diffusionmodules.model import (
11
+ AttnBlock,
12
+ Decoder,
13
+ ResnetBlock,
14
+ )
15
+ from .diffusionmodules.openaimodel import ResBlock, timestep_embedding
16
+ from .attention import BasicTransformerBlock
17
+
18
+ def partialclass(cls, *args, **kwargs):
19
+ class NewCls(cls):
20
+ __init__ = functools.partialmethod(cls.__init__, *args, **kwargs)
21
+
22
+ return NewCls
23
+
24
+
25
+ class VideoResBlock(ResnetBlock):
26
+ def __init__(
27
+ self,
28
+ out_channels,
29
+ *args,
30
+ dropout=0.0,
31
+ video_kernel_size=3,
32
+ alpha=0.0,
33
+ merge_strategy="learned",
34
+ **kwargs,
35
+ ):
36
+ super().__init__(out_channels=out_channels, dropout=dropout, *args, **kwargs)
37
+ if video_kernel_size is None:
38
+ video_kernel_size = [3, 1, 1]
39
+ self.time_stack = ResBlock(
40
+ channels=out_channels,
41
+ emb_channels=0,
42
+ dropout=dropout,
43
+ dims=3,
44
+ use_scale_shift_norm=False,
45
+ use_conv=False,
46
+ up=False,
47
+ down=False,
48
+ kernel_size=video_kernel_size,
49
+ use_checkpoint=False,
50
+ skip_t_emb=True,
51
+ )
52
+
53
+ self.merge_strategy = merge_strategy
54
+ if self.merge_strategy == "fixed":
55
+ self.register_buffer("mix_factor", torch.Tensor([alpha]))
56
+ elif self.merge_strategy == "learned":
57
+ self.register_parameter(
58
+ "mix_factor", torch.nn.Parameter(torch.Tensor([alpha]))
59
+ )
60
+ else:
61
+ raise ValueError(f"unknown merge strategy {self.merge_strategy}")
62
+
63
+ def get_alpha(self, bs):
64
+ if self.merge_strategy == "fixed":
65
+ return self.mix_factor
66
+ elif self.merge_strategy == "learned":
67
+ return torch.sigmoid(self.mix_factor)
68
+ else:
69
+ raise NotImplementedError()
70
+
71
+ def forward(self, x, temb, skip_video=False, timesteps=None):
72
+ b, c, h, w = x.shape
73
+ if timesteps is None:
74
+ timesteps = b
75
+
76
+ x = super().forward(x, temb)
77
+
78
+ if not skip_video:
79
+ x_mix = rearrange(x, "(b t) c h w -> b c t h w", t=timesteps)
80
+
81
+ x = rearrange(x, "(b t) c h w -> b c t h w", t=timesteps)
82
+
83
+ x = self.time_stack(x, temb)
84
+
85
+ alpha = self.get_alpha(bs=b // timesteps).to(x.device)
86
+ x = alpha * x + (1.0 - alpha) * x_mix
87
+
88
+ x = rearrange(x, "b c t h w -> (b t) c h w")
89
+ return x
90
+
91
+
92
+ class AE3DConv(ops.Conv2d):
93
+ def __init__(self, in_channels, out_channels, video_kernel_size=3, *args, **kwargs):
94
+ super().__init__(in_channels, out_channels, *args, **kwargs)
95
+ if isinstance(video_kernel_size, Iterable):
96
+ padding = [int(k // 2) for k in video_kernel_size]
97
+ else:
98
+ padding = int(video_kernel_size // 2)
99
+
100
+ self.time_mix_conv = ops.Conv3d(
101
+ in_channels=out_channels,
102
+ out_channels=out_channels,
103
+ kernel_size=video_kernel_size,
104
+ padding=padding,
105
+ )
106
+
107
+ def forward(self, input, timesteps=None, skip_video=False):
108
+ if timesteps is None:
109
+ timesteps = input.shape[0]
110
+ x = super().forward(input)
111
+ if skip_video:
112
+ return x
113
+ x = rearrange(x, "(b t) c h w -> b c t h w", t=timesteps)
114
+ x = self.time_mix_conv(x)
115
+ return rearrange(x, "b c t h w -> (b t) c h w")
116
+
117
+
118
+ class AttnVideoBlock(AttnBlock):
119
+ def __init__(
120
+ self, in_channels: int, alpha: float = 0, merge_strategy: str = "learned"
121
+ ):
122
+ super().__init__(in_channels)
123
+ # no context, single headed, as in base class
124
+ self.time_mix_block = BasicTransformerBlock(
125
+ dim=in_channels,
126
+ n_heads=1,
127
+ d_head=in_channels,
128
+ checkpoint=False,
129
+ ff_in=True,
130
+ )
131
+
132
+ time_embed_dim = self.in_channels * 4
133
+ self.video_time_embed = torch.nn.Sequential(
134
+ ops.Linear(self.in_channels, time_embed_dim),
135
+ torch.nn.SiLU(),
136
+ ops.Linear(time_embed_dim, self.in_channels),
137
+ )
138
+
139
+ self.merge_strategy = merge_strategy
140
+ if self.merge_strategy == "fixed":
141
+ self.register_buffer("mix_factor", torch.Tensor([alpha]))
142
+ elif self.merge_strategy == "learned":
143
+ self.register_parameter(
144
+ "mix_factor", torch.nn.Parameter(torch.Tensor([alpha]))
145
+ )
146
+ else:
147
+ raise ValueError(f"unknown merge strategy {self.merge_strategy}")
148
+
149
+ def forward(self, x, timesteps=None, skip_time_block=False):
150
+ if skip_time_block:
151
+ return super().forward(x)
152
+
153
+ if timesteps is None:
154
+ timesteps = x.shape[0]
155
+
156
+ x_in = x
157
+ x = self.attention(x)
158
+ h, w = x.shape[2:]
159
+ x = rearrange(x, "b c h w -> b (h w) c")
160
+
161
+ x_mix = x
162
+ num_frames = torch.arange(timesteps, device=x.device)
163
+ num_frames = repeat(num_frames, "t -> b t", b=x.shape[0] // timesteps)
164
+ num_frames = rearrange(num_frames, "b t -> (b t)")
165
+ t_emb = timestep_embedding(num_frames, self.in_channels, repeat_only=False)
166
+ emb = self.video_time_embed(t_emb) # b, n_channels
167
+ emb = emb[:, None, :]
168
+ x_mix = x_mix + emb
169
+
170
+ alpha = self.get_alpha().to(x.device)
171
+ x_mix = self.time_mix_block(x_mix, timesteps=timesteps)
172
+ x = alpha * x + (1.0 - alpha) * x_mix # alpha merge
173
+
174
+ x = rearrange(x, "b (h w) c -> b c h w", h=h, w=w)
175
+ x = self.proj_out(x)
176
+
177
+ return x_in + x
178
+
179
+ def get_alpha(
180
+ self,
181
+ ):
182
+ if self.merge_strategy == "fixed":
183
+ return self.mix_factor
184
+ elif self.merge_strategy == "learned":
185
+ return torch.sigmoid(self.mix_factor)
186
+ else:
187
+ raise NotImplementedError(f"unknown merge strategy {self.merge_strategy}")
188
+
189
+
190
+
191
+ def make_time_attn(
192
+ in_channels,
193
+ attn_type="vanilla",
194
+ attn_kwargs=None,
195
+ alpha: float = 0,
196
+ merge_strategy: str = "learned",
197
+ ):
198
+ return partialclass(
199
+ AttnVideoBlock, in_channels, alpha=alpha, merge_strategy=merge_strategy
200
+ )
201
+
202
+
203
+ class Conv2DWrapper(torch.nn.Conv2d):
204
+ def forward(self, input: torch.Tensor, **kwargs) -> torch.Tensor:
205
+ return super().forward(input)
206
+
207
+
208
+ class VideoDecoder(Decoder):
209
+ available_time_modes = ["all", "conv-only", "attn-only"]
210
+
211
+ def __init__(
212
+ self,
213
+ *args,
214
+ video_kernel_size: Union[int, list] = 3,
215
+ alpha: float = 0.0,
216
+ merge_strategy: str = "learned",
217
+ time_mode: str = "conv-only",
218
+ **kwargs,
219
+ ):
220
+ self.video_kernel_size = video_kernel_size
221
+ self.alpha = alpha
222
+ self.merge_strategy = merge_strategy
223
+ self.time_mode = time_mode
224
+ assert (
225
+ self.time_mode in self.available_time_modes
226
+ ), f"time_mode parameter has to be in {self.available_time_modes}"
227
+
228
+ if self.time_mode != "attn-only":
229
+ kwargs["conv_out_op"] = partialclass(AE3DConv, video_kernel_size=self.video_kernel_size)
230
+ if self.time_mode not in ["conv-only", "only-last-conv"]:
231
+ kwargs["attn_op"] = partialclass(make_time_attn, alpha=self.alpha, merge_strategy=self.merge_strategy)
232
+ if self.time_mode not in ["attn-only", "only-last-conv"]:
233
+ kwargs["resnet_op"] = partialclass(VideoResBlock, video_kernel_size=self.video_kernel_size, alpha=self.alpha, merge_strategy=self.merge_strategy)
234
+
235
+ super().__init__(*args, **kwargs)
236
+
237
+ def get_last_layer(self, skip_time_mix=False, **kwargs):
238
+ if self.time_mode == "attn-only":
239
+ raise NotImplementedError("TODO")
240
+ else:
241
+ return (
242
+ self.conv_out.time_mix_conv.weight
243
+ if not skip_time_mix
244
+ else self.conv_out.weight
245
+ )
comfy/ldm/util.py ADDED
@@ -0,0 +1,197 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import importlib
2
+
3
+ import torch
4
+ from torch import optim
5
+ import numpy as np
6
+
7
+ from inspect import isfunction
8
+ from PIL import Image, ImageDraw, ImageFont
9
+
10
+
11
+ def log_txt_as_img(wh, xc, size=10):
12
+ # wh a tuple of (width, height)
13
+ # xc a list of captions to plot
14
+ b = len(xc)
15
+ txts = list()
16
+ for bi in range(b):
17
+ txt = Image.new("RGB", wh, color="white")
18
+ draw = ImageDraw.Draw(txt)
19
+ font = ImageFont.truetype('data/DejaVuSans.ttf', size=size)
20
+ nc = int(40 * (wh[0] / 256))
21
+ lines = "\n".join(xc[bi][start:start + nc] for start in range(0, len(xc[bi]), nc))
22
+
23
+ try:
24
+ draw.text((0, 0), lines, fill="black", font=font)
25
+ except UnicodeEncodeError:
26
+ print("Cant encode string for logging. Skipping.")
27
+
28
+ txt = np.array(txt).transpose(2, 0, 1) / 127.5 - 1.0
29
+ txts.append(txt)
30
+ txts = np.stack(txts)
31
+ txts = torch.tensor(txts)
32
+ return txts
33
+
34
+
35
+ def ismap(x):
36
+ if not isinstance(x, torch.Tensor):
37
+ return False
38
+ return (len(x.shape) == 4) and (x.shape[1] > 3)
39
+
40
+
41
+ def isimage(x):
42
+ if not isinstance(x,torch.Tensor):
43
+ return False
44
+ return (len(x.shape) == 4) and (x.shape[1] == 3 or x.shape[1] == 1)
45
+
46
+
47
+ def exists(x):
48
+ return x is not None
49
+
50
+
51
+ def default(val, d):
52
+ if exists(val):
53
+ return val
54
+ return d() if isfunction(d) else d
55
+
56
+
57
+ def mean_flat(tensor):
58
+ """
59
+ https://github.com/openai/guided-diffusion/blob/27c20a8fab9cb472df5d6bdd6c8d11c8f430b924/guided_diffusion/nn.py#L86
60
+ Take the mean over all non-batch dimensions.
61
+ """
62
+ return tensor.mean(dim=list(range(1, len(tensor.shape))))
63
+
64
+
65
+ def count_params(model, verbose=False):
66
+ total_params = sum(p.numel() for p in model.parameters())
67
+ if verbose:
68
+ print(f"{model.__class__.__name__} has {total_params*1.e-6:.2f} M params.")
69
+ return total_params
70
+
71
+
72
+ def instantiate_from_config(config):
73
+ if not "target" in config:
74
+ if config == '__is_first_stage__':
75
+ return None
76
+ elif config == "__is_unconditional__":
77
+ return None
78
+ raise KeyError("Expected key `target` to instantiate.")
79
+ return get_obj_from_str(config["target"])(**config.get("params", dict()))
80
+
81
+
82
+ def get_obj_from_str(string, reload=False):
83
+ module, cls = string.rsplit(".", 1)
84
+ if reload:
85
+ module_imp = importlib.import_module(module)
86
+ importlib.reload(module_imp)
87
+ return getattr(importlib.import_module(module, package=None), cls)
88
+
89
+
90
+ class AdamWwithEMAandWings(optim.Optimizer):
91
+ # credit to https://gist.github.com/crowsonkb/65f7265353f403714fce3b2595e0b298
92
+ def __init__(self, params, lr=1.e-3, betas=(0.9, 0.999), eps=1.e-8, # TODO: check hyperparameters before using
93
+ weight_decay=1.e-2, amsgrad=False, ema_decay=0.9999, # ema decay to match previous code
94
+ ema_power=1., param_names=()):
95
+ """AdamW that saves EMA versions of the parameters."""
96
+ if not 0.0 <= lr:
97
+ raise ValueError("Invalid learning rate: {}".format(lr))
98
+ if not 0.0 <= eps:
99
+ raise ValueError("Invalid epsilon value: {}".format(eps))
100
+ if not 0.0 <= betas[0] < 1.0:
101
+ raise ValueError("Invalid beta parameter at index 0: {}".format(betas[0]))
102
+ if not 0.0 <= betas[1] < 1.0:
103
+ raise ValueError("Invalid beta parameter at index 1: {}".format(betas[1]))
104
+ if not 0.0 <= weight_decay:
105
+ raise ValueError("Invalid weight_decay value: {}".format(weight_decay))
106
+ if not 0.0 <= ema_decay <= 1.0:
107
+ raise ValueError("Invalid ema_decay value: {}".format(ema_decay))
108
+ defaults = dict(lr=lr, betas=betas, eps=eps,
109
+ weight_decay=weight_decay, amsgrad=amsgrad, ema_decay=ema_decay,
110
+ ema_power=ema_power, param_names=param_names)
111
+ super().__init__(params, defaults)
112
+
113
+ def __setstate__(self, state):
114
+ super().__setstate__(state)
115
+ for group in self.param_groups:
116
+ group.setdefault('amsgrad', False)
117
+
118
+ @torch.no_grad()
119
+ def step(self, closure=None):
120
+ """Performs a single optimization step.
121
+ Args:
122
+ closure (callable, optional): A closure that reevaluates the model
123
+ and returns the loss.
124
+ """
125
+ loss = None
126
+ if closure is not None:
127
+ with torch.enable_grad():
128
+ loss = closure()
129
+
130
+ for group in self.param_groups:
131
+ params_with_grad = []
132
+ grads = []
133
+ exp_avgs = []
134
+ exp_avg_sqs = []
135
+ ema_params_with_grad = []
136
+ state_sums = []
137
+ max_exp_avg_sqs = []
138
+ state_steps = []
139
+ amsgrad = group['amsgrad']
140
+ beta1, beta2 = group['betas']
141
+ ema_decay = group['ema_decay']
142
+ ema_power = group['ema_power']
143
+
144
+ for p in group['params']:
145
+ if p.grad is None:
146
+ continue
147
+ params_with_grad.append(p)
148
+ if p.grad.is_sparse:
149
+ raise RuntimeError('AdamW does not support sparse gradients')
150
+ grads.append(p.grad)
151
+
152
+ state = self.state[p]
153
+
154
+ # State initialization
155
+ if len(state) == 0:
156
+ state['step'] = 0
157
+ # Exponential moving average of gradient values
158
+ state['exp_avg'] = torch.zeros_like(p, memory_format=torch.preserve_format)
159
+ # Exponential moving average of squared gradient values
160
+ state['exp_avg_sq'] = torch.zeros_like(p, memory_format=torch.preserve_format)
161
+ if amsgrad:
162
+ # Maintains max of all exp. moving avg. of sq. grad. values
163
+ state['max_exp_avg_sq'] = torch.zeros_like(p, memory_format=torch.preserve_format)
164
+ # Exponential moving average of parameter values
165
+ state['param_exp_avg'] = p.detach().float().clone()
166
+
167
+ exp_avgs.append(state['exp_avg'])
168
+ exp_avg_sqs.append(state['exp_avg_sq'])
169
+ ema_params_with_grad.append(state['param_exp_avg'])
170
+
171
+ if amsgrad:
172
+ max_exp_avg_sqs.append(state['max_exp_avg_sq'])
173
+
174
+ # update the steps for each param group update
175
+ state['step'] += 1
176
+ # record the step after step update
177
+ state_steps.append(state['step'])
178
+
179
+ optim._functional.adamw(params_with_grad,
180
+ grads,
181
+ exp_avgs,
182
+ exp_avg_sqs,
183
+ max_exp_avg_sqs,
184
+ state_steps,
185
+ amsgrad=amsgrad,
186
+ beta1=beta1,
187
+ beta2=beta2,
188
+ lr=group['lr'],
189
+ weight_decay=group['weight_decay'],
190
+ eps=group['eps'],
191
+ maximize=False)
192
+
193
+ cur_ema_decay = min(ema_decay, 1 - state['step'] ** -ema_power)
194
+ for param, ema_param in zip(params_with_grad, ema_params_with_grad):
195
+ ema_param.mul_(cur_ema_decay).add_(param.float(), alpha=1 - cur_ema_decay)
196
+
197
+ return loss
comfy/lora.py ADDED
@@ -0,0 +1,224 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import comfy.utils
2
+
3
+ LORA_CLIP_MAP = {
4
+ "mlp.fc1": "mlp_fc1",
5
+ "mlp.fc2": "mlp_fc2",
6
+ "self_attn.k_proj": "self_attn_k_proj",
7
+ "self_attn.q_proj": "self_attn_q_proj",
8
+ "self_attn.v_proj": "self_attn_v_proj",
9
+ "self_attn.out_proj": "self_attn_out_proj",
10
+ }
11
+
12
+
13
+ def load_lora(lora, to_load):
14
+ patch_dict = {}
15
+ loaded_keys = set()
16
+ for x in to_load:
17
+ alpha_name = "{}.alpha".format(x)
18
+ alpha = None
19
+ if alpha_name in lora.keys():
20
+ alpha = lora[alpha_name].item()
21
+ loaded_keys.add(alpha_name)
22
+
23
+ regular_lora = "{}.lora_up.weight".format(x)
24
+ diffusers_lora = "{}_lora.up.weight".format(x)
25
+ transformers_lora = "{}.lora_linear_layer.up.weight".format(x)
26
+ A_name = None
27
+
28
+ if regular_lora in lora.keys():
29
+ A_name = regular_lora
30
+ B_name = "{}.lora_down.weight".format(x)
31
+ mid_name = "{}.lora_mid.weight".format(x)
32
+ elif diffusers_lora in lora.keys():
33
+ A_name = diffusers_lora
34
+ B_name = "{}_lora.down.weight".format(x)
35
+ mid_name = None
36
+ elif transformers_lora in lora.keys():
37
+ A_name = transformers_lora
38
+ B_name ="{}.lora_linear_layer.down.weight".format(x)
39
+ mid_name = None
40
+
41
+ if A_name is not None:
42
+ mid = None
43
+ if mid_name is not None and mid_name in lora.keys():
44
+ mid = lora[mid_name]
45
+ loaded_keys.add(mid_name)
46
+ patch_dict[to_load[x]] = ("lora", (lora[A_name], lora[B_name], alpha, mid))
47
+ loaded_keys.add(A_name)
48
+ loaded_keys.add(B_name)
49
+
50
+
51
+ ######## loha
52
+ hada_w1_a_name = "{}.hada_w1_a".format(x)
53
+ hada_w1_b_name = "{}.hada_w1_b".format(x)
54
+ hada_w2_a_name = "{}.hada_w2_a".format(x)
55
+ hada_w2_b_name = "{}.hada_w2_b".format(x)
56
+ hada_t1_name = "{}.hada_t1".format(x)
57
+ hada_t2_name = "{}.hada_t2".format(x)
58
+ if hada_w1_a_name in lora.keys():
59
+ hada_t1 = None
60
+ hada_t2 = None
61
+ if hada_t1_name in lora.keys():
62
+ hada_t1 = lora[hada_t1_name]
63
+ hada_t2 = lora[hada_t2_name]
64
+ loaded_keys.add(hada_t1_name)
65
+ loaded_keys.add(hada_t2_name)
66
+
67
+ patch_dict[to_load[x]] = ("loha", (lora[hada_w1_a_name], lora[hada_w1_b_name], alpha, lora[hada_w2_a_name], lora[hada_w2_b_name], hada_t1, hada_t2))
68
+ loaded_keys.add(hada_w1_a_name)
69
+ loaded_keys.add(hada_w1_b_name)
70
+ loaded_keys.add(hada_w2_a_name)
71
+ loaded_keys.add(hada_w2_b_name)
72
+
73
+
74
+ ######## lokr
75
+ lokr_w1_name = "{}.lokr_w1".format(x)
76
+ lokr_w2_name = "{}.lokr_w2".format(x)
77
+ lokr_w1_a_name = "{}.lokr_w1_a".format(x)
78
+ lokr_w1_b_name = "{}.lokr_w1_b".format(x)
79
+ lokr_t2_name = "{}.lokr_t2".format(x)
80
+ lokr_w2_a_name = "{}.lokr_w2_a".format(x)
81
+ lokr_w2_b_name = "{}.lokr_w2_b".format(x)
82
+
83
+ lokr_w1 = None
84
+ if lokr_w1_name in lora.keys():
85
+ lokr_w1 = lora[lokr_w1_name]
86
+ loaded_keys.add(lokr_w1_name)
87
+
88
+ lokr_w2 = None
89
+ if lokr_w2_name in lora.keys():
90
+ lokr_w2 = lora[lokr_w2_name]
91
+ loaded_keys.add(lokr_w2_name)
92
+
93
+ lokr_w1_a = None
94
+ if lokr_w1_a_name in lora.keys():
95
+ lokr_w1_a = lora[lokr_w1_a_name]
96
+ loaded_keys.add(lokr_w1_a_name)
97
+
98
+ lokr_w1_b = None
99
+ if lokr_w1_b_name in lora.keys():
100
+ lokr_w1_b = lora[lokr_w1_b_name]
101
+ loaded_keys.add(lokr_w1_b_name)
102
+
103
+ lokr_w2_a = None
104
+ if lokr_w2_a_name in lora.keys():
105
+ lokr_w2_a = lora[lokr_w2_a_name]
106
+ loaded_keys.add(lokr_w2_a_name)
107
+
108
+ lokr_w2_b = None
109
+ if lokr_w2_b_name in lora.keys():
110
+ lokr_w2_b = lora[lokr_w2_b_name]
111
+ loaded_keys.add(lokr_w2_b_name)
112
+
113
+ lokr_t2 = None
114
+ if lokr_t2_name in lora.keys():
115
+ lokr_t2 = lora[lokr_t2_name]
116
+ loaded_keys.add(lokr_t2_name)
117
+
118
+ if (lokr_w1 is not None) or (lokr_w2 is not None) or (lokr_w1_a is not None) or (lokr_w2_a is not None):
119
+ patch_dict[to_load[x]] = ("lokr", (lokr_w1, lokr_w2, alpha, lokr_w1_a, lokr_w1_b, lokr_w2_a, lokr_w2_b, lokr_t2))
120
+
121
+ #glora
122
+ a1_name = "{}.a1.weight".format(x)
123
+ a2_name = "{}.a2.weight".format(x)
124
+ b1_name = "{}.b1.weight".format(x)
125
+ b2_name = "{}.b2.weight".format(x)
126
+ if a1_name in lora:
127
+ patch_dict[to_load[x]] = ("glora", (lora[a1_name], lora[a2_name], lora[b1_name], lora[b2_name], alpha))
128
+ loaded_keys.add(a1_name)
129
+ loaded_keys.add(a2_name)
130
+ loaded_keys.add(b1_name)
131
+ loaded_keys.add(b2_name)
132
+
133
+ w_norm_name = "{}.w_norm".format(x)
134
+ b_norm_name = "{}.b_norm".format(x)
135
+ w_norm = lora.get(w_norm_name, None)
136
+ b_norm = lora.get(b_norm_name, None)
137
+
138
+ if w_norm is not None:
139
+ loaded_keys.add(w_norm_name)
140
+ patch_dict[to_load[x]] = ("diff", (w_norm,))
141
+ if b_norm is not None:
142
+ loaded_keys.add(b_norm_name)
143
+ patch_dict["{}.bias".format(to_load[x][:-len(".weight")])] = ("diff", (b_norm,))
144
+
145
+ diff_name = "{}.diff".format(x)
146
+ diff_weight = lora.get(diff_name, None)
147
+ if diff_weight is not None:
148
+ patch_dict[to_load[x]] = ("diff", (diff_weight,))
149
+ loaded_keys.add(diff_name)
150
+
151
+ diff_bias_name = "{}.diff_b".format(x)
152
+ diff_bias = lora.get(diff_bias_name, None)
153
+ if diff_bias is not None:
154
+ patch_dict["{}.bias".format(to_load[x][:-len(".weight")])] = ("diff", (diff_bias,))
155
+ loaded_keys.add(diff_bias_name)
156
+
157
+ for x in lora.keys():
158
+ if x not in loaded_keys:
159
+ print("lora key not loaded", x)
160
+ return patch_dict
161
+
162
+ def model_lora_keys_clip(model, key_map={}):
163
+ sdk = model.state_dict().keys()
164
+
165
+ text_model_lora_key = "lora_te_text_model_encoder_layers_{}_{}"
166
+ clip_l_present = False
167
+ for b in range(32): #TODO: clean up
168
+ for c in LORA_CLIP_MAP:
169
+ k = "clip_h.transformer.text_model.encoder.layers.{}.{}.weight".format(b, c)
170
+ if k in sdk:
171
+ lora_key = text_model_lora_key.format(b, LORA_CLIP_MAP[c])
172
+ key_map[lora_key] = k
173
+ lora_key = "lora_te1_text_model_encoder_layers_{}_{}".format(b, LORA_CLIP_MAP[c])
174
+ key_map[lora_key] = k
175
+ lora_key = "text_encoder.text_model.encoder.layers.{}.{}".format(b, c) #diffusers lora
176
+ key_map[lora_key] = k
177
+
178
+ k = "clip_l.transformer.text_model.encoder.layers.{}.{}.weight".format(b, c)
179
+ if k in sdk:
180
+ lora_key = text_model_lora_key.format(b, LORA_CLIP_MAP[c])
181
+ key_map[lora_key] = k
182
+ lora_key = "lora_te1_text_model_encoder_layers_{}_{}".format(b, LORA_CLIP_MAP[c]) #SDXL base
183
+ key_map[lora_key] = k
184
+ clip_l_present = True
185
+ lora_key = "text_encoder.text_model.encoder.layers.{}.{}".format(b, c) #diffusers lora
186
+ key_map[lora_key] = k
187
+
188
+ k = "clip_g.transformer.text_model.encoder.layers.{}.{}.weight".format(b, c)
189
+ if k in sdk:
190
+ if clip_l_present:
191
+ lora_key = "lora_te2_text_model_encoder_layers_{}_{}".format(b, LORA_CLIP_MAP[c]) #SDXL base
192
+ key_map[lora_key] = k
193
+ lora_key = "text_encoder_2.text_model.encoder.layers.{}.{}".format(b, c) #diffusers lora
194
+ key_map[lora_key] = k
195
+ else:
196
+ lora_key = "lora_te_text_model_encoder_layers_{}_{}".format(b, LORA_CLIP_MAP[c]) #TODO: test if this is correct for SDXL-Refiner
197
+ key_map[lora_key] = k
198
+ lora_key = "text_encoder.text_model.encoder.layers.{}.{}".format(b, c) #diffusers lora
199
+ key_map[lora_key] = k
200
+
201
+ return key_map
202
+
203
+ def model_lora_keys_unet(model, key_map={}):
204
+ sdk = model.state_dict().keys()
205
+
206
+ for k in sdk:
207
+ if k.startswith("diffusion_model.") and k.endswith(".weight"):
208
+ key_lora = k[len("diffusion_model."):-len(".weight")].replace(".", "_")
209
+ key_map["lora_unet_{}".format(key_lora)] = k
210
+
211
+ diffusers_keys = comfy.utils.unet_to_diffusers(model.model_config.unet_config)
212
+ for k in diffusers_keys:
213
+ if k.endswith(".weight"):
214
+ unet_key = "diffusion_model.{}".format(diffusers_keys[k])
215
+ key_lora = k[:-len(".weight")].replace(".", "_")
216
+ key_map["lora_unet_{}".format(key_lora)] = unet_key
217
+
218
+ diffusers_lora_prefix = ["", "unet."]
219
+ for p in diffusers_lora_prefix:
220
+ diffusers_lora_key = "{}{}".format(p, k[:-len(".weight")].replace(".to_", ".processor.to_"))
221
+ if diffusers_lora_key.endswith(".to_out.0"):
222
+ diffusers_lora_key = diffusers_lora_key[:-2]
223
+ key_map[diffusers_lora_key] = unet_key
224
+ return key_map
comfy/model_base.py ADDED
@@ -0,0 +1,425 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from comfy.ldm.modules.diffusionmodules.openaimodel import UNetModel, Timestep
3
+ from comfy.ldm.modules.encoders.noise_aug_modules import CLIPEmbeddingNoiseAugmentation
4
+ from comfy.ldm.modules.diffusionmodules.upscaling import ImageConcatWithNoiseAugmentation
5
+ import comfy.model_management
6
+ import comfy.conds
7
+ import comfy.ops
8
+ from enum import Enum
9
+ from . import utils
10
+
11
+ class ModelType(Enum):
12
+ EPS = 1
13
+ V_PREDICTION = 2
14
+ V_PREDICTION_EDM = 3
15
+
16
+
17
+ from comfy.model_sampling import EPS, V_PREDICTION, ModelSamplingDiscrete, ModelSamplingContinuousEDM
18
+
19
+
20
+ def model_sampling(model_config, model_type):
21
+ s = ModelSamplingDiscrete
22
+
23
+ if model_type == ModelType.EPS:
24
+ c = EPS
25
+ elif model_type == ModelType.V_PREDICTION:
26
+ c = V_PREDICTION
27
+ elif model_type == ModelType.V_PREDICTION_EDM:
28
+ c = V_PREDICTION
29
+ s = ModelSamplingContinuousEDM
30
+
31
+ class ModelSampling(s, c):
32
+ pass
33
+
34
+ return ModelSampling(model_config)
35
+
36
+
37
+ class BaseModel(torch.nn.Module):
38
+ def __init__(self, model_config, model_type=ModelType.EPS, device=None):
39
+ super().__init__()
40
+
41
+ unet_config = model_config.unet_config
42
+ self.latent_format = model_config.latent_format
43
+ self.model_config = model_config
44
+ self.manual_cast_dtype = model_config.manual_cast_dtype
45
+
46
+ if not unet_config.get("disable_unet_model_creation", False):
47
+ if self.manual_cast_dtype is not None:
48
+ operations = comfy.ops.manual_cast
49
+ else:
50
+ operations = comfy.ops.disable_weight_init
51
+ self.diffusion_model = UNetModel(**unet_config, device=device, operations=operations)
52
+ self.model_type = model_type
53
+ self.model_sampling = model_sampling(model_config, model_type)
54
+
55
+ self.adm_channels = unet_config.get("adm_in_channels", None)
56
+ if self.adm_channels is None:
57
+ self.adm_channels = 0
58
+ self.inpaint_model = False
59
+ print("model_type", model_type.name)
60
+ print("adm", self.adm_channels)
61
+
62
+ def apply_model(self, x, t, c_concat=None, c_crossattn=None, control=None, transformer_options={}, **kwargs):
63
+ sigma = t
64
+ xc = self.model_sampling.calculate_input(sigma, x)
65
+ if c_concat is not None:
66
+ xc = torch.cat([xc] + [c_concat], dim=1)
67
+
68
+ context = c_crossattn
69
+ dtype = self.get_dtype()
70
+
71
+ if self.manual_cast_dtype is not None:
72
+ dtype = self.manual_cast_dtype
73
+
74
+ xc = xc.to(dtype)
75
+ t = self.model_sampling.timestep(t).float()
76
+ context = context.to(dtype)
77
+ extra_conds = {}
78
+ for o in kwargs:
79
+ extra = kwargs[o]
80
+ if hasattr(extra, "dtype"):
81
+ if extra.dtype != torch.int and extra.dtype != torch.long:
82
+ extra = extra.to(dtype)
83
+ extra_conds[o] = extra
84
+
85
+ model_output = self.diffusion_model(xc, t, context=context, control=control, transformer_options=transformer_options, **extra_conds).float()
86
+ return self.model_sampling.calculate_denoised(sigma, model_output, x)
87
+
88
+ def get_dtype(self):
89
+ return self.diffusion_model.dtype
90
+
91
+ def is_adm(self):
92
+ return self.adm_channels > 0
93
+
94
+ def encode_adm(self, **kwargs):
95
+ return None
96
+
97
+ def extra_conds(self, **kwargs):
98
+ out = {}
99
+ if self.inpaint_model:
100
+ concat_keys = ("mask", "masked_image")
101
+ cond_concat = []
102
+ denoise_mask = kwargs.get("concat_mask", kwargs.get("denoise_mask", None))
103
+ concat_latent_image = kwargs.get("concat_latent_image", None)
104
+ if concat_latent_image is None:
105
+ concat_latent_image = kwargs.get("latent_image", None)
106
+ else:
107
+ concat_latent_image = self.process_latent_in(concat_latent_image)
108
+
109
+ noise = kwargs.get("noise", None)
110
+ device = kwargs["device"]
111
+
112
+ if concat_latent_image.shape[1:] != noise.shape[1:]:
113
+ concat_latent_image = utils.common_upscale(concat_latent_image, noise.shape[-1], noise.shape[-2], "bilinear", "center")
114
+
115
+ concat_latent_image = utils.resize_to_batch_size(concat_latent_image, noise.shape[0])
116
+
117
+ if len(denoise_mask.shape) == len(noise.shape):
118
+ denoise_mask = denoise_mask[:,:1]
119
+
120
+ denoise_mask = denoise_mask.reshape((-1, 1, denoise_mask.shape[-2], denoise_mask.shape[-1]))
121
+ if denoise_mask.shape[-2:] != noise.shape[-2:]:
122
+ denoise_mask = utils.common_upscale(denoise_mask, noise.shape[-1], noise.shape[-2], "bilinear", "center")
123
+ denoise_mask = utils.resize_to_batch_size(denoise_mask.round(), noise.shape[0])
124
+
125
+ def blank_inpaint_image_like(latent_image):
126
+ blank_image = torch.ones_like(latent_image)
127
+ # these are the values for "zero" in pixel space translated to latent space
128
+ blank_image[:,0] *= 0.8223
129
+ blank_image[:,1] *= -0.6876
130
+ blank_image[:,2] *= 0.6364
131
+ blank_image[:,3] *= 0.1380
132
+ return blank_image
133
+
134
+ for ck in concat_keys:
135
+ if denoise_mask is not None:
136
+ if ck == "mask":
137
+ cond_concat.append(denoise_mask.to(device))
138
+ elif ck == "masked_image":
139
+ cond_concat.append(concat_latent_image.to(device)) #NOTE: the latent_image should be masked by the mask in pixel space
140
+ else:
141
+ if ck == "mask":
142
+ cond_concat.append(torch.ones_like(noise)[:,:1])
143
+ elif ck == "masked_image":
144
+ cond_concat.append(blank_inpaint_image_like(noise))
145
+ data = torch.cat(cond_concat, dim=1)
146
+ out['c_concat'] = comfy.conds.CONDNoiseShape(data)
147
+
148
+ adm = self.encode_adm(**kwargs)
149
+ if adm is not None:
150
+ out['y'] = comfy.conds.CONDRegular(adm)
151
+
152
+ cross_attn = kwargs.get("cross_attn", None)
153
+ if cross_attn is not None:
154
+ out['c_crossattn'] = comfy.conds.CONDCrossAttn(cross_attn)
155
+
156
+ return out
157
+
158
+ def load_model_weights(self, sd, unet_prefix=""):
159
+ to_load = {}
160
+ keys = list(sd.keys())
161
+ for k in keys:
162
+ if k.startswith(unet_prefix):
163
+ to_load[k[len(unet_prefix):]] = sd.pop(k)
164
+
165
+ to_load = self.model_config.process_unet_state_dict(to_load)
166
+ m, u = self.diffusion_model.load_state_dict(to_load, strict=False)
167
+ if len(m) > 0:
168
+ print("unet missing:", m)
169
+
170
+ if len(u) > 0:
171
+ print("unet unexpected:", u)
172
+ del to_load
173
+ return self
174
+
175
+ def process_latent_in(self, latent):
176
+ return self.latent_format.process_in(latent)
177
+
178
+ def process_latent_out(self, latent):
179
+ return self.latent_format.process_out(latent)
180
+
181
+ def state_dict_for_saving(self, clip_state_dict=None, vae_state_dict=None, clip_vision_state_dict=None):
182
+ extra_sds = []
183
+ if clip_state_dict is not None:
184
+ extra_sds.append(self.model_config.process_clip_state_dict_for_saving(clip_state_dict))
185
+ if vae_state_dict is not None:
186
+ extra_sds.append(self.model_config.process_vae_state_dict_for_saving(vae_state_dict))
187
+ if clip_vision_state_dict is not None:
188
+ extra_sds.append(self.model_config.process_clip_vision_state_dict_for_saving(clip_vision_state_dict))
189
+
190
+ unet_state_dict = self.diffusion_model.state_dict()
191
+ unet_state_dict = self.model_config.process_unet_state_dict_for_saving(unet_state_dict)
192
+
193
+ if self.get_dtype() == torch.float16:
194
+ extra_sds = map(lambda sd: utils.convert_sd_to(sd, torch.float16), extra_sds)
195
+
196
+ if self.model_type == ModelType.V_PREDICTION:
197
+ unet_state_dict["v_pred"] = torch.tensor([])
198
+
199
+ for sd in extra_sds:
200
+ unet_state_dict.update(sd)
201
+
202
+ return unet_state_dict
203
+
204
+ def set_inpaint(self):
205
+ self.inpaint_model = True
206
+
207
+ def memory_required(self, input_shape):
208
+ if comfy.model_management.xformers_enabled() or comfy.model_management.pytorch_attention_flash_attention():
209
+ dtype = self.get_dtype()
210
+ if self.manual_cast_dtype is not None:
211
+ dtype = self.manual_cast_dtype
212
+ #TODO: this needs to be tweaked
213
+ area = input_shape[0] * input_shape[2] * input_shape[3]
214
+ return (area * comfy.model_management.dtype_size(dtype) / 50) * (1024 * 1024)
215
+ else:
216
+ #TODO: this formula might be too aggressive since I tweaked the sub-quad and split algorithms to use less memory.
217
+ area = input_shape[0] * input_shape[2] * input_shape[3]
218
+ return (((area * 0.6) / 0.9) + 1024) * (1024 * 1024)
219
+
220
+
221
+ def unclip_adm(unclip_conditioning, device, noise_augmentor, noise_augment_merge=0.0, seed=None):
222
+ adm_inputs = []
223
+ weights = []
224
+ noise_aug = []
225
+ for unclip_cond in unclip_conditioning:
226
+ for adm_cond in unclip_cond["clip_vision_output"].image_embeds:
227
+ weight = unclip_cond["strength"]
228
+ noise_augment = unclip_cond["noise_augmentation"]
229
+ noise_level = round((noise_augmentor.max_noise_level - 1) * noise_augment)
230
+ c_adm, noise_level_emb = noise_augmentor(adm_cond.to(device), noise_level=torch.tensor([noise_level], device=device), seed=seed)
231
+ adm_out = torch.cat((c_adm, noise_level_emb), 1) * weight
232
+ weights.append(weight)
233
+ noise_aug.append(noise_augment)
234
+ adm_inputs.append(adm_out)
235
+
236
+ if len(noise_aug) > 1:
237
+ adm_out = torch.stack(adm_inputs).sum(0)
238
+ noise_augment = noise_augment_merge
239
+ noise_level = round((noise_augmentor.max_noise_level - 1) * noise_augment)
240
+ c_adm, noise_level_emb = noise_augmentor(adm_out[:, :noise_augmentor.time_embed.dim], noise_level=torch.tensor([noise_level], device=device))
241
+ adm_out = torch.cat((c_adm, noise_level_emb), 1)
242
+
243
+ return adm_out
244
+
245
+ class SD21UNCLIP(BaseModel):
246
+ def __init__(self, model_config, noise_aug_config, model_type=ModelType.V_PREDICTION, device=None):
247
+ super().__init__(model_config, model_type, device=device)
248
+ self.noise_augmentor = CLIPEmbeddingNoiseAugmentation(**noise_aug_config)
249
+
250
+ def encode_adm(self, **kwargs):
251
+ unclip_conditioning = kwargs.get("unclip_conditioning", None)
252
+ device = kwargs["device"]
253
+ if unclip_conditioning is None:
254
+ return torch.zeros((1, self.adm_channels))
255
+ else:
256
+ return unclip_adm(unclip_conditioning, device, self.noise_augmentor, kwargs.get("unclip_noise_augment_merge", 0.05), kwargs.get("seed", 0) - 10)
257
+
258
+ def sdxl_pooled(args, noise_augmentor):
259
+ if "unclip_conditioning" in args:
260
+ return unclip_adm(args.get("unclip_conditioning", None), args["device"], noise_augmentor, seed=args.get("seed", 0) - 10)[:,:1280]
261
+ else:
262
+ return args["pooled_output"]
263
+
264
+ class SDXLRefiner(BaseModel):
265
+ def __init__(self, model_config, model_type=ModelType.EPS, device=None):
266
+ super().__init__(model_config, model_type, device=device)
267
+ self.embedder = Timestep(256)
268
+ self.noise_augmentor = CLIPEmbeddingNoiseAugmentation(**{"noise_schedule_config": {"timesteps": 1000, "beta_schedule": "squaredcos_cap_v2"}, "timestep_dim": 1280})
269
+
270
+ def encode_adm(self, **kwargs):
271
+ clip_pooled = sdxl_pooled(kwargs, self.noise_augmentor)
272
+ width = kwargs.get("width", 768)
273
+ height = kwargs.get("height", 768)
274
+ crop_w = kwargs.get("crop_w", 0)
275
+ crop_h = kwargs.get("crop_h", 0)
276
+
277
+ if kwargs.get("prompt_type", "") == "negative":
278
+ aesthetic_score = kwargs.get("aesthetic_score", 2.5)
279
+ else:
280
+ aesthetic_score = kwargs.get("aesthetic_score", 6)
281
+
282
+ out = []
283
+ out.append(self.embedder(torch.Tensor([height])))
284
+ out.append(self.embedder(torch.Tensor([width])))
285
+ out.append(self.embedder(torch.Tensor([crop_h])))
286
+ out.append(self.embedder(torch.Tensor([crop_w])))
287
+ out.append(self.embedder(torch.Tensor([aesthetic_score])))
288
+ flat = torch.flatten(torch.cat(out)).unsqueeze(dim=0).repeat(clip_pooled.shape[0], 1)
289
+ return torch.cat((clip_pooled.to(flat.device), flat), dim=1)
290
+
291
+ class SDXL(BaseModel):
292
+ def __init__(self, model_config, model_type=ModelType.EPS, device=None):
293
+ super().__init__(model_config, model_type, device=device)
294
+ self.embedder = Timestep(256)
295
+ self.noise_augmentor = CLIPEmbeddingNoiseAugmentation(**{"noise_schedule_config": {"timesteps": 1000, "beta_schedule": "squaredcos_cap_v2"}, "timestep_dim": 1280})
296
+
297
+ def encode_adm(self, **kwargs):
298
+ clip_pooled = sdxl_pooled(kwargs, self.noise_augmentor)
299
+ width = kwargs.get("width", 768)
300
+ height = kwargs.get("height", 768)
301
+ crop_w = kwargs.get("crop_w", 0)
302
+ crop_h = kwargs.get("crop_h", 0)
303
+ target_width = kwargs.get("target_width", width)
304
+ target_height = kwargs.get("target_height", height)
305
+
306
+ out = []
307
+ out.append(self.embedder(torch.Tensor([height])))
308
+ out.append(self.embedder(torch.Tensor([width])))
309
+ out.append(self.embedder(torch.Tensor([crop_h])))
310
+ out.append(self.embedder(torch.Tensor([crop_w])))
311
+ out.append(self.embedder(torch.Tensor([target_height])))
312
+ out.append(self.embedder(torch.Tensor([target_width])))
313
+ flat = torch.flatten(torch.cat(out)).unsqueeze(dim=0).repeat(clip_pooled.shape[0], 1)
314
+ return torch.cat((clip_pooled.to(flat.device), flat), dim=1)
315
+
316
+ class SVD_img2vid(BaseModel):
317
+ def __init__(self, model_config, model_type=ModelType.V_PREDICTION_EDM, device=None):
318
+ super().__init__(model_config, model_type, device=device)
319
+ self.embedder = Timestep(256)
320
+
321
+ def encode_adm(self, **kwargs):
322
+ fps_id = kwargs.get("fps", 6) - 1
323
+ motion_bucket_id = kwargs.get("motion_bucket_id", 127)
324
+ augmentation = kwargs.get("augmentation_level", 0)
325
+
326
+ out = []
327
+ out.append(self.embedder(torch.Tensor([fps_id])))
328
+ out.append(self.embedder(torch.Tensor([motion_bucket_id])))
329
+ out.append(self.embedder(torch.Tensor([augmentation])))
330
+
331
+ flat = torch.flatten(torch.cat(out)).unsqueeze(dim=0)
332
+ return flat
333
+
334
+ def extra_conds(self, **kwargs):
335
+ out = {}
336
+ adm = self.encode_adm(**kwargs)
337
+ if adm is not None:
338
+ out['y'] = comfy.conds.CONDRegular(adm)
339
+
340
+ latent_image = kwargs.get("concat_latent_image", None)
341
+ noise = kwargs.get("noise", None)
342
+ device = kwargs["device"]
343
+
344
+ if latent_image is None:
345
+ latent_image = torch.zeros_like(noise)
346
+
347
+ if latent_image.shape[1:] != noise.shape[1:]:
348
+ latent_image = utils.common_upscale(latent_image, noise.shape[-1], noise.shape[-2], "bilinear", "center")
349
+
350
+ latent_image = utils.resize_to_batch_size(latent_image, noise.shape[0])
351
+
352
+ out['c_concat'] = comfy.conds.CONDNoiseShape(latent_image)
353
+
354
+ cross_attn = kwargs.get("cross_attn", None)
355
+ if cross_attn is not None:
356
+ out['c_crossattn'] = comfy.conds.CONDCrossAttn(cross_attn)
357
+
358
+ if "time_conditioning" in kwargs:
359
+ out["time_context"] = comfy.conds.CONDCrossAttn(kwargs["time_conditioning"])
360
+
361
+ out['image_only_indicator'] = comfy.conds.CONDConstant(torch.zeros((1,), device=device))
362
+ out['num_video_frames'] = comfy.conds.CONDConstant(noise.shape[0])
363
+ return out
364
+
365
+ class Stable_Zero123(BaseModel):
366
+ def __init__(self, model_config, model_type=ModelType.EPS, device=None, cc_projection_weight=None, cc_projection_bias=None):
367
+ super().__init__(model_config, model_type, device=device)
368
+ self.cc_projection = comfy.ops.manual_cast.Linear(cc_projection_weight.shape[1], cc_projection_weight.shape[0], dtype=self.get_dtype(), device=device)
369
+ self.cc_projection.weight.copy_(cc_projection_weight)
370
+ self.cc_projection.bias.copy_(cc_projection_bias)
371
+
372
+ def extra_conds(self, **kwargs):
373
+ out = {}
374
+
375
+ latent_image = kwargs.get("concat_latent_image", None)
376
+ noise = kwargs.get("noise", None)
377
+
378
+ if latent_image is None:
379
+ latent_image = torch.zeros_like(noise)
380
+
381
+ if latent_image.shape[1:] != noise.shape[1:]:
382
+ latent_image = utils.common_upscale(latent_image, noise.shape[-1], noise.shape[-2], "bilinear", "center")
383
+
384
+ latent_image = utils.resize_to_batch_size(latent_image, noise.shape[0])
385
+
386
+ out['c_concat'] = comfy.conds.CONDNoiseShape(latent_image)
387
+
388
+ cross_attn = kwargs.get("cross_attn", None)
389
+ if cross_attn is not None:
390
+ if cross_attn.shape[-1] != 768:
391
+ cross_attn = self.cc_projection(cross_attn)
392
+ out['c_crossattn'] = comfy.conds.CONDCrossAttn(cross_attn)
393
+ return out
394
+
395
+ class SD_X4Upscaler(BaseModel):
396
+ def __init__(self, model_config, model_type=ModelType.V_PREDICTION, device=None):
397
+ super().__init__(model_config, model_type, device=device)
398
+ self.noise_augmentor = ImageConcatWithNoiseAugmentation(noise_schedule_config={"linear_start": 0.0001, "linear_end": 0.02}, max_noise_level=350)
399
+
400
+ def extra_conds(self, **kwargs):
401
+ out = {}
402
+
403
+ image = kwargs.get("concat_image", None)
404
+ noise = kwargs.get("noise", None)
405
+ noise_augment = kwargs.get("noise_augmentation", 0.0)
406
+ device = kwargs["device"]
407
+ seed = kwargs["seed"] - 10
408
+
409
+ noise_level = round((self.noise_augmentor.max_noise_level) * noise_augment)
410
+
411
+ if image is None:
412
+ image = torch.zeros_like(noise)[:,:3]
413
+
414
+ if image.shape[1:] != noise.shape[1:]:
415
+ image = utils.common_upscale(image.to(device), noise.shape[-1], noise.shape[-2], "bilinear", "center")
416
+
417
+ noise_level = torch.tensor([noise_level], device=device)
418
+ if noise_augment > 0:
419
+ image, noise_level = self.noise_augmentor(image.to(device), noise_level=noise_level, seed=seed)
420
+
421
+ image = utils.resize_to_batch_size(image, noise.shape[0])
422
+
423
+ out['c_concat'] = comfy.conds.CONDNoiseShape(image)
424
+ out['y'] = comfy.conds.CONDRegular(noise_level)
425
+ return out
comfy/model_detection.py ADDED
@@ -0,0 +1,320 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import comfy.supported_models
2
+ import comfy.supported_models_base
3
+
4
+ def count_blocks(state_dict_keys, prefix_string):
5
+ count = 0
6
+ while True:
7
+ c = False
8
+ for k in state_dict_keys:
9
+ if k.startswith(prefix_string.format(count)):
10
+ c = True
11
+ break
12
+ if c == False:
13
+ break
14
+ count += 1
15
+ return count
16
+
17
+ def calculate_transformer_depth(prefix, state_dict_keys, state_dict):
18
+ context_dim = None
19
+ use_linear_in_transformer = False
20
+
21
+ transformer_prefix = prefix + "1.transformer_blocks."
22
+ transformer_keys = sorted(list(filter(lambda a: a.startswith(transformer_prefix), state_dict_keys)))
23
+ if len(transformer_keys) > 0:
24
+ last_transformer_depth = count_blocks(state_dict_keys, transformer_prefix + '{}')
25
+ context_dim = state_dict['{}0.attn2.to_k.weight'.format(transformer_prefix)].shape[1]
26
+ use_linear_in_transformer = len(state_dict['{}1.proj_in.weight'.format(prefix)].shape) == 2
27
+ time_stack = '{}1.time_stack.0.attn1.to_q.weight'.format(prefix) in state_dict or '{}1.time_mix_blocks.0.attn1.to_q.weight'.format(prefix) in state_dict
28
+ return last_transformer_depth, context_dim, use_linear_in_transformer, time_stack
29
+ return None
30
+
31
+ def detect_unet_config(state_dict, key_prefix, dtype):
32
+ state_dict_keys = list(state_dict.keys())
33
+
34
+ unet_config = {
35
+ "use_checkpoint": False,
36
+ "image_size": 32,
37
+ "use_spatial_transformer": True,
38
+ "legacy": False
39
+ }
40
+
41
+ y_input = '{}label_emb.0.0.weight'.format(key_prefix)
42
+ if y_input in state_dict_keys:
43
+ unet_config["num_classes"] = "sequential"
44
+ unet_config["adm_in_channels"] = state_dict[y_input].shape[1]
45
+ else:
46
+ unet_config["adm_in_channels"] = None
47
+
48
+ unet_config["dtype"] = dtype
49
+ model_channels = state_dict['{}input_blocks.0.0.weight'.format(key_prefix)].shape[0]
50
+ in_channels = state_dict['{}input_blocks.0.0.weight'.format(key_prefix)].shape[1]
51
+
52
+ out_key = '{}out.2.weight'.format(key_prefix)
53
+ if out_key in state_dict:
54
+ out_channels = state_dict[out_key].shape[0]
55
+ else:
56
+ out_channels = 4
57
+
58
+ num_res_blocks = []
59
+ channel_mult = []
60
+ attention_resolutions = []
61
+ transformer_depth = []
62
+ transformer_depth_output = []
63
+ context_dim = None
64
+ use_linear_in_transformer = False
65
+
66
+ video_model = False
67
+
68
+ current_res = 1
69
+ count = 0
70
+
71
+ last_res_blocks = 0
72
+ last_channel_mult = 0
73
+
74
+ input_block_count = count_blocks(state_dict_keys, '{}input_blocks'.format(key_prefix) + '.{}.')
75
+ for count in range(input_block_count):
76
+ prefix = '{}input_blocks.{}.'.format(key_prefix, count)
77
+ prefix_output = '{}output_blocks.{}.'.format(key_prefix, input_block_count - count - 1)
78
+
79
+ block_keys = sorted(list(filter(lambda a: a.startswith(prefix), state_dict_keys)))
80
+ if len(block_keys) == 0:
81
+ break
82
+
83
+ block_keys_output = sorted(list(filter(lambda a: a.startswith(prefix_output), state_dict_keys)))
84
+
85
+ if "{}0.op.weight".format(prefix) in block_keys: #new layer
86
+ num_res_blocks.append(last_res_blocks)
87
+ channel_mult.append(last_channel_mult)
88
+
89
+ current_res *= 2
90
+ last_res_blocks = 0
91
+ last_channel_mult = 0
92
+ out = calculate_transformer_depth(prefix_output, state_dict_keys, state_dict)
93
+ if out is not None:
94
+ transformer_depth_output.append(out[0])
95
+ else:
96
+ transformer_depth_output.append(0)
97
+ else:
98
+ res_block_prefix = "{}0.in_layers.0.weight".format(prefix)
99
+ if res_block_prefix in block_keys:
100
+ last_res_blocks += 1
101
+ last_channel_mult = state_dict["{}0.out_layers.3.weight".format(prefix)].shape[0] // model_channels
102
+
103
+ out = calculate_transformer_depth(prefix, state_dict_keys, state_dict)
104
+ if out is not None:
105
+ transformer_depth.append(out[0])
106
+ if context_dim is None:
107
+ context_dim = out[1]
108
+ use_linear_in_transformer = out[2]
109
+ video_model = out[3]
110
+ else:
111
+ transformer_depth.append(0)
112
+
113
+ res_block_prefix = "{}0.in_layers.0.weight".format(prefix_output)
114
+ if res_block_prefix in block_keys_output:
115
+ out = calculate_transformer_depth(prefix_output, state_dict_keys, state_dict)
116
+ if out is not None:
117
+ transformer_depth_output.append(out[0])
118
+ else:
119
+ transformer_depth_output.append(0)
120
+
121
+
122
+ num_res_blocks.append(last_res_blocks)
123
+ channel_mult.append(last_channel_mult)
124
+ if "{}middle_block.1.proj_in.weight".format(key_prefix) in state_dict_keys:
125
+ transformer_depth_middle = count_blocks(state_dict_keys, '{}middle_block.1.transformer_blocks.'.format(key_prefix) + '{}')
126
+ else:
127
+ transformer_depth_middle = -1
128
+
129
+ unet_config["in_channels"] = in_channels
130
+ unet_config["out_channels"] = out_channels
131
+ unet_config["model_channels"] = model_channels
132
+ unet_config["num_res_blocks"] = num_res_blocks
133
+ unet_config["transformer_depth"] = transformer_depth
134
+ unet_config["transformer_depth_output"] = transformer_depth_output
135
+ unet_config["channel_mult"] = channel_mult
136
+ unet_config["transformer_depth_middle"] = transformer_depth_middle
137
+ unet_config['use_linear_in_transformer'] = use_linear_in_transformer
138
+ unet_config["context_dim"] = context_dim
139
+
140
+ if video_model:
141
+ unet_config["extra_ff_mix_layer"] = True
142
+ unet_config["use_spatial_context"] = True
143
+ unet_config["merge_strategy"] = "learned_with_images"
144
+ unet_config["merge_factor"] = 0.0
145
+ unet_config["video_kernel_size"] = [3, 1, 1]
146
+ unet_config["use_temporal_resblock"] = True
147
+ unet_config["use_temporal_attention"] = True
148
+ else:
149
+ unet_config["use_temporal_resblock"] = False
150
+ unet_config["use_temporal_attention"] = False
151
+
152
+ return unet_config
153
+
154
+ def model_config_from_unet_config(unet_config):
155
+ for model_config in comfy.supported_models.models:
156
+ if model_config.matches(unet_config):
157
+ return model_config(unet_config)
158
+
159
+ print("no match", unet_config)
160
+ return None
161
+
162
+ def model_config_from_unet(state_dict, unet_key_prefix, dtype, use_base_if_no_match=False):
163
+ unet_config = detect_unet_config(state_dict, unet_key_prefix, dtype)
164
+ model_config = model_config_from_unet_config(unet_config)
165
+ if model_config is None and use_base_if_no_match:
166
+ return comfy.supported_models_base.BASE(unet_config)
167
+ else:
168
+ return model_config
169
+
170
+ def convert_config(unet_config):
171
+ new_config = unet_config.copy()
172
+ num_res_blocks = new_config.get("num_res_blocks", None)
173
+ channel_mult = new_config.get("channel_mult", None)
174
+
175
+ if isinstance(num_res_blocks, int):
176
+ num_res_blocks = len(channel_mult) * [num_res_blocks]
177
+
178
+ if "attention_resolutions" in new_config:
179
+ attention_resolutions = new_config.pop("attention_resolutions")
180
+ transformer_depth = new_config.get("transformer_depth", None)
181
+ transformer_depth_middle = new_config.get("transformer_depth_middle", None)
182
+
183
+ if isinstance(transformer_depth, int):
184
+ transformer_depth = len(channel_mult) * [transformer_depth]
185
+ if transformer_depth_middle is None:
186
+ transformer_depth_middle = transformer_depth[-1]
187
+ t_in = []
188
+ t_out = []
189
+ s = 1
190
+ for i in range(len(num_res_blocks)):
191
+ res = num_res_blocks[i]
192
+ d = 0
193
+ if s in attention_resolutions:
194
+ d = transformer_depth[i]
195
+
196
+ t_in += [d] * res
197
+ t_out += [d] * (res + 1)
198
+ s *= 2
199
+ transformer_depth = t_in
200
+ transformer_depth_output = t_out
201
+ new_config["transformer_depth"] = t_in
202
+ new_config["transformer_depth_output"] = t_out
203
+ new_config["transformer_depth_middle"] = transformer_depth_middle
204
+
205
+ new_config["num_res_blocks"] = num_res_blocks
206
+ return new_config
207
+
208
+
209
+ def unet_config_from_diffusers_unet(state_dict, dtype):
210
+ match = {}
211
+ transformer_depth = []
212
+
213
+ attn_res = 1
214
+ down_blocks = count_blocks(state_dict, "down_blocks.{}")
215
+ for i in range(down_blocks):
216
+ attn_blocks = count_blocks(state_dict, "down_blocks.{}.attentions.".format(i) + '{}')
217
+ for ab in range(attn_blocks):
218
+ transformer_count = count_blocks(state_dict, "down_blocks.{}.attentions.{}.transformer_blocks.".format(i, ab) + '{}')
219
+ transformer_depth.append(transformer_count)
220
+ if transformer_count > 0:
221
+ match["context_dim"] = state_dict["down_blocks.{}.attentions.{}.transformer_blocks.0.attn2.to_k.weight".format(i, ab)].shape[1]
222
+
223
+ attn_res *= 2
224
+ if attn_blocks == 0:
225
+ transformer_depth.append(0)
226
+ transformer_depth.append(0)
227
+
228
+ match["transformer_depth"] = transformer_depth
229
+
230
+ match["model_channels"] = state_dict["conv_in.weight"].shape[0]
231
+ match["in_channels"] = state_dict["conv_in.weight"].shape[1]
232
+ match["adm_in_channels"] = None
233
+ if "class_embedding.linear_1.weight" in state_dict:
234
+ match["adm_in_channels"] = state_dict["class_embedding.linear_1.weight"].shape[1]
235
+ elif "add_embedding.linear_1.weight" in state_dict:
236
+ match["adm_in_channels"] = state_dict["add_embedding.linear_1.weight"].shape[1]
237
+
238
+ SDXL = {'use_checkpoint': False, 'image_size': 32, 'out_channels': 4, 'use_spatial_transformer': True, 'legacy': False,
239
+ 'num_classes': 'sequential', 'adm_in_channels': 2816, 'dtype': dtype, 'in_channels': 4, 'model_channels': 320,
240
+ 'num_res_blocks': [2, 2, 2], 'transformer_depth': [0, 0, 2, 2, 10, 10], 'channel_mult': [1, 2, 4], 'transformer_depth_middle': 10,
241
+ 'use_linear_in_transformer': True, 'context_dim': 2048, 'num_head_channels': 64, 'transformer_depth_output': [0, 0, 0, 2, 2, 2, 10, 10, 10],
242
+ 'use_temporal_attention': False, 'use_temporal_resblock': False}
243
+
244
+ SDXL_refiner = {'use_checkpoint': False, 'image_size': 32, 'out_channels': 4, 'use_spatial_transformer': True, 'legacy': False,
245
+ 'num_classes': 'sequential', 'adm_in_channels': 2560, 'dtype': dtype, 'in_channels': 4, 'model_channels': 384,
246
+ 'num_res_blocks': [2, 2, 2, 2], 'transformer_depth': [0, 0, 4, 4, 4, 4, 0, 0], 'channel_mult': [1, 2, 4, 4], 'transformer_depth_middle': 4,
247
+ 'use_linear_in_transformer': True, 'context_dim': 1280, 'num_head_channels': 64, 'transformer_depth_output': [0, 0, 0, 4, 4, 4, 4, 4, 4, 0, 0, 0],
248
+ 'use_temporal_attention': False, 'use_temporal_resblock': False}
249
+
250
+ SD21 = {'use_checkpoint': False, 'image_size': 32, 'out_channels': 4, 'use_spatial_transformer': True, 'legacy': False,
251
+ 'adm_in_channels': None, 'dtype': dtype, 'in_channels': 4, 'model_channels': 320, 'num_res_blocks': [2, 2, 2, 2],
252
+ 'transformer_depth': [1, 1, 1, 1, 1, 1, 0, 0], 'channel_mult': [1, 2, 4, 4], 'transformer_depth_middle': 1, 'use_linear_in_transformer': True,
253
+ 'context_dim': 1024, 'num_head_channels': 64, 'transformer_depth_output': [1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0],
254
+ 'use_temporal_attention': False, 'use_temporal_resblock': False}
255
+
256
+ SD21_uncliph = {'use_checkpoint': False, 'image_size': 32, 'out_channels': 4, 'use_spatial_transformer': True, 'legacy': False,
257
+ 'num_classes': 'sequential', 'adm_in_channels': 2048, 'dtype': dtype, 'in_channels': 4, 'model_channels': 320,
258
+ 'num_res_blocks': [2, 2, 2, 2], 'transformer_depth': [1, 1, 1, 1, 1, 1, 0, 0], 'channel_mult': [1, 2, 4, 4], 'transformer_depth_middle': 1,
259
+ 'use_linear_in_transformer': True, 'context_dim': 1024, 'num_head_channels': 64, 'transformer_depth_output': [1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0],
260
+ 'use_temporal_attention': False, 'use_temporal_resblock': False}
261
+
262
+ SD21_unclipl = {'use_checkpoint': False, 'image_size': 32, 'out_channels': 4, 'use_spatial_transformer': True, 'legacy': False,
263
+ 'num_classes': 'sequential', 'adm_in_channels': 1536, 'dtype': dtype, 'in_channels': 4, 'model_channels': 320,
264
+ 'num_res_blocks': [2, 2, 2, 2], 'transformer_depth': [1, 1, 1, 1, 1, 1, 0, 0], 'channel_mult': [1, 2, 4, 4], 'transformer_depth_middle': 1,
265
+ 'use_linear_in_transformer': True, 'context_dim': 1024, 'num_head_channels': 64, 'transformer_depth_output': [1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0],
266
+ 'use_temporal_attention': False, 'use_temporal_resblock': False}
267
+
268
+ SD15 = {'use_checkpoint': False, 'image_size': 32, 'out_channels': 4, 'use_spatial_transformer': True, 'legacy': False, 'adm_in_channels': None,
269
+ 'dtype': dtype, 'in_channels': 4, 'model_channels': 320, 'num_res_blocks': [2, 2, 2, 2], 'transformer_depth': [1, 1, 1, 1, 1, 1, 0, 0],
270
+ 'channel_mult': [1, 2, 4, 4], 'transformer_depth_middle': 1, 'use_linear_in_transformer': False, 'context_dim': 768, 'num_heads': 8,
271
+ 'transformer_depth_output': [1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0],
272
+ 'use_temporal_attention': False, 'use_temporal_resblock': False}
273
+
274
+ SDXL_mid_cnet = {'use_checkpoint': False, 'image_size': 32, 'out_channels': 4, 'use_spatial_transformer': True, 'legacy': False,
275
+ 'num_classes': 'sequential', 'adm_in_channels': 2816, 'dtype': dtype, 'in_channels': 4, 'model_channels': 320,
276
+ 'num_res_blocks': [2, 2, 2], 'transformer_depth': [0, 0, 0, 0, 1, 1], 'channel_mult': [1, 2, 4], 'transformer_depth_middle': 1,
277
+ 'use_linear_in_transformer': True, 'context_dim': 2048, 'num_head_channels': 64, 'transformer_depth_output': [0, 0, 0, 0, 0, 0, 1, 1, 1],
278
+ 'use_temporal_attention': False, 'use_temporal_resblock': False}
279
+
280
+ SDXL_small_cnet = {'use_checkpoint': False, 'image_size': 32, 'out_channels': 4, 'use_spatial_transformer': True, 'legacy': False,
281
+ 'num_classes': 'sequential', 'adm_in_channels': 2816, 'dtype': dtype, 'in_channels': 4, 'model_channels': 320,
282
+ 'num_res_blocks': [2, 2, 2], 'transformer_depth': [0, 0, 0, 0, 0, 0], 'channel_mult': [1, 2, 4], 'transformer_depth_middle': 0,
283
+ 'use_linear_in_transformer': True, 'num_head_channels': 64, 'context_dim': 1, 'transformer_depth_output': [0, 0, 0, 0, 0, 0, 0, 0, 0],
284
+ 'use_temporal_attention': False, 'use_temporal_resblock': False}
285
+
286
+ SDXL_diffusers_inpaint = {'use_checkpoint': False, 'image_size': 32, 'out_channels': 4, 'use_spatial_transformer': True, 'legacy': False,
287
+ 'num_classes': 'sequential', 'adm_in_channels': 2816, 'dtype': dtype, 'in_channels': 9, 'model_channels': 320,
288
+ 'num_res_blocks': [2, 2, 2], 'transformer_depth': [0, 0, 2, 2, 10, 10], 'channel_mult': [1, 2, 4], 'transformer_depth_middle': 10,
289
+ 'use_linear_in_transformer': True, 'context_dim': 2048, 'num_head_channels': 64, 'transformer_depth_output': [0, 0, 0, 2, 2, 2, 10, 10, 10],
290
+ 'use_temporal_attention': False, 'use_temporal_resblock': False}
291
+
292
+ SSD_1B = {'use_checkpoint': False, 'image_size': 32, 'out_channels': 4, 'use_spatial_transformer': True, 'legacy': False,
293
+ 'num_classes': 'sequential', 'adm_in_channels': 2816, 'dtype': dtype, 'in_channels': 4, 'model_channels': 320,
294
+ 'num_res_blocks': [2, 2, 2], 'transformer_depth': [0, 0, 2, 2, 4, 4], 'transformer_depth_output': [0, 0, 0, 1, 1, 2, 10, 4, 4],
295
+ 'channel_mult': [1, 2, 4], 'transformer_depth_middle': -1, 'use_linear_in_transformer': True, 'context_dim': 2048, 'num_head_channels': 64,
296
+ 'use_temporal_attention': False, 'use_temporal_resblock': False}
297
+
298
+ Segmind_Vega = {'use_checkpoint': False, 'image_size': 32, 'out_channels': 4, 'use_spatial_transformer': True, 'legacy': False,
299
+ 'num_classes': 'sequential', 'adm_in_channels': 2816, 'dtype': dtype, 'in_channels': 4, 'model_channels': 320,
300
+ 'num_res_blocks': [2, 2, 2], 'transformer_depth': [0, 0, 1, 1, 2, 2], 'transformer_depth_output': [0, 0, 0, 1, 1, 1, 2, 2, 2],
301
+ 'channel_mult': [1, 2, 4], 'transformer_depth_middle': -1, 'use_linear_in_transformer': True, 'context_dim': 2048, 'num_head_channels': 64,
302
+ 'use_temporal_attention': False, 'use_temporal_resblock': False}
303
+
304
+ supported_models = [SDXL, SDXL_refiner, SD21, SD15, SD21_uncliph, SD21_unclipl, SDXL_mid_cnet, SDXL_small_cnet, SDXL_diffusers_inpaint, SSD_1B, Segmind_Vega]
305
+
306
+ for unet_config in supported_models:
307
+ matches = True
308
+ for k in match:
309
+ if match[k] != unet_config[k]:
310
+ matches = False
311
+ break
312
+ if matches:
313
+ return convert_config(unet_config)
314
+ return None
315
+
316
+ def model_config_from_diffusers_unet(state_dict, dtype):
317
+ unet_config = unet_config_from_diffusers_unet(state_dict, dtype)
318
+ if unet_config is not None:
319
+ return model_config_from_unet_config(unet_config)
320
+ return None
comfy/model_management.py ADDED
@@ -0,0 +1,805 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import psutil
2
+ from enum import Enum
3
+ from comfy.cli_args import args
4
+ import comfy.utils
5
+ import torch
6
+ import sys
7
+
8
+ class VRAMState(Enum):
9
+ DISABLED = 0 #No vram present: no need to move models to vram
10
+ NO_VRAM = 1 #Very low vram: enable all the options to save vram
11
+ LOW_VRAM = 2
12
+ NORMAL_VRAM = 3
13
+ HIGH_VRAM = 4
14
+ SHARED = 5 #No dedicated vram: memory shared between CPU and GPU but models still need to be moved between both.
15
+
16
+ class CPUState(Enum):
17
+ GPU = 0
18
+ CPU = 1
19
+ MPS = 2
20
+
21
+ # Determine VRAM State
22
+ vram_state = VRAMState.NORMAL_VRAM
23
+ set_vram_to = VRAMState.NORMAL_VRAM
24
+ cpu_state = CPUState.GPU
25
+
26
+ total_vram = 0
27
+
28
+ lowvram_available = True
29
+ xpu_available = False
30
+
31
+ if args.deterministic:
32
+ print("Using deterministic algorithms for pytorch")
33
+ torch.use_deterministic_algorithms(True, warn_only=True)
34
+
35
+ directml_enabled = False
36
+ if args.directml is not None:
37
+ import torch_directml
38
+ directml_enabled = True
39
+ device_index = args.directml
40
+ if device_index < 0:
41
+ directml_device = torch_directml.device()
42
+ else:
43
+ directml_device = torch_directml.device(device_index)
44
+ print("Using directml with device:", torch_directml.device_name(device_index))
45
+ # torch_directml.disable_tiled_resources(True)
46
+ lowvram_available = False #TODO: need to find a way to get free memory in directml before this can be enabled by default.
47
+
48
+ try:
49
+ import intel_extension_for_pytorch as ipex
50
+ if torch.xpu.is_available():
51
+ xpu_available = True
52
+ except:
53
+ pass
54
+
55
+ try:
56
+ if torch.backends.mps.is_available():
57
+ cpu_state = CPUState.MPS
58
+ import torch.mps
59
+ except:
60
+ pass
61
+
62
+ if args.cpu:
63
+ cpu_state = CPUState.CPU
64
+
65
+ def is_intel_xpu():
66
+ global cpu_state
67
+ global xpu_available
68
+ if cpu_state == CPUState.GPU:
69
+ if xpu_available:
70
+ return True
71
+ return False
72
+
73
+ def get_torch_device():
74
+ global directml_enabled
75
+ global cpu_state
76
+ if directml_enabled:
77
+ global directml_device
78
+ return directml_device
79
+ if cpu_state == CPUState.MPS:
80
+ return torch.device("mps")
81
+ if cpu_state == CPUState.CPU:
82
+ return torch.device("cpu")
83
+ else:
84
+ if is_intel_xpu():
85
+ return torch.device("xpu")
86
+ else:
87
+ return torch.device(torch.cuda.current_device())
88
+
89
+ def get_total_memory(dev=None, torch_total_too=False):
90
+ global directml_enabled
91
+ if dev is None:
92
+ dev = get_torch_device()
93
+
94
+ if hasattr(dev, 'type') and (dev.type == 'cpu' or dev.type == 'mps'):
95
+ mem_total = psutil.virtual_memory().total
96
+ mem_total_torch = mem_total
97
+ else:
98
+ if directml_enabled:
99
+ mem_total = 1024 * 1024 * 1024 #TODO
100
+ mem_total_torch = mem_total
101
+ elif is_intel_xpu():
102
+ stats = torch.xpu.memory_stats(dev)
103
+ mem_reserved = stats['reserved_bytes.all.current']
104
+ mem_total = torch.xpu.get_device_properties(dev).total_memory
105
+ mem_total_torch = mem_reserved
106
+ else:
107
+ stats = torch.cuda.memory_stats(dev)
108
+ mem_reserved = stats['reserved_bytes.all.current']
109
+ _, mem_total_cuda = torch.cuda.mem_get_info(dev)
110
+ mem_total_torch = mem_reserved
111
+ mem_total = mem_total_cuda
112
+
113
+ if torch_total_too:
114
+ return (mem_total, mem_total_torch)
115
+ else:
116
+ return mem_total
117
+
118
+ total_vram = get_total_memory(get_torch_device()) / (1024 * 1024)
119
+ total_ram = psutil.virtual_memory().total / (1024 * 1024)
120
+ print("Total VRAM {:0.0f} MB, total RAM {:0.0f} MB".format(total_vram, total_ram))
121
+ if not args.normalvram and not args.cpu:
122
+ if lowvram_available and total_vram <= 4096:
123
+ print("Trying to enable lowvram mode because your GPU seems to have 4GB or less. If you don't want this use: --normalvram")
124
+ set_vram_to = VRAMState.LOW_VRAM
125
+
126
+ try:
127
+ OOM_EXCEPTION = torch.cuda.OutOfMemoryError
128
+ except:
129
+ OOM_EXCEPTION = Exception
130
+
131
+ XFORMERS_VERSION = ""
132
+ XFORMERS_ENABLED_VAE = True
133
+ if args.disable_xformers:
134
+ XFORMERS_IS_AVAILABLE = False
135
+ else:
136
+ try:
137
+ import xformers
138
+ import xformers.ops
139
+ XFORMERS_IS_AVAILABLE = True
140
+ try:
141
+ XFORMERS_IS_AVAILABLE = xformers._has_cpp_library
142
+ except:
143
+ pass
144
+ try:
145
+ XFORMERS_VERSION = xformers.version.__version__
146
+ print("xformers version:", XFORMERS_VERSION)
147
+ if XFORMERS_VERSION.startswith("0.0.18"):
148
+ print()
149
+ print("WARNING: This version of xformers has a major bug where you will get black images when generating high resolution images.")
150
+ print("Please downgrade or upgrade xformers to a different version.")
151
+ print()
152
+ XFORMERS_ENABLED_VAE = False
153
+ except:
154
+ pass
155
+ except:
156
+ XFORMERS_IS_AVAILABLE = False
157
+
158
+ def is_nvidia():
159
+ global cpu_state
160
+ if cpu_state == CPUState.GPU:
161
+ if torch.version.cuda:
162
+ return True
163
+ return False
164
+
165
+ ENABLE_PYTORCH_ATTENTION = False
166
+ if args.use_pytorch_cross_attention:
167
+ ENABLE_PYTORCH_ATTENTION = True
168
+ XFORMERS_IS_AVAILABLE = False
169
+
170
+ VAE_DTYPE = torch.float32
171
+
172
+ try:
173
+ if is_nvidia():
174
+ torch_version = torch.version.__version__
175
+ if int(torch_version[0]) >= 2:
176
+ if ENABLE_PYTORCH_ATTENTION == False and args.use_split_cross_attention == False and args.use_quad_cross_attention == False:
177
+ ENABLE_PYTORCH_ATTENTION = True
178
+ if torch.cuda.is_bf16_supported() and torch.cuda.get_device_properties(torch.cuda.current_device()).major >= 8:
179
+ VAE_DTYPE = torch.bfloat16
180
+ if is_intel_xpu():
181
+ if args.use_split_cross_attention == False and args.use_quad_cross_attention == False:
182
+ ENABLE_PYTORCH_ATTENTION = True
183
+ except:
184
+ pass
185
+
186
+ if is_intel_xpu():
187
+ VAE_DTYPE = torch.bfloat16
188
+
189
+ if args.cpu_vae:
190
+ VAE_DTYPE = torch.float32
191
+
192
+ if args.fp16_vae:
193
+ VAE_DTYPE = torch.float16
194
+ elif args.bf16_vae:
195
+ VAE_DTYPE = torch.bfloat16
196
+ elif args.fp32_vae:
197
+ VAE_DTYPE = torch.float32
198
+
199
+
200
+ if ENABLE_PYTORCH_ATTENTION:
201
+ torch.backends.cuda.enable_math_sdp(True)
202
+ torch.backends.cuda.enable_flash_sdp(True)
203
+ torch.backends.cuda.enable_mem_efficient_sdp(True)
204
+
205
+ if args.lowvram:
206
+ set_vram_to = VRAMState.LOW_VRAM
207
+ lowvram_available = True
208
+ elif args.novram:
209
+ set_vram_to = VRAMState.NO_VRAM
210
+ elif args.highvram or args.gpu_only:
211
+ vram_state = VRAMState.HIGH_VRAM
212
+
213
+ FORCE_FP32 = False
214
+ FORCE_FP16 = False
215
+ if args.force_fp32:
216
+ print("Forcing FP32, if this improves things please report it.")
217
+ FORCE_FP32 = True
218
+
219
+ if args.force_fp16:
220
+ print("Forcing FP16.")
221
+ FORCE_FP16 = True
222
+
223
+ if lowvram_available:
224
+ if set_vram_to in (VRAMState.LOW_VRAM, VRAMState.NO_VRAM):
225
+ vram_state = set_vram_to
226
+
227
+
228
+ if cpu_state != CPUState.GPU:
229
+ vram_state = VRAMState.DISABLED
230
+
231
+ if cpu_state == CPUState.MPS:
232
+ vram_state = VRAMState.SHARED
233
+
234
+ print(f"Set vram state to: {vram_state.name}")
235
+
236
+ DISABLE_SMART_MEMORY = args.disable_smart_memory
237
+
238
+ if DISABLE_SMART_MEMORY:
239
+ print("Disabling smart memory management")
240
+
241
+ def get_torch_device_name(device):
242
+ if hasattr(device, 'type'):
243
+ if device.type == "cuda":
244
+ try:
245
+ allocator_backend = torch.cuda.get_allocator_backend()
246
+ except:
247
+ allocator_backend = ""
248
+ return "{} {} : {}".format(device, torch.cuda.get_device_name(device), allocator_backend)
249
+ else:
250
+ return "{}".format(device.type)
251
+ elif is_intel_xpu():
252
+ return "{} {}".format(device, torch.xpu.get_device_name(device))
253
+ else:
254
+ return "CUDA {}: {}".format(device, torch.cuda.get_device_name(device))
255
+
256
+ try:
257
+ print("Device:", get_torch_device_name(get_torch_device()))
258
+ except:
259
+ print("Could not pick default device.")
260
+
261
+ print("VAE dtype:", VAE_DTYPE)
262
+
263
+ current_loaded_models = []
264
+
265
+ def module_size(module):
266
+ module_mem = 0
267
+ sd = module.state_dict()
268
+ for k in sd:
269
+ t = sd[k]
270
+ module_mem += t.nelement() * t.element_size()
271
+ return module_mem
272
+
273
+ class LoadedModel:
274
+ def __init__(self, model):
275
+ self.model = model
276
+ self.model_accelerated = False
277
+ self.device = model.load_device
278
+
279
+ def model_memory(self):
280
+ return self.model.model_size()
281
+
282
+ def model_memory_required(self, device):
283
+ if device == self.model.current_device:
284
+ return 0
285
+ else:
286
+ return self.model_memory()
287
+
288
+ def model_load(self, lowvram_model_memory=0):
289
+ patch_model_to = None
290
+ if lowvram_model_memory == 0:
291
+ patch_model_to = self.device
292
+
293
+ self.model.model_patches_to(self.device)
294
+ self.model.model_patches_to(self.model.model_dtype())
295
+
296
+ try:
297
+ self.real_model = self.model.patch_model(device_to=patch_model_to) #TODO: do something with loras and offloading to CPU
298
+ except Exception as e:
299
+ self.model.unpatch_model(self.model.offload_device)
300
+ self.model_unload()
301
+ raise e
302
+
303
+ if lowvram_model_memory > 0:
304
+ print("loading in lowvram mode", lowvram_model_memory/(1024 * 1024))
305
+ mem_counter = 0
306
+ for m in self.real_model.modules():
307
+ if hasattr(m, "comfy_cast_weights"):
308
+ m.prev_comfy_cast_weights = m.comfy_cast_weights
309
+ m.comfy_cast_weights = True
310
+ module_mem = module_size(m)
311
+ if mem_counter + module_mem < lowvram_model_memory:
312
+ m.to(self.device)
313
+ mem_counter += module_mem
314
+ elif hasattr(m, "weight"): #only modules with comfy_cast_weights can be set to lowvram mode
315
+ m.to(self.device)
316
+ mem_counter += module_size(m)
317
+ print("lowvram: loaded module regularly", m)
318
+
319
+ self.model_accelerated = True
320
+
321
+ if is_intel_xpu() and not args.disable_ipex_optimize:
322
+ self.real_model = torch.xpu.optimize(self.real_model.eval(), inplace=True, auto_kernel_selection=True, graph_mode=True)
323
+
324
+ return self.real_model
325
+
326
+ def model_unload(self):
327
+ if self.model_accelerated:
328
+ for m in self.real_model.modules():
329
+ if hasattr(m, "prev_comfy_cast_weights"):
330
+ m.comfy_cast_weights = m.prev_comfy_cast_weights
331
+ del m.prev_comfy_cast_weights
332
+
333
+ self.model_accelerated = False
334
+
335
+ self.model.unpatch_model(self.model.offload_device)
336
+ self.model.model_patches_to(self.model.offload_device)
337
+
338
+ def __eq__(self, other):
339
+ return self.model is other.model
340
+
341
+ def minimum_inference_memory():
342
+ return (1024 * 1024 * 1024)
343
+
344
+ def unload_model_clones(model):
345
+ to_unload = []
346
+ for i in range(len(current_loaded_models)):
347
+ if model.is_clone(current_loaded_models[i].model):
348
+ to_unload = [i] + to_unload
349
+
350
+ for i in to_unload:
351
+ print("unload clone", i)
352
+ current_loaded_models.pop(i).model_unload()
353
+
354
+ def free_memory(memory_required, device, keep_loaded=[]):
355
+ unloaded_model = False
356
+ for i in range(len(current_loaded_models) -1, -1, -1):
357
+ if not DISABLE_SMART_MEMORY:
358
+ if get_free_memory(device) > memory_required:
359
+ break
360
+ shift_model = current_loaded_models[i]
361
+ if shift_model.device == device:
362
+ if shift_model not in keep_loaded:
363
+ m = current_loaded_models.pop(i)
364
+ m.model_unload()
365
+ del m
366
+ unloaded_model = True
367
+
368
+ if unloaded_model:
369
+ soft_empty_cache()
370
+ else:
371
+ if vram_state != VRAMState.HIGH_VRAM:
372
+ mem_free_total, mem_free_torch = get_free_memory(device, torch_free_too=True)
373
+ if mem_free_torch > mem_free_total * 0.25:
374
+ soft_empty_cache()
375
+
376
+ def load_models_gpu(models, memory_required=0):
377
+ global vram_state
378
+
379
+ inference_memory = minimum_inference_memory()
380
+ extra_mem = max(inference_memory, memory_required)
381
+
382
+ models_to_load = []
383
+ models_already_loaded = []
384
+ for x in models:
385
+ loaded_model = LoadedModel(x)
386
+
387
+ if loaded_model in current_loaded_models:
388
+ index = current_loaded_models.index(loaded_model)
389
+ current_loaded_models.insert(0, current_loaded_models.pop(index))
390
+ models_already_loaded.append(loaded_model)
391
+ else:
392
+ if hasattr(x, "model"):
393
+ print(f"Requested to load {x.model.__class__.__name__}")
394
+ models_to_load.append(loaded_model)
395
+
396
+ if len(models_to_load) == 0:
397
+ devs = set(map(lambda a: a.device, models_already_loaded))
398
+ for d in devs:
399
+ if d != torch.device("cpu"):
400
+ free_memory(extra_mem, d, models_already_loaded)
401
+ return
402
+
403
+ print(f"Loading {len(models_to_load)} new model{'s' if len(models_to_load) > 1 else ''}")
404
+
405
+ total_memory_required = {}
406
+ for loaded_model in models_to_load:
407
+ unload_model_clones(loaded_model.model)
408
+ total_memory_required[loaded_model.device] = total_memory_required.get(loaded_model.device, 0) + loaded_model.model_memory_required(loaded_model.device)
409
+
410
+ for device in total_memory_required:
411
+ if device != torch.device("cpu"):
412
+ free_memory(total_memory_required[device] * 1.3 + extra_mem, device, models_already_loaded)
413
+
414
+ for loaded_model in models_to_load:
415
+ model = loaded_model.model
416
+ torch_dev = model.load_device
417
+ if is_device_cpu(torch_dev):
418
+ vram_set_state = VRAMState.DISABLED
419
+ else:
420
+ vram_set_state = vram_state
421
+ lowvram_model_memory = 0
422
+ if lowvram_available and (vram_set_state == VRAMState.LOW_VRAM or vram_set_state == VRAMState.NORMAL_VRAM):
423
+ model_size = loaded_model.model_memory_required(torch_dev)
424
+ current_free_mem = get_free_memory(torch_dev)
425
+ lowvram_model_memory = int(max(64 * (1024 * 1024), (current_free_mem - 1024 * (1024 * 1024)) / 1.3 ))
426
+ if model_size > (current_free_mem - inference_memory): #only switch to lowvram if really necessary
427
+ vram_set_state = VRAMState.LOW_VRAM
428
+ else:
429
+ lowvram_model_memory = 0
430
+
431
+ if vram_set_state == VRAMState.NO_VRAM:
432
+ lowvram_model_memory = 64 * 1024 * 1024
433
+
434
+ cur_loaded_model = loaded_model.model_load(lowvram_model_memory)
435
+ current_loaded_models.insert(0, loaded_model)
436
+ return
437
+
438
+
439
+ def load_model_gpu(model):
440
+ return load_models_gpu([model])
441
+
442
+ def cleanup_models():
443
+ to_delete = []
444
+ for i in range(len(current_loaded_models)):
445
+ if sys.getrefcount(current_loaded_models[i].model) <= 2:
446
+ to_delete = [i] + to_delete
447
+
448
+ for i in to_delete:
449
+ x = current_loaded_models.pop(i)
450
+ x.model_unload()
451
+ del x
452
+
453
+ def dtype_size(dtype):
454
+ dtype_size = 4
455
+ if dtype == torch.float16 or dtype == torch.bfloat16:
456
+ dtype_size = 2
457
+ elif dtype == torch.float32:
458
+ dtype_size = 4
459
+ else:
460
+ try:
461
+ dtype_size = dtype.itemsize
462
+ except: #Old pytorch doesn't have .itemsize
463
+ pass
464
+ return dtype_size
465
+
466
+ def unet_offload_device():
467
+ if vram_state == VRAMState.HIGH_VRAM:
468
+ return get_torch_device()
469
+ else:
470
+ return torch.device("cpu")
471
+
472
+ def unet_inital_load_device(parameters, dtype):
473
+ torch_dev = get_torch_device()
474
+ if vram_state == VRAMState.HIGH_VRAM:
475
+ return torch_dev
476
+
477
+ cpu_dev = torch.device("cpu")
478
+ if DISABLE_SMART_MEMORY:
479
+ return cpu_dev
480
+
481
+ model_size = dtype_size(dtype) * parameters
482
+
483
+ mem_dev = get_free_memory(torch_dev)
484
+ mem_cpu = get_free_memory(cpu_dev)
485
+ if mem_dev > mem_cpu and model_size < mem_dev:
486
+ return torch_dev
487
+ else:
488
+ return cpu_dev
489
+
490
+ def unet_dtype(device=None, model_params=0):
491
+ if args.bf16_unet:
492
+ return torch.bfloat16
493
+ if args.fp16_unet:
494
+ return torch.float16
495
+ if args.fp8_e4m3fn_unet:
496
+ return torch.float8_e4m3fn
497
+ if args.fp8_e5m2_unet:
498
+ return torch.float8_e5m2
499
+ if should_use_fp16(device=device, model_params=model_params, manual_cast=True):
500
+ return torch.float16
501
+ return torch.float32
502
+
503
+ # None means no manual cast
504
+ def unet_manual_cast(weight_dtype, inference_device):
505
+ if weight_dtype == torch.float32:
506
+ return None
507
+
508
+ fp16_supported = comfy.model_management.should_use_fp16(inference_device, prioritize_performance=False)
509
+ if fp16_supported and weight_dtype == torch.float16:
510
+ return None
511
+
512
+ if fp16_supported:
513
+ return torch.float16
514
+ else:
515
+ return torch.float32
516
+
517
+ def text_encoder_offload_device():
518
+ if args.gpu_only:
519
+ return get_torch_device()
520
+ else:
521
+ return torch.device("cpu")
522
+
523
+ def text_encoder_device():
524
+ if args.gpu_only:
525
+ return get_torch_device()
526
+ elif vram_state == VRAMState.HIGH_VRAM or vram_state == VRAMState.NORMAL_VRAM:
527
+ if is_intel_xpu():
528
+ return torch.device("cpu")
529
+ if should_use_fp16(prioritize_performance=False):
530
+ return get_torch_device()
531
+ else:
532
+ return torch.device("cpu")
533
+ else:
534
+ return torch.device("cpu")
535
+
536
+ def text_encoder_dtype(device=None):
537
+ if args.fp8_e4m3fn_text_enc:
538
+ return torch.float8_e4m3fn
539
+ elif args.fp8_e5m2_text_enc:
540
+ return torch.float8_e5m2
541
+ elif args.fp16_text_enc:
542
+ return torch.float16
543
+ elif args.fp32_text_enc:
544
+ return torch.float32
545
+
546
+ if is_device_cpu(device):
547
+ return torch.float16
548
+
549
+ return torch.float16
550
+
551
+
552
+ def intermediate_device():
553
+ if args.gpu_only:
554
+ return get_torch_device()
555
+ else:
556
+ return torch.device("cpu")
557
+
558
+ def vae_device():
559
+ if args.cpu_vae:
560
+ return torch.device("cpu")
561
+ return get_torch_device()
562
+
563
+ def vae_offload_device():
564
+ if args.gpu_only:
565
+ return get_torch_device()
566
+ else:
567
+ return torch.device("cpu")
568
+
569
+ def vae_dtype():
570
+ global VAE_DTYPE
571
+ return VAE_DTYPE
572
+
573
+ def get_autocast_device(dev):
574
+ if hasattr(dev, 'type'):
575
+ return dev.type
576
+ return "cuda"
577
+
578
+ def supports_dtype(device, dtype): #TODO
579
+ if dtype == torch.float32:
580
+ return True
581
+ if is_device_cpu(device):
582
+ return False
583
+ if dtype == torch.float16:
584
+ return True
585
+ if dtype == torch.bfloat16:
586
+ return True
587
+ return False
588
+
589
+ def device_supports_non_blocking(device):
590
+ if is_device_mps(device):
591
+ return False #pytorch bug? mps doesn't support non blocking
592
+ return True
593
+
594
+ def cast_to_device(tensor, device, dtype, copy=False):
595
+ device_supports_cast = False
596
+ if tensor.dtype == torch.float32 or tensor.dtype == torch.float16:
597
+ device_supports_cast = True
598
+ elif tensor.dtype == torch.bfloat16:
599
+ if hasattr(device, 'type') and device.type.startswith("cuda"):
600
+ device_supports_cast = True
601
+ elif is_intel_xpu():
602
+ device_supports_cast = True
603
+
604
+ non_blocking = device_supports_non_blocking(device)
605
+
606
+ if device_supports_cast:
607
+ if copy:
608
+ if tensor.device == device:
609
+ return tensor.to(dtype, copy=copy, non_blocking=non_blocking)
610
+ return tensor.to(device, copy=copy, non_blocking=non_blocking).to(dtype, non_blocking=non_blocking)
611
+ else:
612
+ return tensor.to(device, non_blocking=non_blocking).to(dtype, non_blocking=non_blocking)
613
+ else:
614
+ return tensor.to(device, dtype, copy=copy, non_blocking=non_blocking)
615
+
616
+ def xformers_enabled():
617
+ global directml_enabled
618
+ global cpu_state
619
+ if cpu_state != CPUState.GPU:
620
+ return False
621
+ if is_intel_xpu():
622
+ return False
623
+ if directml_enabled:
624
+ return False
625
+ return XFORMERS_IS_AVAILABLE
626
+
627
+
628
+ def xformers_enabled_vae():
629
+ enabled = xformers_enabled()
630
+ if not enabled:
631
+ return False
632
+
633
+ return XFORMERS_ENABLED_VAE
634
+
635
+ def pytorch_attention_enabled():
636
+ global ENABLE_PYTORCH_ATTENTION
637
+ return ENABLE_PYTORCH_ATTENTION
638
+
639
+ def pytorch_attention_flash_attention():
640
+ global ENABLE_PYTORCH_ATTENTION
641
+ if ENABLE_PYTORCH_ATTENTION:
642
+ #TODO: more reliable way of checking for flash attention?
643
+ if is_nvidia(): #pytorch flash attention only works on Nvidia
644
+ return True
645
+ return False
646
+
647
+ def get_free_memory(dev=None, torch_free_too=False):
648
+ global directml_enabled
649
+ if dev is None:
650
+ dev = get_torch_device()
651
+
652
+ if hasattr(dev, 'type') and (dev.type == 'cpu' or dev.type == 'mps'):
653
+ mem_free_total = psutil.virtual_memory().available
654
+ mem_free_torch = mem_free_total
655
+ else:
656
+ if directml_enabled:
657
+ mem_free_total = 1024 * 1024 * 1024 #TODO
658
+ mem_free_torch = mem_free_total
659
+ elif is_intel_xpu():
660
+ stats = torch.xpu.memory_stats(dev)
661
+ mem_active = stats['active_bytes.all.current']
662
+ mem_allocated = stats['allocated_bytes.all.current']
663
+ mem_reserved = stats['reserved_bytes.all.current']
664
+ mem_free_torch = mem_reserved - mem_active
665
+ mem_free_total = torch.xpu.get_device_properties(dev).total_memory - mem_allocated
666
+ else:
667
+ stats = torch.cuda.memory_stats(dev)
668
+ mem_active = stats['active_bytes.all.current']
669
+ mem_reserved = stats['reserved_bytes.all.current']
670
+ mem_free_cuda, _ = torch.cuda.mem_get_info(dev)
671
+ mem_free_torch = mem_reserved - mem_active
672
+ mem_free_total = mem_free_cuda + mem_free_torch
673
+
674
+ if torch_free_too:
675
+ return (mem_free_total, mem_free_torch)
676
+ else:
677
+ return mem_free_total
678
+
679
+ def cpu_mode():
680
+ global cpu_state
681
+ return cpu_state == CPUState.CPU
682
+
683
+ def mps_mode():
684
+ global cpu_state
685
+ return cpu_state == CPUState.MPS
686
+
687
+ def is_device_cpu(device):
688
+ if hasattr(device, 'type'):
689
+ if (device.type == 'cpu'):
690
+ return True
691
+ return False
692
+
693
+ def is_device_mps(device):
694
+ if hasattr(device, 'type'):
695
+ if (device.type == 'mps'):
696
+ return True
697
+ return False
698
+
699
+ def should_use_fp16(device=None, model_params=0, prioritize_performance=True, manual_cast=False):
700
+ global directml_enabled
701
+
702
+ if device is not None:
703
+ if is_device_cpu(device):
704
+ return False
705
+
706
+ if FORCE_FP16:
707
+ return True
708
+
709
+ if device is not None: #TODO
710
+ if is_device_mps(device):
711
+ return False
712
+
713
+ if FORCE_FP32:
714
+ return False
715
+
716
+ if directml_enabled:
717
+ return False
718
+
719
+ if cpu_mode() or mps_mode():
720
+ return False #TODO ?
721
+
722
+ if is_intel_xpu():
723
+ return True
724
+
725
+ if torch.version.hip:
726
+ return True
727
+
728
+ props = torch.cuda.get_device_properties("cuda")
729
+ if props.major >= 8:
730
+ return True
731
+
732
+ if props.major < 6:
733
+ return False
734
+
735
+ fp16_works = False
736
+ #FP16 is confirmed working on a 1080 (GP104) but it's a bit slower than FP32 so it should only be enabled
737
+ #when the model doesn't actually fit on the card
738
+ #TODO: actually test if GP106 and others have the same type of behavior
739
+ nvidia_10_series = ["1080", "1070", "titan x", "p3000", "p3200", "p4000", "p4200", "p5000", "p5200", "p6000", "1060", "1050"]
740
+ for x in nvidia_10_series:
741
+ if x in props.name.lower():
742
+ fp16_works = True
743
+
744
+ if fp16_works or manual_cast:
745
+ free_model_memory = (get_free_memory() * 0.9 - minimum_inference_memory())
746
+ if (not prioritize_performance) or model_params * 4 > free_model_memory:
747
+ return True
748
+
749
+ if props.major < 7:
750
+ return False
751
+
752
+ #FP16 is just broken on these cards
753
+ nvidia_16_series = ["1660", "1650", "1630", "T500", "T550", "T600", "MX550", "MX450", "CMP 30HX", "T2000", "T1000", "T1200"]
754
+ for x in nvidia_16_series:
755
+ if x in props.name:
756
+ return False
757
+
758
+ return True
759
+
760
+ def soft_empty_cache(force=False):
761
+ global cpu_state
762
+ if cpu_state == CPUState.MPS:
763
+ torch.mps.empty_cache()
764
+ elif is_intel_xpu():
765
+ torch.xpu.empty_cache()
766
+ elif torch.cuda.is_available():
767
+ if force or is_nvidia(): #This seems to make things worse on ROCm so I only do it for cuda
768
+ torch.cuda.empty_cache()
769
+ torch.cuda.ipc_collect()
770
+
771
+ def unload_all_models():
772
+ free_memory(1e30, get_torch_device())
773
+
774
+
775
+ def resolve_lowvram_weight(weight, model, key): #TODO: remove
776
+ return weight
777
+
778
+ #TODO: might be cleaner to put this somewhere else
779
+ import threading
780
+
781
+ class InterruptProcessingException(Exception):
782
+ pass
783
+
784
+ interrupt_processing_mutex = threading.RLock()
785
+
786
+ interrupt_processing = False
787
+ def interrupt_current_processing(value=True):
788
+ global interrupt_processing
789
+ global interrupt_processing_mutex
790
+ with interrupt_processing_mutex:
791
+ interrupt_processing = value
792
+
793
+ def processing_interrupted():
794
+ global interrupt_processing
795
+ global interrupt_processing_mutex
796
+ with interrupt_processing_mutex:
797
+ return interrupt_processing
798
+
799
+ def throw_exception_if_processing_interrupted():
800
+ global interrupt_processing
801
+ global interrupt_processing_mutex
802
+ with interrupt_processing_mutex:
803
+ if interrupt_processing:
804
+ interrupt_processing = False
805
+ raise InterruptProcessingException()
comfy/model_patcher.py ADDED
@@ -0,0 +1,357 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import copy
3
+ import inspect
4
+
5
+ import comfy.utils
6
+ import comfy.model_management
7
+
8
+ class ModelPatcher:
9
+ def __init__(self, model, load_device, offload_device, size=0, current_device=None, weight_inplace_update=False):
10
+ self.size = size
11
+ self.model = model
12
+ self.patches = {}
13
+ self.backup = {}
14
+ self.object_patches = {}
15
+ self.object_patches_backup = {}
16
+ self.model_options = {"transformer_options":{}}
17
+ self.model_size()
18
+ self.load_device = load_device
19
+ self.offload_device = offload_device
20
+ if current_device is None:
21
+ self.current_device = self.offload_device
22
+ else:
23
+ self.current_device = current_device
24
+
25
+ self.weight_inplace_update = weight_inplace_update
26
+
27
+ def model_size(self):
28
+ if self.size > 0:
29
+ return self.size
30
+ model_sd = self.model.state_dict()
31
+ self.size = comfy.model_management.module_size(self.model)
32
+ self.model_keys = set(model_sd.keys())
33
+ return self.size
34
+
35
+ def clone(self):
36
+ n = ModelPatcher(self.model, self.load_device, self.offload_device, self.size, self.current_device, weight_inplace_update=self.weight_inplace_update)
37
+ n.patches = {}
38
+ for k in self.patches:
39
+ n.patches[k] = self.patches[k][:]
40
+
41
+ n.object_patches = self.object_patches.copy()
42
+ n.model_options = copy.deepcopy(self.model_options)
43
+ n.model_keys = self.model_keys
44
+ return n
45
+
46
+ def is_clone(self, other):
47
+ if hasattr(other, 'model') and self.model is other.model:
48
+ return True
49
+ return False
50
+
51
+ def memory_required(self, input_shape):
52
+ return self.model.memory_required(input_shape=input_shape)
53
+
54
+ def set_model_sampler_cfg_function(self, sampler_cfg_function, disable_cfg1_optimization=False):
55
+ if len(inspect.signature(sampler_cfg_function).parameters) == 3:
56
+ self.model_options["sampler_cfg_function"] = lambda args: sampler_cfg_function(args["cond"], args["uncond"], args["cond_scale"]) #Old way
57
+ else:
58
+ self.model_options["sampler_cfg_function"] = sampler_cfg_function
59
+ if disable_cfg1_optimization:
60
+ self.model_options["disable_cfg1_optimization"] = True
61
+
62
+ def set_model_sampler_post_cfg_function(self, post_cfg_function, disable_cfg1_optimization=False):
63
+ self.model_options["sampler_post_cfg_function"] = self.model_options.get("sampler_post_cfg_function", []) + [post_cfg_function]
64
+ if disable_cfg1_optimization:
65
+ self.model_options["disable_cfg1_optimization"] = True
66
+
67
+ def set_model_unet_function_wrapper(self, unet_wrapper_function):
68
+ self.model_options["model_function_wrapper"] = unet_wrapper_function
69
+
70
+ def set_model_patch(self, patch, name):
71
+ to = self.model_options["transformer_options"]
72
+ if "patches" not in to:
73
+ to["patches"] = {}
74
+ to["patches"][name] = to["patches"].get(name, []) + [patch]
75
+
76
+ def set_model_patch_replace(self, patch, name, block_name, number, transformer_index=None):
77
+ to = self.model_options["transformer_options"]
78
+ if "patches_replace" not in to:
79
+ to["patches_replace"] = {}
80
+ if name not in to["patches_replace"]:
81
+ to["patches_replace"][name] = {}
82
+ if transformer_index is not None:
83
+ block = (block_name, number, transformer_index)
84
+ else:
85
+ block = (block_name, number)
86
+ to["patches_replace"][name][block] = patch
87
+
88
+ def set_model_attn1_patch(self, patch):
89
+ self.set_model_patch(patch, "attn1_patch")
90
+
91
+ def set_model_attn2_patch(self, patch):
92
+ self.set_model_patch(patch, "attn2_patch")
93
+
94
+ def set_model_attn1_replace(self, patch, block_name, number, transformer_index=None):
95
+ self.set_model_patch_replace(patch, "attn1", block_name, number, transformer_index)
96
+
97
+ def set_model_attn2_replace(self, patch, block_name, number, transformer_index=None):
98
+ self.set_model_patch_replace(patch, "attn2", block_name, number, transformer_index)
99
+
100
+ def set_model_attn1_output_patch(self, patch):
101
+ self.set_model_patch(patch, "attn1_output_patch")
102
+
103
+ def set_model_attn2_output_patch(self, patch):
104
+ self.set_model_patch(patch, "attn2_output_patch")
105
+
106
+ def set_model_input_block_patch(self, patch):
107
+ self.set_model_patch(patch, "input_block_patch")
108
+
109
+ def set_model_input_block_patch_after_skip(self, patch):
110
+ self.set_model_patch(patch, "input_block_patch_after_skip")
111
+
112
+ def set_model_output_block_patch(self, patch):
113
+ self.set_model_patch(patch, "output_block_patch")
114
+
115
+ def add_object_patch(self, name, obj):
116
+ self.object_patches[name] = obj
117
+
118
+ def model_patches_to(self, device):
119
+ to = self.model_options["transformer_options"]
120
+ if "patches" in to:
121
+ patches = to["patches"]
122
+ for name in patches:
123
+ patch_list = patches[name]
124
+ for i in range(len(patch_list)):
125
+ if hasattr(patch_list[i], "to"):
126
+ patch_list[i] = patch_list[i].to(device)
127
+ if "patches_replace" in to:
128
+ patches = to["patches_replace"]
129
+ for name in patches:
130
+ patch_list = patches[name]
131
+ for k in patch_list:
132
+ if hasattr(patch_list[k], "to"):
133
+ patch_list[k] = patch_list[k].to(device)
134
+ if "model_function_wrapper" in self.model_options:
135
+ wrap_func = self.model_options["model_function_wrapper"]
136
+ if hasattr(wrap_func, "to"):
137
+ self.model_options["model_function_wrapper"] = wrap_func.to(device)
138
+
139
+ def model_dtype(self):
140
+ if hasattr(self.model, "get_dtype"):
141
+ return self.model.get_dtype()
142
+
143
+ def add_patches(self, patches, strength_patch=1.0, strength_model=1.0):
144
+ p = set()
145
+ for k in patches:
146
+ if k in self.model_keys:
147
+ p.add(k)
148
+ current_patches = self.patches.get(k, [])
149
+ current_patches.append((strength_patch, patches[k], strength_model))
150
+ self.patches[k] = current_patches
151
+
152
+ return list(p)
153
+
154
+ def get_key_patches(self, filter_prefix=None):
155
+ comfy.model_management.unload_model_clones(self)
156
+ model_sd = self.model_state_dict()
157
+ p = {}
158
+ for k in model_sd:
159
+ if filter_prefix is not None:
160
+ if not k.startswith(filter_prefix):
161
+ continue
162
+ if k in self.patches:
163
+ p[k] = [model_sd[k]] + self.patches[k]
164
+ else:
165
+ p[k] = (model_sd[k],)
166
+ return p
167
+
168
+ def model_state_dict(self, filter_prefix=None):
169
+ sd = self.model.state_dict()
170
+ keys = list(sd.keys())
171
+ if filter_prefix is not None:
172
+ for k in keys:
173
+ if not k.startswith(filter_prefix):
174
+ sd.pop(k)
175
+ return sd
176
+
177
+ def patch_model(self, device_to=None, patch_weights=True):
178
+ for k in self.object_patches:
179
+ old = getattr(self.model, k)
180
+ if k not in self.object_patches_backup:
181
+ self.object_patches_backup[k] = old
182
+ setattr(self.model, k, self.object_patches[k])
183
+
184
+ if patch_weights:
185
+ model_sd = self.model_state_dict()
186
+ for key in self.patches:
187
+ if key not in model_sd:
188
+ print("could not patch. key doesn't exist in model:", key)
189
+ continue
190
+
191
+ weight = model_sd[key]
192
+
193
+ inplace_update = self.weight_inplace_update
194
+
195
+ if key not in self.backup:
196
+ self.backup[key] = weight.to(device=self.offload_device, copy=inplace_update)
197
+
198
+ if device_to is not None:
199
+ temp_weight = comfy.model_management.cast_to_device(weight, device_to, torch.float32, copy=True)
200
+ else:
201
+ temp_weight = weight.to(torch.float32, copy=True)
202
+ out_weight = self.calculate_weight(self.patches[key], temp_weight, key).to(weight.dtype)
203
+ if inplace_update:
204
+ comfy.utils.copy_to_param(self.model, key, out_weight)
205
+ else:
206
+ comfy.utils.set_attr(self.model, key, out_weight)
207
+ del temp_weight
208
+
209
+ if device_to is not None:
210
+ self.model.to(device_to)
211
+ self.current_device = device_to
212
+
213
+ return self.model
214
+
215
+ def calculate_weight(self, patches, weight, key):
216
+ for p in patches:
217
+ alpha = p[0]
218
+ v = p[1]
219
+ strength_model = p[2]
220
+
221
+ if strength_model != 1.0:
222
+ weight *= strength_model
223
+
224
+ if isinstance(v, list):
225
+ v = (self.calculate_weight(v[1:], v[0].clone(), key), )
226
+
227
+ if len(v) == 1:
228
+ patch_type = "diff"
229
+ elif len(v) == 2:
230
+ patch_type = v[0]
231
+ v = v[1]
232
+
233
+ if patch_type == "diff":
234
+ w1 = v[0]
235
+ if alpha != 0.0:
236
+ if w1.shape != weight.shape:
237
+ print("WARNING SHAPE MISMATCH {} WEIGHT NOT MERGED {} != {}".format(key, w1.shape, weight.shape))
238
+ else:
239
+ weight += alpha * comfy.model_management.cast_to_device(w1, weight.device, weight.dtype)
240
+ elif patch_type == "lora": #lora/locon
241
+ mat1 = comfy.model_management.cast_to_device(v[0], weight.device, torch.float32)
242
+ mat2 = comfy.model_management.cast_to_device(v[1], weight.device, torch.float32)
243
+ if v[2] is not None:
244
+ alpha *= v[2] / mat2.shape[0]
245
+ if v[3] is not None:
246
+ #locon mid weights, hopefully the math is fine because I didn't properly test it
247
+ mat3 = comfy.model_management.cast_to_device(v[3], weight.device, torch.float32)
248
+ final_shape = [mat2.shape[1], mat2.shape[0], mat3.shape[2], mat3.shape[3]]
249
+ mat2 = torch.mm(mat2.transpose(0, 1).flatten(start_dim=1), mat3.transpose(0, 1).flatten(start_dim=1)).reshape(final_shape).transpose(0, 1)
250
+ try:
251
+ weight += (alpha * torch.mm(mat1.flatten(start_dim=1), mat2.flatten(start_dim=1))).reshape(weight.shape).type(weight.dtype)
252
+ except Exception as e:
253
+ print("ERROR", key, e)
254
+ elif patch_type == "lokr":
255
+ w1 = v[0]
256
+ w2 = v[1]
257
+ w1_a = v[3]
258
+ w1_b = v[4]
259
+ w2_a = v[5]
260
+ w2_b = v[6]
261
+ t2 = v[7]
262
+ dim = None
263
+
264
+ if w1 is None:
265
+ dim = w1_b.shape[0]
266
+ w1 = torch.mm(comfy.model_management.cast_to_device(w1_a, weight.device, torch.float32),
267
+ comfy.model_management.cast_to_device(w1_b, weight.device, torch.float32))
268
+ else:
269
+ w1 = comfy.model_management.cast_to_device(w1, weight.device, torch.float32)
270
+
271
+ if w2 is None:
272
+ dim = w2_b.shape[0]
273
+ if t2 is None:
274
+ w2 = torch.mm(comfy.model_management.cast_to_device(w2_a, weight.device, torch.float32),
275
+ comfy.model_management.cast_to_device(w2_b, weight.device, torch.float32))
276
+ else:
277
+ w2 = torch.einsum('i j k l, j r, i p -> p r k l',
278
+ comfy.model_management.cast_to_device(t2, weight.device, torch.float32),
279
+ comfy.model_management.cast_to_device(w2_b, weight.device, torch.float32),
280
+ comfy.model_management.cast_to_device(w2_a, weight.device, torch.float32))
281
+ else:
282
+ w2 = comfy.model_management.cast_to_device(w2, weight.device, torch.float32)
283
+
284
+ if len(w2.shape) == 4:
285
+ w1 = w1.unsqueeze(2).unsqueeze(2)
286
+ if v[2] is not None and dim is not None:
287
+ alpha *= v[2] / dim
288
+
289
+ try:
290
+ weight += alpha * torch.kron(w1, w2).reshape(weight.shape).type(weight.dtype)
291
+ except Exception as e:
292
+ print("ERROR", key, e)
293
+ elif patch_type == "loha":
294
+ w1a = v[0]
295
+ w1b = v[1]
296
+ if v[2] is not None:
297
+ alpha *= v[2] / w1b.shape[0]
298
+ w2a = v[3]
299
+ w2b = v[4]
300
+ if v[5] is not None: #cp decomposition
301
+ t1 = v[5]
302
+ t2 = v[6]
303
+ m1 = torch.einsum('i j k l, j r, i p -> p r k l',
304
+ comfy.model_management.cast_to_device(t1, weight.device, torch.float32),
305
+ comfy.model_management.cast_to_device(w1b, weight.device, torch.float32),
306
+ comfy.model_management.cast_to_device(w1a, weight.device, torch.float32))
307
+
308
+ m2 = torch.einsum('i j k l, j r, i p -> p r k l',
309
+ comfy.model_management.cast_to_device(t2, weight.device, torch.float32),
310
+ comfy.model_management.cast_to_device(w2b, weight.device, torch.float32),
311
+ comfy.model_management.cast_to_device(w2a, weight.device, torch.float32))
312
+ else:
313
+ m1 = torch.mm(comfy.model_management.cast_to_device(w1a, weight.device, torch.float32),
314
+ comfy.model_management.cast_to_device(w1b, weight.device, torch.float32))
315
+ m2 = torch.mm(comfy.model_management.cast_to_device(w2a, weight.device, torch.float32),
316
+ comfy.model_management.cast_to_device(w2b, weight.device, torch.float32))
317
+
318
+ try:
319
+ weight += (alpha * m1 * m2).reshape(weight.shape).type(weight.dtype)
320
+ except Exception as e:
321
+ print("ERROR", key, e)
322
+ elif patch_type == "glora":
323
+ if v[4] is not None:
324
+ alpha *= v[4] / v[0].shape[0]
325
+
326
+ a1 = comfy.model_management.cast_to_device(v[0].flatten(start_dim=1), weight.device, torch.float32)
327
+ a2 = comfy.model_management.cast_to_device(v[1].flatten(start_dim=1), weight.device, torch.float32)
328
+ b1 = comfy.model_management.cast_to_device(v[2].flatten(start_dim=1), weight.device, torch.float32)
329
+ b2 = comfy.model_management.cast_to_device(v[3].flatten(start_dim=1), weight.device, torch.float32)
330
+
331
+ weight += ((torch.mm(b2, b1) + torch.mm(torch.mm(weight.flatten(start_dim=1), a2), a1)) * alpha).reshape(weight.shape).type(weight.dtype)
332
+ else:
333
+ print("patch type not recognized", patch_type, key)
334
+
335
+ return weight
336
+
337
+ def unpatch_model(self, device_to=None):
338
+ keys = list(self.backup.keys())
339
+
340
+ if self.weight_inplace_update:
341
+ for k in keys:
342
+ comfy.utils.copy_to_param(self.model, k, self.backup[k])
343
+ else:
344
+ for k in keys:
345
+ comfy.utils.set_attr(self.model, k, self.backup[k])
346
+
347
+ self.backup = {}
348
+
349
+ if device_to is not None:
350
+ self.model.to(device_to)
351
+ self.current_device = device_to
352
+
353
+ keys = list(self.object_patches_backup.keys())
354
+ for k in keys:
355
+ setattr(self.model, k, self.object_patches_backup[k])
356
+
357
+ self.object_patches_backup = {}
comfy/model_sampling.py ADDED
@@ -0,0 +1,134 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from comfy.ldm.modules.diffusionmodules.util import make_beta_schedule
3
+ import math
4
+
5
+ class EPS:
6
+ def calculate_input(self, sigma, noise):
7
+ sigma = sigma.view(sigma.shape[:1] + (1,) * (noise.ndim - 1))
8
+ return noise / (sigma ** 2 + self.sigma_data ** 2) ** 0.5
9
+
10
+ def calculate_denoised(self, sigma, model_output, model_input):
11
+ sigma = sigma.view(sigma.shape[:1] + (1,) * (model_output.ndim - 1))
12
+ return model_input - model_output * sigma
13
+
14
+
15
+ class V_PREDICTION(EPS):
16
+ def calculate_denoised(self, sigma, model_output, model_input):
17
+ sigma = sigma.view(sigma.shape[:1] + (1,) * (model_output.ndim - 1))
18
+ return model_input * self.sigma_data ** 2 / (sigma ** 2 + self.sigma_data ** 2) - model_output * sigma * self.sigma_data / (sigma ** 2 + self.sigma_data ** 2) ** 0.5
19
+
20
+
21
+ class ModelSamplingDiscrete(torch.nn.Module):
22
+ def __init__(self, model_config=None):
23
+ super().__init__()
24
+
25
+ if model_config is not None:
26
+ sampling_settings = model_config.sampling_settings
27
+ else:
28
+ sampling_settings = {}
29
+
30
+ beta_schedule = sampling_settings.get("beta_schedule", "linear")
31
+ linear_start = sampling_settings.get("linear_start", 0.00085)
32
+ linear_end = sampling_settings.get("linear_end", 0.012)
33
+
34
+ self._register_schedule(given_betas=None, beta_schedule=beta_schedule, timesteps=1000, linear_start=linear_start, linear_end=linear_end, cosine_s=8e-3)
35
+ self.sigma_data = 1.0
36
+
37
+ def _register_schedule(self, given_betas=None, beta_schedule="linear", timesteps=1000,
38
+ linear_start=1e-4, linear_end=2e-2, cosine_s=8e-3):
39
+ if given_betas is not None:
40
+ betas = given_betas
41
+ else:
42
+ betas = make_beta_schedule(beta_schedule, timesteps, linear_start=linear_start, linear_end=linear_end, cosine_s=cosine_s)
43
+ alphas = 1. - betas
44
+ alphas_cumprod = torch.cumprod(alphas, dim=0)
45
+
46
+ timesteps, = betas.shape
47
+ self.num_timesteps = int(timesteps)
48
+ self.linear_start = linear_start
49
+ self.linear_end = linear_end
50
+
51
+ # self.register_buffer('betas', torch.tensor(betas, dtype=torch.float32))
52
+ # self.register_buffer('alphas_cumprod', torch.tensor(alphas_cumprod, dtype=torch.float32))
53
+ # self.register_buffer('alphas_cumprod_prev', torch.tensor(alphas_cumprod_prev, dtype=torch.float32))
54
+
55
+ sigmas = ((1 - alphas_cumprod) / alphas_cumprod) ** 0.5
56
+ self.set_sigmas(sigmas)
57
+
58
+ def set_sigmas(self, sigmas):
59
+ self.register_buffer('sigmas', sigmas.float())
60
+ self.register_buffer('log_sigmas', sigmas.log().float())
61
+
62
+ @property
63
+ def sigma_min(self):
64
+ return self.sigmas[0]
65
+
66
+ @property
67
+ def sigma_max(self):
68
+ return self.sigmas[-1]
69
+
70
+ def timestep(self, sigma):
71
+ log_sigma = sigma.log()
72
+ dists = log_sigma.to(self.log_sigmas.device) - self.log_sigmas[:, None]
73
+ return dists.abs().argmin(dim=0).view(sigma.shape).to(sigma.device)
74
+
75
+ def sigma(self, timestep):
76
+ t = torch.clamp(timestep.float().to(self.log_sigmas.device), min=0, max=(len(self.sigmas) - 1))
77
+ low_idx = t.floor().long()
78
+ high_idx = t.ceil().long()
79
+ w = t.frac()
80
+ log_sigma = (1 - w) * self.log_sigmas[low_idx] + w * self.log_sigmas[high_idx]
81
+ return log_sigma.exp().to(timestep.device)
82
+
83
+ def percent_to_sigma(self, percent):
84
+ if percent <= 0.0:
85
+ return 999999999.9
86
+ if percent >= 1.0:
87
+ return 0.0
88
+ percent = 1.0 - percent
89
+ return self.sigma(torch.tensor(percent * 999.0)).item()
90
+
91
+
92
+ class ModelSamplingContinuousEDM(torch.nn.Module):
93
+ def __init__(self, model_config=None):
94
+ super().__init__()
95
+ self.sigma_data = 1.0
96
+
97
+ if model_config is not None:
98
+ sampling_settings = model_config.sampling_settings
99
+ else:
100
+ sampling_settings = {}
101
+
102
+ sigma_min = sampling_settings.get("sigma_min", 0.002)
103
+ sigma_max = sampling_settings.get("sigma_max", 120.0)
104
+ self.set_sigma_range(sigma_min, sigma_max)
105
+
106
+ def set_sigma_range(self, sigma_min, sigma_max):
107
+ sigmas = torch.linspace(math.log(sigma_min), math.log(sigma_max), 1000).exp()
108
+
109
+ self.register_buffer('sigmas', sigmas) #for compatibility with some schedulers
110
+ self.register_buffer('log_sigmas', sigmas.log())
111
+
112
+ @property
113
+ def sigma_min(self):
114
+ return self.sigmas[0]
115
+
116
+ @property
117
+ def sigma_max(self):
118
+ return self.sigmas[-1]
119
+
120
+ def timestep(self, sigma):
121
+ return 0.25 * sigma.log()
122
+
123
+ def sigma(self, timestep):
124
+ return (timestep / 0.25).exp()
125
+
126
+ def percent_to_sigma(self, percent):
127
+ if percent <= 0.0:
128
+ return 999999999.9
129
+ if percent >= 1.0:
130
+ return 0.0
131
+ percent = 1.0 - percent
132
+
133
+ log_sigma_min = math.log(self.sigma_min)
134
+ return math.exp((math.log(self.sigma_max) - log_sigma_min) * percent + log_sigma_min)
comfy/ops.py ADDED
@@ -0,0 +1,114 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import comfy.model_management
3
+
4
+ def cast_bias_weight(s, input):
5
+ bias = None
6
+ non_blocking = comfy.model_management.device_supports_non_blocking(input.device)
7
+ if s.bias is not None:
8
+ bias = s.bias.to(device=input.device, dtype=input.dtype, non_blocking=non_blocking)
9
+ weight = s.weight.to(device=input.device, dtype=input.dtype, non_blocking=non_blocking)
10
+ return weight, bias
11
+
12
+
13
+ class disable_weight_init:
14
+ class Linear(torch.nn.Linear):
15
+ comfy_cast_weights = False
16
+ def reset_parameters(self):
17
+ return None
18
+
19
+ def forward_comfy_cast_weights(self, input):
20
+ weight, bias = cast_bias_weight(self, input)
21
+ return torch.nn.functional.linear(input, weight, bias)
22
+
23
+ def forward(self, *args, **kwargs):
24
+ if self.comfy_cast_weights:
25
+ return self.forward_comfy_cast_weights(*args, **kwargs)
26
+ else:
27
+ return super().forward(*args, **kwargs)
28
+
29
+ class Conv2d(torch.nn.Conv2d):
30
+ comfy_cast_weights = False
31
+ def reset_parameters(self):
32
+ return None
33
+
34
+ def forward_comfy_cast_weights(self, input):
35
+ weight, bias = cast_bias_weight(self, input)
36
+ return self._conv_forward(input, weight, bias)
37
+
38
+ def forward(self, *args, **kwargs):
39
+ if self.comfy_cast_weights:
40
+ return self.forward_comfy_cast_weights(*args, **kwargs)
41
+ else:
42
+ return super().forward(*args, **kwargs)
43
+
44
+ class Conv3d(torch.nn.Conv3d):
45
+ comfy_cast_weights = False
46
+ def reset_parameters(self):
47
+ return None
48
+
49
+ def forward_comfy_cast_weights(self, input):
50
+ weight, bias = cast_bias_weight(self, input)
51
+ return self._conv_forward(input, weight, bias)
52
+
53
+ def forward(self, *args, **kwargs):
54
+ if self.comfy_cast_weights:
55
+ return self.forward_comfy_cast_weights(*args, **kwargs)
56
+ else:
57
+ return super().forward(*args, **kwargs)
58
+
59
+ class GroupNorm(torch.nn.GroupNorm):
60
+ comfy_cast_weights = False
61
+ def reset_parameters(self):
62
+ return None
63
+
64
+ def forward_comfy_cast_weights(self, input):
65
+ weight, bias = cast_bias_weight(self, input)
66
+ return torch.nn.functional.group_norm(input, self.num_groups, weight, bias, self.eps)
67
+
68
+ def forward(self, *args, **kwargs):
69
+ if self.comfy_cast_weights:
70
+ return self.forward_comfy_cast_weights(*args, **kwargs)
71
+ else:
72
+ return super().forward(*args, **kwargs)
73
+
74
+
75
+ class LayerNorm(torch.nn.LayerNorm):
76
+ comfy_cast_weights = False
77
+ def reset_parameters(self):
78
+ return None
79
+
80
+ def forward_comfy_cast_weights(self, input):
81
+ weight, bias = cast_bias_weight(self, input)
82
+ return torch.nn.functional.layer_norm(input, self.normalized_shape, weight, bias, self.eps)
83
+
84
+ def forward(self, *args, **kwargs):
85
+ if self.comfy_cast_weights:
86
+ return self.forward_comfy_cast_weights(*args, **kwargs)
87
+ else:
88
+ return super().forward(*args, **kwargs)
89
+
90
+ @classmethod
91
+ def conv_nd(s, dims, *args, **kwargs):
92
+ if dims == 2:
93
+ return s.Conv2d(*args, **kwargs)
94
+ elif dims == 3:
95
+ return s.Conv3d(*args, **kwargs)
96
+ else:
97
+ raise ValueError(f"unsupported dimensions: {dims}")
98
+
99
+
100
+ class manual_cast(disable_weight_init):
101
+ class Linear(disable_weight_init.Linear):
102
+ comfy_cast_weights = True
103
+
104
+ class Conv2d(disable_weight_init.Conv2d):
105
+ comfy_cast_weights = True
106
+
107
+ class Conv3d(disable_weight_init.Conv3d):
108
+ comfy_cast_weights = True
109
+
110
+ class GroupNorm(disable_weight_init.GroupNorm):
111
+ comfy_cast_weights = True
112
+
113
+ class LayerNorm(disable_weight_init.LayerNorm):
114
+ comfy_cast_weights = True
comfy/options.py ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+
2
+ args_parsing = False
3
+
4
+ def enable_args_parsing(enable=True):
5
+ global args_parsing
6
+ args_parsing = enable
comfy/sample.py ADDED
@@ -0,0 +1,118 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import comfy.model_management
3
+ import comfy.samplers
4
+ import comfy.conds
5
+ import comfy.utils
6
+ import math
7
+ import numpy as np
8
+
9
+ def prepare_noise(latent_image, seed, noise_inds=None):
10
+ """
11
+ creates random noise given a latent image and a seed.
12
+ optional arg skip can be used to skip and discard x number of noise generations for a given seed
13
+ """
14
+ generator = torch.manual_seed(seed)
15
+ if noise_inds is None:
16
+ return torch.randn(latent_image.size(), dtype=latent_image.dtype, layout=latent_image.layout, generator=generator, device="cpu")
17
+
18
+ unique_inds, inverse = np.unique(noise_inds, return_inverse=True)
19
+ noises = []
20
+ for i in range(unique_inds[-1]+1):
21
+ noise = torch.randn([1] + list(latent_image.size())[1:], dtype=latent_image.dtype, layout=latent_image.layout, generator=generator, device="cpu")
22
+ if i in unique_inds:
23
+ noises.append(noise)
24
+ noises = [noises[i] for i in inverse]
25
+ noises = torch.cat(noises, axis=0)
26
+ return noises
27
+
28
+ def prepare_mask(noise_mask, shape, device):
29
+ """ensures noise mask is of proper dimensions"""
30
+ noise_mask = torch.nn.functional.interpolate(noise_mask.reshape((-1, 1, noise_mask.shape[-2], noise_mask.shape[-1])), size=(shape[2], shape[3]), mode="bilinear")
31
+ noise_mask = torch.cat([noise_mask] * shape[1], dim=1)
32
+ noise_mask = comfy.utils.repeat_to_batch_size(noise_mask, shape[0])
33
+ noise_mask = noise_mask.to(device)
34
+ return noise_mask
35
+
36
+ def get_models_from_cond(cond, model_type):
37
+ models = []
38
+ for c in cond:
39
+ if model_type in c:
40
+ models += [c[model_type]]
41
+ return models
42
+
43
+ def convert_cond(cond):
44
+ out = []
45
+ for c in cond:
46
+ temp = c[1].copy()
47
+ model_conds = temp.get("model_conds", {})
48
+ if c[0] is not None:
49
+ model_conds["c_crossattn"] = comfy.conds.CONDCrossAttn(c[0]) #TODO: remove
50
+ temp["cross_attn"] = c[0]
51
+ temp["model_conds"] = model_conds
52
+ out.append(temp)
53
+ return out
54
+
55
+ def get_additional_models(positive, negative, dtype):
56
+ """loads additional models in positive and negative conditioning"""
57
+ control_nets = set(get_models_from_cond(positive, "control") + get_models_from_cond(negative, "control"))
58
+
59
+ inference_memory = 0
60
+ control_models = []
61
+ for m in control_nets:
62
+ control_models += m.get_models()
63
+ inference_memory += m.inference_memory_requirements(dtype)
64
+
65
+ gligen = get_models_from_cond(positive, "gligen") + get_models_from_cond(negative, "gligen")
66
+ gligen = [x[1] for x in gligen]
67
+ models = control_models + gligen
68
+ return models, inference_memory
69
+
70
+ def cleanup_additional_models(models):
71
+ """cleanup additional models that were loaded"""
72
+ for m in models:
73
+ if hasattr(m, 'cleanup'):
74
+ m.cleanup()
75
+
76
+ def prepare_sampling(model, noise_shape, positive, negative, noise_mask):
77
+ device = model.load_device
78
+ positive = convert_cond(positive)
79
+ negative = convert_cond(negative)
80
+
81
+ if noise_mask is not None:
82
+ noise_mask = prepare_mask(noise_mask, noise_shape, device)
83
+
84
+ real_model = None
85
+ models, inference_memory = get_additional_models(positive, negative, model.model_dtype())
86
+ comfy.model_management.load_models_gpu([model] + models, model.memory_required([noise_shape[0] * 2] + list(noise_shape[1:])) + inference_memory)
87
+ real_model = model.model
88
+
89
+ return real_model, positive, negative, noise_mask, models
90
+
91
+
92
+ def sample(model, noise, steps, cfg, sampler_name, scheduler, positive, negative, latent_image, denoise=1.0, disable_noise=False, start_step=None, last_step=None, force_full_denoise=False, noise_mask=None, sigmas=None, callback=None, disable_pbar=False, seed=None):
93
+ real_model, positive_copy, negative_copy, noise_mask, models = prepare_sampling(model, noise.shape, positive, negative, noise_mask)
94
+
95
+ noise = noise.to(model.load_device)
96
+ latent_image = latent_image.to(model.load_device)
97
+
98
+ sampler = comfy.samplers.KSampler(real_model, steps=steps, device=model.load_device, sampler=sampler_name, scheduler=scheduler, denoise=denoise, model_options=model.model_options)
99
+
100
+ samples = sampler.sample(noise, positive_copy, negative_copy, cfg=cfg, latent_image=latent_image, start_step=start_step, last_step=last_step, force_full_denoise=force_full_denoise, denoise_mask=noise_mask, sigmas=sigmas, callback=callback, disable_pbar=disable_pbar, seed=seed)
101
+ samples = samples.to(comfy.model_management.intermediate_device())
102
+
103
+ cleanup_additional_models(models)
104
+ cleanup_additional_models(set(get_models_from_cond(positive_copy, "control") + get_models_from_cond(negative_copy, "control")))
105
+ return samples
106
+
107
+ def sample_custom(model, noise, cfg, sampler, sigmas, positive, negative, latent_image, noise_mask=None, callback=None, disable_pbar=False, seed=None):
108
+ real_model, positive_copy, negative_copy, noise_mask, models = prepare_sampling(model, noise.shape, positive, negative, noise_mask)
109
+ noise = noise.to(model.load_device)
110
+ latent_image = latent_image.to(model.load_device)
111
+ sigmas = sigmas.to(model.load_device)
112
+
113
+ samples = comfy.samplers.sample(real_model, noise, positive_copy, negative_copy, cfg, model.load_device, sampler, sigmas, model_options=model.model_options, latent_image=latent_image, denoise_mask=noise_mask, callback=callback, disable_pbar=disable_pbar, seed=seed)
114
+ samples = samples.to(comfy.model_management.intermediate_device())
115
+ cleanup_additional_models(models)
116
+ cleanup_additional_models(set(get_models_from_cond(positive_copy, "control") + get_models_from_cond(negative_copy, "control")))
117
+ return samples
118
+