parsee-mizuhashi commited on
Commit
c3e525b
1 Parent(s): 00c9528

Upload 156 files

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. LICENSE +674 -0
  2. README.md +4 -4
  3. app.py +149 -0
  4. comfy/checkpoint_pickle.py +13 -0
  5. comfy/cldm/cldm.py +312 -0
  6. comfy/cli_args.py +126 -0
  7. comfy/clip_config_bigg.json +23 -0
  8. comfy/clip_model.py +194 -0
  9. comfy/clip_vision.py +116 -0
  10. comfy/clip_vision_config_g.json +18 -0
  11. comfy/clip_vision_config_h.json +18 -0
  12. comfy/clip_vision_config_vitl.json +18 -0
  13. comfy/conds.py +78 -0
  14. comfy/controlnet.py +544 -0
  15. comfy/diffusers_convert.py +265 -0
  16. comfy/diffusers_load.py +36 -0
  17. comfy/extra_samplers/uni_pc.py +875 -0
  18. comfy/gligen.py +343 -0
  19. comfy/k_diffusion/sampling.py +810 -0
  20. comfy/k_diffusion/utils.py +313 -0
  21. comfy/latent_formats.py +104 -0
  22. comfy/ldm/cascade/common.py +161 -0
  23. comfy/ldm/cascade/controlnet.py +93 -0
  24. comfy/ldm/cascade/stage_a.py +258 -0
  25. comfy/ldm/cascade/stage_b.py +257 -0
  26. comfy/ldm/cascade/stage_c.py +274 -0
  27. comfy/ldm/cascade/stage_c_coder.py +95 -0
  28. comfy/ldm/models/autoencoder.py +228 -0
  29. comfy/ldm/modules/attention.py +800 -0
  30. comfy/ldm/modules/diffusionmodules/__init__.py +0 -0
  31. comfy/ldm/modules/diffusionmodules/model.py +650 -0
  32. comfy/ldm/modules/diffusionmodules/openaimodel.py +889 -0
  33. comfy/ldm/modules/diffusionmodules/upscaling.py +85 -0
  34. comfy/ldm/modules/diffusionmodules/util.py +306 -0
  35. comfy/ldm/modules/distributions/__init__.py +0 -0
  36. comfy/ldm/modules/distributions/distributions.py +92 -0
  37. comfy/ldm/modules/ema.py +80 -0
  38. comfy/ldm/modules/encoders/__init__.py +0 -0
  39. comfy/ldm/modules/encoders/noise_aug_modules.py +35 -0
  40. comfy/ldm/modules/sub_quadratic_attention.py +273 -0
  41. comfy/ldm/modules/temporal_ae.py +245 -0
  42. comfy/ldm/util.py +197 -0
  43. comfy/lora.py +234 -0
  44. comfy/model_base.py +491 -0
  45. comfy/model_detection.py +363 -0
  46. comfy/model_management.py +859 -0
  47. comfy/model_patcher.py +359 -0
  48. comfy/model_sampling.py +200 -0
  49. comfy/ops.py +161 -0
  50. comfy/options.py +6 -0
LICENSE ADDED
@@ -0,0 +1,674 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ GNU GENERAL PUBLIC LICENSE
2
+ Version 3, 29 June 2007
3
+
4
+ Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
5
+ Everyone is permitted to copy and distribute verbatim copies
6
+ of this license document, but changing it is not allowed.
7
+
8
+ Preamble
9
+
10
+ The GNU General Public License is a free, copyleft license for
11
+ software and other kinds of works.
12
+
13
+ The licenses for most software and other practical works are designed
14
+ to take away your freedom to share and change the works. By contrast,
15
+ the GNU General Public License is intended to guarantee your freedom to
16
+ share and change all versions of a program--to make sure it remains free
17
+ software for all its users. We, the Free Software Foundation, use the
18
+ GNU General Public License for most of our software; it applies also to
19
+ any other work released this way by its authors. You can apply it to
20
+ your programs, too.
21
+
22
+ When we speak of free software, we are referring to freedom, not
23
+ price. Our General Public Licenses are designed to make sure that you
24
+ have the freedom to distribute copies of free software (and charge for
25
+ them if you wish), that you receive source code or can get it if you
26
+ want it, that you can change the software or use pieces of it in new
27
+ free programs, and that you know you can do these things.
28
+
29
+ To protect your rights, we need to prevent others from denying you
30
+ these rights or asking you to surrender the rights. Therefore, you have
31
+ certain responsibilities if you distribute copies of the software, or if
32
+ you modify it: responsibilities to respect the freedom of others.
33
+
34
+ For example, if you distribute copies of such a program, whether
35
+ gratis or for a fee, you must pass on to the recipients the same
36
+ freedoms that you received. You must make sure that they, too, receive
37
+ or can get the source code. And you must show them these terms so they
38
+ know their rights.
39
+
40
+ Developers that use the GNU GPL protect your rights with two steps:
41
+ (1) assert copyright on the software, and (2) offer you this License
42
+ giving you legal permission to copy, distribute and/or modify it.
43
+
44
+ For the developers' and authors' protection, the GPL clearly explains
45
+ that there is no warranty for this free software. For both users' and
46
+ authors' sake, the GPL requires that modified versions be marked as
47
+ changed, so that their problems will not be attributed erroneously to
48
+ authors of previous versions.
49
+
50
+ Some devices are designed to deny users access to install or run
51
+ modified versions of the software inside them, although the manufacturer
52
+ can do so. This is fundamentally incompatible with the aim of
53
+ protecting users' freedom to change the software. The systematic
54
+ pattern of such abuse occurs in the area of products for individuals to
55
+ use, which is precisely where it is most unacceptable. Therefore, we
56
+ have designed this version of the GPL to prohibit the practice for those
57
+ products. If such problems arise substantially in other domains, we
58
+ stand ready to extend this provision to those domains in future versions
59
+ of the GPL, as needed to protect the freedom of users.
60
+
61
+ Finally, every program is threatened constantly by software patents.
62
+ States should not allow patents to restrict development and use of
63
+ software on general-purpose computers, but in those that do, we wish to
64
+ avoid the special danger that patents applied to a free program could
65
+ make it effectively proprietary. To prevent this, the GPL assures that
66
+ patents cannot be used to render the program non-free.
67
+
68
+ The precise terms and conditions for copying, distribution and
69
+ modification follow.
70
+
71
+ TERMS AND CONDITIONS
72
+
73
+ 0. Definitions.
74
+
75
+ "This License" refers to version 3 of the GNU General Public License.
76
+
77
+ "Copyright" also means copyright-like laws that apply to other kinds of
78
+ works, such as semiconductor masks.
79
+
80
+ "The Program" refers to any copyrightable work licensed under this
81
+ License. Each licensee is addressed as "you". "Licensees" and
82
+ "recipients" may be individuals or organizations.
83
+
84
+ To "modify" a work means to copy from or adapt all or part of the work
85
+ in a fashion requiring copyright permission, other than the making of an
86
+ exact copy. The resulting work is called a "modified version" of the
87
+ earlier work or a work "based on" the earlier work.
88
+
89
+ A "covered work" means either the unmodified Program or a work based
90
+ on the Program.
91
+
92
+ To "propagate" a work means to do anything with it that, without
93
+ permission, would make you directly or secondarily liable for
94
+ infringement under applicable copyright law, except executing it on a
95
+ computer or modifying a private copy. Propagation includes copying,
96
+ distribution (with or without modification), making available to the
97
+ public, and in some countries other activities as well.
98
+
99
+ To "convey" a work means any kind of propagation that enables other
100
+ parties to make or receive copies. Mere interaction with a user through
101
+ a computer network, with no transfer of a copy, is not conveying.
102
+
103
+ An interactive user interface displays "Appropriate Legal Notices"
104
+ to the extent that it includes a convenient and prominently visible
105
+ feature that (1) displays an appropriate copyright notice, and (2)
106
+ tells the user that there is no warranty for the work (except to the
107
+ extent that warranties are provided), that licensees may convey the
108
+ work under this License, and how to view a copy of this License. If
109
+ the interface presents a list of user commands or options, such as a
110
+ menu, a prominent item in the list meets this criterion.
111
+
112
+ 1. Source Code.
113
+
114
+ The "source code" for a work means the preferred form of the work
115
+ for making modifications to it. "Object code" means any non-source
116
+ form of a work.
117
+
118
+ A "Standard Interface" means an interface that either is an official
119
+ standard defined by a recognized standards body, or, in the case of
120
+ interfaces specified for a particular programming language, one that
121
+ is widely used among developers working in that language.
122
+
123
+ The "System Libraries" of an executable work include anything, other
124
+ than the work as a whole, that (a) is included in the normal form of
125
+ packaging a Major Component, but which is not part of that Major
126
+ Component, and (b) serves only to enable use of the work with that
127
+ Major Component, or to implement a Standard Interface for which an
128
+ implementation is available to the public in source code form. A
129
+ "Major Component", in this context, means a major essential component
130
+ (kernel, window system, and so on) of the specific operating system
131
+ (if any) on which the executable work runs, or a compiler used to
132
+ produce the work, or an object code interpreter used to run it.
133
+
134
+ The "Corresponding Source" for a work in object code form means all
135
+ the source code needed to generate, install, and (for an executable
136
+ work) run the object code and to modify the work, including scripts to
137
+ control those activities. However, it does not include the work's
138
+ System Libraries, or general-purpose tools or generally available free
139
+ programs which are used unmodified in performing those activities but
140
+ which are not part of the work. For example, Corresponding Source
141
+ includes interface definition files associated with source files for
142
+ the work, and the source code for shared libraries and dynamically
143
+ linked subprograms that the work is specifically designed to require,
144
+ such as by intimate data communication or control flow between those
145
+ subprograms and other parts of the work.
146
+
147
+ The Corresponding Source need not include anything that users
148
+ can regenerate automatically from other parts of the Corresponding
149
+ Source.
150
+
151
+ The Corresponding Source for a work in source code form is that
152
+ same work.
153
+
154
+ 2. Basic Permissions.
155
+
156
+ All rights granted under this License are granted for the term of
157
+ copyright on the Program, and are irrevocable provided the stated
158
+ conditions are met. This License explicitly affirms your unlimited
159
+ permission to run the unmodified Program. The output from running a
160
+ covered work is covered by this License only if the output, given its
161
+ content, constitutes a covered work. This License acknowledges your
162
+ rights of fair use or other equivalent, as provided by copyright law.
163
+
164
+ You may make, run and propagate covered works that you do not
165
+ convey, without conditions so long as your license otherwise remains
166
+ in force. You may convey covered works to others for the sole purpose
167
+ of having them make modifications exclusively for you, or provide you
168
+ with facilities for running those works, provided that you comply with
169
+ the terms of this License in conveying all material for which you do
170
+ not control copyright. Those thus making or running the covered works
171
+ for you must do so exclusively on your behalf, under your direction
172
+ and control, on terms that prohibit them from making any copies of
173
+ your copyrighted material outside their relationship with you.
174
+
175
+ Conveying under any other circumstances is permitted solely under
176
+ the conditions stated below. Sublicensing is not allowed; section 10
177
+ makes it unnecessary.
178
+
179
+ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180
+
181
+ No covered work shall be deemed part of an effective technological
182
+ measure under any applicable law fulfilling obligations under article
183
+ 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184
+ similar laws prohibiting or restricting circumvention of such
185
+ measures.
186
+
187
+ When you convey a covered work, you waive any legal power to forbid
188
+ circumvention of technological measures to the extent such circumvention
189
+ is effected by exercising rights under this License with respect to
190
+ the covered work, and you disclaim any intention to limit operation or
191
+ modification of the work as a means of enforcing, against the work's
192
+ users, your or third parties' legal rights to forbid circumvention of
193
+ technological measures.
194
+
195
+ 4. Conveying Verbatim Copies.
196
+
197
+ You may convey verbatim copies of the Program's source code as you
198
+ receive it, in any medium, provided that you conspicuously and
199
+ appropriately publish on each copy an appropriate copyright notice;
200
+ keep intact all notices stating that this License and any
201
+ non-permissive terms added in accord with section 7 apply to the code;
202
+ keep intact all notices of the absence of any warranty; and give all
203
+ recipients a copy of this License along with the Program.
204
+
205
+ You may charge any price or no price for each copy that you convey,
206
+ and you may offer support or warranty protection for a fee.
207
+
208
+ 5. Conveying Modified Source Versions.
209
+
210
+ You may convey a work based on the Program, or the modifications to
211
+ produce it from the Program, in the form of source code under the
212
+ terms of section 4, provided that you also meet all of these conditions:
213
+
214
+ a) The work must carry prominent notices stating that you modified
215
+ it, and giving a relevant date.
216
+
217
+ b) The work must carry prominent notices stating that it is
218
+ released under this License and any conditions added under section
219
+ 7. This requirement modifies the requirement in section 4 to
220
+ "keep intact all notices".
221
+
222
+ c) You must license the entire work, as a whole, under this
223
+ License to anyone who comes into possession of a copy. This
224
+ License will therefore apply, along with any applicable section 7
225
+ additional terms, to the whole of the work, and all its parts,
226
+ regardless of how they are packaged. This License gives no
227
+ permission to license the work in any other way, but it does not
228
+ invalidate such permission if you have separately received it.
229
+
230
+ d) If the work has interactive user interfaces, each must display
231
+ Appropriate Legal Notices; however, if the Program has interactive
232
+ interfaces that do not display Appropriate Legal Notices, your
233
+ work need not make them do so.
234
+
235
+ A compilation of a covered work with other separate and independent
236
+ works, which are not by their nature extensions of the covered work,
237
+ and which are not combined with it such as to form a larger program,
238
+ in or on a volume of a storage or distribution medium, is called an
239
+ "aggregate" if the compilation and its resulting copyright are not
240
+ used to limit the access or legal rights of the compilation's users
241
+ beyond what the individual works permit. Inclusion of a covered work
242
+ in an aggregate does not cause this License to apply to the other
243
+ parts of the aggregate.
244
+
245
+ 6. Conveying Non-Source Forms.
246
+
247
+ You may convey a covered work in object code form under the terms
248
+ of sections 4 and 5, provided that you also convey the
249
+ machine-readable Corresponding Source under the terms of this License,
250
+ in one of these ways:
251
+
252
+ a) Convey the object code in, or embodied in, a physical product
253
+ (including a physical distribution medium), accompanied by the
254
+ Corresponding Source fixed on a durable physical medium
255
+ customarily used for software interchange.
256
+
257
+ b) Convey the object code in, or embodied in, a physical product
258
+ (including a physical distribution medium), accompanied by a
259
+ written offer, valid for at least three years and valid for as
260
+ long as you offer spare parts or customer support for that product
261
+ model, to give anyone who possesses the object code either (1) a
262
+ copy of the Corresponding Source for all the software in the
263
+ product that is covered by this License, on a durable physical
264
+ medium customarily used for software interchange, for a price no
265
+ more than your reasonable cost of physically performing this
266
+ conveying of source, or (2) access to copy the
267
+ Corresponding Source from a network server at no charge.
268
+
269
+ c) Convey individual copies of the object code with a copy of the
270
+ written offer to provide the Corresponding Source. This
271
+ alternative is allowed only occasionally and noncommercially, and
272
+ only if you received the object code with such an offer, in accord
273
+ with subsection 6b.
274
+
275
+ d) Convey the object code by offering access from a designated
276
+ place (gratis or for a charge), and offer equivalent access to the
277
+ Corresponding Source in the same way through the same place at no
278
+ further charge. You need not require recipients to copy the
279
+ Corresponding Source along with the object code. If the place to
280
+ copy the object code is a network server, the Corresponding Source
281
+ may be on a different server (operated by you or a third party)
282
+ that supports equivalent copying facilities, provided you maintain
283
+ clear directions next to the object code saying where to find the
284
+ Corresponding Source. Regardless of what server hosts the
285
+ Corresponding Source, you remain obligated to ensure that it is
286
+ available for as long as needed to satisfy these requirements.
287
+
288
+ e) Convey the object code using peer-to-peer transmission, provided
289
+ you inform other peers where the object code and Corresponding
290
+ Source of the work are being offered to the general public at no
291
+ charge under subsection 6d.
292
+
293
+ A separable portion of the object code, whose source code is excluded
294
+ from the Corresponding Source as a System Library, need not be
295
+ included in conveying the object code work.
296
+
297
+ A "User Product" is either (1) a "consumer product", which means any
298
+ tangible personal property which is normally used for personal, family,
299
+ or household purposes, or (2) anything designed or sold for incorporation
300
+ into a dwelling. In determining whether a product is a consumer product,
301
+ doubtful cases shall be resolved in favor of coverage. For a particular
302
+ product received by a particular user, "normally used" refers to a
303
+ typical or common use of that class of product, regardless of the status
304
+ of the particular user or of the way in which the particular user
305
+ actually uses, or expects or is expected to use, the product. A product
306
+ is a consumer product regardless of whether the product has substantial
307
+ commercial, industrial or non-consumer uses, unless such uses represent
308
+ the only significant mode of use of the product.
309
+
310
+ "Installation Information" for a User Product means any methods,
311
+ procedures, authorization keys, or other information required to install
312
+ and execute modified versions of a covered work in that User Product from
313
+ a modified version of its Corresponding Source. The information must
314
+ suffice to ensure that the continued functioning of the modified object
315
+ code is in no case prevented or interfered with solely because
316
+ modification has been made.
317
+
318
+ If you convey an object code work under this section in, or with, or
319
+ specifically for use in, a User Product, and the conveying occurs as
320
+ part of a transaction in which the right of possession and use of the
321
+ User Product is transferred to the recipient in perpetuity or for a
322
+ fixed term (regardless of how the transaction is characterized), the
323
+ Corresponding Source conveyed under this section must be accompanied
324
+ by the Installation Information. But this requirement does not apply
325
+ if neither you nor any third party retains the ability to install
326
+ modified object code on the User Product (for example, the work has
327
+ been installed in ROM).
328
+
329
+ The requirement to provide Installation Information does not include a
330
+ requirement to continue to provide support service, warranty, or updates
331
+ for a work that has been modified or installed by the recipient, or for
332
+ the User Product in which it has been modified or installed. Access to a
333
+ network may be denied when the modification itself materially and
334
+ adversely affects the operation of the network or violates the rules and
335
+ protocols for communication across the network.
336
+
337
+ Corresponding Source conveyed, and Installation Information provided,
338
+ in accord with this section must be in a format that is publicly
339
+ documented (and with an implementation available to the public in
340
+ source code form), and must require no special password or key for
341
+ unpacking, reading or copying.
342
+
343
+ 7. Additional Terms.
344
+
345
+ "Additional permissions" are terms that supplement the terms of this
346
+ License by making exceptions from one or more of its conditions.
347
+ Additional permissions that are applicable to the entire Program shall
348
+ be treated as though they were included in this License, to the extent
349
+ that they are valid under applicable law. If additional permissions
350
+ apply only to part of the Program, that part may be used separately
351
+ under those permissions, but the entire Program remains governed by
352
+ this License without regard to the additional permissions.
353
+
354
+ When you convey a copy of a covered work, you may at your option
355
+ remove any additional permissions from that copy, or from any part of
356
+ it. (Additional permissions may be written to require their own
357
+ removal in certain cases when you modify the work.) You may place
358
+ additional permissions on material, added by you to a covered work,
359
+ for which you have or can give appropriate copyright permission.
360
+
361
+ Notwithstanding any other provision of this License, for material you
362
+ add to a covered work, you may (if authorized by the copyright holders of
363
+ that material) supplement the terms of this License with terms:
364
+
365
+ a) Disclaiming warranty or limiting liability differently from the
366
+ terms of sections 15 and 16 of this License; or
367
+
368
+ b) Requiring preservation of specified reasonable legal notices or
369
+ author attributions in that material or in the Appropriate Legal
370
+ Notices displayed by works containing it; or
371
+
372
+ c) Prohibiting misrepresentation of the origin of that material, or
373
+ requiring that modified versions of such material be marked in
374
+ reasonable ways as different from the original version; or
375
+
376
+ d) Limiting the use for publicity purposes of names of licensors or
377
+ authors of the material; or
378
+
379
+ e) Declining to grant rights under trademark law for use of some
380
+ trade names, trademarks, or service marks; or
381
+
382
+ f) Requiring indemnification of licensors and authors of that
383
+ material by anyone who conveys the material (or modified versions of
384
+ it) with contractual assumptions of liability to the recipient, for
385
+ any liability that these contractual assumptions directly impose on
386
+ those licensors and authors.
387
+
388
+ All other non-permissive additional terms are considered "further
389
+ restrictions" within the meaning of section 10. If the Program as you
390
+ received it, or any part of it, contains a notice stating that it is
391
+ governed by this License along with a term that is a further
392
+ restriction, you may remove that term. If a license document contains
393
+ a further restriction but permits relicensing or conveying under this
394
+ License, you may add to a covered work material governed by the terms
395
+ of that license document, provided that the further restriction does
396
+ not survive such relicensing or conveying.
397
+
398
+ If you add terms to a covered work in accord with this section, you
399
+ must place, in the relevant source files, a statement of the
400
+ additional terms that apply to those files, or a notice indicating
401
+ where to find the applicable terms.
402
+
403
+ Additional terms, permissive or non-permissive, may be stated in the
404
+ form of a separately written license, or stated as exceptions;
405
+ the above requirements apply either way.
406
+
407
+ 8. Termination.
408
+
409
+ You may not propagate or modify a covered work except as expressly
410
+ provided under this License. Any attempt otherwise to propagate or
411
+ modify it is void, and will automatically terminate your rights under
412
+ this License (including any patent licenses granted under the third
413
+ paragraph of section 11).
414
+
415
+ However, if you cease all violation of this License, then your
416
+ license from a particular copyright holder is reinstated (a)
417
+ provisionally, unless and until the copyright holder explicitly and
418
+ finally terminates your license, and (b) permanently, if the copyright
419
+ holder fails to notify you of the violation by some reasonable means
420
+ prior to 60 days after the cessation.
421
+
422
+ Moreover, your license from a particular copyright holder is
423
+ reinstated permanently if the copyright holder notifies you of the
424
+ violation by some reasonable means, this is the first time you have
425
+ received notice of violation of this License (for any work) from that
426
+ copyright holder, and you cure the violation prior to 30 days after
427
+ your receipt of the notice.
428
+
429
+ Termination of your rights under this section does not terminate the
430
+ licenses of parties who have received copies or rights from you under
431
+ this License. If your rights have been terminated and not permanently
432
+ reinstated, you do not qualify to receive new licenses for the same
433
+ material under section 10.
434
+
435
+ 9. Acceptance Not Required for Having Copies.
436
+
437
+ You are not required to accept this License in order to receive or
438
+ run a copy of the Program. Ancillary propagation of a covered work
439
+ occurring solely as a consequence of using peer-to-peer transmission
440
+ to receive a copy likewise does not require acceptance. However,
441
+ nothing other than this License grants you permission to propagate or
442
+ modify any covered work. These actions infringe copyright if you do
443
+ not accept this License. Therefore, by modifying or propagating a
444
+ covered work, you indicate your acceptance of this License to do so.
445
+
446
+ 10. Automatic Licensing of Downstream Recipients.
447
+
448
+ Each time you convey a covered work, the recipient automatically
449
+ receives a license from the original licensors, to run, modify and
450
+ propagate that work, subject to this License. You are not responsible
451
+ for enforcing compliance by third parties with this License.
452
+
453
+ An "entity transaction" is a transaction transferring control of an
454
+ organization, or substantially all assets of one, or subdividing an
455
+ organization, or merging organizations. If propagation of a covered
456
+ work results from an entity transaction, each party to that
457
+ transaction who receives a copy of the work also receives whatever
458
+ licenses to the work the party's predecessor in interest had or could
459
+ give under the previous paragraph, plus a right to possession of the
460
+ Corresponding Source of the work from the predecessor in interest, if
461
+ the predecessor has it or can get it with reasonable efforts.
462
+
463
+ You may not impose any further restrictions on the exercise of the
464
+ rights granted or affirmed under this License. For example, you may
465
+ not impose a license fee, royalty, or other charge for exercise of
466
+ rights granted under this License, and you may not initiate litigation
467
+ (including a cross-claim or counterclaim in a lawsuit) alleging that
468
+ any patent claim is infringed by making, using, selling, offering for
469
+ sale, or importing the Program or any portion of it.
470
+
471
+ 11. Patents.
472
+
473
+ A "contributor" is a copyright holder who authorizes use under this
474
+ License of the Program or a work on which the Program is based. The
475
+ work thus licensed is called the contributor's "contributor version".
476
+
477
+ A contributor's "essential patent claims" are all patent claims
478
+ owned or controlled by the contributor, whether already acquired or
479
+ hereafter acquired, that would be infringed by some manner, permitted
480
+ by this License, of making, using, or selling its contributor version,
481
+ but do not include claims that would be infringed only as a
482
+ consequence of further modification of the contributor version. For
483
+ purposes of this definition, "control" includes the right to grant
484
+ patent sublicenses in a manner consistent with the requirements of
485
+ this License.
486
+
487
+ Each contributor grants you a non-exclusive, worldwide, royalty-free
488
+ patent license under the contributor's essential patent claims, to
489
+ make, use, sell, offer for sale, import and otherwise run, modify and
490
+ propagate the contents of its contributor version.
491
+
492
+ In the following three paragraphs, a "patent license" is any express
493
+ agreement or commitment, however denominated, not to enforce a patent
494
+ (such as an express permission to practice a patent or covenant not to
495
+ sue for patent infringement). To "grant" such a patent license to a
496
+ party means to make such an agreement or commitment not to enforce a
497
+ patent against the party.
498
+
499
+ If you convey a covered work, knowingly relying on a patent license,
500
+ and the Corresponding Source of the work is not available for anyone
501
+ to copy, free of charge and under the terms of this License, through a
502
+ publicly available network server or other readily accessible means,
503
+ then you must either (1) cause the Corresponding Source to be so
504
+ available, or (2) arrange to deprive yourself of the benefit of the
505
+ patent license for this particular work, or (3) arrange, in a manner
506
+ consistent with the requirements of this License, to extend the patent
507
+ license to downstream recipients. "Knowingly relying" means you have
508
+ actual knowledge that, but for the patent license, your conveying the
509
+ covered work in a country, or your recipient's use of the covered work
510
+ in a country, would infringe one or more identifiable patents in that
511
+ country that you have reason to believe are valid.
512
+
513
+ If, pursuant to or in connection with a single transaction or
514
+ arrangement, you convey, or propagate by procuring conveyance of, a
515
+ covered work, and grant a patent license to some of the parties
516
+ receiving the covered work authorizing them to use, propagate, modify
517
+ or convey a specific copy of the covered work, then the patent license
518
+ you grant is automatically extended to all recipients of the covered
519
+ work and works based on it.
520
+
521
+ A patent license is "discriminatory" if it does not include within
522
+ the scope of its coverage, prohibits the exercise of, or is
523
+ conditioned on the non-exercise of one or more of the rights that are
524
+ specifically granted under this License. You may not convey a covered
525
+ work if you are a party to an arrangement with a third party that is
526
+ in the business of distributing software, under which you make payment
527
+ to the third party based on the extent of your activity of conveying
528
+ the work, and under which the third party grants, to any of the
529
+ parties who would receive the covered work from you, a discriminatory
530
+ patent license (a) in connection with copies of the covered work
531
+ conveyed by you (or copies made from those copies), or (b) primarily
532
+ for and in connection with specific products or compilations that
533
+ contain the covered work, unless you entered into that arrangement,
534
+ or that patent license was granted, prior to 28 March 2007.
535
+
536
+ Nothing in this License shall be construed as excluding or limiting
537
+ any implied license or other defenses to infringement that may
538
+ otherwise be available to you under applicable patent law.
539
+
540
+ 12. No Surrender of Others' Freedom.
541
+
542
+ If conditions are imposed on you (whether by court order, agreement or
543
+ otherwise) that contradict the conditions of this License, they do not
544
+ excuse you from the conditions of this License. If you cannot convey a
545
+ covered work so as to satisfy simultaneously your obligations under this
546
+ License and any other pertinent obligations, then as a consequence you may
547
+ not convey it at all. For example, if you agree to terms that obligate you
548
+ to collect a royalty for further conveying from those to whom you convey
549
+ the Program, the only way you could satisfy both those terms and this
550
+ License would be to refrain entirely from conveying the Program.
551
+
552
+ 13. Use with the GNU Affero General Public License.
553
+
554
+ Notwithstanding any other provision of this License, you have
555
+ permission to link or combine any covered work with a work licensed
556
+ under version 3 of the GNU Affero General Public License into a single
557
+ combined work, and to convey the resulting work. The terms of this
558
+ License will continue to apply to the part which is the covered work,
559
+ but the special requirements of the GNU Affero General Public License,
560
+ section 13, concerning interaction through a network will apply to the
561
+ combination as such.
562
+
563
+ 14. Revised Versions of this License.
564
+
565
+ The Free Software Foundation may publish revised and/or new versions of
566
+ the GNU General Public License from time to time. Such new versions will
567
+ be similar in spirit to the present version, but may differ in detail to
568
+ address new problems or concerns.
569
+
570
+ Each version is given a distinguishing version number. If the
571
+ Program specifies that a certain numbered version of the GNU General
572
+ Public License "or any later version" applies to it, you have the
573
+ option of following the terms and conditions either of that numbered
574
+ version or of any later version published by the Free Software
575
+ Foundation. If the Program does not specify a version number of the
576
+ GNU General Public License, you may choose any version ever published
577
+ by the Free Software Foundation.
578
+
579
+ If the Program specifies that a proxy can decide which future
580
+ versions of the GNU General Public License can be used, that proxy's
581
+ public statement of acceptance of a version permanently authorizes you
582
+ to choose that version for the Program.
583
+
584
+ Later license versions may give you additional or different
585
+ permissions. However, no additional obligations are imposed on any
586
+ author or copyright holder as a result of your choosing to follow a
587
+ later version.
588
+
589
+ 15. Disclaimer of Warranty.
590
+
591
+ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592
+ APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593
+ HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594
+ OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595
+ THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596
+ PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597
+ IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598
+ ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599
+
600
+ 16. Limitation of Liability.
601
+
602
+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603
+ WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604
+ THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605
+ GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606
+ USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607
+ DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608
+ PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609
+ EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610
+ SUCH DAMAGES.
611
+
612
+ 17. Interpretation of Sections 15 and 16.
613
+
614
+ If the disclaimer of warranty and limitation of liability provided
615
+ above cannot be given local legal effect according to their terms,
616
+ reviewing courts shall apply local law that most closely approximates
617
+ an absolute waiver of all civil liability in connection with the
618
+ Program, unless a warranty or assumption of liability accompanies a
619
+ copy of the Program in return for a fee.
620
+
621
+ END OF TERMS AND CONDITIONS
622
+
623
+ How to Apply These Terms to Your New Programs
624
+
625
+ If you develop a new program, and you want it to be of the greatest
626
+ possible use to the public, the best way to achieve this is to make it
627
+ free software which everyone can redistribute and change under these terms.
628
+
629
+ To do so, attach the following notices to the program. It is safest
630
+ to attach them to the start of each source file to most effectively
631
+ state the exclusion of warranty; and each file should have at least
632
+ the "copyright" line and a pointer to where the full notice is found.
633
+
634
+ <one line to give the program's name and a brief idea of what it does.>
635
+ Copyright (C) <year> <name of author>
636
+
637
+ This program is free software: you can redistribute it and/or modify
638
+ it under the terms of the GNU General Public License as published by
639
+ the Free Software Foundation, either version 3 of the License, or
640
+ (at your option) any later version.
641
+
642
+ This program is distributed in the hope that it will be useful,
643
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
644
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645
+ GNU General Public License for more details.
646
+
647
+ You should have received a copy of the GNU General Public License
648
+ along with this program. If not, see <https://www.gnu.org/licenses/>.
649
+
650
+ Also add information on how to contact you by electronic and paper mail.
651
+
652
+ If the program does terminal interaction, make it output a short
653
+ notice like this when it starts in an interactive mode:
654
+
655
+ <program> Copyright (C) <year> <name of author>
656
+ This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657
+ This is free software, and you are welcome to redistribute it
658
+ under certain conditions; type `show c' for details.
659
+
660
+ The hypothetical commands `show w' and `show c' should show the appropriate
661
+ parts of the General Public License. Of course, your program's commands
662
+ might be different; for a GUI interface, you would use an "about box".
663
+
664
+ You should also get your employer (if you work as a programmer) or school,
665
+ if any, to sign a "copyright disclaimer" for the program, if necessary.
666
+ For more information on this, and how to apply and follow the GNU GPL, see
667
+ <https://www.gnu.org/licenses/>.
668
+
669
+ The GNU General Public License does not permit incorporating your program
670
+ into proprietary programs. If your program is a subroutine library, you
671
+ may consider it more useful to permit linking proprietary applications with
672
+ the library. If this is what you want to do, use the GNU Lesser General
673
+ Public License instead of this License. But first, please read
674
+ <https://www.gnu.org/licenses/why-not-lgpl.html>.
README.md CHANGED
@@ -1,13 +1,13 @@
1
  ---
2
  title: Mangaka
3
- emoji: 🚀
4
  colorFrom: gray
5
  colorTo: gray
6
  sdk: gradio
7
  sdk_version: 4.21.0
8
  app_file: app.py
9
- pinned: false
10
- license: mit
11
  ---
12
 
13
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
1
  ---
2
  title: Mangaka
3
+ emoji: 🖌️
4
  colorFrom: gray
5
  colorTo: gray
6
  sdk: gradio
7
  sdk_version: 4.21.0
8
  app_file: app.py
9
+ pinned: true
10
+ license: gpl-3.0
11
  ---
12
 
13
+ :3
app.py ADDED
@@ -0,0 +1,149 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from PIL import Image, ImageOps, ImageSequence
3
+ import numpy as np
4
+
5
+ import comfy.sample
6
+ import comfy.sd
7
+
8
+ import comfy.model_management
9
+
10
+ def vencode(vae, pth):
11
+ pilimg = pth
12
+ pixels = np.array(pilimg).astype(np.float32) / 255.0
13
+ pixels = torch.from_numpy(pixels)[None,]
14
+ t = vae.encode(pixels[:,:,:,:3])
15
+ return {"samples":t}
16
+ from pathlib import Path
17
+ if not Path("model.safetensors").exists():
18
+ import requests
19
+ with open("model.safetensors", "wb") as f:
20
+ f.write(requests.get("https://huggingface.co/parsee-mizuhashi/mangaka/resolve/main/mangaka.safetensors?download=true").content)
21
+ MODEL_FILE = "model.safetensors"
22
+ unet, clip, vae = comfy.sd.load_checkpoint_guess_config(MODEL_FILE, output_vae=True, output_clip=True)[:3]# :3
23
+ BASE_NEG = "(low-quality worst-quality:1.4 (bad-anatomy (inaccurate-limb:1.2 bad-composition inaccurate-eyes extra-digit fewer-digits (extra-arms:1.2)"
24
+ DEVICE = comfy.model_management.get_torch_device()
25
+
26
+ def common_ksampler(model, seed, steps, cfg, sampler_name, scheduler, positive, negative, latent, denoise=1.0):
27
+
28
+ noise_mask = None
29
+ if "noise_mask" in latent:
30
+ noise_mask = latent["noise_mask"]
31
+ latnt = latent["samples"]
32
+ noise = comfy.sample.prepare_noise(latnt, seed, None)
33
+ disable_pbar = True
34
+ samples = comfy.sample.sample(model, noise, steps, cfg, sampler_name, scheduler, positive, negative, latnt,
35
+ denoise=denoise, noise_mask=noise_mask, disable_pbar=disable_pbar, seed=seed)
36
+ out = samples
37
+ return out
38
+ def set_mask(samples, mask):
39
+ s = samples.copy()
40
+ s["noise_mask"] = mask.reshape((-1, 1, mask.shape[-2], mask.shape[-1]))
41
+ return s
42
+ def load_image_mask(image):
43
+ image_path = image
44
+ i = Image.open(image_path)
45
+ i = ImageOps.exif_transpose(i)
46
+ if i.getbands() != ("R", "G", "B", "A"):
47
+ if i.mode == 'I':
48
+ i = i.point(lambda i: i * (1 / 255))
49
+ i = i.convert("RGBA")
50
+ mask = None
51
+ c = "A"
52
+ if c in i.getbands():
53
+ mask = np.array(i.getchannel(c)).astype(np.float32) / 255.0
54
+ mask = torch.from_numpy(mask)
55
+ else:
56
+ mask = torch.zeros((64,64), dtype=torch.float32, device="cpu")
57
+ return mask.unsqueeze(0)
58
+ @torch.no_grad()
59
+ def main(img, variant, positive, negative, pilimg):
60
+ variant = min(int(variant), limits[img])
61
+
62
+ global unet, clip, vae
63
+ mask = load_image_mask(f"./mangaka-d/{img}/i{variant}.png")
64
+
65
+ tkns = clip.tokenize("(greyscale monochrome black-and-white:1.3)" + positive)
66
+ cond, c = clip.encode_from_tokens(tkns, return_pooled=True)
67
+
68
+ uncond_tkns = clip.tokenize(BASE_NEG + negative)
69
+ uncond, uc = clip.encode_from_tokens(uncond_tkns, return_pooled=True)
70
+ cn = [[cond, {"pooled_output": c}]]
71
+ un = [[uncond, {"pooled_output": uc}]]
72
+
73
+ latent = vencode(vae, pilimg)
74
+ latent = set_mask(latent, mask)
75
+
76
+ denoised = common_ksampler(unet, 0, 20, 7, 'ddpm', 'karras', cn, un, latent, denoise=1)
77
+ decoded = vae.decode(denoised)
78
+ i = 255. * decoded[0].cpu().numpy()
79
+ img = Image.fromarray(np.clip(i, 0, 255).astype(np.uint8))
80
+ return img
81
+
82
+ limits = {
83
+ "1": 4,
84
+ "2": 4,
85
+ "3": 5,
86
+ "4": 6,
87
+ "5": 4,
88
+ "6": 6,
89
+ "7": 8,
90
+ "8": 5,
91
+ "9": 5,
92
+ "s1": 4,
93
+ "s2": 6,
94
+ "s3": 5,
95
+ "s4": 5,
96
+ "s5": 4,
97
+ "s6": 4
98
+ }
99
+ import gradio as gr
100
+ def visualize_fn(page, panel):
101
+ base = f"./mangaka-d/{page}/base.png"
102
+ base = Image.open(base)
103
+ if panel == "none":
104
+ return base
105
+ panel = min(int(panel), limits[page])
106
+ mask = f"./mangaka-d/{page}/i{panel}.png"
107
+ base = base.convert("RGBA")
108
+ mask = Image.open(mask)
109
+ #remove all green and blue from the mask
110
+ mask = mask.convert("RGBA")
111
+ data = mask.getdata()
112
+ data = [
113
+ (255, 0, 0, 255) if pixel[:3] == (255, 255, 255) else pixel
114
+ for pixel in mask.getdata()
115
+ ]
116
+ mask.putdata(data)
117
+ #overlay the mask on the base
118
+ base.paste(mask, (0,0), mask)
119
+ return base
120
+ def reset_fn(page):
121
+ base = f"./mangaka-d/{page}/base.png"
122
+ base = Image.open(base)
123
+ return base
124
+ with gr.Blocks() as demo:
125
+ with gr.Tab("Mangaka"):
126
+ with gr.Row():
127
+ with gr.Column():
128
+ positive = gr.Textbox(label="Positive prompt", lines=2)
129
+ negative = gr.Textbox(label="Negative prompt")
130
+ with gr.Accordion("Page Settings"):
131
+ with gr.Row():
132
+ with gr.Column():
133
+ page = gr.Dropdown(label="Page", choices=["1", "2", "3", "4", "5", "6", "7", "8", "9", "s1", "s2", "s3", "s4", "s5", "s6"], value="s1")
134
+ panel = gr.Dropdown(label="Panel", choices=["1", "2", "3", "4", "5", "6", "7", "8", "none"], value="1")
135
+ visualize = gr.Button("Visualize")
136
+ with gr.Column():
137
+ visualize_output = gr.Image(interactive=False)
138
+ visualize.click(visualize_fn, inputs=[page, panel], outputs=visualize_output)
139
+ with gr.Column():
140
+ with gr.Row():
141
+ with gr.Column():
142
+ generate = gr.Button("Generate", variant="primary")
143
+ with gr.Column():
144
+ reset = gr.Button("Reset", variant="stop")
145
+ current_panel = gr.Image(interactive=False)
146
+ reset.click(reset_fn, inputs=[page], outputs=current_panel)
147
+ generate.click(main, inputs=[page, panel, positive, negative, current_panel], outputs=current_panel)
148
+
149
+ demo.launch()
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,194 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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).reshape((attention_mask.shape[0], 1, -1, attention_mask.shape[-1])).expand(attention_mask.shape[0], 1, attention_mask.shape[-1], attention_mask.shape[-1])
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
+ embed_dim = config_dict["hidden_size"]
123
+ self.text_projection = operations.Linear(embed_dim, embed_dim, bias=False, dtype=dtype, device=device)
124
+ self.text_projection.weight.copy_(torch.eye(embed_dim))
125
+ self.dtype = dtype
126
+
127
+ def get_input_embeddings(self):
128
+ return self.text_model.embeddings.token_embedding
129
+
130
+ def set_input_embeddings(self, embeddings):
131
+ self.text_model.embeddings.token_embedding = embeddings
132
+
133
+ def forward(self, *args, **kwargs):
134
+ x = self.text_model(*args, **kwargs)
135
+ out = self.text_projection(x[2])
136
+ return (x[0], x[1], out, x[2])
137
+
138
+
139
+ class CLIPVisionEmbeddings(torch.nn.Module):
140
+ def __init__(self, embed_dim, num_channels=3, patch_size=14, image_size=224, dtype=None, device=None, operations=None):
141
+ super().__init__()
142
+ self.class_embedding = torch.nn.Parameter(torch.empty(embed_dim, dtype=dtype, device=device))
143
+
144
+ self.patch_embedding = operations.Conv2d(
145
+ in_channels=num_channels,
146
+ out_channels=embed_dim,
147
+ kernel_size=patch_size,
148
+ stride=patch_size,
149
+ bias=False,
150
+ dtype=dtype,
151
+ device=device
152
+ )
153
+
154
+ num_patches = (image_size // patch_size) ** 2
155
+ num_positions = num_patches + 1
156
+ self.position_embedding = torch.nn.Embedding(num_positions, embed_dim, dtype=dtype, device=device)
157
+
158
+ def forward(self, pixel_values):
159
+ embeds = self.patch_embedding(pixel_values).flatten(2).transpose(1, 2)
160
+ 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)
161
+
162
+
163
+ class CLIPVision(torch.nn.Module):
164
+ def __init__(self, config_dict, dtype, device, operations):
165
+ super().__init__()
166
+ num_layers = config_dict["num_hidden_layers"]
167
+ embed_dim = config_dict["hidden_size"]
168
+ heads = config_dict["num_attention_heads"]
169
+ intermediate_size = config_dict["intermediate_size"]
170
+ intermediate_activation = config_dict["hidden_act"]
171
+
172
+ self.embeddings = CLIPVisionEmbeddings(embed_dim, config_dict["num_channels"], config_dict["patch_size"], config_dict["image_size"], dtype=torch.float32, device=device, operations=operations)
173
+ self.pre_layrnorm = operations.LayerNorm(embed_dim)
174
+ self.encoder = CLIPEncoder(num_layers, embed_dim, heads, intermediate_size, intermediate_activation, dtype, device, operations)
175
+ self.post_layernorm = operations.LayerNorm(embed_dim)
176
+
177
+ def forward(self, pixel_values, attention_mask=None, intermediate_output=None):
178
+ x = self.embeddings(pixel_values)
179
+ x = self.pre_layrnorm(x)
180
+ #TODO: attention_mask?
181
+ x, i = self.encoder(x, mask=None, intermediate_output=intermediate_output)
182
+ pooled_output = self.post_layernorm(x[:, 0, :])
183
+ return x, i, pooled_output
184
+
185
+ class CLIPVisionModelProjection(torch.nn.Module):
186
+ def __init__(self, config_dict, dtype, device, operations):
187
+ super().__init__()
188
+ self.vision_model = CLIPVision(config_dict, dtype, device, operations)
189
+ self.visual_projection = operations.Linear(config_dict["hidden_size"], config_dict["projection_dim"], bias=False)
190
+
191
+ def forward(self, *args, **kwargs):
192
+ x = self.vision_model(*args, **kwargs)
193
+ out = self.visual_projection(x[2])
194
+ 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,544 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ import comfy.ldm.cascade.controlnet
13
+
14
+
15
+ def broadcast_image_to(tensor, target_batch_size, batched_number):
16
+ current_batch_size = tensor.shape[0]
17
+ #print(current_batch_size, target_batch_size)
18
+ if current_batch_size == 1:
19
+ return tensor
20
+
21
+ per_batch = target_batch_size // batched_number
22
+ tensor = tensor[:per_batch]
23
+
24
+ if per_batch > tensor.shape[0]:
25
+ tensor = torch.cat([tensor] * (per_batch // tensor.shape[0]) + [tensor[:(per_batch % tensor.shape[0])]], dim=0)
26
+
27
+ current_batch_size = tensor.shape[0]
28
+ if current_batch_size == target_batch_size:
29
+ return tensor
30
+ else:
31
+ return torch.cat([tensor] * batched_number, dim=0)
32
+
33
+ class ControlBase:
34
+ def __init__(self, device=None):
35
+ self.cond_hint_original = None
36
+ self.cond_hint = None
37
+ self.strength = 1.0
38
+ self.timestep_percent_range = (0.0, 1.0)
39
+ self.global_average_pooling = False
40
+ self.timestep_range = None
41
+ self.compression_ratio = 8
42
+ self.upscale_algorithm = 'nearest-exact'
43
+
44
+ if device is None:
45
+ device = comfy.model_management.get_torch_device()
46
+ self.device = device
47
+ self.previous_controlnet = None
48
+
49
+ def set_cond_hint(self, cond_hint, strength=1.0, timestep_percent_range=(0.0, 1.0)):
50
+ self.cond_hint_original = cond_hint
51
+ self.strength = strength
52
+ self.timestep_percent_range = timestep_percent_range
53
+ return self
54
+
55
+ def pre_run(self, model, percent_to_timestep_function):
56
+ self.timestep_range = (percent_to_timestep_function(self.timestep_percent_range[0]), percent_to_timestep_function(self.timestep_percent_range[1]))
57
+ if self.previous_controlnet is not None:
58
+ self.previous_controlnet.pre_run(model, percent_to_timestep_function)
59
+
60
+ def set_previous_controlnet(self, controlnet):
61
+ self.previous_controlnet = controlnet
62
+ return self
63
+
64
+ def cleanup(self):
65
+ if self.previous_controlnet is not None:
66
+ self.previous_controlnet.cleanup()
67
+ if self.cond_hint is not None:
68
+ del self.cond_hint
69
+ self.cond_hint = None
70
+ self.timestep_range = None
71
+
72
+ def get_models(self):
73
+ out = []
74
+ if self.previous_controlnet is not None:
75
+ out += self.previous_controlnet.get_models()
76
+ return out
77
+
78
+ def copy_to(self, c):
79
+ c.cond_hint_original = self.cond_hint_original
80
+ c.strength = self.strength
81
+ c.timestep_percent_range = self.timestep_percent_range
82
+ c.global_average_pooling = self.global_average_pooling
83
+ c.compression_ratio = self.compression_ratio
84
+ c.upscale_algorithm = self.upscale_algorithm
85
+
86
+ def inference_memory_requirements(self, dtype):
87
+ if self.previous_controlnet is not None:
88
+ return self.previous_controlnet.inference_memory_requirements(dtype)
89
+ return 0
90
+
91
+ def control_merge(self, control_input, control_output, control_prev, output_dtype):
92
+ out = {'input':[], 'middle':[], 'output': []}
93
+
94
+ if control_input is not None:
95
+ for i in range(len(control_input)):
96
+ key = 'input'
97
+ x = control_input[i]
98
+ if x is not None:
99
+ x *= self.strength
100
+ if x.dtype != output_dtype:
101
+ x = x.to(output_dtype)
102
+ out[key].insert(0, x)
103
+
104
+ if control_output is not None:
105
+ for i in range(len(control_output)):
106
+ if i == (len(control_output) - 1):
107
+ key = 'middle'
108
+ index = 0
109
+ else:
110
+ key = 'output'
111
+ index = i
112
+ x = control_output[i]
113
+ if x is not None:
114
+ if self.global_average_pooling:
115
+ x = torch.mean(x, dim=(2, 3), keepdim=True).repeat(1, 1, x.shape[2], x.shape[3])
116
+
117
+ x *= self.strength
118
+ if x.dtype != output_dtype:
119
+ x = x.to(output_dtype)
120
+
121
+ out[key].append(x)
122
+ if control_prev is not None:
123
+ for x in ['input', 'middle', 'output']:
124
+ o = out[x]
125
+ for i in range(len(control_prev[x])):
126
+ prev_val = control_prev[x][i]
127
+ if i >= len(o):
128
+ o.append(prev_val)
129
+ elif prev_val is not None:
130
+ if o[i] is None:
131
+ o[i] = prev_val
132
+ else:
133
+ if o[i].shape[0] < prev_val.shape[0]:
134
+ o[i] = prev_val + o[i]
135
+ else:
136
+ o[i] += prev_val
137
+ return out
138
+
139
+ class ControlNet(ControlBase):
140
+ def __init__(self, control_model, global_average_pooling=False, device=None, load_device=None, manual_cast_dtype=None):
141
+ super().__init__(device)
142
+ self.control_model = control_model
143
+ self.load_device = load_device
144
+ self.control_model_wrapped = comfy.model_patcher.ModelPatcher(self.control_model, load_device=load_device, offload_device=comfy.model_management.unet_offload_device())
145
+ self.global_average_pooling = global_average_pooling
146
+ self.model_sampling_current = None
147
+ self.manual_cast_dtype = manual_cast_dtype
148
+
149
+ def get_control(self, x_noisy, t, cond, batched_number):
150
+ control_prev = None
151
+ if self.previous_controlnet is not None:
152
+ control_prev = self.previous_controlnet.get_control(x_noisy, t, cond, batched_number)
153
+
154
+ if self.timestep_range is not None:
155
+ if t[0] > self.timestep_range[0] or t[0] < self.timestep_range[1]:
156
+ if control_prev is not None:
157
+ return control_prev
158
+ else:
159
+ return None
160
+
161
+ dtype = self.control_model.dtype
162
+ if self.manual_cast_dtype is not None:
163
+ dtype = self.manual_cast_dtype
164
+
165
+ output_dtype = x_noisy.dtype
166
+ if self.cond_hint is None or x_noisy.shape[2] * self.compression_ratio != self.cond_hint.shape[2] or x_noisy.shape[3] * self.compression_ratio != self.cond_hint.shape[3]:
167
+ if self.cond_hint is not None:
168
+ del self.cond_hint
169
+ self.cond_hint = None
170
+ self.cond_hint = comfy.utils.common_upscale(self.cond_hint_original, x_noisy.shape[3] * self.compression_ratio, x_noisy.shape[2] * self.compression_ratio, self.upscale_algorithm, "center").to(dtype).to(self.device)
171
+ if x_noisy.shape[0] != self.cond_hint.shape[0]:
172
+ self.cond_hint = broadcast_image_to(self.cond_hint, x_noisy.shape[0], batched_number)
173
+
174
+ context = cond.get('crossattn_controlnet', cond['c_crossattn'])
175
+ y = cond.get('y', None)
176
+ if y is not None:
177
+ y = y.to(dtype)
178
+ timestep = self.model_sampling_current.timestep(t)
179
+ x_noisy = self.model_sampling_current.calculate_input(t, x_noisy)
180
+
181
+ control = self.control_model(x=x_noisy.to(dtype), hint=self.cond_hint, timesteps=timestep.float(), context=context.to(dtype), y=y)
182
+ return self.control_merge(None, control, control_prev, output_dtype)
183
+
184
+ def copy(self):
185
+ c = ControlNet(self.control_model, global_average_pooling=self.global_average_pooling, load_device=self.load_device, manual_cast_dtype=self.manual_cast_dtype)
186
+ self.copy_to(c)
187
+ return c
188
+
189
+ def get_models(self):
190
+ out = super().get_models()
191
+ out.append(self.control_model_wrapped)
192
+ return out
193
+
194
+ def pre_run(self, model, percent_to_timestep_function):
195
+ super().pre_run(model, percent_to_timestep_function)
196
+ self.model_sampling_current = model.model_sampling
197
+
198
+ def cleanup(self):
199
+ self.model_sampling_current = None
200
+ super().cleanup()
201
+
202
+ class ControlLoraOps:
203
+ class Linear(torch.nn.Module):
204
+ def __init__(self, in_features: int, out_features: int, bias: bool = True,
205
+ device=None, dtype=None) -> None:
206
+ factory_kwargs = {'device': device, 'dtype': dtype}
207
+ super().__init__()
208
+ self.in_features = in_features
209
+ self.out_features = out_features
210
+ self.weight = None
211
+ self.up = None
212
+ self.down = None
213
+ self.bias = None
214
+
215
+ def forward(self, input):
216
+ weight, bias = comfy.ops.cast_bias_weight(self, input)
217
+ if self.up is not None:
218
+ 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)
219
+ else:
220
+ return torch.nn.functional.linear(input, weight, bias)
221
+
222
+ class Conv2d(torch.nn.Module):
223
+ def __init__(
224
+ self,
225
+ in_channels,
226
+ out_channels,
227
+ kernel_size,
228
+ stride=1,
229
+ padding=0,
230
+ dilation=1,
231
+ groups=1,
232
+ bias=True,
233
+ padding_mode='zeros',
234
+ device=None,
235
+ dtype=None
236
+ ):
237
+ super().__init__()
238
+ self.in_channels = in_channels
239
+ self.out_channels = out_channels
240
+ self.kernel_size = kernel_size
241
+ self.stride = stride
242
+ self.padding = padding
243
+ self.dilation = dilation
244
+ self.transposed = False
245
+ self.output_padding = 0
246
+ self.groups = groups
247
+ self.padding_mode = padding_mode
248
+
249
+ self.weight = None
250
+ self.bias = None
251
+ self.up = None
252
+ self.down = None
253
+
254
+
255
+ def forward(self, input):
256
+ weight, bias = comfy.ops.cast_bias_weight(self, input)
257
+ if self.up is not None:
258
+ 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)
259
+ else:
260
+ return torch.nn.functional.conv2d(input, weight, bias, self.stride, self.padding, self.dilation, self.groups)
261
+
262
+
263
+ class ControlLora(ControlNet):
264
+ def __init__(self, control_weights, global_average_pooling=False, device=None):
265
+ ControlBase.__init__(self, device)
266
+ self.control_weights = control_weights
267
+ self.global_average_pooling = global_average_pooling
268
+
269
+ def pre_run(self, model, percent_to_timestep_function):
270
+ super().pre_run(model, percent_to_timestep_function)
271
+ controlnet_config = model.model_config.unet_config.copy()
272
+ controlnet_config.pop("out_channels")
273
+ controlnet_config["hint_channels"] = self.control_weights["input_hint_block.0.weight"].shape[1]
274
+ self.manual_cast_dtype = model.manual_cast_dtype
275
+ dtype = model.get_dtype()
276
+ if self.manual_cast_dtype is None:
277
+ class control_lora_ops(ControlLoraOps, comfy.ops.disable_weight_init):
278
+ pass
279
+ else:
280
+ class control_lora_ops(ControlLoraOps, comfy.ops.manual_cast):
281
+ pass
282
+ dtype = self.manual_cast_dtype
283
+
284
+ controlnet_config["operations"] = control_lora_ops
285
+ controlnet_config["dtype"] = dtype
286
+ self.control_model = comfy.cldm.cldm.ControlNet(**controlnet_config)
287
+ self.control_model.to(comfy.model_management.get_torch_device())
288
+ diffusion_model = model.diffusion_model
289
+ sd = diffusion_model.state_dict()
290
+ cm = self.control_model.state_dict()
291
+
292
+ for k in sd:
293
+ weight = sd[k]
294
+ try:
295
+ comfy.utils.set_attr_param(self.control_model, k, weight)
296
+ except:
297
+ pass
298
+
299
+ for k in self.control_weights:
300
+ if k not in {"lora_controlnet"}:
301
+ comfy.utils.set_attr_param(self.control_model, k, self.control_weights[k].to(dtype).to(comfy.model_management.get_torch_device()))
302
+
303
+ def copy(self):
304
+ c = ControlLora(self.control_weights, global_average_pooling=self.global_average_pooling)
305
+ self.copy_to(c)
306
+ return c
307
+
308
+ def cleanup(self):
309
+ del self.control_model
310
+ self.control_model = None
311
+ super().cleanup()
312
+
313
+ def get_models(self):
314
+ out = ControlBase.get_models(self)
315
+ return out
316
+
317
+ def inference_memory_requirements(self, dtype):
318
+ return comfy.utils.calculate_parameters(self.control_weights) * comfy.model_management.dtype_size(dtype) + ControlBase.inference_memory_requirements(self, dtype)
319
+
320
+ def load_controlnet(ckpt_path, model=None):
321
+ controlnet_data = comfy.utils.load_torch_file(ckpt_path, safe_load=True)
322
+ if "lora_controlnet" in controlnet_data:
323
+ return ControlLora(controlnet_data)
324
+
325
+ controlnet_config = None
326
+ supported_inference_dtypes = None
327
+
328
+ if "controlnet_cond_embedding.conv_in.weight" in controlnet_data: #diffusers format
329
+ controlnet_config = comfy.model_detection.unet_config_from_diffusers_unet(controlnet_data)
330
+ diffusers_keys = comfy.utils.unet_to_diffusers(controlnet_config)
331
+ diffusers_keys["controlnet_mid_block.weight"] = "middle_block_out.0.weight"
332
+ diffusers_keys["controlnet_mid_block.bias"] = "middle_block_out.0.bias"
333
+
334
+ count = 0
335
+ loop = True
336
+ while loop:
337
+ suffix = [".weight", ".bias"]
338
+ for s in suffix:
339
+ k_in = "controlnet_down_blocks.{}{}".format(count, s)
340
+ k_out = "zero_convs.{}.0{}".format(count, s)
341
+ if k_in not in controlnet_data:
342
+ loop = False
343
+ break
344
+ diffusers_keys[k_in] = k_out
345
+ count += 1
346
+
347
+ count = 0
348
+ loop = True
349
+ while loop:
350
+ suffix = [".weight", ".bias"]
351
+ for s in suffix:
352
+ if count == 0:
353
+ k_in = "controlnet_cond_embedding.conv_in{}".format(s)
354
+ else:
355
+ k_in = "controlnet_cond_embedding.blocks.{}{}".format(count - 1, s)
356
+ k_out = "input_hint_block.{}{}".format(count * 2, s)
357
+ if k_in not in controlnet_data:
358
+ k_in = "controlnet_cond_embedding.conv_out{}".format(s)
359
+ loop = False
360
+ diffusers_keys[k_in] = k_out
361
+ count += 1
362
+
363
+ new_sd = {}
364
+ for k in diffusers_keys:
365
+ if k in controlnet_data:
366
+ new_sd[diffusers_keys[k]] = controlnet_data.pop(k)
367
+
368
+ leftover_keys = controlnet_data.keys()
369
+ if len(leftover_keys) > 0:
370
+ print("leftover keys:", leftover_keys)
371
+ controlnet_data = new_sd
372
+
373
+ pth_key = 'control_model.zero_convs.0.0.weight'
374
+ pth = False
375
+ key = 'zero_convs.0.0.weight'
376
+ if pth_key in controlnet_data:
377
+ pth = True
378
+ key = pth_key
379
+ prefix = "control_model."
380
+ elif key in controlnet_data:
381
+ prefix = ""
382
+ else:
383
+ net = load_t2i_adapter(controlnet_data)
384
+ if net is None:
385
+ print("error checkpoint does not contain controlnet or t2i adapter data", ckpt_path)
386
+ return net
387
+
388
+ if controlnet_config is None:
389
+ model_config = comfy.model_detection.model_config_from_unet(controlnet_data, prefix, True)
390
+ supported_inference_dtypes = model_config.supported_inference_dtypes
391
+ controlnet_config = model_config.unet_config
392
+
393
+ load_device = comfy.model_management.get_torch_device()
394
+ if supported_inference_dtypes is None:
395
+ unet_dtype = comfy.model_management.unet_dtype()
396
+ else:
397
+ unet_dtype = comfy.model_management.unet_dtype(supported_dtypes=supported_inference_dtypes)
398
+
399
+ manual_cast_dtype = comfy.model_management.unet_manual_cast(unet_dtype, load_device)
400
+ if manual_cast_dtype is not None:
401
+ controlnet_config["operations"] = comfy.ops.manual_cast
402
+ controlnet_config["dtype"] = unet_dtype
403
+ controlnet_config.pop("out_channels")
404
+ controlnet_config["hint_channels"] = controlnet_data["{}input_hint_block.0.weight".format(prefix)].shape[1]
405
+ control_model = comfy.cldm.cldm.ControlNet(**controlnet_config)
406
+
407
+ if pth:
408
+ if 'difference' in controlnet_data:
409
+ if model is not None:
410
+ comfy.model_management.load_models_gpu([model])
411
+ model_sd = model.model_state_dict()
412
+ for x in controlnet_data:
413
+ c_m = "control_model."
414
+ if x.startswith(c_m):
415
+ sd_key = "diffusion_model.{}".format(x[len(c_m):])
416
+ if sd_key in model_sd:
417
+ cd = controlnet_data[x]
418
+ cd += model_sd[sd_key].type(cd.dtype).to(cd.device)
419
+ else:
420
+ print("WARNING: Loaded a diff controlnet without a model. It will very likely not work.")
421
+
422
+ class WeightsLoader(torch.nn.Module):
423
+ pass
424
+ w = WeightsLoader()
425
+ w.control_model = control_model
426
+ missing, unexpected = w.load_state_dict(controlnet_data, strict=False)
427
+ else:
428
+ missing, unexpected = control_model.load_state_dict(controlnet_data, strict=False)
429
+ print(missing, unexpected)
430
+
431
+ global_average_pooling = False
432
+ filename = os.path.splitext(ckpt_path)[0]
433
+ if filename.endswith("_shuffle") or filename.endswith("_shuffle_fp16"): #TODO: smarter way of enabling global_average_pooling
434
+ global_average_pooling = True
435
+
436
+ control = ControlNet(control_model, global_average_pooling=global_average_pooling, load_device=load_device, manual_cast_dtype=manual_cast_dtype)
437
+ return control
438
+
439
+ class T2IAdapter(ControlBase):
440
+ def __init__(self, t2i_model, channels_in, compression_ratio, upscale_algorithm, device=None):
441
+ super().__init__(device)
442
+ self.t2i_model = t2i_model
443
+ self.channels_in = channels_in
444
+ self.control_input = None
445
+ self.compression_ratio = compression_ratio
446
+ self.upscale_algorithm = upscale_algorithm
447
+
448
+ def scale_image_to(self, width, height):
449
+ unshuffle_amount = self.t2i_model.unshuffle_amount
450
+ width = math.ceil(width / unshuffle_amount) * unshuffle_amount
451
+ height = math.ceil(height / unshuffle_amount) * unshuffle_amount
452
+ return width, height
453
+
454
+ def get_control(self, x_noisy, t, cond, batched_number):
455
+ control_prev = None
456
+ if self.previous_controlnet is not None:
457
+ control_prev = self.previous_controlnet.get_control(x_noisy, t, cond, batched_number)
458
+
459
+ if self.timestep_range is not None:
460
+ if t[0] > self.timestep_range[0] or t[0] < self.timestep_range[1]:
461
+ if control_prev is not None:
462
+ return control_prev
463
+ else:
464
+ return None
465
+
466
+ if self.cond_hint is None or x_noisy.shape[2] * self.compression_ratio != self.cond_hint.shape[2] or x_noisy.shape[3] * self.compression_ratio != self.cond_hint.shape[3]:
467
+ if self.cond_hint is not None:
468
+ del self.cond_hint
469
+ self.control_input = None
470
+ self.cond_hint = None
471
+ width, height = self.scale_image_to(x_noisy.shape[3] * self.compression_ratio, x_noisy.shape[2] * self.compression_ratio)
472
+ self.cond_hint = comfy.utils.common_upscale(self.cond_hint_original, width, height, self.upscale_algorithm, "center").float().to(self.device)
473
+ if self.channels_in == 1 and self.cond_hint.shape[1] > 1:
474
+ self.cond_hint = torch.mean(self.cond_hint, 1, keepdim=True)
475
+ if x_noisy.shape[0] != self.cond_hint.shape[0]:
476
+ self.cond_hint = broadcast_image_to(self.cond_hint, x_noisy.shape[0], batched_number)
477
+ if self.control_input is None:
478
+ self.t2i_model.to(x_noisy.dtype)
479
+ self.t2i_model.to(self.device)
480
+ self.control_input = self.t2i_model(self.cond_hint.to(x_noisy.dtype))
481
+ self.t2i_model.cpu()
482
+
483
+ control_input = list(map(lambda a: None if a is None else a.clone(), self.control_input))
484
+ mid = None
485
+ if self.t2i_model.xl == True:
486
+ mid = control_input[-1:]
487
+ control_input = control_input[:-1]
488
+ return self.control_merge(control_input, mid, control_prev, x_noisy.dtype)
489
+
490
+ def copy(self):
491
+ c = T2IAdapter(self.t2i_model, self.channels_in, self.compression_ratio, self.upscale_algorithm)
492
+ self.copy_to(c)
493
+ return c
494
+
495
+ def load_t2i_adapter(t2i_data):
496
+ compression_ratio = 8
497
+ upscale_algorithm = 'nearest-exact'
498
+
499
+ if 'adapter' in t2i_data:
500
+ t2i_data = t2i_data['adapter']
501
+ if 'adapter.body.0.resnets.0.block1.weight' in t2i_data: #diffusers format
502
+ prefix_replace = {}
503
+ for i in range(4):
504
+ for j in range(2):
505
+ prefix_replace["adapter.body.{}.resnets.{}.".format(i, j)] = "body.{}.".format(i * 2 + j)
506
+ prefix_replace["adapter.body.{}.".format(i, j)] = "body.{}.".format(i * 2)
507
+ prefix_replace["adapter."] = ""
508
+ t2i_data = comfy.utils.state_dict_prefix_replace(t2i_data, prefix_replace)
509
+ keys = t2i_data.keys()
510
+
511
+ if "body.0.in_conv.weight" in keys:
512
+ cin = t2i_data['body.0.in_conv.weight'].shape[1]
513
+ model_ad = comfy.t2i_adapter.adapter.Adapter_light(cin=cin, channels=[320, 640, 1280, 1280], nums_rb=4)
514
+ elif 'conv_in.weight' in keys:
515
+ cin = t2i_data['conv_in.weight'].shape[1]
516
+ channel = t2i_data['conv_in.weight'].shape[0]
517
+ ksize = t2i_data['body.0.block2.weight'].shape[2]
518
+ use_conv = False
519
+ down_opts = list(filter(lambda a: a.endswith("down_opt.op.weight"), keys))
520
+ if len(down_opts) > 0:
521
+ use_conv = True
522
+ xl = False
523
+ if cin == 256 or cin == 768:
524
+ xl = True
525
+ 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)
526
+ elif "backbone.0.0.weight" in keys:
527
+ model_ad = comfy.ldm.cascade.controlnet.ControlNet(c_in=t2i_data['backbone.0.0.weight'].shape[1], proj_blocks=[0, 4, 8, 12, 51, 55, 59, 63])
528
+ compression_ratio = 32
529
+ upscale_algorithm = 'bilinear'
530
+ elif "backbone.10.blocks.0.weight" in keys:
531
+ model_ad = comfy.ldm.cascade.controlnet.ControlNet(c_in=t2i_data['backbone.0.weight'].shape[1], bottleneck_mode="large", proj_blocks=[0, 4, 8, 12, 51, 55, 59, 63])
532
+ compression_ratio = 1
533
+ upscale_algorithm = 'nearest-exact'
534
+ else:
535
+ return None
536
+
537
+ missing, unexpected = model_ad.load_state_dict(t2i_data)
538
+ if len(missing) > 0:
539
+ print("t2i missing", missing)
540
+
541
+ if len(unexpected) > 0:
542
+ print("t2i unexpected", unexpected)
543
+
544
+ return T2IAdapter(model_ad, model_ad.input_channels, compression_ratio, upscale_algorithm)
comfy/diffusers_convert.py ADDED
@@ -0,0 +1,265 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ text_proj = "transformer.text_projection.weight"
241
+ if k.endswith(text_proj):
242
+ new_state_dict[k.replace(text_proj, "text_projection")] = v.transpose(0, 1).contiguous()
243
+ else:
244
+ relabelled_key = textenc_pattern.sub(lambda m: protected[re.escape(m.group(0))], k)
245
+ new_state_dict[relabelled_key] = v
246
+
247
+ for k_pre, tensors in capture_qkv_weight.items():
248
+ if None in tensors:
249
+ raise Exception("CORRUPTED MODEL: one of the q-k-v values for the text encoder was missing")
250
+ relabelled_key = textenc_pattern.sub(lambda m: protected[re.escape(m.group(0))], k_pre)
251
+ new_state_dict[relabelled_key + ".in_proj_weight"] = torch.cat(tensors)
252
+
253
+ for k_pre, tensors in capture_qkv_bias.items():
254
+ if None in tensors:
255
+ raise Exception("CORRUPTED MODEL: one of the q-k-v values for the text encoder was missing")
256
+ relabelled_key = textenc_pattern.sub(lambda m: protected[re.escape(m.group(0))], k_pre)
257
+ new_state_dict[relabelled_key + ".in_proj_bias"] = torch.cat(tensors)
258
+
259
+ return new_state_dict
260
+
261
+
262
+ def convert_text_enc_state_dict(text_enc_dict):
263
+ return text_enc_dict
264
+
265
+
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,875 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ ):
362
+ """Construct a UniPC.
363
+
364
+ We support both data_prediction and noise_prediction.
365
+ """
366
+ self.model = model_fn
367
+ self.noise_schedule = noise_schedule
368
+ self.variant = variant
369
+ self.predict_x0 = predict_x0
370
+ self.thresholding = thresholding
371
+ self.max_val = max_val
372
+
373
+ def dynamic_thresholding_fn(self, x0, t=None):
374
+ """
375
+ The dynamic thresholding method.
376
+ """
377
+ dims = x0.dim()
378
+ p = self.dynamic_thresholding_ratio
379
+ s = torch.quantile(torch.abs(x0).reshape((x0.shape[0], -1)), p, dim=1)
380
+ s = expand_dims(torch.maximum(s, self.thresholding_max_val * torch.ones_like(s).to(s.device)), dims)
381
+ x0 = torch.clamp(x0, -s, s) / s
382
+ return x0
383
+
384
+ def noise_prediction_fn(self, x, t):
385
+ """
386
+ Return the noise prediction model.
387
+ """
388
+ return self.model(x, t)
389
+
390
+ def data_prediction_fn(self, x, t):
391
+ """
392
+ Return the data prediction model (with thresholding).
393
+ """
394
+ noise = self.noise_prediction_fn(x, t)
395
+ dims = x.dim()
396
+ alpha_t, sigma_t = self.noise_schedule.marginal_alpha(t), self.noise_schedule.marginal_std(t)
397
+ x0 = (x - expand_dims(sigma_t, dims) * noise) / expand_dims(alpha_t, dims)
398
+ if self.thresholding:
399
+ p = 0.995 # A hyperparameter in the paper of "Imagen" [1].
400
+ s = torch.quantile(torch.abs(x0).reshape((x0.shape[0], -1)), p, dim=1)
401
+ s = expand_dims(torch.maximum(s, self.max_val * torch.ones_like(s).to(s.device)), dims)
402
+ x0 = torch.clamp(x0, -s, s) / s
403
+ return x0
404
+
405
+ def model_fn(self, x, t):
406
+ """
407
+ Convert the model to the noise prediction model or the data prediction model.
408
+ """
409
+ if self.predict_x0:
410
+ return self.data_prediction_fn(x, t)
411
+ else:
412
+ return self.noise_prediction_fn(x, t)
413
+
414
+ def get_time_steps(self, skip_type, t_T, t_0, N, device):
415
+ """Compute the intermediate time steps for sampling.
416
+ """
417
+ if skip_type == 'logSNR':
418
+ lambda_T = self.noise_schedule.marginal_lambda(torch.tensor(t_T).to(device))
419
+ lambda_0 = self.noise_schedule.marginal_lambda(torch.tensor(t_0).to(device))
420
+ logSNR_steps = torch.linspace(lambda_T.cpu().item(), lambda_0.cpu().item(), N + 1).to(device)
421
+ return self.noise_schedule.inverse_lambda(logSNR_steps)
422
+ elif skip_type == 'time_uniform':
423
+ return torch.linspace(t_T, t_0, N + 1).to(device)
424
+ elif skip_type == 'time_quadratic':
425
+ t_order = 2
426
+ t = torch.linspace(t_T**(1. / t_order), t_0**(1. / t_order), N + 1).pow(t_order).to(device)
427
+ return t
428
+ else:
429
+ raise ValueError("Unsupported skip_type {}, need to be 'logSNR' or 'time_uniform' or 'time_quadratic'".format(skip_type))
430
+
431
+ def get_orders_and_timesteps_for_singlestep_solver(self, steps, order, skip_type, t_T, t_0, device):
432
+ """
433
+ Get the order of each step for sampling by the singlestep DPM-Solver.
434
+ """
435
+ if order == 3:
436
+ K = steps // 3 + 1
437
+ if steps % 3 == 0:
438
+ orders = [3,] * (K - 2) + [2, 1]
439
+ elif steps % 3 == 1:
440
+ orders = [3,] * (K - 1) + [1]
441
+ else:
442
+ orders = [3,] * (K - 1) + [2]
443
+ elif order == 2:
444
+ if steps % 2 == 0:
445
+ K = steps // 2
446
+ orders = [2,] * K
447
+ else:
448
+ K = steps // 2 + 1
449
+ orders = [2,] * (K - 1) + [1]
450
+ elif order == 1:
451
+ K = steps
452
+ orders = [1,] * steps
453
+ else:
454
+ raise ValueError("'order' must be '1' or '2' or '3'.")
455
+ if skip_type == 'logSNR':
456
+ # To reproduce the results in DPM-Solver paper
457
+ timesteps_outer = self.get_time_steps(skip_type, t_T, t_0, K, device)
458
+ else:
459
+ timesteps_outer = self.get_time_steps(skip_type, t_T, t_0, steps, device)[torch.cumsum(torch.tensor([0,] + orders), 0).to(device)]
460
+ return timesteps_outer, orders
461
+
462
+ def denoise_to_zero_fn(self, x, s):
463
+ """
464
+ Denoise at the final step, which is equivalent to solve the ODE from lambda_s to infty by first-order discretization.
465
+ """
466
+ return self.data_prediction_fn(x, s)
467
+
468
+ def multistep_uni_pc_update(self, x, model_prev_list, t_prev_list, t, order, **kwargs):
469
+ if len(t.shape) == 0:
470
+ t = t.view(-1)
471
+ if 'bh' in self.variant:
472
+ return self.multistep_uni_pc_bh_update(x, model_prev_list, t_prev_list, t, order, **kwargs)
473
+ else:
474
+ assert self.variant == 'vary_coeff'
475
+ return self.multistep_uni_pc_vary_update(x, model_prev_list, t_prev_list, t, order, **kwargs)
476
+
477
+ def multistep_uni_pc_vary_update(self, x, model_prev_list, t_prev_list, t, order, use_corrector=True):
478
+ print(f'using unified predictor-corrector with order {order} (solver type: vary coeff)')
479
+ ns = self.noise_schedule
480
+ assert order <= len(model_prev_list)
481
+
482
+ # first compute rks
483
+ t_prev_0 = t_prev_list[-1]
484
+ lambda_prev_0 = ns.marginal_lambda(t_prev_0)
485
+ lambda_t = ns.marginal_lambda(t)
486
+ model_prev_0 = model_prev_list[-1]
487
+ sigma_prev_0, sigma_t = ns.marginal_std(t_prev_0), ns.marginal_std(t)
488
+ log_alpha_t = ns.marginal_log_mean_coeff(t)
489
+ alpha_t = torch.exp(log_alpha_t)
490
+
491
+ h = lambda_t - lambda_prev_0
492
+
493
+ rks = []
494
+ D1s = []
495
+ for i in range(1, order):
496
+ t_prev_i = t_prev_list[-(i + 1)]
497
+ model_prev_i = model_prev_list[-(i + 1)]
498
+ lambda_prev_i = ns.marginal_lambda(t_prev_i)
499
+ rk = (lambda_prev_i - lambda_prev_0) / h
500
+ rks.append(rk)
501
+ D1s.append((model_prev_i - model_prev_0) / rk)
502
+
503
+ rks.append(1.)
504
+ rks = torch.tensor(rks, device=x.device)
505
+
506
+ K = len(rks)
507
+ # build C matrix
508
+ C = []
509
+
510
+ col = torch.ones_like(rks)
511
+ for k in range(1, K + 1):
512
+ C.append(col)
513
+ col = col * rks / (k + 1)
514
+ C = torch.stack(C, dim=1)
515
+
516
+ if len(D1s) > 0:
517
+ D1s = torch.stack(D1s, dim=1) # (B, K)
518
+ C_inv_p = torch.linalg.inv(C[:-1, :-1])
519
+ A_p = C_inv_p
520
+
521
+ if use_corrector:
522
+ print('using corrector')
523
+ C_inv = torch.linalg.inv(C)
524
+ A_c = C_inv
525
+
526
+ hh = -h if self.predict_x0 else h
527
+ h_phi_1 = torch.expm1(hh)
528
+ h_phi_ks = []
529
+ factorial_k = 1
530
+ h_phi_k = h_phi_1
531
+ for k in range(1, K + 2):
532
+ h_phi_ks.append(h_phi_k)
533
+ h_phi_k = h_phi_k / hh - 1 / factorial_k
534
+ factorial_k *= (k + 1)
535
+
536
+ model_t = None
537
+ if self.predict_x0:
538
+ x_t_ = (
539
+ sigma_t / sigma_prev_0 * x
540
+ - alpha_t * h_phi_1 * model_prev_0
541
+ )
542
+ # now predictor
543
+ x_t = x_t_
544
+ if len(D1s) > 0:
545
+ # compute the residuals for predictor
546
+ for k in range(K - 1):
547
+ x_t = x_t - alpha_t * h_phi_ks[k + 1] * torch.einsum('bkchw,k->bchw', D1s, A_p[k])
548
+ # now corrector
549
+ if use_corrector:
550
+ model_t = self.model_fn(x_t, t)
551
+ D1_t = (model_t - model_prev_0)
552
+ x_t = x_t_
553
+ k = 0
554
+ for k in range(K - 1):
555
+ x_t = x_t - alpha_t * h_phi_ks[k + 1] * torch.einsum('bkchw,k->bchw', D1s, A_c[k][:-1])
556
+ x_t = x_t - alpha_t * h_phi_ks[K] * (D1_t * A_c[k][-1])
557
+ else:
558
+ log_alpha_prev_0, log_alpha_t = ns.marginal_log_mean_coeff(t_prev_0), ns.marginal_log_mean_coeff(t)
559
+ x_t_ = (
560
+ (torch.exp(log_alpha_t - log_alpha_prev_0)) * x
561
+ - (sigma_t * h_phi_1) * model_prev_0
562
+ )
563
+ # now predictor
564
+ x_t = x_t_
565
+ if len(D1s) > 0:
566
+ # compute the residuals for predictor
567
+ for k in range(K - 1):
568
+ x_t = x_t - sigma_t * h_phi_ks[k + 1] * torch.einsum('bkchw,k->bchw', D1s, A_p[k])
569
+ # now corrector
570
+ if use_corrector:
571
+ model_t = self.model_fn(x_t, t)
572
+ D1_t = (model_t - model_prev_0)
573
+ x_t = x_t_
574
+ k = 0
575
+ for k in range(K - 1):
576
+ x_t = x_t - sigma_t * h_phi_ks[k + 1] * torch.einsum('bkchw,k->bchw', D1s, A_c[k][:-1])
577
+ x_t = x_t - sigma_t * h_phi_ks[K] * (D1_t * A_c[k][-1])
578
+ return x_t, model_t
579
+
580
+ def multistep_uni_pc_bh_update(self, x, model_prev_list, t_prev_list, t, order, x_t=None, use_corrector=True):
581
+ # print(f'using unified predictor-corrector with order {order} (solver type: B(h))')
582
+ ns = self.noise_schedule
583
+ assert order <= len(model_prev_list)
584
+ dims = x.dim()
585
+
586
+ # first compute rks
587
+ t_prev_0 = t_prev_list[-1]
588
+ lambda_prev_0 = ns.marginal_lambda(t_prev_0)
589
+ lambda_t = ns.marginal_lambda(t)
590
+ model_prev_0 = model_prev_list[-1]
591
+ sigma_prev_0, sigma_t = ns.marginal_std(t_prev_0), ns.marginal_std(t)
592
+ log_alpha_prev_0, log_alpha_t = ns.marginal_log_mean_coeff(t_prev_0), ns.marginal_log_mean_coeff(t)
593
+ alpha_t = torch.exp(log_alpha_t)
594
+
595
+ h = lambda_t - lambda_prev_0
596
+
597
+ rks = []
598
+ D1s = []
599
+ for i in range(1, order):
600
+ t_prev_i = t_prev_list[-(i + 1)]
601
+ model_prev_i = model_prev_list[-(i + 1)]
602
+ lambda_prev_i = ns.marginal_lambda(t_prev_i)
603
+ rk = ((lambda_prev_i - lambda_prev_0) / h)[0]
604
+ rks.append(rk)
605
+ D1s.append((model_prev_i - model_prev_0) / rk)
606
+
607
+ rks.append(1.)
608
+ rks = torch.tensor(rks, device=x.device)
609
+
610
+ R = []
611
+ b = []
612
+
613
+ hh = -h[0] if self.predict_x0 else h[0]
614
+ h_phi_1 = torch.expm1(hh) # h\phi_1(h) = e^h - 1
615
+ h_phi_k = h_phi_1 / hh - 1
616
+
617
+ factorial_i = 1
618
+
619
+ if self.variant == 'bh1':
620
+ B_h = hh
621
+ elif self.variant == 'bh2':
622
+ B_h = torch.expm1(hh)
623
+ else:
624
+ raise NotImplementedError()
625
+
626
+ for i in range(1, order + 1):
627
+ R.append(torch.pow(rks, i - 1))
628
+ b.append(h_phi_k * factorial_i / B_h)
629
+ factorial_i *= (i + 1)
630
+ h_phi_k = h_phi_k / hh - 1 / factorial_i
631
+
632
+ R = torch.stack(R)
633
+ b = torch.tensor(b, device=x.device)
634
+
635
+ # now predictor
636
+ use_predictor = len(D1s) > 0 and x_t is None
637
+ if len(D1s) > 0:
638
+ D1s = torch.stack(D1s, dim=1) # (B, K)
639
+ if x_t is None:
640
+ # for order 2, we use a simplified version
641
+ if order == 2:
642
+ rhos_p = torch.tensor([0.5], device=b.device)
643
+ else:
644
+ rhos_p = torch.linalg.solve(R[:-1, :-1], b[:-1])
645
+ else:
646
+ D1s = None
647
+
648
+ if use_corrector:
649
+ # print('using corrector')
650
+ # for order 1, we use a simplified version
651
+ if order == 1:
652
+ rhos_c = torch.tensor([0.5], device=b.device)
653
+ else:
654
+ rhos_c = torch.linalg.solve(R, b)
655
+
656
+ model_t = None
657
+ if self.predict_x0:
658
+ x_t_ = (
659
+ expand_dims(sigma_t / sigma_prev_0, dims) * x
660
+ - expand_dims(alpha_t * h_phi_1, dims)* model_prev_0
661
+ )
662
+
663
+ if x_t is None:
664
+ if use_predictor:
665
+ pred_res = torch.einsum('k,bkchw->bchw', rhos_p, D1s)
666
+ else:
667
+ pred_res = 0
668
+ x_t = x_t_ - expand_dims(alpha_t * B_h, dims) * pred_res
669
+
670
+ if use_corrector:
671
+ model_t = self.model_fn(x_t, t)
672
+ if D1s is not None:
673
+ corr_res = torch.einsum('k,bkchw->bchw', rhos_c[:-1], D1s)
674
+ else:
675
+ corr_res = 0
676
+ D1_t = (model_t - model_prev_0)
677
+ x_t = x_t_ - expand_dims(alpha_t * B_h, dims) * (corr_res + rhos_c[-1] * D1_t)
678
+ else:
679
+ x_t_ = (
680
+ expand_dims(torch.exp(log_alpha_t - log_alpha_prev_0), dims) * x
681
+ - expand_dims(sigma_t * h_phi_1, dims) * model_prev_0
682
+ )
683
+ if x_t is None:
684
+ if use_predictor:
685
+ pred_res = torch.einsum('k,bkchw->bchw', rhos_p, D1s)
686
+ else:
687
+ pred_res = 0
688
+ x_t = x_t_ - expand_dims(sigma_t * B_h, dims) * pred_res
689
+
690
+ if use_corrector:
691
+ model_t = self.model_fn(x_t, t)
692
+ if D1s is not None:
693
+ corr_res = torch.einsum('k,bkchw->bchw', rhos_c[:-1], D1s)
694
+ else:
695
+ corr_res = 0
696
+ D1_t = (model_t - model_prev_0)
697
+ x_t = x_t_ - expand_dims(sigma_t * B_h, dims) * (corr_res + rhos_c[-1] * D1_t)
698
+ return x_t, model_t
699
+
700
+
701
+ def sample(self, x, timesteps, t_start=None, t_end=None, order=3, skip_type='time_uniform',
702
+ method='singlestep', lower_order_final=True, denoise_to_zero=False, solver_type='dpm_solver',
703
+ atol=0.0078, rtol=0.05, corrector=False, callback=None, disable_pbar=False
704
+ ):
705
+ # t_0 = 1. / self.noise_schedule.total_N if t_end is None else t_end
706
+ # t_T = self.noise_schedule.T if t_start is None else t_start
707
+ device = x.device
708
+ steps = len(timesteps) - 1
709
+ if method == 'multistep':
710
+ assert steps >= order
711
+ # timesteps = self.get_time_steps(skip_type=skip_type, t_T=t_T, t_0=t_0, N=steps, device=device)
712
+ assert timesteps.shape[0] - 1 == steps
713
+ # with torch.no_grad():
714
+ for step_index in trange(steps, disable=disable_pbar):
715
+ if step_index == 0:
716
+ vec_t = timesteps[0].expand((x.shape[0]))
717
+ model_prev_list = [self.model_fn(x, vec_t)]
718
+ t_prev_list = [vec_t]
719
+ elif step_index < order:
720
+ init_order = step_index
721
+ # Init the first `order` values by lower order multistep DPM-Solver.
722
+ # for init_order in range(1, order):
723
+ vec_t = timesteps[init_order].expand(x.shape[0])
724
+ x, model_x = self.multistep_uni_pc_update(x, model_prev_list, t_prev_list, vec_t, init_order, use_corrector=True)
725
+ if model_x is None:
726
+ model_x = self.model_fn(x, vec_t)
727
+ model_prev_list.append(model_x)
728
+ t_prev_list.append(vec_t)
729
+ else:
730
+ extra_final_step = 0
731
+ if step_index == (steps - 1):
732
+ extra_final_step = 1
733
+ for step in range(step_index, step_index + 1 + extra_final_step):
734
+ vec_t = timesteps[step].expand(x.shape[0])
735
+ if lower_order_final:
736
+ step_order = min(order, steps + 1 - step)
737
+ else:
738
+ step_order = order
739
+ # print('this step order:', step_order)
740
+ if step == steps:
741
+ # print('do not run corrector at the last step')
742
+ use_corrector = False
743
+ else:
744
+ use_corrector = True
745
+ x, model_x = self.multistep_uni_pc_update(x, model_prev_list, t_prev_list, vec_t, step_order, use_corrector=use_corrector)
746
+ for i in range(order - 1):
747
+ t_prev_list[i] = t_prev_list[i + 1]
748
+ model_prev_list[i] = model_prev_list[i + 1]
749
+ t_prev_list[-1] = vec_t
750
+ # We do not need to evaluate the final model value.
751
+ if step < steps:
752
+ if model_x is None:
753
+ model_x = self.model_fn(x, vec_t)
754
+ model_prev_list[-1] = model_x
755
+ if callback is not None:
756
+ callback({'x': x, 'i': step_index, 'denoised': model_prev_list[-1]})
757
+ else:
758
+ raise NotImplementedError()
759
+ # if denoise_to_zero:
760
+ # x = self.denoise_to_zero_fn(x, torch.ones((x.shape[0],)).to(device) * t_0)
761
+ return x
762
+
763
+
764
+ #############################################################
765
+ # other utility functions
766
+ #############################################################
767
+
768
+ def interpolate_fn(x, xp, yp):
769
+ """
770
+ A piecewise linear function y = f(x), using xp and yp as keypoints.
771
+ We implement f(x) in a differentiable way (i.e. applicable for autograd).
772
+ 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.)
773
+
774
+ Args:
775
+ 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).
776
+ xp: PyTorch tensor with shape [C, K], where K is the number of keypoints.
777
+ yp: PyTorch tensor with shape [C, K].
778
+ Returns:
779
+ The function values f(x), with shape [N, C].
780
+ """
781
+ N, K = x.shape[0], xp.shape[1]
782
+ all_x = torch.cat([x.unsqueeze(2), xp.unsqueeze(0).repeat((N, 1, 1))], dim=2)
783
+ sorted_all_x, x_indices = torch.sort(all_x, dim=2)
784
+ x_idx = torch.argmin(x_indices, dim=2)
785
+ cand_start_idx = x_idx - 1
786
+ start_idx = torch.where(
787
+ torch.eq(x_idx, 0),
788
+ torch.tensor(1, device=x.device),
789
+ torch.where(
790
+ torch.eq(x_idx, K), torch.tensor(K - 2, device=x.device), cand_start_idx,
791
+ ),
792
+ )
793
+ end_idx = torch.where(torch.eq(start_idx, cand_start_idx), start_idx + 2, start_idx + 1)
794
+ start_x = torch.gather(sorted_all_x, dim=2, index=start_idx.unsqueeze(2)).squeeze(2)
795
+ end_x = torch.gather(sorted_all_x, dim=2, index=end_idx.unsqueeze(2)).squeeze(2)
796
+ start_idx2 = torch.where(
797
+ torch.eq(x_idx, 0),
798
+ torch.tensor(0, device=x.device),
799
+ torch.where(
800
+ torch.eq(x_idx, K), torch.tensor(K - 2, device=x.device), cand_start_idx,
801
+ ),
802
+ )
803
+ y_positions_expanded = yp.unsqueeze(0).expand(N, -1, -1)
804
+ start_y = torch.gather(y_positions_expanded, dim=2, index=start_idx2.unsqueeze(2)).squeeze(2)
805
+ end_y = torch.gather(y_positions_expanded, dim=2, index=(start_idx2 + 1).unsqueeze(2)).squeeze(2)
806
+ cand = start_y + (x - start_x) * (end_y - start_y) / (end_x - start_x)
807
+ return cand
808
+
809
+
810
+ def expand_dims(v, dims):
811
+ """
812
+ Expand the tensor `v` to the dim `dims`.
813
+
814
+ Args:
815
+ `v`: a PyTorch tensor with shape [N].
816
+ `dim`: a `int`.
817
+ Returns:
818
+ a PyTorch tensor with shape [N, 1, 1, ..., 1] and the total dimension is `dims`.
819
+ """
820
+ return v[(...,) + (None,)*(dims - 1)]
821
+
822
+
823
+ class SigmaConvert:
824
+ schedule = ""
825
+ def marginal_log_mean_coeff(self, sigma):
826
+ return 0.5 * torch.log(1 / ((sigma * sigma) + 1))
827
+
828
+ def marginal_alpha(self, t):
829
+ return torch.exp(self.marginal_log_mean_coeff(t))
830
+
831
+ def marginal_std(self, t):
832
+ return torch.sqrt(1. - torch.exp(2. * self.marginal_log_mean_coeff(t)))
833
+
834
+ def marginal_lambda(self, t):
835
+ """
836
+ Compute lambda_t = log(alpha_t) - log(sigma_t) of a given continuous-time label t in [0, T].
837
+ """
838
+ log_mean_coeff = self.marginal_log_mean_coeff(t)
839
+ log_std = 0.5 * torch.log(1. - torch.exp(2. * log_mean_coeff))
840
+ return log_mean_coeff - log_std
841
+
842
+ def predict_eps_sigma(model, input, sigma_in, **kwargs):
843
+ sigma = sigma_in.view(sigma_in.shape[:1] + (1,) * (input.ndim - 1))
844
+ input = input * ((sigma ** 2 + 1.0) ** 0.5)
845
+ return (input - model(input, sigma_in, **kwargs)) / sigma
846
+
847
+
848
+ def sample_unipc(model, noise, sigmas, extra_args=None, callback=None, disable=False, variant='bh1'):
849
+ timesteps = sigmas.clone()
850
+ if sigmas[-1] == 0:
851
+ timesteps = sigmas[:]
852
+ timesteps[-1] = 0.001
853
+ else:
854
+ timesteps = sigmas.clone()
855
+ ns = SigmaConvert()
856
+
857
+ noise = noise / torch.sqrt(1.0 + timesteps[0] ** 2.0)
858
+ model_type = "noise"
859
+
860
+ model_fn = model_wrapper(
861
+ lambda input, sigma, **kwargs: predict_eps_sigma(model, input, sigma, **kwargs),
862
+ ns,
863
+ model_type=model_type,
864
+ guidance_type="uncond",
865
+ model_kwargs=extra_args,
866
+ )
867
+
868
+ order = min(3, len(timesteps) - 2)
869
+ uni_pc = UniPC(model_fn, ns, predict_x0=True, thresholding=False, variant=variant)
870
+ x = uni_pc.sample(noise, timesteps=timesteps, skip_type="time_uniform", method="multistep", order=order, lower_order_final=True, callback=callback, disable_pbar=disable)
871
+ x /= ns.marginal_alpha(timesteps[-1])
872
+ return x
873
+
874
+ def sample_unipc_bh2(model, noise, sigmas, extra_args=None, callback=None, disable=False):
875
+ return sample_unipc(model, noise, sigmas, extra_args, callback, disable, variant='bh2')
comfy/gligen.py ADDED
@@ -0,0 +1,343 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from torch import nn
3
+ from .ldm.modules.attention import CrossAttention
4
+ from inspect import isfunction
5
+ import comfy.ops
6
+ ops = comfy.ops.manual_cast
7
+
8
+ def exists(val):
9
+ return val is not None
10
+
11
+
12
+ def uniq(arr):
13
+ return{el: True for el in arr}.keys()
14
+
15
+
16
+ def default(val, d):
17
+ if exists(val):
18
+ return val
19
+ return d() if isfunction(d) else d
20
+
21
+
22
+ # feedforward
23
+ class GEGLU(nn.Module):
24
+ def __init__(self, dim_in, dim_out):
25
+ super().__init__()
26
+ self.proj = ops.Linear(dim_in, dim_out * 2)
27
+
28
+ def forward(self, x):
29
+ x, gate = self.proj(x).chunk(2, dim=-1)
30
+ return x * torch.nn.functional.gelu(gate)
31
+
32
+
33
+ class FeedForward(nn.Module):
34
+ def __init__(self, dim, dim_out=None, mult=4, glu=False, dropout=0.):
35
+ super().__init__()
36
+ inner_dim = int(dim * mult)
37
+ dim_out = default(dim_out, dim)
38
+ project_in = nn.Sequential(
39
+ ops.Linear(dim, inner_dim),
40
+ nn.GELU()
41
+ ) if not glu else GEGLU(dim, inner_dim)
42
+
43
+ self.net = nn.Sequential(
44
+ project_in,
45
+ nn.Dropout(dropout),
46
+ ops.Linear(inner_dim, dim_out)
47
+ )
48
+
49
+ def forward(self, x):
50
+ return self.net(x)
51
+
52
+
53
+ class GatedCrossAttentionDense(nn.Module):
54
+ def __init__(self, query_dim, context_dim, n_heads, d_head):
55
+ super().__init__()
56
+
57
+ self.attn = CrossAttention(
58
+ query_dim=query_dim,
59
+ context_dim=context_dim,
60
+ heads=n_heads,
61
+ dim_head=d_head,
62
+ operations=ops)
63
+ self.ff = FeedForward(query_dim, glu=True)
64
+
65
+ self.norm1 = ops.LayerNorm(query_dim)
66
+ self.norm2 = ops.LayerNorm(query_dim)
67
+
68
+ self.register_parameter('alpha_attn', nn.Parameter(torch.tensor(0.)))
69
+ self.register_parameter('alpha_dense', nn.Parameter(torch.tensor(0.)))
70
+
71
+ # this can be useful: we can externally change magnitude of tanh(alpha)
72
+ # for example, when it is set to 0, then the entire model is same as
73
+ # original one
74
+ self.scale = 1
75
+
76
+ def forward(self, x, objs):
77
+
78
+ x = x + self.scale * \
79
+ torch.tanh(self.alpha_attn) * self.attn(self.norm1(x), objs, objs)
80
+ x = x + self.scale * \
81
+ torch.tanh(self.alpha_dense) * self.ff(self.norm2(x))
82
+
83
+ return x
84
+
85
+
86
+ class GatedSelfAttentionDense(nn.Module):
87
+ def __init__(self, query_dim, context_dim, n_heads, d_head):
88
+ super().__init__()
89
+
90
+ # we need a linear projection since we need cat visual feature and obj
91
+ # feature
92
+ self.linear = ops.Linear(context_dim, query_dim)
93
+
94
+ self.attn = CrossAttention(
95
+ query_dim=query_dim,
96
+ context_dim=query_dim,
97
+ heads=n_heads,
98
+ dim_head=d_head,
99
+ operations=ops)
100
+ self.ff = FeedForward(query_dim, glu=True)
101
+
102
+ self.norm1 = ops.LayerNorm(query_dim)
103
+ self.norm2 = ops.LayerNorm(query_dim)
104
+
105
+ self.register_parameter('alpha_attn', nn.Parameter(torch.tensor(0.)))
106
+ self.register_parameter('alpha_dense', nn.Parameter(torch.tensor(0.)))
107
+
108
+ # this can be useful: we can externally change magnitude of tanh(alpha)
109
+ # for example, when it is set to 0, then the entire model is same as
110
+ # original one
111
+ self.scale = 1
112
+
113
+ def forward(self, x, objs):
114
+
115
+ N_visual = x.shape[1]
116
+ objs = self.linear(objs)
117
+
118
+ x = x + self.scale * torch.tanh(self.alpha_attn) * self.attn(
119
+ self.norm1(torch.cat([x, objs], dim=1)))[:, 0:N_visual, :]
120
+ x = x + self.scale * \
121
+ torch.tanh(self.alpha_dense) * self.ff(self.norm2(x))
122
+
123
+ return x
124
+
125
+
126
+ class GatedSelfAttentionDense2(nn.Module):
127
+ def __init__(self, query_dim, context_dim, n_heads, d_head):
128
+ super().__init__()
129
+
130
+ # we need a linear projection since we need cat visual feature and obj
131
+ # feature
132
+ self.linear = ops.Linear(context_dim, query_dim)
133
+
134
+ self.attn = CrossAttention(
135
+ query_dim=query_dim, context_dim=query_dim, dim_head=d_head, operations=ops)
136
+ self.ff = FeedForward(query_dim, glu=True)
137
+
138
+ self.norm1 = ops.LayerNorm(query_dim)
139
+ self.norm2 = ops.LayerNorm(query_dim)
140
+
141
+ self.register_parameter('alpha_attn', nn.Parameter(torch.tensor(0.)))
142
+ self.register_parameter('alpha_dense', nn.Parameter(torch.tensor(0.)))
143
+
144
+ # this can be useful: we can externally change magnitude of tanh(alpha)
145
+ # for example, when it is set to 0, then the entire model is same as
146
+ # original one
147
+ self.scale = 1
148
+
149
+ def forward(self, x, objs):
150
+
151
+ B, N_visual, _ = x.shape
152
+ B, N_ground, _ = objs.shape
153
+
154
+ objs = self.linear(objs)
155
+
156
+ # sanity check
157
+ size_v = math.sqrt(N_visual)
158
+ size_g = math.sqrt(N_ground)
159
+ assert int(size_v) == size_v, "Visual tokens must be square rootable"
160
+ assert int(size_g) == size_g, "Grounding tokens must be square rootable"
161
+ size_v = int(size_v)
162
+ size_g = int(size_g)
163
+
164
+ # select grounding token and resize it to visual token size as residual
165
+ out = self.attn(self.norm1(torch.cat([x, objs], dim=1)))[
166
+ :, N_visual:, :]
167
+ out = out.permute(0, 2, 1).reshape(B, -1, size_g, size_g)
168
+ out = torch.nn.functional.interpolate(
169
+ out, (size_v, size_v), mode='bicubic')
170
+ residual = out.reshape(B, -1, N_visual).permute(0, 2, 1)
171
+
172
+ # add residual to visual feature
173
+ x = x + self.scale * torch.tanh(self.alpha_attn) * residual
174
+ x = x + self.scale * \
175
+ torch.tanh(self.alpha_dense) * self.ff(self.norm2(x))
176
+
177
+ return x
178
+
179
+
180
+ class FourierEmbedder():
181
+ def __init__(self, num_freqs=64, temperature=100):
182
+
183
+ self.num_freqs = num_freqs
184
+ self.temperature = temperature
185
+ self.freq_bands = temperature ** (torch.arange(num_freqs) / num_freqs)
186
+
187
+ @torch.no_grad()
188
+ def __call__(self, x, cat_dim=-1):
189
+ "x: arbitrary shape of tensor. dim: cat dim"
190
+ out = []
191
+ for freq in self.freq_bands:
192
+ out.append(torch.sin(freq * x))
193
+ out.append(torch.cos(freq * x))
194
+ return torch.cat(out, cat_dim)
195
+
196
+
197
+ class PositionNet(nn.Module):
198
+ def __init__(self, in_dim, out_dim, fourier_freqs=8):
199
+ super().__init__()
200
+ self.in_dim = in_dim
201
+ self.out_dim = out_dim
202
+
203
+ self.fourier_embedder = FourierEmbedder(num_freqs=fourier_freqs)
204
+ self.position_dim = fourier_freqs * 2 * 4 # 2 is sin&cos, 4 is xyxy
205
+
206
+ self.linears = nn.Sequential(
207
+ ops.Linear(self.in_dim + self.position_dim, 512),
208
+ nn.SiLU(),
209
+ ops.Linear(512, 512),
210
+ nn.SiLU(),
211
+ ops.Linear(512, out_dim),
212
+ )
213
+
214
+ self.null_positive_feature = torch.nn.Parameter(
215
+ torch.zeros([self.in_dim]))
216
+ self.null_position_feature = torch.nn.Parameter(
217
+ torch.zeros([self.position_dim]))
218
+
219
+ def forward(self, boxes, masks, positive_embeddings):
220
+ B, N, _ = boxes.shape
221
+ masks = masks.unsqueeze(-1)
222
+ positive_embeddings = positive_embeddings
223
+
224
+ # embedding position (it may includes padding as placeholder)
225
+ xyxy_embedding = self.fourier_embedder(boxes) # B*N*4 --> B*N*C
226
+
227
+ # learnable null embedding
228
+ positive_null = self.null_positive_feature.to(device=boxes.device, dtype=boxes.dtype).view(1, 1, -1)
229
+ xyxy_null = self.null_position_feature.to(device=boxes.device, dtype=boxes.dtype).view(1, 1, -1)
230
+
231
+ # replace padding with learnable null embedding
232
+ positive_embeddings = positive_embeddings * \
233
+ masks + (1 - masks) * positive_null
234
+ xyxy_embedding = xyxy_embedding * masks + (1 - masks) * xyxy_null
235
+
236
+ objs = self.linears(
237
+ torch.cat([positive_embeddings, xyxy_embedding], dim=-1))
238
+ assert objs.shape == torch.Size([B, N, self.out_dim])
239
+ return objs
240
+
241
+
242
+ class Gligen(nn.Module):
243
+ def __init__(self, modules, position_net, key_dim):
244
+ super().__init__()
245
+ self.module_list = nn.ModuleList(modules)
246
+ self.position_net = position_net
247
+ self.key_dim = key_dim
248
+ self.max_objs = 30
249
+ self.current_device = torch.device("cpu")
250
+
251
+ def _set_position(self, boxes, masks, positive_embeddings):
252
+ objs = self.position_net(boxes, masks, positive_embeddings)
253
+ def func(x, extra_options):
254
+ key = extra_options["transformer_index"]
255
+ module = self.module_list[key]
256
+ return module(x, objs.to(device=x.device, dtype=x.dtype))
257
+ return func
258
+
259
+ def set_position(self, latent_image_shape, position_params, device):
260
+ batch, c, h, w = latent_image_shape
261
+ masks = torch.zeros([self.max_objs], device="cpu")
262
+ boxes = []
263
+ positive_embeddings = []
264
+ for p in position_params:
265
+ x1 = (p[4]) / w
266
+ y1 = (p[3]) / h
267
+ x2 = (p[4] + p[2]) / w
268
+ y2 = (p[3] + p[1]) / h
269
+ masks[len(boxes)] = 1.0
270
+ boxes += [torch.tensor((x1, y1, x2, y2)).unsqueeze(0)]
271
+ positive_embeddings += [p[0]]
272
+ append_boxes = []
273
+ append_conds = []
274
+ if len(boxes) < self.max_objs:
275
+ append_boxes = [torch.zeros(
276
+ [self.max_objs - len(boxes), 4], device="cpu")]
277
+ append_conds = [torch.zeros(
278
+ [self.max_objs - len(boxes), self.key_dim], device="cpu")]
279
+
280
+ box_out = torch.cat(
281
+ boxes + append_boxes).unsqueeze(0).repeat(batch, 1, 1)
282
+ masks = masks.unsqueeze(0).repeat(batch, 1)
283
+ conds = torch.cat(positive_embeddings +
284
+ append_conds).unsqueeze(0).repeat(batch, 1, 1)
285
+ return self._set_position(
286
+ box_out.to(device),
287
+ masks.to(device),
288
+ conds.to(device))
289
+
290
+ def set_empty(self, latent_image_shape, device):
291
+ batch, c, h, w = latent_image_shape
292
+ masks = torch.zeros([self.max_objs], device="cpu").repeat(batch, 1)
293
+ box_out = torch.zeros([self.max_objs, 4],
294
+ device="cpu").repeat(batch, 1, 1)
295
+ conds = torch.zeros([self.max_objs, self.key_dim],
296
+ device="cpu").repeat(batch, 1, 1)
297
+ return self._set_position(
298
+ box_out.to(device),
299
+ masks.to(device),
300
+ conds.to(device))
301
+
302
+
303
+ def load_gligen(sd):
304
+ sd_k = sd.keys()
305
+ output_list = []
306
+ key_dim = 768
307
+ for a in ["input_blocks", "middle_block", "output_blocks"]:
308
+ for b in range(20):
309
+ k_temp = filter(lambda k: "{}.{}.".format(a, b)
310
+ in k and ".fuser." in k, sd_k)
311
+ k_temp = map(lambda k: (k, k.split(".fuser.")[-1]), k_temp)
312
+
313
+ n_sd = {}
314
+ for k in k_temp:
315
+ n_sd[k[1]] = sd[k[0]]
316
+ if len(n_sd) > 0:
317
+ query_dim = n_sd["linear.weight"].shape[0]
318
+ key_dim = n_sd["linear.weight"].shape[1]
319
+
320
+ if key_dim == 768: # SD1.x
321
+ n_heads = 8
322
+ d_head = query_dim // n_heads
323
+ else:
324
+ d_head = 64
325
+ n_heads = query_dim // d_head
326
+
327
+ gated = GatedSelfAttentionDense(
328
+ query_dim, key_dim, n_heads, d_head)
329
+ gated.load_state_dict(n_sd, strict=False)
330
+ output_list.append(gated)
331
+
332
+ if "position_net.null_positive_feature" in sd_k:
333
+ in_dim = sd["position_net.null_positive_feature"].shape[0]
334
+ out_dim = sd["position_net.linears.4.weight"].shape[0]
335
+
336
+ class WeightsLoader(torch.nn.Module):
337
+ pass
338
+ w = WeightsLoader()
339
+ w.position_net = PositionNet(in_dim, out_dim)
340
+ w.load_state_dict(sd, strict=False)
341
+
342
+ gligen = Gligen(output_list, w.position_net, key_dim)
343
+ 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,104 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+
3
+ class LatentFormat:
4
+ scale_factor = 1.0
5
+ latent_rgb_factors = None
6
+ taesd_decoder_name = None
7
+
8
+ def process_in(self, latent):
9
+ return latent * self.scale_factor
10
+
11
+ def process_out(self, latent):
12
+ return latent / self.scale_factor
13
+
14
+ class SD15(LatentFormat):
15
+ def __init__(self, scale_factor=0.18215):
16
+ self.scale_factor = scale_factor
17
+ self.latent_rgb_factors = [
18
+ # R G B
19
+ [ 0.3512, 0.2297, 0.3227],
20
+ [ 0.3250, 0.4974, 0.2350],
21
+ [-0.2829, 0.1762, 0.2721],
22
+ [-0.2120, -0.2616, -0.7177]
23
+ ]
24
+ self.taesd_decoder_name = "taesd_decoder"
25
+
26
+ class SDXL(LatentFormat):
27
+ def __init__(self):
28
+ self.scale_factor = 0.13025
29
+ self.latent_rgb_factors = [
30
+ # R G B
31
+ [ 0.3920, 0.4054, 0.4549],
32
+ [-0.2634, -0.0196, 0.0653],
33
+ [ 0.0568, 0.1687, -0.0755],
34
+ [-0.3112, -0.2359, -0.2076]
35
+ ]
36
+ self.taesd_decoder_name = "taesdxl_decoder"
37
+
38
+ class SDXL_Playground_2_5(LatentFormat):
39
+ def __init__(self):
40
+ self.scale_factor = 0.5
41
+ self.latents_mean = torch.tensor([-1.6574, 1.886, -1.383, 2.5155]).view(1, 4, 1, 1)
42
+ self.latents_std = torch.tensor([8.4927, 5.9022, 6.5498, 5.2299]).view(1, 4, 1, 1)
43
+
44
+ self.latent_rgb_factors = [
45
+ # R G B
46
+ [ 0.3920, 0.4054, 0.4549],
47
+ [-0.2634, -0.0196, 0.0653],
48
+ [ 0.0568, 0.1687, -0.0755],
49
+ [-0.3112, -0.2359, -0.2076]
50
+ ]
51
+ self.taesd_decoder_name = "taesdxl_decoder"
52
+
53
+ def process_in(self, latent):
54
+ latents_mean = self.latents_mean.to(latent.device, latent.dtype)
55
+ latents_std = self.latents_std.to(latent.device, latent.dtype)
56
+ return (latent - latents_mean) * self.scale_factor / latents_std
57
+
58
+ def process_out(self, latent):
59
+ latents_mean = self.latents_mean.to(latent.device, latent.dtype)
60
+ latents_std = self.latents_std.to(latent.device, latent.dtype)
61
+ return latent * latents_std / self.scale_factor + latents_mean
62
+
63
+
64
+ class SD_X4(LatentFormat):
65
+ def __init__(self):
66
+ self.scale_factor = 0.08333
67
+ self.latent_rgb_factors = [
68
+ [-0.2340, -0.3863, -0.3257],
69
+ [ 0.0994, 0.0885, -0.0908],
70
+ [-0.2833, -0.2349, -0.3741],
71
+ [ 0.2523, -0.0055, -0.1651]
72
+ ]
73
+
74
+ class SC_Prior(LatentFormat):
75
+ def __init__(self):
76
+ self.scale_factor = 1.0
77
+ self.latent_rgb_factors = [
78
+ [-0.0326, -0.0204, -0.0127],
79
+ [-0.1592, -0.0427, 0.0216],
80
+ [ 0.0873, 0.0638, -0.0020],
81
+ [-0.0602, 0.0442, 0.1304],
82
+ [ 0.0800, -0.0313, -0.1796],
83
+ [-0.0810, -0.0638, -0.1581],
84
+ [ 0.1791, 0.1180, 0.0967],
85
+ [ 0.0740, 0.1416, 0.0432],
86
+ [-0.1745, -0.1888, -0.1373],
87
+ [ 0.2412, 0.1577, 0.0928],
88
+ [ 0.1908, 0.0998, 0.0682],
89
+ [ 0.0209, 0.0365, -0.0092],
90
+ [ 0.0448, -0.0650, -0.1728],
91
+ [-0.1658, -0.1045, -0.1308],
92
+ [ 0.0542, 0.1545, 0.1325],
93
+ [-0.0352, -0.1672, -0.2541]
94
+ ]
95
+
96
+ class SC_B(LatentFormat):
97
+ def __init__(self):
98
+ self.scale_factor = 1.0
99
+ self.latent_rgb_factors = [
100
+ [ 0.1121, 0.2006, 0.1023],
101
+ [-0.2093, -0.0222, -0.0195],
102
+ [-0.3087, -0.1535, 0.0366],
103
+ [ 0.0290, -0.1574, -0.4078]
104
+ ]
comfy/ldm/cascade/common.py ADDED
@@ -0,0 +1,161 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ This file is part of ComfyUI.
3
+ Copyright (C) 2024 Stability AI
4
+
5
+ This program is free software: you can redistribute it and/or modify
6
+ it under the terms of the GNU General Public License as published by
7
+ the Free Software Foundation, either version 3 of the License, or
8
+ (at your option) any later version.
9
+
10
+ This program is distributed in the hope that it will be useful,
11
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
12
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13
+ GNU General Public License for more details.
14
+
15
+ You should have received a copy of the GNU General Public License
16
+ along with this program. If not, see <https://www.gnu.org/licenses/>.
17
+ """
18
+
19
+ import torch
20
+ import torch.nn as nn
21
+ from comfy.ldm.modules.attention import optimized_attention
22
+
23
+ class Linear(torch.nn.Linear):
24
+ def reset_parameters(self):
25
+ return None
26
+
27
+ class Conv2d(torch.nn.Conv2d):
28
+ def reset_parameters(self):
29
+ return None
30
+
31
+ class OptimizedAttention(nn.Module):
32
+ def __init__(self, c, nhead, dropout=0.0, dtype=None, device=None, operations=None):
33
+ super().__init__()
34
+ self.heads = nhead
35
+
36
+ self.to_q = operations.Linear(c, c, bias=True, dtype=dtype, device=device)
37
+ self.to_k = operations.Linear(c, c, bias=True, dtype=dtype, device=device)
38
+ self.to_v = operations.Linear(c, c, bias=True, dtype=dtype, device=device)
39
+
40
+ self.out_proj = operations.Linear(c, c, bias=True, dtype=dtype, device=device)
41
+
42
+ def forward(self, q, k, v):
43
+ q = self.to_q(q)
44
+ k = self.to_k(k)
45
+ v = self.to_v(v)
46
+
47
+ out = optimized_attention(q, k, v, self.heads)
48
+
49
+ return self.out_proj(out)
50
+
51
+ class Attention2D(nn.Module):
52
+ def __init__(self, c, nhead, dropout=0.0, dtype=None, device=None, operations=None):
53
+ super().__init__()
54
+ self.attn = OptimizedAttention(c, nhead, dtype=dtype, device=device, operations=operations)
55
+ # self.attn = nn.MultiheadAttention(c, nhead, dropout=dropout, bias=True, batch_first=True, dtype=dtype, device=device)
56
+
57
+ def forward(self, x, kv, self_attn=False):
58
+ orig_shape = x.shape
59
+ x = x.view(x.size(0), x.size(1), -1).permute(0, 2, 1) # Bx4xHxW -> Bx(HxW)x4
60
+ if self_attn:
61
+ kv = torch.cat([x, kv], dim=1)
62
+ # x = self.attn(x, kv, kv, need_weights=False)[0]
63
+ x = self.attn(x, kv, kv)
64
+ x = x.permute(0, 2, 1).view(*orig_shape)
65
+ return x
66
+
67
+
68
+ def LayerNorm2d_op(operations):
69
+ class LayerNorm2d(operations.LayerNorm):
70
+ def __init__(self, *args, **kwargs):
71
+ super().__init__(*args, **kwargs)
72
+
73
+ def forward(self, x):
74
+ return super().forward(x.permute(0, 2, 3, 1)).permute(0, 3, 1, 2)
75
+ return LayerNorm2d
76
+
77
+ class GlobalResponseNorm(nn.Module):
78
+ "from https://github.com/facebookresearch/ConvNeXt-V2/blob/3608f67cc1dae164790c5d0aead7bf2d73d9719b/models/utils.py#L105"
79
+ def __init__(self, dim, dtype=None, device=None):
80
+ super().__init__()
81
+ self.gamma = nn.Parameter(torch.zeros(1, 1, 1, dim, dtype=dtype, device=device))
82
+ self.beta = nn.Parameter(torch.zeros(1, 1, 1, dim, dtype=dtype, device=device))
83
+
84
+ def forward(self, x):
85
+ Gx = torch.norm(x, p=2, dim=(1, 2), keepdim=True)
86
+ Nx = Gx / (Gx.mean(dim=-1, keepdim=True) + 1e-6)
87
+ return self.gamma.to(device=x.device, dtype=x.dtype) * (x * Nx) + self.beta.to(device=x.device, dtype=x.dtype) + x
88
+
89
+
90
+ class ResBlock(nn.Module):
91
+ def __init__(self, c, c_skip=0, kernel_size=3, dropout=0.0, dtype=None, device=None, operations=None): # , num_heads=4, expansion=2):
92
+ super().__init__()
93
+ self.depthwise = operations.Conv2d(c, c, kernel_size=kernel_size, padding=kernel_size // 2, groups=c, dtype=dtype, device=device)
94
+ # self.depthwise = SAMBlock(c, num_heads, expansion)
95
+ self.norm = LayerNorm2d_op(operations)(c, elementwise_affine=False, eps=1e-6, dtype=dtype, device=device)
96
+ self.channelwise = nn.Sequential(
97
+ operations.Linear(c + c_skip, c * 4, dtype=dtype, device=device),
98
+ nn.GELU(),
99
+ GlobalResponseNorm(c * 4, dtype=dtype, device=device),
100
+ nn.Dropout(dropout),
101
+ operations.Linear(c * 4, c, dtype=dtype, device=device)
102
+ )
103
+
104
+ def forward(self, x, x_skip=None):
105
+ x_res = x
106
+ x = self.norm(self.depthwise(x))
107
+ if x_skip is not None:
108
+ x = torch.cat([x, x_skip], dim=1)
109
+ x = self.channelwise(x.permute(0, 2, 3, 1)).permute(0, 3, 1, 2)
110
+ return x + x_res
111
+
112
+
113
+ class AttnBlock(nn.Module):
114
+ def __init__(self, c, c_cond, nhead, self_attn=True, dropout=0.0, dtype=None, device=None, operations=None):
115
+ super().__init__()
116
+ self.self_attn = self_attn
117
+ self.norm = LayerNorm2d_op(operations)(c, elementwise_affine=False, eps=1e-6, dtype=dtype, device=device)
118
+ self.attention = Attention2D(c, nhead, dropout, dtype=dtype, device=device, operations=operations)
119
+ self.kv_mapper = nn.Sequential(
120
+ nn.SiLU(),
121
+ operations.Linear(c_cond, c, dtype=dtype, device=device)
122
+ )
123
+
124
+ def forward(self, x, kv):
125
+ kv = self.kv_mapper(kv)
126
+ x = x + self.attention(self.norm(x), kv, self_attn=self.self_attn)
127
+ return x
128
+
129
+
130
+ class FeedForwardBlock(nn.Module):
131
+ def __init__(self, c, dropout=0.0, dtype=None, device=None, operations=None):
132
+ super().__init__()
133
+ self.norm = LayerNorm2d_op(operations)(c, elementwise_affine=False, eps=1e-6, dtype=dtype, device=device)
134
+ self.channelwise = nn.Sequential(
135
+ operations.Linear(c, c * 4, dtype=dtype, device=device),
136
+ nn.GELU(),
137
+ GlobalResponseNorm(c * 4, dtype=dtype, device=device),
138
+ nn.Dropout(dropout),
139
+ operations.Linear(c * 4, c, dtype=dtype, device=device)
140
+ )
141
+
142
+ def forward(self, x):
143
+ x = x + self.channelwise(self.norm(x).permute(0, 2, 3, 1)).permute(0, 3, 1, 2)
144
+ return x
145
+
146
+
147
+ class TimestepBlock(nn.Module):
148
+ def __init__(self, c, c_timestep, conds=['sca'], dtype=None, device=None, operations=None):
149
+ super().__init__()
150
+ self.mapper = operations.Linear(c_timestep, c * 2, dtype=dtype, device=device)
151
+ self.conds = conds
152
+ for cname in conds:
153
+ setattr(self, f"mapper_{cname}", operations.Linear(c_timestep, c * 2, dtype=dtype, device=device))
154
+
155
+ def forward(self, x, t):
156
+ t = t.chunk(len(self.conds) + 1, dim=1)
157
+ a, b = self.mapper(t[0])[:, :, None, None].chunk(2, dim=1)
158
+ for i, c in enumerate(self.conds):
159
+ ac, bc = getattr(self, f"mapper_{c}")(t[i + 1])[:, :, None, None].chunk(2, dim=1)
160
+ a, b = a + ac, b + bc
161
+ return x * (1 + a) + b
comfy/ldm/cascade/controlnet.py ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ This file is part of ComfyUI.
3
+ Copyright (C) 2024 Stability AI
4
+
5
+ This program is free software: you can redistribute it and/or modify
6
+ it under the terms of the GNU General Public License as published by
7
+ the Free Software Foundation, either version 3 of the License, or
8
+ (at your option) any later version.
9
+
10
+ This program is distributed in the hope that it will be useful,
11
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
12
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13
+ GNU General Public License for more details.
14
+
15
+ You should have received a copy of the GNU General Public License
16
+ along with this program. If not, see <https://www.gnu.org/licenses/>.
17
+ """
18
+
19
+ import torch
20
+ import torchvision
21
+ from torch import nn
22
+ from .common import LayerNorm2d_op
23
+
24
+
25
+ class CNetResBlock(nn.Module):
26
+ def __init__(self, c, dtype=None, device=None, operations=None):
27
+ super().__init__()
28
+ self.blocks = nn.Sequential(
29
+ LayerNorm2d_op(operations)(c, dtype=dtype, device=device),
30
+ nn.GELU(),
31
+ operations.Conv2d(c, c, kernel_size=3, padding=1),
32
+ LayerNorm2d_op(operations)(c, dtype=dtype, device=device),
33
+ nn.GELU(),
34
+ operations.Conv2d(c, c, kernel_size=3, padding=1),
35
+ )
36
+
37
+ def forward(self, x):
38
+ return x + self.blocks(x)
39
+
40
+
41
+ class ControlNet(nn.Module):
42
+ def __init__(self, c_in=3, c_proj=2048, proj_blocks=None, bottleneck_mode=None, dtype=None, device=None, operations=nn):
43
+ super().__init__()
44
+ if bottleneck_mode is None:
45
+ bottleneck_mode = 'effnet'
46
+ self.proj_blocks = proj_blocks
47
+ if bottleneck_mode == 'effnet':
48
+ embd_channels = 1280
49
+ self.backbone = torchvision.models.efficientnet_v2_s().features.eval()
50
+ if c_in != 3:
51
+ in_weights = self.backbone[0][0].weight.data
52
+ self.backbone[0][0] = operations.Conv2d(c_in, 24, kernel_size=3, stride=2, bias=False, dtype=dtype, device=device)
53
+ if c_in > 3:
54
+ # nn.init.constant_(self.backbone[0][0].weight, 0)
55
+ self.backbone[0][0].weight.data[:, :3] = in_weights[:, :3].clone()
56
+ else:
57
+ self.backbone[0][0].weight.data = in_weights[:, :c_in].clone()
58
+ elif bottleneck_mode == 'simple':
59
+ embd_channels = c_in
60
+ self.backbone = nn.Sequential(
61
+ operations.Conv2d(embd_channels, embd_channels * 4, kernel_size=3, padding=1, dtype=dtype, device=device),
62
+ nn.LeakyReLU(0.2, inplace=True),
63
+ operations.Conv2d(embd_channels * 4, embd_channels, kernel_size=3, padding=1, dtype=dtype, device=device),
64
+ )
65
+ elif bottleneck_mode == 'large':
66
+ self.backbone = nn.Sequential(
67
+ operations.Conv2d(c_in, 4096 * 4, kernel_size=1, dtype=dtype, device=device),
68
+ nn.LeakyReLU(0.2, inplace=True),
69
+ operations.Conv2d(4096 * 4, 1024, kernel_size=1, dtype=dtype, device=device),
70
+ *[CNetResBlock(1024, dtype=dtype, device=device, operations=operations) for _ in range(8)],
71
+ operations.Conv2d(1024, 1280, kernel_size=1, dtype=dtype, device=device),
72
+ )
73
+ embd_channels = 1280
74
+ else:
75
+ raise ValueError(f'Unknown bottleneck mode: {bottleneck_mode}')
76
+ self.projections = nn.ModuleList()
77
+ for _ in range(len(proj_blocks)):
78
+ self.projections.append(nn.Sequential(
79
+ operations.Conv2d(embd_channels, embd_channels, kernel_size=1, bias=False, dtype=dtype, device=device),
80
+ nn.LeakyReLU(0.2, inplace=True),
81
+ operations.Conv2d(embd_channels, c_proj, kernel_size=1, bias=False, dtype=dtype, device=device),
82
+ ))
83
+ # nn.init.constant_(self.projections[-1][-1].weight, 0) # zero output projection
84
+ self.xl = False
85
+ self.input_channels = c_in
86
+ self.unshuffle_amount = 8
87
+
88
+ def forward(self, x):
89
+ x = self.backbone(x)
90
+ proj_outputs = [None for _ in range(max(self.proj_blocks) + 1)]
91
+ for i, idx in enumerate(self.proj_blocks):
92
+ proj_outputs[idx] = self.projections[i](x)
93
+ return proj_outputs
comfy/ldm/cascade/stage_a.py ADDED
@@ -0,0 +1,258 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ This file is part of ComfyUI.
3
+ Copyright (C) 2024 Stability AI
4
+
5
+ This program is free software: you can redistribute it and/or modify
6
+ it under the terms of the GNU General Public License as published by
7
+ the Free Software Foundation, either version 3 of the License, or
8
+ (at your option) any later version.
9
+
10
+ This program is distributed in the hope that it will be useful,
11
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
12
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13
+ GNU General Public License for more details.
14
+
15
+ You should have received a copy of the GNU General Public License
16
+ along with this program. If not, see <https://www.gnu.org/licenses/>.
17
+ """
18
+
19
+ import torch
20
+ from torch import nn
21
+ from torch.autograd import Function
22
+
23
+ class vector_quantize(Function):
24
+ @staticmethod
25
+ def forward(ctx, x, codebook):
26
+ with torch.no_grad():
27
+ codebook_sqr = torch.sum(codebook ** 2, dim=1)
28
+ x_sqr = torch.sum(x ** 2, dim=1, keepdim=True)
29
+
30
+ dist = torch.addmm(codebook_sqr + x_sqr, x, codebook.t(), alpha=-2.0, beta=1.0)
31
+ _, indices = dist.min(dim=1)
32
+
33
+ ctx.save_for_backward(indices, codebook)
34
+ ctx.mark_non_differentiable(indices)
35
+
36
+ nn = torch.index_select(codebook, 0, indices)
37
+ return nn, indices
38
+
39
+ @staticmethod
40
+ def backward(ctx, grad_output, grad_indices):
41
+ grad_inputs, grad_codebook = None, None
42
+
43
+ if ctx.needs_input_grad[0]:
44
+ grad_inputs = grad_output.clone()
45
+ if ctx.needs_input_grad[1]:
46
+ # Gradient wrt. the codebook
47
+ indices, codebook = ctx.saved_tensors
48
+
49
+ grad_codebook = torch.zeros_like(codebook)
50
+ grad_codebook.index_add_(0, indices, grad_output)
51
+
52
+ return (grad_inputs, grad_codebook)
53
+
54
+
55
+ class VectorQuantize(nn.Module):
56
+ def __init__(self, embedding_size, k, ema_decay=0.99, ema_loss=False):
57
+ """
58
+ Takes an input of variable size (as long as the last dimension matches the embedding size).
59
+ Returns one tensor containing the nearest neigbour embeddings to each of the inputs,
60
+ with the same size as the input, vq and commitment components for the loss as a touple
61
+ in the second output and the indices of the quantized vectors in the third:
62
+ quantized, (vq_loss, commit_loss), indices
63
+ """
64
+ super(VectorQuantize, self).__init__()
65
+
66
+ self.codebook = nn.Embedding(k, embedding_size)
67
+ self.codebook.weight.data.uniform_(-1./k, 1./k)
68
+ self.vq = vector_quantize.apply
69
+
70
+ self.ema_decay = ema_decay
71
+ self.ema_loss = ema_loss
72
+ if ema_loss:
73
+ self.register_buffer('ema_element_count', torch.ones(k))
74
+ self.register_buffer('ema_weight_sum', torch.zeros_like(self.codebook.weight))
75
+
76
+ def _laplace_smoothing(self, x, epsilon):
77
+ n = torch.sum(x)
78
+ return ((x + epsilon) / (n + x.size(0) * epsilon) * n)
79
+
80
+ def _updateEMA(self, z_e_x, indices):
81
+ mask = nn.functional.one_hot(indices, self.ema_element_count.size(0)).float()
82
+ elem_count = mask.sum(dim=0)
83
+ weight_sum = torch.mm(mask.t(), z_e_x)
84
+
85
+ self.ema_element_count = (self.ema_decay * self.ema_element_count) + ((1-self.ema_decay) * elem_count)
86
+ self.ema_element_count = self._laplace_smoothing(self.ema_element_count, 1e-5)
87
+ self.ema_weight_sum = (self.ema_decay * self.ema_weight_sum) + ((1-self.ema_decay) * weight_sum)
88
+
89
+ self.codebook.weight.data = self.ema_weight_sum / self.ema_element_count.unsqueeze(-1)
90
+
91
+ def idx2vq(self, idx, dim=-1):
92
+ q_idx = self.codebook(idx)
93
+ if dim != -1:
94
+ q_idx = q_idx.movedim(-1, dim)
95
+ return q_idx
96
+
97
+ def forward(self, x, get_losses=True, dim=-1):
98
+ if dim != -1:
99
+ x = x.movedim(dim, -1)
100
+ z_e_x = x.contiguous().view(-1, x.size(-1)) if len(x.shape) > 2 else x
101
+ z_q_x, indices = self.vq(z_e_x, self.codebook.weight.detach())
102
+ vq_loss, commit_loss = None, None
103
+ if self.ema_loss and self.training:
104
+ self._updateEMA(z_e_x.detach(), indices.detach())
105
+ # pick the graded embeddings after updating the codebook in order to have a more accurate commitment loss
106
+ z_q_x_grd = torch.index_select(self.codebook.weight, dim=0, index=indices)
107
+ if get_losses:
108
+ vq_loss = (z_q_x_grd - z_e_x.detach()).pow(2).mean()
109
+ commit_loss = (z_e_x - z_q_x_grd.detach()).pow(2).mean()
110
+
111
+ z_q_x = z_q_x.view(x.shape)
112
+ if dim != -1:
113
+ z_q_x = z_q_x.movedim(-1, dim)
114
+ return z_q_x, (vq_loss, commit_loss), indices.view(x.shape[:-1])
115
+
116
+
117
+ class ResBlock(nn.Module):
118
+ def __init__(self, c, c_hidden):
119
+ super().__init__()
120
+ # depthwise/attention
121
+ self.norm1 = nn.LayerNorm(c, elementwise_affine=False, eps=1e-6)
122
+ self.depthwise = nn.Sequential(
123
+ nn.ReplicationPad2d(1),
124
+ nn.Conv2d(c, c, kernel_size=3, groups=c)
125
+ )
126
+
127
+ # channelwise
128
+ self.norm2 = nn.LayerNorm(c, elementwise_affine=False, eps=1e-6)
129
+ self.channelwise = nn.Sequential(
130
+ nn.Linear(c, c_hidden),
131
+ nn.GELU(),
132
+ nn.Linear(c_hidden, c),
133
+ )
134
+
135
+ self.gammas = nn.Parameter(torch.zeros(6), requires_grad=True)
136
+
137
+ # Init weights
138
+ def _basic_init(module):
139
+ if isinstance(module, nn.Linear) or isinstance(module, nn.Conv2d):
140
+ torch.nn.init.xavier_uniform_(module.weight)
141
+ if module.bias is not None:
142
+ nn.init.constant_(module.bias, 0)
143
+
144
+ self.apply(_basic_init)
145
+
146
+ def _norm(self, x, norm):
147
+ return norm(x.permute(0, 2, 3, 1)).permute(0, 3, 1, 2)
148
+
149
+ def forward(self, x):
150
+ mods = self.gammas
151
+
152
+ x_temp = self._norm(x, self.norm1) * (1 + mods[0]) + mods[1]
153
+ try:
154
+ x = x + self.depthwise(x_temp) * mods[2]
155
+ except: #operation not implemented for bf16
156
+ x_temp = self.depthwise[0](x_temp.float()).to(x.dtype)
157
+ x = x + self.depthwise[1](x_temp) * mods[2]
158
+
159
+ x_temp = self._norm(x, self.norm2) * (1 + mods[3]) + mods[4]
160
+ x = x + self.channelwise(x_temp.permute(0, 2, 3, 1)).permute(0, 3, 1, 2) * mods[5]
161
+
162
+ return x
163
+
164
+
165
+ class StageA(nn.Module):
166
+ def __init__(self, levels=2, bottleneck_blocks=12, c_hidden=384, c_latent=4, codebook_size=8192,
167
+ scale_factor=0.43): # 0.3764
168
+ super().__init__()
169
+ self.c_latent = c_latent
170
+ self.scale_factor = scale_factor
171
+ c_levels = [c_hidden // (2 ** i) for i in reversed(range(levels))]
172
+
173
+ # Encoder blocks
174
+ self.in_block = nn.Sequential(
175
+ nn.PixelUnshuffle(2),
176
+ nn.Conv2d(3 * 4, c_levels[0], kernel_size=1)
177
+ )
178
+ down_blocks = []
179
+ for i in range(levels):
180
+ if i > 0:
181
+ down_blocks.append(nn.Conv2d(c_levels[i - 1], c_levels[i], kernel_size=4, stride=2, padding=1))
182
+ block = ResBlock(c_levels[i], c_levels[i] * 4)
183
+ down_blocks.append(block)
184
+ down_blocks.append(nn.Sequential(
185
+ nn.Conv2d(c_levels[-1], c_latent, kernel_size=1, bias=False),
186
+ nn.BatchNorm2d(c_latent), # then normalize them to have mean 0 and std 1
187
+ ))
188
+ self.down_blocks = nn.Sequential(*down_blocks)
189
+ self.down_blocks[0]
190
+
191
+ self.codebook_size = codebook_size
192
+ self.vquantizer = VectorQuantize(c_latent, k=codebook_size)
193
+
194
+ # Decoder blocks
195
+ up_blocks = [nn.Sequential(
196
+ nn.Conv2d(c_latent, c_levels[-1], kernel_size=1)
197
+ )]
198
+ for i in range(levels):
199
+ for j in range(bottleneck_blocks if i == 0 else 1):
200
+ block = ResBlock(c_levels[levels - 1 - i], c_levels[levels - 1 - i] * 4)
201
+ up_blocks.append(block)
202
+ if i < levels - 1:
203
+ up_blocks.append(
204
+ nn.ConvTranspose2d(c_levels[levels - 1 - i], c_levels[levels - 2 - i], kernel_size=4, stride=2,
205
+ padding=1))
206
+ self.up_blocks = nn.Sequential(*up_blocks)
207
+ self.out_block = nn.Sequential(
208
+ nn.Conv2d(c_levels[0], 3 * 4, kernel_size=1),
209
+ nn.PixelShuffle(2),
210
+ )
211
+
212
+ def encode(self, x, quantize=False):
213
+ x = self.in_block(x)
214
+ x = self.down_blocks(x)
215
+ if quantize:
216
+ qe, (vq_loss, commit_loss), indices = self.vquantizer.forward(x, dim=1)
217
+ return qe / self.scale_factor, x / self.scale_factor, indices, vq_loss + commit_loss * 0.25
218
+ else:
219
+ return x / self.scale_factor
220
+
221
+ def decode(self, x):
222
+ x = x * self.scale_factor
223
+ x = self.up_blocks(x)
224
+ x = self.out_block(x)
225
+ return x
226
+
227
+ def forward(self, x, quantize=False):
228
+ qe, x, _, vq_loss = self.encode(x, quantize)
229
+ x = self.decode(qe)
230
+ return x, vq_loss
231
+
232
+
233
+ class Discriminator(nn.Module):
234
+ def __init__(self, c_in=3, c_cond=0, c_hidden=512, depth=6):
235
+ super().__init__()
236
+ d = max(depth - 3, 3)
237
+ layers = [
238
+ nn.utils.spectral_norm(nn.Conv2d(c_in, c_hidden // (2 ** d), kernel_size=3, stride=2, padding=1)),
239
+ nn.LeakyReLU(0.2),
240
+ ]
241
+ for i in range(depth - 1):
242
+ c_in = c_hidden // (2 ** max((d - i), 0))
243
+ c_out = c_hidden // (2 ** max((d - 1 - i), 0))
244
+ layers.append(nn.utils.spectral_norm(nn.Conv2d(c_in, c_out, kernel_size=3, stride=2, padding=1)))
245
+ layers.append(nn.InstanceNorm2d(c_out))
246
+ layers.append(nn.LeakyReLU(0.2))
247
+ self.encoder = nn.Sequential(*layers)
248
+ self.shuffle = nn.Conv2d((c_hidden + c_cond) if c_cond > 0 else c_hidden, 1, kernel_size=1)
249
+ self.logits = nn.Sigmoid()
250
+
251
+ def forward(self, x, cond=None):
252
+ x = self.encoder(x)
253
+ if cond is not None:
254
+ cond = cond.view(cond.size(0), cond.size(1), 1, 1, ).expand(-1, -1, x.size(-2), x.size(-1))
255
+ x = torch.cat([x, cond], dim=1)
256
+ x = self.shuffle(x)
257
+ x = self.logits(x)
258
+ return x
comfy/ldm/cascade/stage_b.py ADDED
@@ -0,0 +1,257 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ This file is part of ComfyUI.
3
+ Copyright (C) 2024 Stability AI
4
+
5
+ This program is free software: you can redistribute it and/or modify
6
+ it under the terms of the GNU General Public License as published by
7
+ the Free Software Foundation, either version 3 of the License, or
8
+ (at your option) any later version.
9
+
10
+ This program is distributed in the hope that it will be useful,
11
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
12
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13
+ GNU General Public License for more details.
14
+
15
+ You should have received a copy of the GNU General Public License
16
+ along with this program. If not, see <https://www.gnu.org/licenses/>.
17
+ """
18
+
19
+ import math
20
+ import numpy as np
21
+ import torch
22
+ from torch import nn
23
+ from .common import AttnBlock, LayerNorm2d_op, ResBlock, FeedForwardBlock, TimestepBlock
24
+
25
+ class StageB(nn.Module):
26
+ def __init__(self, c_in=4, c_out=4, c_r=64, patch_size=2, c_cond=1280, c_hidden=[320, 640, 1280, 1280],
27
+ nhead=[-1, -1, 20, 20], blocks=[[2, 6, 28, 6], [6, 28, 6, 2]],
28
+ block_repeat=[[1, 1, 1, 1], [3, 3, 2, 2]], level_config=['CT', 'CT', 'CTA', 'CTA'], c_clip=1280,
29
+ c_clip_seq=4, c_effnet=16, c_pixels=3, kernel_size=3, dropout=[0, 0, 0.0, 0.0], self_attn=True,
30
+ t_conds=['sca'], stable_cascade_stage=None, dtype=None, device=None, operations=None):
31
+ super().__init__()
32
+ self.dtype = dtype
33
+ self.c_r = c_r
34
+ self.t_conds = t_conds
35
+ self.c_clip_seq = c_clip_seq
36
+ if not isinstance(dropout, list):
37
+ dropout = [dropout] * len(c_hidden)
38
+ if not isinstance(self_attn, list):
39
+ self_attn = [self_attn] * len(c_hidden)
40
+
41
+ # CONDITIONING
42
+ self.effnet_mapper = nn.Sequential(
43
+ operations.Conv2d(c_effnet, c_hidden[0] * 4, kernel_size=1, dtype=dtype, device=device),
44
+ nn.GELU(),
45
+ operations.Conv2d(c_hidden[0] * 4, c_hidden[0], kernel_size=1, dtype=dtype, device=device),
46
+ LayerNorm2d_op(operations)(c_hidden[0], elementwise_affine=False, eps=1e-6, dtype=dtype, device=device)
47
+ )
48
+ self.pixels_mapper = nn.Sequential(
49
+ operations.Conv2d(c_pixels, c_hidden[0] * 4, kernel_size=1, dtype=dtype, device=device),
50
+ nn.GELU(),
51
+ operations.Conv2d(c_hidden[0] * 4, c_hidden[0], kernel_size=1, dtype=dtype, device=device),
52
+ LayerNorm2d_op(operations)(c_hidden[0], elementwise_affine=False, eps=1e-6, dtype=dtype, device=device)
53
+ )
54
+ self.clip_mapper = operations.Linear(c_clip, c_cond * c_clip_seq, dtype=dtype, device=device)
55
+ self.clip_norm = operations.LayerNorm(c_cond, elementwise_affine=False, eps=1e-6, dtype=dtype, device=device)
56
+
57
+ self.embedding = nn.Sequential(
58
+ nn.PixelUnshuffle(patch_size),
59
+ operations.Conv2d(c_in * (patch_size ** 2), c_hidden[0], kernel_size=1, dtype=dtype, device=device),
60
+ LayerNorm2d_op(operations)(c_hidden[0], elementwise_affine=False, eps=1e-6, dtype=dtype, device=device)
61
+ )
62
+
63
+ def get_block(block_type, c_hidden, nhead, c_skip=0, dropout=0, self_attn=True):
64
+ if block_type == 'C':
65
+ return ResBlock(c_hidden, c_skip, kernel_size=kernel_size, dropout=dropout, dtype=dtype, device=device, operations=operations)
66
+ elif block_type == 'A':
67
+ return AttnBlock(c_hidden, c_cond, nhead, self_attn=self_attn, dropout=dropout, dtype=dtype, device=device, operations=operations)
68
+ elif block_type == 'F':
69
+ return FeedForwardBlock(c_hidden, dropout=dropout, dtype=dtype, device=device, operations=operations)
70
+ elif block_type == 'T':
71
+ return TimestepBlock(c_hidden, c_r, conds=t_conds, dtype=dtype, device=device, operations=operations)
72
+ else:
73
+ raise Exception(f'Block type {block_type} not supported')
74
+
75
+ # BLOCKS
76
+ # -- down blocks
77
+ self.down_blocks = nn.ModuleList()
78
+ self.down_downscalers = nn.ModuleList()
79
+ self.down_repeat_mappers = nn.ModuleList()
80
+ for i in range(len(c_hidden)):
81
+ if i > 0:
82
+ self.down_downscalers.append(nn.Sequential(
83
+ LayerNorm2d_op(operations)(c_hidden[i - 1], elementwise_affine=False, eps=1e-6, dtype=dtype, device=device),
84
+ operations.Conv2d(c_hidden[i - 1], c_hidden[i], kernel_size=2, stride=2, dtype=dtype, device=device),
85
+ ))
86
+ else:
87
+ self.down_downscalers.append(nn.Identity())
88
+ down_block = nn.ModuleList()
89
+ for _ in range(blocks[0][i]):
90
+ for block_type in level_config[i]:
91
+ block = get_block(block_type, c_hidden[i], nhead[i], dropout=dropout[i], self_attn=self_attn[i])
92
+ down_block.append(block)
93
+ self.down_blocks.append(down_block)
94
+ if block_repeat is not None:
95
+ block_repeat_mappers = nn.ModuleList()
96
+ for _ in range(block_repeat[0][i] - 1):
97
+ block_repeat_mappers.append(operations.Conv2d(c_hidden[i], c_hidden[i], kernel_size=1, dtype=dtype, device=device))
98
+ self.down_repeat_mappers.append(block_repeat_mappers)
99
+
100
+ # -- up blocks
101
+ self.up_blocks = nn.ModuleList()
102
+ self.up_upscalers = nn.ModuleList()
103
+ self.up_repeat_mappers = nn.ModuleList()
104
+ for i in reversed(range(len(c_hidden))):
105
+ if i > 0:
106
+ self.up_upscalers.append(nn.Sequential(
107
+ LayerNorm2d_op(operations)(c_hidden[i], elementwise_affine=False, eps=1e-6, dtype=dtype, device=device),
108
+ operations.ConvTranspose2d(c_hidden[i], c_hidden[i - 1], kernel_size=2, stride=2, dtype=dtype, device=device),
109
+ ))
110
+ else:
111
+ self.up_upscalers.append(nn.Identity())
112
+ up_block = nn.ModuleList()
113
+ for j in range(blocks[1][::-1][i]):
114
+ for k, block_type in enumerate(level_config[i]):
115
+ c_skip = c_hidden[i] if i < len(c_hidden) - 1 and j == k == 0 else 0
116
+ block = get_block(block_type, c_hidden[i], nhead[i], c_skip=c_skip, dropout=dropout[i],
117
+ self_attn=self_attn[i])
118
+ up_block.append(block)
119
+ self.up_blocks.append(up_block)
120
+ if block_repeat is not None:
121
+ block_repeat_mappers = nn.ModuleList()
122
+ for _ in range(block_repeat[1][::-1][i] - 1):
123
+ block_repeat_mappers.append(operations.Conv2d(c_hidden[i], c_hidden[i], kernel_size=1, dtype=dtype, device=device))
124
+ self.up_repeat_mappers.append(block_repeat_mappers)
125
+
126
+ # OUTPUT
127
+ self.clf = nn.Sequential(
128
+ LayerNorm2d_op(operations)(c_hidden[0], elementwise_affine=False, eps=1e-6, dtype=dtype, device=device),
129
+ operations.Conv2d(c_hidden[0], c_out * (patch_size ** 2), kernel_size=1, dtype=dtype, device=device),
130
+ nn.PixelShuffle(patch_size),
131
+ )
132
+
133
+ # --- WEIGHT INIT ---
134
+ # self.apply(self._init_weights) # General init
135
+ # nn.init.normal_(self.clip_mapper.weight, std=0.02) # conditionings
136
+ # nn.init.normal_(self.effnet_mapper[0].weight, std=0.02) # conditionings
137
+ # nn.init.normal_(self.effnet_mapper[2].weight, std=0.02) # conditionings
138
+ # nn.init.normal_(self.pixels_mapper[0].weight, std=0.02) # conditionings
139
+ # nn.init.normal_(self.pixels_mapper[2].weight, std=0.02) # conditionings
140
+ # torch.nn.init.xavier_uniform_(self.embedding[1].weight, 0.02) # inputs
141
+ # nn.init.constant_(self.clf[1].weight, 0) # outputs
142
+ #
143
+ # # blocks
144
+ # for level_block in self.down_blocks + self.up_blocks:
145
+ # for block in level_block:
146
+ # if isinstance(block, ResBlock) or isinstance(block, FeedForwardBlock):
147
+ # block.channelwise[-1].weight.data *= np.sqrt(1 / sum(blocks[0]))
148
+ # elif isinstance(block, TimestepBlock):
149
+ # for layer in block.modules():
150
+ # if isinstance(layer, nn.Linear):
151
+ # nn.init.constant_(layer.weight, 0)
152
+ #
153
+ # def _init_weights(self, m):
154
+ # if isinstance(m, (nn.Conv2d, nn.Linear)):
155
+ # torch.nn.init.xavier_uniform_(m.weight)
156
+ # if m.bias is not None:
157
+ # nn.init.constant_(m.bias, 0)
158
+
159
+ def gen_r_embedding(self, r, max_positions=10000):
160
+ r = r * max_positions
161
+ half_dim = self.c_r // 2
162
+ emb = math.log(max_positions) / (half_dim - 1)
163
+ emb = torch.arange(half_dim, device=r.device).float().mul(-emb).exp()
164
+ emb = r[:, None] * emb[None, :]
165
+ emb = torch.cat([emb.sin(), emb.cos()], dim=1)
166
+ if self.c_r % 2 == 1: # zero pad
167
+ emb = nn.functional.pad(emb, (0, 1), mode='constant')
168
+ return emb
169
+
170
+ def gen_c_embeddings(self, clip):
171
+ if len(clip.shape) == 2:
172
+ clip = clip.unsqueeze(1)
173
+ clip = self.clip_mapper(clip).view(clip.size(0), clip.size(1) * self.c_clip_seq, -1)
174
+ clip = self.clip_norm(clip)
175
+ return clip
176
+
177
+ def _down_encode(self, x, r_embed, clip):
178
+ level_outputs = []
179
+ block_group = zip(self.down_blocks, self.down_downscalers, self.down_repeat_mappers)
180
+ for down_block, downscaler, repmap in block_group:
181
+ x = downscaler(x)
182
+ for i in range(len(repmap) + 1):
183
+ for block in down_block:
184
+ if isinstance(block, ResBlock) or (
185
+ hasattr(block, '_fsdp_wrapped_module') and isinstance(block._fsdp_wrapped_module,
186
+ ResBlock)):
187
+ x = block(x)
188
+ elif isinstance(block, AttnBlock) or (
189
+ hasattr(block, '_fsdp_wrapped_module') and isinstance(block._fsdp_wrapped_module,
190
+ AttnBlock)):
191
+ x = block(x, clip)
192
+ elif isinstance(block, TimestepBlock) or (
193
+ hasattr(block, '_fsdp_wrapped_module') and isinstance(block._fsdp_wrapped_module,
194
+ TimestepBlock)):
195
+ x = block(x, r_embed)
196
+ else:
197
+ x = block(x)
198
+ if i < len(repmap):
199
+ x = repmap[i](x)
200
+ level_outputs.insert(0, x)
201
+ return level_outputs
202
+
203
+ def _up_decode(self, level_outputs, r_embed, clip):
204
+ x = level_outputs[0]
205
+ block_group = zip(self.up_blocks, self.up_upscalers, self.up_repeat_mappers)
206
+ for i, (up_block, upscaler, repmap) in enumerate(block_group):
207
+ for j in range(len(repmap) + 1):
208
+ for k, block in enumerate(up_block):
209
+ if isinstance(block, ResBlock) or (
210
+ hasattr(block, '_fsdp_wrapped_module') and isinstance(block._fsdp_wrapped_module,
211
+ ResBlock)):
212
+ skip = level_outputs[i] if k == 0 and i > 0 else None
213
+ if skip is not None and (x.size(-1) != skip.size(-1) or x.size(-2) != skip.size(-2)):
214
+ x = torch.nn.functional.interpolate(x, skip.shape[-2:], mode='bilinear',
215
+ align_corners=True)
216
+ x = block(x, skip)
217
+ elif isinstance(block, AttnBlock) or (
218
+ hasattr(block, '_fsdp_wrapped_module') and isinstance(block._fsdp_wrapped_module,
219
+ AttnBlock)):
220
+ x = block(x, clip)
221
+ elif isinstance(block, TimestepBlock) or (
222
+ hasattr(block, '_fsdp_wrapped_module') and isinstance(block._fsdp_wrapped_module,
223
+ TimestepBlock)):
224
+ x = block(x, r_embed)
225
+ else:
226
+ x = block(x)
227
+ if j < len(repmap):
228
+ x = repmap[j](x)
229
+ x = upscaler(x)
230
+ return x
231
+
232
+ def forward(self, x, r, effnet, clip, pixels=None, **kwargs):
233
+ if pixels is None:
234
+ pixels = x.new_zeros(x.size(0), 3, 8, 8)
235
+
236
+ # Process the conditioning embeddings
237
+ r_embed = self.gen_r_embedding(r).to(dtype=x.dtype)
238
+ for c in self.t_conds:
239
+ t_cond = kwargs.get(c, torch.zeros_like(r))
240
+ r_embed = torch.cat([r_embed, self.gen_r_embedding(t_cond).to(dtype=x.dtype)], dim=1)
241
+ clip = self.gen_c_embeddings(clip)
242
+
243
+ # Model Blocks
244
+ x = self.embedding(x)
245
+ x = x + self.effnet_mapper(
246
+ nn.functional.interpolate(effnet, size=x.shape[-2:], mode='bilinear', align_corners=True))
247
+ x = x + nn.functional.interpolate(self.pixels_mapper(pixels), size=x.shape[-2:], mode='bilinear',
248
+ align_corners=True)
249
+ level_outputs = self._down_encode(x, r_embed, clip)
250
+ x = self._up_decode(level_outputs, r_embed, clip)
251
+ return self.clf(x)
252
+
253
+ def update_weights_ema(self, src_model, beta=0.999):
254
+ for self_params, src_params in zip(self.parameters(), src_model.parameters()):
255
+ self_params.data = self_params.data * beta + src_params.data.clone().to(self_params.device) * (1 - beta)
256
+ for self_buffers, src_buffers in zip(self.buffers(), src_model.buffers()):
257
+ self_buffers.data = self_buffers.data * beta + src_buffers.data.clone().to(self_buffers.device) * (1 - beta)
comfy/ldm/cascade/stage_c.py ADDED
@@ -0,0 +1,274 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ This file is part of ComfyUI.
3
+ Copyright (C) 2024 Stability AI
4
+
5
+ This program is free software: you can redistribute it and/or modify
6
+ it under the terms of the GNU General Public License as published by
7
+ the Free Software Foundation, either version 3 of the License, or
8
+ (at your option) any later version.
9
+
10
+ This program is distributed in the hope that it will be useful,
11
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
12
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13
+ GNU General Public License for more details.
14
+
15
+ You should have received a copy of the GNU General Public License
16
+ along with this program. If not, see <https://www.gnu.org/licenses/>.
17
+ """
18
+
19
+ import torch
20
+ from torch import nn
21
+ import numpy as np
22
+ import math
23
+ from .common import AttnBlock, LayerNorm2d_op, ResBlock, FeedForwardBlock, TimestepBlock
24
+ # from .controlnet import ControlNetDeliverer
25
+
26
+ class UpDownBlock2d(nn.Module):
27
+ def __init__(self, c_in, c_out, mode, enabled=True, dtype=None, device=None, operations=None):
28
+ super().__init__()
29
+ assert mode in ['up', 'down']
30
+ interpolation = nn.Upsample(scale_factor=2 if mode == 'up' else 0.5, mode='bilinear',
31
+ align_corners=True) if enabled else nn.Identity()
32
+ mapping = operations.Conv2d(c_in, c_out, kernel_size=1, dtype=dtype, device=device)
33
+ self.blocks = nn.ModuleList([interpolation, mapping] if mode == 'up' else [mapping, interpolation])
34
+
35
+ def forward(self, x):
36
+ for block in self.blocks:
37
+ x = block(x)
38
+ return x
39
+
40
+
41
+ class StageC(nn.Module):
42
+ def __init__(self, c_in=16, c_out=16, c_r=64, patch_size=1, c_cond=2048, c_hidden=[2048, 2048], nhead=[32, 32],
43
+ blocks=[[8, 24], [24, 8]], block_repeat=[[1, 1], [1, 1]], level_config=['CTA', 'CTA'],
44
+ c_clip_text=1280, c_clip_text_pooled=1280, c_clip_img=768, c_clip_seq=4, kernel_size=3,
45
+ dropout=[0.0, 0.0], self_attn=True, t_conds=['sca', 'crp'], switch_level=[False], stable_cascade_stage=None,
46
+ dtype=None, device=None, operations=None):
47
+ super().__init__()
48
+ self.dtype = dtype
49
+ self.c_r = c_r
50
+ self.t_conds = t_conds
51
+ self.c_clip_seq = c_clip_seq
52
+ if not isinstance(dropout, list):
53
+ dropout = [dropout] * len(c_hidden)
54
+ if not isinstance(self_attn, list):
55
+ self_attn = [self_attn] * len(c_hidden)
56
+
57
+ # CONDITIONING
58
+ self.clip_txt_mapper = operations.Linear(c_clip_text, c_cond, dtype=dtype, device=device)
59
+ self.clip_txt_pooled_mapper = operations.Linear(c_clip_text_pooled, c_cond * c_clip_seq, dtype=dtype, device=device)
60
+ self.clip_img_mapper = operations.Linear(c_clip_img, c_cond * c_clip_seq, dtype=dtype, device=device)
61
+ self.clip_norm = operations.LayerNorm(c_cond, elementwise_affine=False, eps=1e-6, dtype=dtype, device=device)
62
+
63
+ self.embedding = nn.Sequential(
64
+ nn.PixelUnshuffle(patch_size),
65
+ operations.Conv2d(c_in * (patch_size ** 2), c_hidden[0], kernel_size=1, dtype=dtype, device=device),
66
+ LayerNorm2d_op(operations)(c_hidden[0], elementwise_affine=False, eps=1e-6)
67
+ )
68
+
69
+ def get_block(block_type, c_hidden, nhead, c_skip=0, dropout=0, self_attn=True):
70
+ if block_type == 'C':
71
+ return ResBlock(c_hidden, c_skip, kernel_size=kernel_size, dropout=dropout, dtype=dtype, device=device, operations=operations)
72
+ elif block_type == 'A':
73
+ return AttnBlock(c_hidden, c_cond, nhead, self_attn=self_attn, dropout=dropout, dtype=dtype, device=device, operations=operations)
74
+ elif block_type == 'F':
75
+ return FeedForwardBlock(c_hidden, dropout=dropout, dtype=dtype, device=device, operations=operations)
76
+ elif block_type == 'T':
77
+ return TimestepBlock(c_hidden, c_r, conds=t_conds, dtype=dtype, device=device, operations=operations)
78
+ else:
79
+ raise Exception(f'Block type {block_type} not supported')
80
+
81
+ # BLOCKS
82
+ # -- down blocks
83
+ self.down_blocks = nn.ModuleList()
84
+ self.down_downscalers = nn.ModuleList()
85
+ self.down_repeat_mappers = nn.ModuleList()
86
+ for i in range(len(c_hidden)):
87
+ if i > 0:
88
+ self.down_downscalers.append(nn.Sequential(
89
+ LayerNorm2d_op(operations)(c_hidden[i - 1], elementwise_affine=False, eps=1e-6),
90
+ UpDownBlock2d(c_hidden[i - 1], c_hidden[i], mode='down', enabled=switch_level[i - 1], dtype=dtype, device=device, operations=operations)
91
+ ))
92
+ else:
93
+ self.down_downscalers.append(nn.Identity())
94
+ down_block = nn.ModuleList()
95
+ for _ in range(blocks[0][i]):
96
+ for block_type in level_config[i]:
97
+ block = get_block(block_type, c_hidden[i], nhead[i], dropout=dropout[i], self_attn=self_attn[i])
98
+ down_block.append(block)
99
+ self.down_blocks.append(down_block)
100
+ if block_repeat is not None:
101
+ block_repeat_mappers = nn.ModuleList()
102
+ for _ in range(block_repeat[0][i] - 1):
103
+ block_repeat_mappers.append(operations.Conv2d(c_hidden[i], c_hidden[i], kernel_size=1, dtype=dtype, device=device))
104
+ self.down_repeat_mappers.append(block_repeat_mappers)
105
+
106
+ # -- up blocks
107
+ self.up_blocks = nn.ModuleList()
108
+ self.up_upscalers = nn.ModuleList()
109
+ self.up_repeat_mappers = nn.ModuleList()
110
+ for i in reversed(range(len(c_hidden))):
111
+ if i > 0:
112
+ self.up_upscalers.append(nn.Sequential(
113
+ LayerNorm2d_op(operations)(c_hidden[i], elementwise_affine=False, eps=1e-6),
114
+ UpDownBlock2d(c_hidden[i], c_hidden[i - 1], mode='up', enabled=switch_level[i - 1], dtype=dtype, device=device, operations=operations)
115
+ ))
116
+ else:
117
+ self.up_upscalers.append(nn.Identity())
118
+ up_block = nn.ModuleList()
119
+ for j in range(blocks[1][::-1][i]):
120
+ for k, block_type in enumerate(level_config[i]):
121
+ c_skip = c_hidden[i] if i < len(c_hidden) - 1 and j == k == 0 else 0
122
+ block = get_block(block_type, c_hidden[i], nhead[i], c_skip=c_skip, dropout=dropout[i],
123
+ self_attn=self_attn[i])
124
+ up_block.append(block)
125
+ self.up_blocks.append(up_block)
126
+ if block_repeat is not None:
127
+ block_repeat_mappers = nn.ModuleList()
128
+ for _ in range(block_repeat[1][::-1][i] - 1):
129
+ block_repeat_mappers.append(operations.Conv2d(c_hidden[i], c_hidden[i], kernel_size=1, dtype=dtype, device=device))
130
+ self.up_repeat_mappers.append(block_repeat_mappers)
131
+
132
+ # OUTPUT
133
+ self.clf = nn.Sequential(
134
+ LayerNorm2d_op(operations)(c_hidden[0], elementwise_affine=False, eps=1e-6, dtype=dtype, device=device),
135
+ operations.Conv2d(c_hidden[0], c_out * (patch_size ** 2), kernel_size=1, dtype=dtype, device=device),
136
+ nn.PixelShuffle(patch_size),
137
+ )
138
+
139
+ # --- WEIGHT INIT ---
140
+ # self.apply(self._init_weights) # General init
141
+ # nn.init.normal_(self.clip_txt_mapper.weight, std=0.02) # conditionings
142
+ # nn.init.normal_(self.clip_txt_pooled_mapper.weight, std=0.02) # conditionings
143
+ # nn.init.normal_(self.clip_img_mapper.weight, std=0.02) # conditionings
144
+ # torch.nn.init.xavier_uniform_(self.embedding[1].weight, 0.02) # inputs
145
+ # nn.init.constant_(self.clf[1].weight, 0) # outputs
146
+ #
147
+ # # blocks
148
+ # for level_block in self.down_blocks + self.up_blocks:
149
+ # for block in level_block:
150
+ # if isinstance(block, ResBlock) or isinstance(block, FeedForwardBlock):
151
+ # block.channelwise[-1].weight.data *= np.sqrt(1 / sum(blocks[0]))
152
+ # elif isinstance(block, TimestepBlock):
153
+ # for layer in block.modules():
154
+ # if isinstance(layer, nn.Linear):
155
+ # nn.init.constant_(layer.weight, 0)
156
+ #
157
+ # def _init_weights(self, m):
158
+ # if isinstance(m, (nn.Conv2d, nn.Linear)):
159
+ # torch.nn.init.xavier_uniform_(m.weight)
160
+ # if m.bias is not None:
161
+ # nn.init.constant_(m.bias, 0)
162
+
163
+ def gen_r_embedding(self, r, max_positions=10000):
164
+ r = r * max_positions
165
+ half_dim = self.c_r // 2
166
+ emb = math.log(max_positions) / (half_dim - 1)
167
+ emb = torch.arange(half_dim, device=r.device).float().mul(-emb).exp()
168
+ emb = r[:, None] * emb[None, :]
169
+ emb = torch.cat([emb.sin(), emb.cos()], dim=1)
170
+ if self.c_r % 2 == 1: # zero pad
171
+ emb = nn.functional.pad(emb, (0, 1), mode='constant')
172
+ return emb
173
+
174
+ def gen_c_embeddings(self, clip_txt, clip_txt_pooled, clip_img):
175
+ clip_txt = self.clip_txt_mapper(clip_txt)
176
+ if len(clip_txt_pooled.shape) == 2:
177
+ clip_txt_pooled = clip_txt_pooled.unsqueeze(1)
178
+ if len(clip_img.shape) == 2:
179
+ clip_img = clip_img.unsqueeze(1)
180
+ clip_txt_pool = self.clip_txt_pooled_mapper(clip_txt_pooled).view(clip_txt_pooled.size(0), clip_txt_pooled.size(1) * self.c_clip_seq, -1)
181
+ clip_img = self.clip_img_mapper(clip_img).view(clip_img.size(0), clip_img.size(1) * self.c_clip_seq, -1)
182
+ clip = torch.cat([clip_txt, clip_txt_pool, clip_img], dim=1)
183
+ clip = self.clip_norm(clip)
184
+ return clip
185
+
186
+ def _down_encode(self, x, r_embed, clip, cnet=None):
187
+ level_outputs = []
188
+ block_group = zip(self.down_blocks, self.down_downscalers, self.down_repeat_mappers)
189
+ for down_block, downscaler, repmap in block_group:
190
+ x = downscaler(x)
191
+ for i in range(len(repmap) + 1):
192
+ for block in down_block:
193
+ if isinstance(block, ResBlock) or (
194
+ hasattr(block, '_fsdp_wrapped_module') and isinstance(block._fsdp_wrapped_module,
195
+ ResBlock)):
196
+ if cnet is not None:
197
+ next_cnet = cnet.pop()
198
+ if next_cnet is not None:
199
+ x = x + nn.functional.interpolate(next_cnet, size=x.shape[-2:], mode='bilinear',
200
+ align_corners=True).to(x.dtype)
201
+ x = block(x)
202
+ elif isinstance(block, AttnBlock) or (
203
+ hasattr(block, '_fsdp_wrapped_module') and isinstance(block._fsdp_wrapped_module,
204
+ AttnBlock)):
205
+ x = block(x, clip)
206
+ elif isinstance(block, TimestepBlock) or (
207
+ hasattr(block, '_fsdp_wrapped_module') and isinstance(block._fsdp_wrapped_module,
208
+ TimestepBlock)):
209
+ x = block(x, r_embed)
210
+ else:
211
+ x = block(x)
212
+ if i < len(repmap):
213
+ x = repmap[i](x)
214
+ level_outputs.insert(0, x)
215
+ return level_outputs
216
+
217
+ def _up_decode(self, level_outputs, r_embed, clip, cnet=None):
218
+ x = level_outputs[0]
219
+ block_group = zip(self.up_blocks, self.up_upscalers, self.up_repeat_mappers)
220
+ for i, (up_block, upscaler, repmap) in enumerate(block_group):
221
+ for j in range(len(repmap) + 1):
222
+ for k, block in enumerate(up_block):
223
+ if isinstance(block, ResBlock) or (
224
+ hasattr(block, '_fsdp_wrapped_module') and isinstance(block._fsdp_wrapped_module,
225
+ ResBlock)):
226
+ skip = level_outputs[i] if k == 0 and i > 0 else None
227
+ if skip is not None and (x.size(-1) != skip.size(-1) or x.size(-2) != skip.size(-2)):
228
+ x = torch.nn.functional.interpolate(x, skip.shape[-2:], mode='bilinear',
229
+ align_corners=True)
230
+ if cnet is not None:
231
+ next_cnet = cnet.pop()
232
+ if next_cnet is not None:
233
+ x = x + nn.functional.interpolate(next_cnet, size=x.shape[-2:], mode='bilinear',
234
+ align_corners=True).to(x.dtype)
235
+ x = block(x, skip)
236
+ elif isinstance(block, AttnBlock) or (
237
+ hasattr(block, '_fsdp_wrapped_module') and isinstance(block._fsdp_wrapped_module,
238
+ AttnBlock)):
239
+ x = block(x, clip)
240
+ elif isinstance(block, TimestepBlock) or (
241
+ hasattr(block, '_fsdp_wrapped_module') and isinstance(block._fsdp_wrapped_module,
242
+ TimestepBlock)):
243
+ x = block(x, r_embed)
244
+ else:
245
+ x = block(x)
246
+ if j < len(repmap):
247
+ x = repmap[j](x)
248
+ x = upscaler(x)
249
+ return x
250
+
251
+ def forward(self, x, r, clip_text, clip_text_pooled, clip_img, control=None, **kwargs):
252
+ # Process the conditioning embeddings
253
+ r_embed = self.gen_r_embedding(r).to(dtype=x.dtype)
254
+ for c in self.t_conds:
255
+ t_cond = kwargs.get(c, torch.zeros_like(r))
256
+ r_embed = torch.cat([r_embed, self.gen_r_embedding(t_cond).to(dtype=x.dtype)], dim=1)
257
+ clip = self.gen_c_embeddings(clip_text, clip_text_pooled, clip_img)
258
+
259
+ if control is not None:
260
+ cnet = control.get("input")
261
+ else:
262
+ cnet = None
263
+
264
+ # Model Blocks
265
+ x = self.embedding(x)
266
+ level_outputs = self._down_encode(x, r_embed, clip, cnet)
267
+ x = self._up_decode(level_outputs, r_embed, clip, cnet)
268
+ return self.clf(x)
269
+
270
+ def update_weights_ema(self, src_model, beta=0.999):
271
+ for self_params, src_params in zip(self.parameters(), src_model.parameters()):
272
+ self_params.data = self_params.data * beta + src_params.data.clone().to(self_params.device) * (1 - beta)
273
+ for self_buffers, src_buffers in zip(self.buffers(), src_model.buffers()):
274
+ self_buffers.data = self_buffers.data * beta + src_buffers.data.clone().to(self_buffers.device) * (1 - beta)
comfy/ldm/cascade/stage_c_coder.py ADDED
@@ -0,0 +1,95 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ This file is part of ComfyUI.
3
+ Copyright (C) 2024 Stability AI
4
+
5
+ This program is free software: you can redistribute it and/or modify
6
+ it under the terms of the GNU General Public License as published by
7
+ the Free Software Foundation, either version 3 of the License, or
8
+ (at your option) any later version.
9
+
10
+ This program is distributed in the hope that it will be useful,
11
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
12
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13
+ GNU General Public License for more details.
14
+
15
+ You should have received a copy of the GNU General Public License
16
+ along with this program. If not, see <https://www.gnu.org/licenses/>.
17
+ """
18
+ import torch
19
+ import torchvision
20
+ from torch import nn
21
+
22
+
23
+ # EfficientNet
24
+ class EfficientNetEncoder(nn.Module):
25
+ def __init__(self, c_latent=16):
26
+ super().__init__()
27
+ self.backbone = torchvision.models.efficientnet_v2_s().features.eval()
28
+ self.mapper = nn.Sequential(
29
+ nn.Conv2d(1280, c_latent, kernel_size=1, bias=False),
30
+ nn.BatchNorm2d(c_latent, affine=False), # then normalize them to have mean 0 and std 1
31
+ )
32
+ self.mean = nn.Parameter(torch.tensor([0.485, 0.456, 0.406]))
33
+ self.std = nn.Parameter(torch.tensor([0.229, 0.224, 0.225]))
34
+
35
+ def forward(self, x):
36
+ x = x * 0.5 + 0.5
37
+ x = (x - self.mean.view([3,1,1])) / self.std.view([3,1,1])
38
+ o = self.mapper(self.backbone(x))
39
+ return o
40
+
41
+
42
+ # Fast Decoder for Stage C latents. E.g. 16 x 24 x 24 -> 3 x 192 x 192
43
+ class Previewer(nn.Module):
44
+ def __init__(self, c_in=16, c_hidden=512, c_out=3):
45
+ super().__init__()
46
+ self.blocks = nn.Sequential(
47
+ nn.Conv2d(c_in, c_hidden, kernel_size=1), # 16 channels to 512 channels
48
+ nn.GELU(),
49
+ nn.BatchNorm2d(c_hidden),
50
+
51
+ nn.Conv2d(c_hidden, c_hidden, kernel_size=3, padding=1),
52
+ nn.GELU(),
53
+ nn.BatchNorm2d(c_hidden),
54
+
55
+ nn.ConvTranspose2d(c_hidden, c_hidden // 2, kernel_size=2, stride=2), # 16 -> 32
56
+ nn.GELU(),
57
+ nn.BatchNorm2d(c_hidden // 2),
58
+
59
+ nn.Conv2d(c_hidden // 2, c_hidden // 2, kernel_size=3, padding=1),
60
+ nn.GELU(),
61
+ nn.BatchNorm2d(c_hidden // 2),
62
+
63
+ nn.ConvTranspose2d(c_hidden // 2, c_hidden // 4, kernel_size=2, stride=2), # 32 -> 64
64
+ nn.GELU(),
65
+ nn.BatchNorm2d(c_hidden // 4),
66
+
67
+ nn.Conv2d(c_hidden // 4, c_hidden // 4, kernel_size=3, padding=1),
68
+ nn.GELU(),
69
+ nn.BatchNorm2d(c_hidden // 4),
70
+
71
+ nn.ConvTranspose2d(c_hidden // 4, c_hidden // 4, kernel_size=2, stride=2), # 64 -> 128
72
+ nn.GELU(),
73
+ nn.BatchNorm2d(c_hidden // 4),
74
+
75
+ nn.Conv2d(c_hidden // 4, c_hidden // 4, kernel_size=3, padding=1),
76
+ nn.GELU(),
77
+ nn.BatchNorm2d(c_hidden // 4),
78
+
79
+ nn.Conv2d(c_hidden // 4, c_out, kernel_size=1),
80
+ )
81
+
82
+ def forward(self, x):
83
+ return (self.blocks(x) - 0.5) * 2.0
84
+
85
+ class StageC_coder(nn.Module):
86
+ def __init__(self):
87
+ super().__init__()
88
+ self.previewer = Previewer()
89
+ self.encoder = EfficientNetEncoder()
90
+
91
+ def encode(self, x):
92
+ return self.encoder(x)
93
+
94
+ def decode(self, x):
95
+ return self.previewer(x)
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,800 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ if len(mask.shape) == 2:
118
+ bs = 1
119
+ else:
120
+ bs = mask.shape[0]
121
+ mask = mask.reshape(bs, -1, mask.shape[-2], mask.shape[-1]).expand(b, heads, -1, -1).reshape(-1, mask.shape[-2], mask.shape[-1])
122
+ sim.add_(mask)
123
+
124
+ # attention, what we cannot get enough of
125
+ sim = sim.softmax(dim=-1)
126
+
127
+ out = einsum('b i j, b j d -> b i d', sim.to(v.dtype), v)
128
+ out = (
129
+ out.unsqueeze(0)
130
+ .reshape(b, heads, -1, dim_head)
131
+ .permute(0, 2, 1, 3)
132
+ .reshape(b, -1, heads * dim_head)
133
+ )
134
+ return out
135
+
136
+
137
+ def attention_sub_quad(query, key, value, heads, mask=None):
138
+ b, _, dim_head = query.shape
139
+ dim_head //= heads
140
+
141
+ scale = dim_head ** -0.5
142
+ query = query.unsqueeze(3).reshape(b, -1, heads, dim_head).permute(0, 2, 1, 3).reshape(b * heads, -1, dim_head)
143
+ value = value.unsqueeze(3).reshape(b, -1, heads, dim_head).permute(0, 2, 1, 3).reshape(b * heads, -1, dim_head)
144
+
145
+ key = key.unsqueeze(3).reshape(b, -1, heads, dim_head).permute(0, 2, 3, 1).reshape(b * heads, dim_head, -1)
146
+
147
+ dtype = query.dtype
148
+ upcast_attention = _ATTN_PRECISION =="fp32" and query.dtype != torch.float32
149
+ if upcast_attention:
150
+ bytes_per_token = torch.finfo(torch.float32).bits//8
151
+ else:
152
+ bytes_per_token = torch.finfo(query.dtype).bits//8
153
+ batch_x_heads, q_tokens, _ = query.shape
154
+ _, _, k_tokens = key.shape
155
+ qk_matmul_size_bytes = batch_x_heads * bytes_per_token * q_tokens * k_tokens
156
+
157
+ mem_free_total, mem_free_torch = model_management.get_free_memory(query.device, True)
158
+
159
+ kv_chunk_size_min = None
160
+ kv_chunk_size = None
161
+ query_chunk_size = None
162
+
163
+ for x in [4096, 2048, 1024, 512, 256]:
164
+ count = mem_free_total / (batch_x_heads * bytes_per_token * x * 4.0)
165
+ if count >= k_tokens:
166
+ kv_chunk_size = k_tokens
167
+ query_chunk_size = x
168
+ break
169
+
170
+ if query_chunk_size is None:
171
+ query_chunk_size = 512
172
+
173
+ if mask is not None:
174
+ if len(mask.shape) == 2:
175
+ bs = 1
176
+ else:
177
+ bs = mask.shape[0]
178
+ mask = mask.reshape(bs, -1, mask.shape[-2], mask.shape[-1]).expand(b, heads, -1, -1).reshape(-1, mask.shape[-2], mask.shape[-1])
179
+
180
+ hidden_states = efficient_dot_product_attention(
181
+ query,
182
+ key,
183
+ value,
184
+ query_chunk_size=query_chunk_size,
185
+ kv_chunk_size=kv_chunk_size,
186
+ kv_chunk_size_min=kv_chunk_size_min,
187
+ use_checkpoint=False,
188
+ upcast_attention=upcast_attention,
189
+ mask=mask,
190
+ )
191
+
192
+ hidden_states = hidden_states.to(dtype)
193
+
194
+ hidden_states = hidden_states.unflatten(0, (-1, heads)).transpose(1,2).flatten(start_dim=2)
195
+ return hidden_states
196
+
197
+ def attention_split(q, k, v, heads, mask=None):
198
+ b, _, dim_head = q.shape
199
+ dim_head //= heads
200
+ scale = dim_head ** -0.5
201
+
202
+ h = heads
203
+ q, k, v = map(
204
+ lambda t: t.unsqueeze(3)
205
+ .reshape(b, -1, heads, dim_head)
206
+ .permute(0, 2, 1, 3)
207
+ .reshape(b * heads, -1, dim_head)
208
+ .contiguous(),
209
+ (q, k, v),
210
+ )
211
+
212
+ r1 = torch.zeros(q.shape[0], q.shape[1], v.shape[2], device=q.device, dtype=q.dtype)
213
+
214
+ mem_free_total = model_management.get_free_memory(q.device)
215
+
216
+ if _ATTN_PRECISION =="fp32":
217
+ element_size = 4
218
+ else:
219
+ element_size = q.element_size()
220
+
221
+ gb = 1024 ** 3
222
+ tensor_size = q.shape[0] * q.shape[1] * k.shape[1] * element_size
223
+ modifier = 3
224
+ mem_required = tensor_size * modifier
225
+ steps = 1
226
+
227
+
228
+ if mem_required > mem_free_total:
229
+ steps = 2**(math.ceil(math.log(mem_required / mem_free_total, 2)))
230
+ # print(f"Expected tensor size:{tensor_size/gb:0.1f}GB, cuda free:{mem_free_cuda/gb:0.1f}GB "
231
+ # f"torch free:{mem_free_torch/gb:0.1f} total:{mem_free_total/gb:0.1f} steps:{steps}")
232
+
233
+ if steps > 64:
234
+ max_res = math.floor(math.sqrt(math.sqrt(mem_free_total / 2.5)) / 8) * 64
235
+ raise RuntimeError(f'Not enough memory, use lower resolution (max approx. {max_res}x{max_res}). '
236
+ f'Need: {mem_required/64/gb:0.1f}GB free, Have:{mem_free_total/gb:0.1f}GB free')
237
+
238
+ if mask is not None:
239
+ if len(mask.shape) == 2:
240
+ bs = 1
241
+ else:
242
+ bs = mask.shape[0]
243
+ mask = mask.reshape(bs, -1, mask.shape[-2], mask.shape[-1]).expand(b, heads, -1, -1).reshape(-1, mask.shape[-2], mask.shape[-1])
244
+
245
+ # print("steps", steps, mem_required, mem_free_total, modifier, q.element_size(), tensor_size)
246
+ first_op_done = False
247
+ cleared_cache = False
248
+ while True:
249
+ try:
250
+ slice_size = q.shape[1] // steps if (q.shape[1] % steps) == 0 else q.shape[1]
251
+ for i in range(0, q.shape[1], slice_size):
252
+ end = i + slice_size
253
+ if _ATTN_PRECISION =="fp32":
254
+ with torch.autocast(enabled=False, device_type = 'cuda'):
255
+ s1 = einsum('b i d, b j d -> b i j', q[:, i:end].float(), k.float()) * scale
256
+ else:
257
+ s1 = einsum('b i d, b j d -> b i j', q[:, i:end], k) * scale
258
+
259
+ if mask is not None:
260
+ if len(mask.shape) == 2:
261
+ s1 += mask[i:end]
262
+ else:
263
+ s1 += mask[:, i:end]
264
+
265
+ s2 = s1.softmax(dim=-1).to(v.dtype)
266
+ del s1
267
+ first_op_done = True
268
+
269
+ r1[:, i:end] = einsum('b i j, b j d -> b i d', s2, v)
270
+ del s2
271
+ break
272
+ except model_management.OOM_EXCEPTION as e:
273
+ if first_op_done == False:
274
+ model_management.soft_empty_cache(True)
275
+ if cleared_cache == False:
276
+ cleared_cache = True
277
+ print("out of memory error, emptying cache and trying again")
278
+ continue
279
+ steps *= 2
280
+ if steps > 64:
281
+ raise e
282
+ print("out of memory error, increasing steps and trying again", steps)
283
+ else:
284
+ raise e
285
+
286
+ del q, k, v
287
+
288
+ r1 = (
289
+ r1.unsqueeze(0)
290
+ .reshape(b, heads, -1, dim_head)
291
+ .permute(0, 2, 1, 3)
292
+ .reshape(b, -1, heads * dim_head)
293
+ )
294
+ return r1
295
+
296
+ BROKEN_XFORMERS = False
297
+ try:
298
+ x_vers = xformers.__version__
299
+ #I think 0.0.23 is also broken (q with bs bigger than 65535 gives CUDA error)
300
+ BROKEN_XFORMERS = x_vers.startswith("0.0.21") or x_vers.startswith("0.0.22") or x_vers.startswith("0.0.23")
301
+ except:
302
+ pass
303
+
304
+ def attention_xformers(q, k, v, heads, mask=None):
305
+ b, _, dim_head = q.shape
306
+ dim_head //= heads
307
+ if BROKEN_XFORMERS:
308
+ if b * heads > 65535:
309
+ return attention_pytorch(q, k, v, heads, mask)
310
+
311
+ q, k, v = map(
312
+ lambda t: t.unsqueeze(3)
313
+ .reshape(b, -1, heads, dim_head)
314
+ .permute(0, 2, 1, 3)
315
+ .reshape(b * heads, -1, dim_head)
316
+ .contiguous(),
317
+ (q, k, v),
318
+ )
319
+
320
+ if mask is not None:
321
+ pad = 8 - q.shape[1] % 8
322
+ mask_out = torch.empty([q.shape[0], q.shape[1], q.shape[1] + pad], dtype=q.dtype, device=q.device)
323
+ mask_out[:, :, :mask.shape[-1]] = mask
324
+ mask = mask_out[:, :, :mask.shape[-1]]
325
+
326
+ out = xformers.ops.memory_efficient_attention(q, k, v, attn_bias=mask)
327
+
328
+ out = (
329
+ out.unsqueeze(0)
330
+ .reshape(b, heads, -1, dim_head)
331
+ .permute(0, 2, 1, 3)
332
+ .reshape(b, -1, heads * dim_head)
333
+ )
334
+ return out
335
+
336
+ def attention_pytorch(q, k, v, heads, mask=None):
337
+ b, _, dim_head = q.shape
338
+ dim_head //= heads
339
+ q, k, v = map(
340
+ lambda t: t.view(b, -1, heads, dim_head).transpose(1, 2),
341
+ (q, k, v),
342
+ )
343
+
344
+ out = torch.nn.functional.scaled_dot_product_attention(q, k, v, attn_mask=mask, dropout_p=0.0, is_causal=False)
345
+ out = (
346
+ out.transpose(1, 2).reshape(b, -1, heads * dim_head)
347
+ )
348
+ return out
349
+
350
+
351
+ optimized_attention = attention_basic
352
+
353
+ if model_management.xformers_enabled():
354
+ print("Using xformers cross attention")
355
+ optimized_attention = attention_xformers
356
+ elif model_management.pytorch_attention_enabled():
357
+ print("Using pytorch cross attention")
358
+ optimized_attention = attention_pytorch
359
+ else:
360
+ if args.use_split_cross_attention:
361
+ print("Using split optimization for cross attention")
362
+ optimized_attention = attention_split
363
+ else:
364
+ print("Using sub quadratic optimization for cross attention, if you have memory or speed issues try using: --use-split-cross-attention")
365
+ optimized_attention = attention_sub_quad
366
+
367
+ optimized_attention_masked = optimized_attention
368
+
369
+ def optimized_attention_for_device(device, mask=False, small_input=False):
370
+ if small_input:
371
+ if model_management.pytorch_attention_enabled():
372
+ return attention_pytorch #TODO: need to confirm but this is probably slightly faster for small inputs in all cases
373
+ else:
374
+ return attention_basic
375
+
376
+ if device == torch.device("cpu"):
377
+ return attention_sub_quad
378
+
379
+ if mask:
380
+ return optimized_attention_masked
381
+
382
+ return optimized_attention
383
+
384
+
385
+ class CrossAttention(nn.Module):
386
+ def __init__(self, query_dim, context_dim=None, heads=8, dim_head=64, dropout=0., dtype=None, device=None, operations=ops):
387
+ super().__init__()
388
+ inner_dim = dim_head * heads
389
+ context_dim = default(context_dim, query_dim)
390
+
391
+ self.heads = heads
392
+ self.dim_head = dim_head
393
+
394
+ self.to_q = operations.Linear(query_dim, inner_dim, bias=False, dtype=dtype, device=device)
395
+ self.to_k = operations.Linear(context_dim, inner_dim, bias=False, dtype=dtype, device=device)
396
+ self.to_v = operations.Linear(context_dim, inner_dim, bias=False, dtype=dtype, device=device)
397
+
398
+ self.to_out = nn.Sequential(operations.Linear(inner_dim, query_dim, dtype=dtype, device=device), nn.Dropout(dropout))
399
+
400
+ def forward(self, x, context=None, value=None, mask=None):
401
+ q = self.to_q(x)
402
+ context = default(context, x)
403
+ k = self.to_k(context)
404
+ if value is not None:
405
+ v = self.to_v(value)
406
+ del value
407
+ else:
408
+ v = self.to_v(context)
409
+
410
+ if mask is None:
411
+ out = optimized_attention(q, k, v, self.heads)
412
+ else:
413
+ out = optimized_attention_masked(q, k, v, self.heads, mask)
414
+ return self.to_out(out)
415
+
416
+
417
+ class BasicTransformerBlock(nn.Module):
418
+ def __init__(self, dim, n_heads, d_head, dropout=0., context_dim=None, gated_ff=True, checkpoint=True, ff_in=False, inner_dim=None,
419
+ disable_self_attn=False, disable_temporal_crossattention=False, switch_temporal_ca_to_sa=False, dtype=None, device=None, operations=ops):
420
+ super().__init__()
421
+
422
+ self.ff_in = ff_in or inner_dim is not None
423
+ if inner_dim is None:
424
+ inner_dim = dim
425
+
426
+ self.is_res = inner_dim == dim
427
+
428
+ if self.ff_in:
429
+ self.norm_in = operations.LayerNorm(dim, dtype=dtype, device=device)
430
+ self.ff_in = FeedForward(dim, dim_out=inner_dim, dropout=dropout, glu=gated_ff, dtype=dtype, device=device, operations=operations)
431
+
432
+ self.disable_self_attn = disable_self_attn
433
+ self.attn1 = CrossAttention(query_dim=inner_dim, heads=n_heads, dim_head=d_head, dropout=dropout,
434
+ 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
435
+ self.ff = FeedForward(inner_dim, dim_out=dim, dropout=dropout, glu=gated_ff, dtype=dtype, device=device, operations=operations)
436
+
437
+ if disable_temporal_crossattention:
438
+ if switch_temporal_ca_to_sa:
439
+ raise ValueError
440
+ else:
441
+ self.attn2 = None
442
+ else:
443
+ context_dim_attn2 = None
444
+ if not switch_temporal_ca_to_sa:
445
+ context_dim_attn2 = context_dim
446
+
447
+ self.attn2 = CrossAttention(query_dim=inner_dim, context_dim=context_dim_attn2,
448
+ heads=n_heads, dim_head=d_head, dropout=dropout, dtype=dtype, device=device, operations=operations) # is self-attn if context is none
449
+ self.norm2 = operations.LayerNorm(inner_dim, dtype=dtype, device=device)
450
+
451
+ self.norm1 = operations.LayerNorm(inner_dim, dtype=dtype, device=device)
452
+ self.norm3 = operations.LayerNorm(inner_dim, dtype=dtype, device=device)
453
+ self.checkpoint = checkpoint
454
+ self.n_heads = n_heads
455
+ self.d_head = d_head
456
+ self.switch_temporal_ca_to_sa = switch_temporal_ca_to_sa
457
+
458
+ def forward(self, x, context=None, transformer_options={}):
459
+ return checkpoint(self._forward, (x, context, transformer_options), self.parameters(), self.checkpoint)
460
+
461
+ def _forward(self, x, context=None, transformer_options={}):
462
+ extra_options = {}
463
+ block = transformer_options.get("block", None)
464
+ block_index = transformer_options.get("block_index", 0)
465
+ transformer_patches = {}
466
+ transformer_patches_replace = {}
467
+
468
+ for k in transformer_options:
469
+ if k == "patches":
470
+ transformer_patches = transformer_options[k]
471
+ elif k == "patches_replace":
472
+ transformer_patches_replace = transformer_options[k]
473
+ else:
474
+ extra_options[k] = transformer_options[k]
475
+
476
+ extra_options["n_heads"] = self.n_heads
477
+ extra_options["dim_head"] = self.d_head
478
+
479
+ if self.ff_in:
480
+ x_skip = x
481
+ x = self.ff_in(self.norm_in(x))
482
+ if self.is_res:
483
+ x += x_skip
484
+
485
+ n = self.norm1(x)
486
+ if self.disable_self_attn:
487
+ context_attn1 = context
488
+ else:
489
+ context_attn1 = None
490
+ value_attn1 = None
491
+
492
+ if "attn1_patch" in transformer_patches:
493
+ patch = transformer_patches["attn1_patch"]
494
+ if context_attn1 is None:
495
+ context_attn1 = n
496
+ value_attn1 = context_attn1
497
+ for p in patch:
498
+ n, context_attn1, value_attn1 = p(n, context_attn1, value_attn1, extra_options)
499
+
500
+ if block is not None:
501
+ transformer_block = (block[0], block[1], block_index)
502
+ else:
503
+ transformer_block = None
504
+ attn1_replace_patch = transformer_patches_replace.get("attn1", {})
505
+ block_attn1 = transformer_block
506
+ if block_attn1 not in attn1_replace_patch:
507
+ block_attn1 = block
508
+
509
+ if block_attn1 in attn1_replace_patch:
510
+ if context_attn1 is None:
511
+ context_attn1 = n
512
+ value_attn1 = n
513
+ n = self.attn1.to_q(n)
514
+ context_attn1 = self.attn1.to_k(context_attn1)
515
+ value_attn1 = self.attn1.to_v(value_attn1)
516
+ n = attn1_replace_patch[block_attn1](n, context_attn1, value_attn1, extra_options)
517
+ n = self.attn1.to_out(n)
518
+ else:
519
+ n = self.attn1(n, context=context_attn1, value=value_attn1)
520
+
521
+ if "attn1_output_patch" in transformer_patches:
522
+ patch = transformer_patches["attn1_output_patch"]
523
+ for p in patch:
524
+ n = p(n, extra_options)
525
+
526
+ x += n
527
+ if "middle_patch" in transformer_patches:
528
+ patch = transformer_patches["middle_patch"]
529
+ for p in patch:
530
+ x = p(x, extra_options)
531
+
532
+ if self.attn2 is not None:
533
+ n = self.norm2(x)
534
+ if self.switch_temporal_ca_to_sa:
535
+ context_attn2 = n
536
+ else:
537
+ context_attn2 = context
538
+ value_attn2 = None
539
+ if "attn2_patch" in transformer_patches:
540
+ patch = transformer_patches["attn2_patch"]
541
+ value_attn2 = context_attn2
542
+ for p in patch:
543
+ n, context_attn2, value_attn2 = p(n, context_attn2, value_attn2, extra_options)
544
+
545
+ attn2_replace_patch = transformer_patches_replace.get("attn2", {})
546
+ block_attn2 = transformer_block
547
+ if block_attn2 not in attn2_replace_patch:
548
+ block_attn2 = block
549
+
550
+ if block_attn2 in attn2_replace_patch:
551
+ if value_attn2 is None:
552
+ value_attn2 = context_attn2
553
+ n = self.attn2.to_q(n)
554
+ context_attn2 = self.attn2.to_k(context_attn2)
555
+ value_attn2 = self.attn2.to_v(value_attn2)
556
+ n = attn2_replace_patch[block_attn2](n, context_attn2, value_attn2, extra_options)
557
+ n = self.attn2.to_out(n)
558
+ else:
559
+ n = self.attn2(n, context=context_attn2, value=value_attn2)
560
+
561
+ if "attn2_output_patch" in transformer_patches:
562
+ patch = transformer_patches["attn2_output_patch"]
563
+ for p in patch:
564
+ n = p(n, extra_options)
565
+
566
+ x += n
567
+ if self.is_res:
568
+ x_skip = x
569
+ x = self.ff(self.norm3(x))
570
+ if self.is_res:
571
+ x += x_skip
572
+
573
+ return x
574
+
575
+
576
+ class SpatialTransformer(nn.Module):
577
+ """
578
+ Transformer block for image-like data.
579
+ First, project the input (aka embedding)
580
+ and reshape to b, t, d.
581
+ Then apply standard transformer action.
582
+ Finally, reshape to image
583
+ NEW: use_linear for more efficiency instead of the 1x1 convs
584
+ """
585
+ def __init__(self, in_channels, n_heads, d_head,
586
+ depth=1, dropout=0., context_dim=None,
587
+ disable_self_attn=False, use_linear=False,
588
+ use_checkpoint=True, dtype=None, device=None, operations=ops):
589
+ super().__init__()
590
+ if exists(context_dim) and not isinstance(context_dim, list):
591
+ context_dim = [context_dim] * depth
592
+ self.in_channels = in_channels
593
+ inner_dim = n_heads * d_head
594
+ self.norm = operations.GroupNorm(num_groups=32, num_channels=in_channels, eps=1e-6, affine=True, dtype=dtype, device=device)
595
+ if not use_linear:
596
+ self.proj_in = operations.Conv2d(in_channels,
597
+ inner_dim,
598
+ kernel_size=1,
599
+ stride=1,
600
+ padding=0, dtype=dtype, device=device)
601
+ else:
602
+ self.proj_in = operations.Linear(in_channels, inner_dim, dtype=dtype, device=device)
603
+
604
+ self.transformer_blocks = nn.ModuleList(
605
+ [BasicTransformerBlock(inner_dim, n_heads, d_head, dropout=dropout, context_dim=context_dim[d],
606
+ disable_self_attn=disable_self_attn, checkpoint=use_checkpoint, dtype=dtype, device=device, operations=operations)
607
+ for d in range(depth)]
608
+ )
609
+ if not use_linear:
610
+ self.proj_out = operations.Conv2d(inner_dim,in_channels,
611
+ kernel_size=1,
612
+ stride=1,
613
+ padding=0, dtype=dtype, device=device)
614
+ else:
615
+ self.proj_out = operations.Linear(in_channels, inner_dim, dtype=dtype, device=device)
616
+ self.use_linear = use_linear
617
+
618
+ def forward(self, x, context=None, transformer_options={}):
619
+ # note: if no context is given, cross-attention defaults to self-attention
620
+ if not isinstance(context, list):
621
+ context = [context] * len(self.transformer_blocks)
622
+ b, c, h, w = x.shape
623
+ x_in = x
624
+ x = self.norm(x)
625
+ if not self.use_linear:
626
+ x = self.proj_in(x)
627
+ x = rearrange(x, 'b c h w -> b (h w) c').contiguous()
628
+ if self.use_linear:
629
+ x = self.proj_in(x)
630
+ for i, block in enumerate(self.transformer_blocks):
631
+ transformer_options["block_index"] = i
632
+ x = block(x, context=context[i], transformer_options=transformer_options)
633
+ if self.use_linear:
634
+ x = self.proj_out(x)
635
+ x = rearrange(x, 'b (h w) c -> b c h w', h=h, w=w).contiguous()
636
+ if not self.use_linear:
637
+ x = self.proj_out(x)
638
+ return x + x_in
639
+
640
+
641
+ class SpatialVideoTransformer(SpatialTransformer):
642
+ def __init__(
643
+ self,
644
+ in_channels,
645
+ n_heads,
646
+ d_head,
647
+ depth=1,
648
+ dropout=0.0,
649
+ use_linear=False,
650
+ context_dim=None,
651
+ use_spatial_context=False,
652
+ timesteps=None,
653
+ merge_strategy: str = "fixed",
654
+ merge_factor: float = 0.5,
655
+ time_context_dim=None,
656
+ ff_in=False,
657
+ checkpoint=False,
658
+ time_depth=1,
659
+ disable_self_attn=False,
660
+ disable_temporal_crossattention=False,
661
+ max_time_embed_period: int = 10000,
662
+ dtype=None, device=None, operations=ops
663
+ ):
664
+ super().__init__(
665
+ in_channels,
666
+ n_heads,
667
+ d_head,
668
+ depth=depth,
669
+ dropout=dropout,
670
+ use_checkpoint=checkpoint,
671
+ context_dim=context_dim,
672
+ use_linear=use_linear,
673
+ disable_self_attn=disable_self_attn,
674
+ dtype=dtype, device=device, operations=operations
675
+ )
676
+ self.time_depth = time_depth
677
+ self.depth = depth
678
+ self.max_time_embed_period = max_time_embed_period
679
+
680
+ time_mix_d_head = d_head
681
+ n_time_mix_heads = n_heads
682
+
683
+ time_mix_inner_dim = int(time_mix_d_head * n_time_mix_heads)
684
+
685
+ inner_dim = n_heads * d_head
686
+ if use_spatial_context:
687
+ time_context_dim = context_dim
688
+
689
+ self.time_stack = nn.ModuleList(
690
+ [
691
+ BasicTransformerBlock(
692
+ inner_dim,
693
+ n_time_mix_heads,
694
+ time_mix_d_head,
695
+ dropout=dropout,
696
+ context_dim=time_context_dim,
697
+ # timesteps=timesteps,
698
+ checkpoint=checkpoint,
699
+ ff_in=ff_in,
700
+ inner_dim=time_mix_inner_dim,
701
+ disable_self_attn=disable_self_attn,
702
+ disable_temporal_crossattention=disable_temporal_crossattention,
703
+ dtype=dtype, device=device, operations=operations
704
+ )
705
+ for _ in range(self.depth)
706
+ ]
707
+ )
708
+
709
+ assert len(self.time_stack) == len(self.transformer_blocks)
710
+
711
+ self.use_spatial_context = use_spatial_context
712
+ self.in_channels = in_channels
713
+
714
+ time_embed_dim = self.in_channels * 4
715
+ self.time_pos_embed = nn.Sequential(
716
+ operations.Linear(self.in_channels, time_embed_dim, dtype=dtype, device=device),
717
+ nn.SiLU(),
718
+ operations.Linear(time_embed_dim, self.in_channels, dtype=dtype, device=device),
719
+ )
720
+
721
+ self.time_mixer = AlphaBlender(
722
+ alpha=merge_factor, merge_strategy=merge_strategy
723
+ )
724
+
725
+ def forward(
726
+ self,
727
+ x: torch.Tensor,
728
+ context: Optional[torch.Tensor] = None,
729
+ time_context: Optional[torch.Tensor] = None,
730
+ timesteps: Optional[int] = None,
731
+ image_only_indicator: Optional[torch.Tensor] = None,
732
+ transformer_options={}
733
+ ) -> torch.Tensor:
734
+ _, _, h, w = x.shape
735
+ x_in = x
736
+ spatial_context = None
737
+ if exists(context):
738
+ spatial_context = context
739
+
740
+ if self.use_spatial_context:
741
+ assert (
742
+ context.ndim == 3
743
+ ), f"n dims of spatial context should be 3 but are {context.ndim}"
744
+
745
+ if time_context is None:
746
+ time_context = context
747
+ time_context_first_timestep = time_context[::timesteps]
748
+ time_context = repeat(
749
+ time_context_first_timestep, "b ... -> (b n) ...", n=h * w
750
+ )
751
+ elif time_context is not None and not self.use_spatial_context:
752
+ time_context = repeat(time_context, "b ... -> (b n) ...", n=h * w)
753
+ if time_context.ndim == 2:
754
+ time_context = rearrange(time_context, "b c -> b 1 c")
755
+
756
+ x = self.norm(x)
757
+ if not self.use_linear:
758
+ x = self.proj_in(x)
759
+ x = rearrange(x, "b c h w -> b (h w) c")
760
+ if self.use_linear:
761
+ x = self.proj_in(x)
762
+
763
+ num_frames = torch.arange(timesteps, device=x.device)
764
+ num_frames = repeat(num_frames, "t -> b t", b=x.shape[0] // timesteps)
765
+ num_frames = rearrange(num_frames, "b t -> (b t)")
766
+ t_emb = timestep_embedding(num_frames, self.in_channels, repeat_only=False, max_period=self.max_time_embed_period).to(x.dtype)
767
+ emb = self.time_pos_embed(t_emb)
768
+ emb = emb[:, None, :]
769
+
770
+ for it_, (block, mix_block) in enumerate(
771
+ zip(self.transformer_blocks, self.time_stack)
772
+ ):
773
+ transformer_options["block_index"] = it_
774
+ x = block(
775
+ x,
776
+ context=spatial_context,
777
+ transformer_options=transformer_options,
778
+ )
779
+
780
+ x_mix = x
781
+ x_mix = x_mix + emb
782
+
783
+ B, S, C = x_mix.shape
784
+ x_mix = rearrange(x_mix, "(b t) s c -> (b s) t c", t=timesteps)
785
+ x_mix = mix_block(x_mix, context=time_context) #TODO: transformer_options
786
+ x_mix = rearrange(
787
+ x_mix, "(b s) t c -> (b t) s c", s=S, b=B // timesteps, c=C, t=timesteps
788
+ )
789
+
790
+ x = self.time_mixer(x_spatial=x, x_temporal=x_mix, image_only_indicator=image_only_indicator)
791
+
792
+ if self.use_linear:
793
+ x = self.proj_out(x)
794
+ x = rearrange(x, "b (h w) c -> b c h w", h=h, w=w)
795
+ if not self.use_linear:
796
+ x = self.proj_out(x)
797
+ out = x + x_in
798
+ return out
799
+
800
+
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,889 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
488
+ time_embed_dim = model_channels * 4
489
+ self.time_embed = nn.Sequential(
490
+ operations.Linear(model_channels, time_embed_dim, dtype=self.dtype, device=device),
491
+ nn.SiLU(),
492
+ operations.Linear(time_embed_dim, time_embed_dim, dtype=self.dtype, device=device),
493
+ )
494
+
495
+ if self.num_classes is not None:
496
+ if isinstance(self.num_classes, int):
497
+ self.label_emb = nn.Embedding(num_classes, time_embed_dim, dtype=self.dtype, device=device)
498
+ elif self.num_classes == "continuous":
499
+ print("setting up linear c_adm embedding layer")
500
+ self.label_emb = nn.Linear(1, time_embed_dim)
501
+ elif self.num_classes == "sequential":
502
+ assert adm_in_channels is not None
503
+ self.label_emb = nn.Sequential(
504
+ nn.Sequential(
505
+ operations.Linear(adm_in_channels, time_embed_dim, dtype=self.dtype, device=device),
506
+ nn.SiLU(),
507
+ operations.Linear(time_embed_dim, time_embed_dim, dtype=self.dtype, device=device),
508
+ )
509
+ )
510
+ else:
511
+ raise ValueError()
512
+
513
+ self.input_blocks = nn.ModuleList(
514
+ [
515
+ TimestepEmbedSequential(
516
+ operations.conv_nd(dims, in_channels, model_channels, 3, padding=1, dtype=self.dtype, device=device)
517
+ )
518
+ ]
519
+ )
520
+ self._feature_size = model_channels
521
+ input_block_chans = [model_channels]
522
+ ch = model_channels
523
+ ds = 1
524
+
525
+ def get_attention_layer(
526
+ ch,
527
+ num_heads,
528
+ dim_head,
529
+ depth=1,
530
+ context_dim=None,
531
+ use_checkpoint=False,
532
+ disable_self_attn=False,
533
+ ):
534
+ if use_temporal_attention:
535
+ return SpatialVideoTransformer(
536
+ ch,
537
+ num_heads,
538
+ dim_head,
539
+ depth=depth,
540
+ context_dim=context_dim,
541
+ time_context_dim=time_context_dim,
542
+ dropout=dropout,
543
+ ff_in=extra_ff_mix_layer,
544
+ use_spatial_context=use_spatial_context,
545
+ merge_strategy=merge_strategy,
546
+ merge_factor=merge_factor,
547
+ checkpoint=use_checkpoint,
548
+ use_linear=use_linear_in_transformer,
549
+ disable_self_attn=disable_self_attn,
550
+ disable_temporal_crossattention=disable_temporal_crossattention,
551
+ max_time_embed_period=max_ddpm_temb_period,
552
+ dtype=self.dtype, device=device, operations=operations
553
+ )
554
+ else:
555
+ return SpatialTransformer(
556
+ ch, num_heads, dim_head, depth=depth, context_dim=context_dim,
557
+ disable_self_attn=disable_self_attn, use_linear=use_linear_in_transformer,
558
+ use_checkpoint=use_checkpoint, dtype=self.dtype, device=device, operations=operations
559
+ )
560
+
561
+ def get_resblock(
562
+ merge_factor,
563
+ merge_strategy,
564
+ video_kernel_size,
565
+ ch,
566
+ time_embed_dim,
567
+ dropout,
568
+ out_channels,
569
+ dims,
570
+ use_checkpoint,
571
+ use_scale_shift_norm,
572
+ down=False,
573
+ up=False,
574
+ dtype=None,
575
+ device=None,
576
+ operations=ops
577
+ ):
578
+ if self.use_temporal_resblocks:
579
+ return VideoResBlock(
580
+ merge_factor=merge_factor,
581
+ merge_strategy=merge_strategy,
582
+ video_kernel_size=video_kernel_size,
583
+ channels=ch,
584
+ emb_channels=time_embed_dim,
585
+ dropout=dropout,
586
+ out_channels=out_channels,
587
+ dims=dims,
588
+ use_checkpoint=use_checkpoint,
589
+ use_scale_shift_norm=use_scale_shift_norm,
590
+ down=down,
591
+ up=up,
592
+ dtype=dtype,
593
+ device=device,
594
+ operations=operations
595
+ )
596
+ else:
597
+ return ResBlock(
598
+ channels=ch,
599
+ emb_channels=time_embed_dim,
600
+ dropout=dropout,
601
+ out_channels=out_channels,
602
+ use_checkpoint=use_checkpoint,
603
+ dims=dims,
604
+ use_scale_shift_norm=use_scale_shift_norm,
605
+ down=down,
606
+ up=up,
607
+ dtype=dtype,
608
+ device=device,
609
+ operations=operations
610
+ )
611
+
612
+ for level, mult in enumerate(channel_mult):
613
+ for nr in range(self.num_res_blocks[level]):
614
+ layers = [
615
+ get_resblock(
616
+ merge_factor=merge_factor,
617
+ merge_strategy=merge_strategy,
618
+ video_kernel_size=video_kernel_size,
619
+ ch=ch,
620
+ time_embed_dim=time_embed_dim,
621
+ dropout=dropout,
622
+ out_channels=mult * model_channels,
623
+ dims=dims,
624
+ use_checkpoint=use_checkpoint,
625
+ use_scale_shift_norm=use_scale_shift_norm,
626
+ dtype=self.dtype,
627
+ device=device,
628
+ operations=operations,
629
+ )
630
+ ]
631
+ ch = mult * model_channels
632
+ num_transformers = transformer_depth.pop(0)
633
+ if num_transformers > 0:
634
+ if num_head_channels == -1:
635
+ dim_head = ch // num_heads
636
+ else:
637
+ num_heads = ch // num_head_channels
638
+ dim_head = num_head_channels
639
+ if legacy:
640
+ #num_heads = 1
641
+ dim_head = ch // num_heads if use_spatial_transformer else num_head_channels
642
+ if exists(disable_self_attentions):
643
+ disabled_sa = disable_self_attentions[level]
644
+ else:
645
+ disabled_sa = False
646
+
647
+ if not exists(num_attention_blocks) or nr < num_attention_blocks[level]:
648
+ layers.append(get_attention_layer(
649
+ ch, num_heads, dim_head, depth=num_transformers, context_dim=context_dim,
650
+ disable_self_attn=disabled_sa, use_checkpoint=use_checkpoint)
651
+ )
652
+ self.input_blocks.append(TimestepEmbedSequential(*layers))
653
+ self._feature_size += ch
654
+ input_block_chans.append(ch)
655
+ if level != len(channel_mult) - 1:
656
+ out_ch = ch
657
+ self.input_blocks.append(
658
+ TimestepEmbedSequential(
659
+ get_resblock(
660
+ merge_factor=merge_factor,
661
+ merge_strategy=merge_strategy,
662
+ video_kernel_size=video_kernel_size,
663
+ ch=ch,
664
+ time_embed_dim=time_embed_dim,
665
+ dropout=dropout,
666
+ out_channels=out_ch,
667
+ dims=dims,
668
+ use_checkpoint=use_checkpoint,
669
+ use_scale_shift_norm=use_scale_shift_norm,
670
+ down=True,
671
+ dtype=self.dtype,
672
+ device=device,
673
+ operations=operations
674
+ )
675
+ if resblock_updown
676
+ else Downsample(
677
+ ch, conv_resample, dims=dims, out_channels=out_ch, dtype=self.dtype, device=device, operations=operations
678
+ )
679
+ )
680
+ )
681
+ ch = out_ch
682
+ input_block_chans.append(ch)
683
+ ds *= 2
684
+ self._feature_size += ch
685
+
686
+ if num_head_channels == -1:
687
+ dim_head = ch // num_heads
688
+ else:
689
+ num_heads = ch // num_head_channels
690
+ dim_head = num_head_channels
691
+ if legacy:
692
+ #num_heads = 1
693
+ dim_head = ch // num_heads if use_spatial_transformer else num_head_channels
694
+ mid_block = [
695
+ get_resblock(
696
+ merge_factor=merge_factor,
697
+ merge_strategy=merge_strategy,
698
+ video_kernel_size=video_kernel_size,
699
+ ch=ch,
700
+ time_embed_dim=time_embed_dim,
701
+ dropout=dropout,
702
+ out_channels=None,
703
+ dims=dims,
704
+ use_checkpoint=use_checkpoint,
705
+ use_scale_shift_norm=use_scale_shift_norm,
706
+ dtype=self.dtype,
707
+ device=device,
708
+ operations=operations
709
+ )]
710
+
711
+ self.middle_block = None
712
+ if transformer_depth_middle >= -1:
713
+ if transformer_depth_middle >= 0:
714
+ mid_block += [get_attention_layer( # always uses a self-attn
715
+ ch, num_heads, dim_head, depth=transformer_depth_middle, context_dim=context_dim,
716
+ disable_self_attn=disable_middle_self_attn, use_checkpoint=use_checkpoint
717
+ ),
718
+ get_resblock(
719
+ merge_factor=merge_factor,
720
+ merge_strategy=merge_strategy,
721
+ video_kernel_size=video_kernel_size,
722
+ ch=ch,
723
+ time_embed_dim=time_embed_dim,
724
+ dropout=dropout,
725
+ out_channels=None,
726
+ dims=dims,
727
+ use_checkpoint=use_checkpoint,
728
+ use_scale_shift_norm=use_scale_shift_norm,
729
+ dtype=self.dtype,
730
+ device=device,
731
+ operations=operations
732
+ )]
733
+ self.middle_block = TimestepEmbedSequential(*mid_block)
734
+ self._feature_size += ch
735
+
736
+ self.output_blocks = nn.ModuleList([])
737
+ for level, mult in list(enumerate(channel_mult))[::-1]:
738
+ for i in range(self.num_res_blocks[level] + 1):
739
+ ich = input_block_chans.pop()
740
+ layers = [
741
+ get_resblock(
742
+ merge_factor=merge_factor,
743
+ merge_strategy=merge_strategy,
744
+ video_kernel_size=video_kernel_size,
745
+ ch=ch + ich,
746
+ time_embed_dim=time_embed_dim,
747
+ dropout=dropout,
748
+ out_channels=model_channels * mult,
749
+ dims=dims,
750
+ use_checkpoint=use_checkpoint,
751
+ use_scale_shift_norm=use_scale_shift_norm,
752
+ dtype=self.dtype,
753
+ device=device,
754
+ operations=operations
755
+ )
756
+ ]
757
+ ch = model_channels * mult
758
+ num_transformers = transformer_depth_output.pop()
759
+ if num_transformers > 0:
760
+ if num_head_channels == -1:
761
+ dim_head = ch // num_heads
762
+ else:
763
+ num_heads = ch // num_head_channels
764
+ dim_head = num_head_channels
765
+ if legacy:
766
+ #num_heads = 1
767
+ dim_head = ch // num_heads if use_spatial_transformer else num_head_channels
768
+ if exists(disable_self_attentions):
769
+ disabled_sa = disable_self_attentions[level]
770
+ else:
771
+ disabled_sa = False
772
+
773
+ if not exists(num_attention_blocks) or i < num_attention_blocks[level]:
774
+ layers.append(
775
+ get_attention_layer(
776
+ ch, num_heads, dim_head, depth=num_transformers, context_dim=context_dim,
777
+ disable_self_attn=disabled_sa, use_checkpoint=use_checkpoint
778
+ )
779
+ )
780
+ if level and i == self.num_res_blocks[level]:
781
+ out_ch = ch
782
+ layers.append(
783
+ get_resblock(
784
+ merge_factor=merge_factor,
785
+ merge_strategy=merge_strategy,
786
+ video_kernel_size=video_kernel_size,
787
+ ch=ch,
788
+ time_embed_dim=time_embed_dim,
789
+ dropout=dropout,
790
+ out_channels=out_ch,
791
+ dims=dims,
792
+ use_checkpoint=use_checkpoint,
793
+ use_scale_shift_norm=use_scale_shift_norm,
794
+ up=True,
795
+ dtype=self.dtype,
796
+ device=device,
797
+ operations=operations
798
+ )
799
+ if resblock_updown
800
+ else Upsample(ch, conv_resample, dims=dims, out_channels=out_ch, dtype=self.dtype, device=device, operations=operations)
801
+ )
802
+ ds //= 2
803
+ self.output_blocks.append(TimestepEmbedSequential(*layers))
804
+ self._feature_size += ch
805
+
806
+ self.out = nn.Sequential(
807
+ operations.GroupNorm(32, ch, dtype=self.dtype, device=device),
808
+ nn.SiLU(),
809
+ zero_module(operations.conv_nd(dims, model_channels, out_channels, 3, padding=1, dtype=self.dtype, device=device)),
810
+ )
811
+ if self.predict_codebook_ids:
812
+ self.id_predictor = nn.Sequential(
813
+ operations.GroupNorm(32, ch, dtype=self.dtype, device=device),
814
+ operations.conv_nd(dims, model_channels, n_embed, 1, dtype=self.dtype, device=device),
815
+ #nn.LogSoftmax(dim=1) # change to cross_entropy and produce non-normalized logits
816
+ )
817
+
818
+ def forward(self, x, timesteps=None, context=None, y=None, control=None, transformer_options={}, **kwargs):
819
+ """
820
+ Apply the model to an input batch.
821
+ :param x: an [N x C x ...] Tensor of inputs.
822
+ :param timesteps: a 1-D batch of timesteps.
823
+ :param context: conditioning plugged in via crossattn
824
+ :param y: an [N] Tensor of labels, if class-conditional.
825
+ :return: an [N x C x ...] Tensor of outputs.
826
+ """
827
+ transformer_options["original_shape"] = list(x.shape)
828
+ transformer_options["transformer_index"] = 0
829
+ transformer_patches = transformer_options.get("patches", {})
830
+
831
+ num_video_frames = kwargs.get("num_video_frames", self.default_num_video_frames)
832
+ image_only_indicator = kwargs.get("image_only_indicator", None)
833
+ time_context = kwargs.get("time_context", None)
834
+
835
+ assert (y is not None) == (
836
+ self.num_classes is not None
837
+ ), "must specify y if and only if the model is class-conditional"
838
+ hs = []
839
+ t_emb = timestep_embedding(timesteps, self.model_channels, repeat_only=False).to(x.dtype)
840
+ emb = self.time_embed(t_emb)
841
+
842
+ if self.num_classes is not None:
843
+ assert y.shape[0] == x.shape[0]
844
+ emb = emb + self.label_emb(y)
845
+
846
+ h = x
847
+ for id, module in enumerate(self.input_blocks):
848
+ transformer_options["block"] = ("input", id)
849
+ 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)
850
+ h = apply_control(h, control, 'input')
851
+ if "input_block_patch" in transformer_patches:
852
+ patch = transformer_patches["input_block_patch"]
853
+ for p in patch:
854
+ h = p(h, transformer_options)
855
+
856
+ hs.append(h)
857
+ if "input_block_patch_after_skip" in transformer_patches:
858
+ patch = transformer_patches["input_block_patch_after_skip"]
859
+ for p in patch:
860
+ h = p(h, transformer_options)
861
+
862
+ transformer_options["block"] = ("middle", 0)
863
+ if self.middle_block is not None:
864
+ 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)
865
+ h = apply_control(h, control, 'middle')
866
+
867
+
868
+ for id, module in enumerate(self.output_blocks):
869
+ transformer_options["block"] = ("output", id)
870
+ hsp = hs.pop()
871
+ hsp = apply_control(hsp, control, 'output')
872
+
873
+ if "output_block_patch" in transformer_patches:
874
+ patch = transformer_patches["output_block_patch"]
875
+ for p in patch:
876
+ h, hsp = p(h, hsp, transformer_options)
877
+
878
+ h = th.cat([h, hsp], dim=1)
879
+ del hsp
880
+ if len(hs) > 0:
881
+ output_shape = hs[-1].shape
882
+ else:
883
+ output_shape = None
884
+ 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)
885
+ h = h.type(x.dtype)
886
+ if self.predict_codebook_ids:
887
+ return self.id_predictor(h)
888
+ else:
889
+ 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,306 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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, device) -> 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(device)
55
+ elif self.merge_strategy == "learned":
56
+ alpha = torch.sigmoid(self.mix_factor.to(device))
57
+ # make shape compatible
58
+ # alpha = repeat(alpha, '1 -> s () ()', s = t * bs)
59
+ elif self.merge_strategy == "learned_with_images":
60
+ if image_only_indicator is None:
61
+ alpha = rearrange(torch.sigmoid(self.mix_factor.to(device)), "... -> ... 1")
62
+ else:
63
+ alpha = torch.where(
64
+ image_only_indicator.bool(),
65
+ torch.ones(1, 1, device=image_only_indicator.device),
66
+ rearrange(torch.sigmoid(self.mix_factor.to(image_only_indicator.device)), "... -> ... 1"),
67
+ )
68
+ alpha = rearrange(alpha, self.rearrange_pattern)
69
+ # make shape compatible
70
+ # alpha = repeat(alpha, '1 -> s () ()', s = t * bs)
71
+ else:
72
+ raise NotImplementedError()
73
+ return alpha
74
+
75
+ def forward(
76
+ self,
77
+ x_spatial,
78
+ x_temporal,
79
+ image_only_indicator=None,
80
+ ) -> torch.Tensor:
81
+ alpha = self.get_alpha(image_only_indicator, x_spatial.device)
82
+ x = (
83
+ alpha.to(x_spatial.dtype) * x_spatial
84
+ + (1.0 - alpha).to(x_spatial.dtype) * x_temporal
85
+ )
86
+ return x
87
+
88
+
89
+ def make_beta_schedule(schedule, n_timestep, linear_start=1e-4, linear_end=2e-2, cosine_s=8e-3):
90
+ if schedule == "linear":
91
+ betas = (
92
+ torch.linspace(linear_start ** 0.5, linear_end ** 0.5, n_timestep, dtype=torch.float64) ** 2
93
+ )
94
+
95
+ elif schedule == "cosine":
96
+ timesteps = (
97
+ torch.arange(n_timestep + 1, dtype=torch.float64) / n_timestep + cosine_s
98
+ )
99
+ alphas = timesteps / (1 + cosine_s) * np.pi / 2
100
+ alphas = torch.cos(alphas).pow(2)
101
+ alphas = alphas / alphas[0]
102
+ betas = 1 - alphas[1:] / alphas[:-1]
103
+ betas = torch.clamp(betas, min=0, max=0.999)
104
+
105
+ elif schedule == "squaredcos_cap_v2": # used for karlo prior
106
+ # return early
107
+ return betas_for_alpha_bar(
108
+ n_timestep,
109
+ lambda t: math.cos((t + 0.008) / 1.008 * math.pi / 2) ** 2,
110
+ )
111
+
112
+ elif schedule == "sqrt_linear":
113
+ betas = torch.linspace(linear_start, linear_end, n_timestep, dtype=torch.float64)
114
+ elif schedule == "sqrt":
115
+ betas = torch.linspace(linear_start, linear_end, n_timestep, dtype=torch.float64) ** 0.5
116
+ else:
117
+ raise ValueError(f"schedule '{schedule}' unknown.")
118
+ return betas
119
+
120
+
121
+ def make_ddim_timesteps(ddim_discr_method, num_ddim_timesteps, num_ddpm_timesteps, verbose=True):
122
+ if ddim_discr_method == 'uniform':
123
+ c = num_ddpm_timesteps // num_ddim_timesteps
124
+ ddim_timesteps = np.asarray(list(range(0, num_ddpm_timesteps, c)))
125
+ elif ddim_discr_method == 'quad':
126
+ ddim_timesteps = ((np.linspace(0, np.sqrt(num_ddpm_timesteps * .8), num_ddim_timesteps)) ** 2).astype(int)
127
+ else:
128
+ raise NotImplementedError(f'There is no ddim discretization method called "{ddim_discr_method}"')
129
+
130
+ # assert ddim_timesteps.shape[0] == num_ddim_timesteps
131
+ # add one to get the final alpha values right (the ones from first scale to data during sampling)
132
+ steps_out = ddim_timesteps + 1
133
+ if verbose:
134
+ print(f'Selected timesteps for ddim sampler: {steps_out}')
135
+ return steps_out
136
+
137
+
138
+ def make_ddim_sampling_parameters(alphacums, ddim_timesteps, eta, verbose=True):
139
+ # select alphas for computing the variance schedule
140
+ alphas = alphacums[ddim_timesteps]
141
+ alphas_prev = np.asarray([alphacums[0]] + alphacums[ddim_timesteps[:-1]].tolist())
142
+
143
+ # according the the formula provided in https://arxiv.org/abs/2010.02502
144
+ sigmas = eta * np.sqrt((1 - alphas_prev) / (1 - alphas) * (1 - alphas / alphas_prev))
145
+ if verbose:
146
+ print(f'Selected alphas for ddim sampler: a_t: {alphas}; a_(t-1): {alphas_prev}')
147
+ print(f'For the chosen value of eta, which is {eta}, '
148
+ f'this results in the following sigma_t schedule for ddim sampler {sigmas}')
149
+ return sigmas, alphas, alphas_prev
150
+
151
+
152
+ def betas_for_alpha_bar(num_diffusion_timesteps, alpha_bar, max_beta=0.999):
153
+ """
154
+ Create a beta schedule that discretizes the given alpha_t_bar function,
155
+ which defines the cumulative product of (1-beta) over time from t = [0,1].
156
+ :param num_diffusion_timesteps: the number of betas to produce.
157
+ :param alpha_bar: a lambda that takes an argument t from 0 to 1 and
158
+ produces the cumulative product of (1-beta) up to that
159
+ part of the diffusion process.
160
+ :param max_beta: the maximum beta to use; use values lower than 1 to
161
+ prevent singularities.
162
+ """
163
+ betas = []
164
+ for i in range(num_diffusion_timesteps):
165
+ t1 = i / num_diffusion_timesteps
166
+ t2 = (i + 1) / num_diffusion_timesteps
167
+ betas.append(min(1 - alpha_bar(t2) / alpha_bar(t1), max_beta))
168
+ return np.array(betas)
169
+
170
+
171
+ def extract_into_tensor(a, t, x_shape):
172
+ b, *_ = t.shape
173
+ out = a.gather(-1, t)
174
+ return out.reshape(b, *((1,) * (len(x_shape) - 1)))
175
+
176
+
177
+ def checkpoint(func, inputs, params, flag):
178
+ """
179
+ Evaluate a function without caching intermediate activations, allowing for
180
+ reduced memory at the expense of extra compute in the backward pass.
181
+ :param func: the function to evaluate.
182
+ :param inputs: the argument sequence to pass to `func`.
183
+ :param params: a sequence of parameters `func` depends on but does not
184
+ explicitly take as arguments.
185
+ :param flag: if False, disable gradient checkpointing.
186
+ """
187
+ if flag:
188
+ args = tuple(inputs) + tuple(params)
189
+ return CheckpointFunction.apply(func, len(inputs), *args)
190
+ else:
191
+ return func(*inputs)
192
+
193
+
194
+ class CheckpointFunction(torch.autograd.Function):
195
+ @staticmethod
196
+ def forward(ctx, run_function, length, *args):
197
+ ctx.run_function = run_function
198
+ ctx.input_tensors = list(args[:length])
199
+ ctx.input_params = list(args[length:])
200
+ ctx.gpu_autocast_kwargs = {"enabled": torch.is_autocast_enabled(),
201
+ "dtype": torch.get_autocast_gpu_dtype(),
202
+ "cache_enabled": torch.is_autocast_cache_enabled()}
203
+ with torch.no_grad():
204
+ output_tensors = ctx.run_function(*ctx.input_tensors)
205
+ return output_tensors
206
+
207
+ @staticmethod
208
+ def backward(ctx, *output_grads):
209
+ ctx.input_tensors = [x.detach().requires_grad_(True) for x in ctx.input_tensors]
210
+ with torch.enable_grad(), \
211
+ torch.cuda.amp.autocast(**ctx.gpu_autocast_kwargs):
212
+ # Fixes a bug where the first op in run_function modifies the
213
+ # Tensor storage in place, which is not allowed for detach()'d
214
+ # Tensors.
215
+ shallow_copies = [x.view_as(x) for x in ctx.input_tensors]
216
+ output_tensors = ctx.run_function(*shallow_copies)
217
+ input_grads = torch.autograd.grad(
218
+ output_tensors,
219
+ ctx.input_tensors + ctx.input_params,
220
+ output_grads,
221
+ allow_unused=True,
222
+ )
223
+ del ctx.input_tensors
224
+ del ctx.input_params
225
+ del output_tensors
226
+ return (None, None) + input_grads
227
+
228
+
229
+ def timestep_embedding(timesteps, dim, max_period=10000, repeat_only=False):
230
+ """
231
+ Create sinusoidal timestep embeddings.
232
+ :param timesteps: a 1-D Tensor of N indices, one per batch element.
233
+ These may be fractional.
234
+ :param dim: the dimension of the output.
235
+ :param max_period: controls the minimum frequency of the embeddings.
236
+ :return: an [N x dim] Tensor of positional embeddings.
237
+ """
238
+ if not repeat_only:
239
+ half = dim // 2
240
+ freqs = torch.exp(
241
+ -math.log(max_period) * torch.arange(start=0, end=half, dtype=torch.float32, device=timesteps.device) / half
242
+ )
243
+ args = timesteps[:, None].float() * freqs[None]
244
+ embedding = torch.cat([torch.cos(args), torch.sin(args)], dim=-1)
245
+ if dim % 2:
246
+ embedding = torch.cat([embedding, torch.zeros_like(embedding[:, :1])], dim=-1)
247
+ else:
248
+ embedding = repeat(timesteps, 'b -> b d', d=dim)
249
+ return embedding
250
+
251
+
252
+ def zero_module(module):
253
+ """
254
+ Zero out the parameters of a module and return it.
255
+ """
256
+ for p in module.parameters():
257
+ p.detach().zero_()
258
+ return module
259
+
260
+
261
+ def scale_module(module, scale):
262
+ """
263
+ Scale the parameters of a module and return it.
264
+ """
265
+ for p in module.parameters():
266
+ p.detach().mul_(scale)
267
+ return module
268
+
269
+
270
+ def mean_flat(tensor):
271
+ """
272
+ Take the mean over all non-batch dimensions.
273
+ """
274
+ return tensor.mean(dim=list(range(1, len(tensor.shape))))
275
+
276
+
277
+ def avg_pool_nd(dims, *args, **kwargs):
278
+ """
279
+ Create a 1D, 2D, or 3D average pooling module.
280
+ """
281
+ if dims == 1:
282
+ return nn.AvgPool1d(*args, **kwargs)
283
+ elif dims == 2:
284
+ return nn.AvgPool2d(*args, **kwargs)
285
+ elif dims == 3:
286
+ return nn.AvgPool3d(*args, **kwargs)
287
+ raise ValueError(f"unsupported dimensions: {dims}")
288
+
289
+
290
+ class HybridConditioner(nn.Module):
291
+
292
+ def __init__(self, c_concat_config, c_crossattn_config):
293
+ super().__init__()
294
+ self.concat_conditioner = instantiate_from_config(c_concat_config)
295
+ self.crossattn_conditioner = instantiate_from_config(c_crossattn_config)
296
+
297
+ def forward(self, c_concat, c_crossattn):
298
+ c_concat = self.concat_conditioner(c_concat)
299
+ c_crossattn = self.crossattn_conditioner(c_crossattn)
300
+ return {'c_concat': [c_concat], 'c_crossattn': [c_crossattn]}
301
+
302
+
303
+ def noise_like(shape, device, repeat=False):
304
+ repeat_noise = lambda: torch.randn((1, *shape[1:]), device=device).repeat(shape[0], *((1,) * (len(shape) - 1)))
305
+ noise = lambda: torch.randn(shape, device=device)
306
+ 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,234 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ lora_key = "lora_prior_te_text_model_encoder_layers_{}_{}".format(b, LORA_CLIP_MAP[c]) #cascade lora: TODO put lora key prefix in the model config
201
+ key_map[lora_key] = k
202
+
203
+
204
+ k = "clip_g.transformer.text_projection.weight"
205
+ if k in sdk:
206
+ key_map["lora_prior_te_text_projection"] = k #cascade lora?
207
+ # key_map["text_encoder.text_projection"] = k #TODO: check if other lora have the text_projection too
208
+ # key_map["lora_te_text_projection"] = k
209
+
210
+ return key_map
211
+
212
+ def model_lora_keys_unet(model, key_map={}):
213
+ sdk = model.state_dict().keys()
214
+
215
+ for k in sdk:
216
+ if k.startswith("diffusion_model.") and k.endswith(".weight"):
217
+ key_lora = k[len("diffusion_model."):-len(".weight")].replace(".", "_")
218
+ key_map["lora_unet_{}".format(key_lora)] = k
219
+ key_map["lora_prior_unet_{}".format(key_lora)] = k #cascade lora: TODO put lora key prefix in the model config
220
+
221
+ diffusers_keys = comfy.utils.unet_to_diffusers(model.model_config.unet_config)
222
+ for k in diffusers_keys:
223
+ if k.endswith(".weight"):
224
+ unet_key = "diffusion_model.{}".format(diffusers_keys[k])
225
+ key_lora = k[:-len(".weight")].replace(".", "_")
226
+ key_map["lora_unet_{}".format(key_lora)] = unet_key
227
+
228
+ diffusers_lora_prefix = ["", "unet."]
229
+ for p in diffusers_lora_prefix:
230
+ diffusers_lora_key = "{}{}".format(p, k[:-len(".weight")].replace(".to_", ".processor.to_"))
231
+ if diffusers_lora_key.endswith(".to_out.0"):
232
+ diffusers_lora_key = diffusers_lora_key[:-2]
233
+ key_map[diffusers_lora_key] = unet_key
234
+ return key_map
comfy/model_base.py ADDED
@@ -0,0 +1,491 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from comfy.ldm.modules.diffusionmodules.openaimodel import UNetModel, Timestep
3
+ from comfy.ldm.cascade.stage_c import StageC
4
+ from comfy.ldm.cascade.stage_b import StageB
5
+ from comfy.ldm.modules.encoders.noise_aug_modules import CLIPEmbeddingNoiseAugmentation
6
+ from comfy.ldm.modules.diffusionmodules.upscaling import ImageConcatWithNoiseAugmentation
7
+ import comfy.model_management
8
+ import comfy.conds
9
+ import comfy.ops
10
+ from enum import Enum
11
+ from . import utils
12
+
13
+ class ModelType(Enum):
14
+ EPS = 1
15
+ V_PREDICTION = 2
16
+ V_PREDICTION_EDM = 3
17
+ STABLE_CASCADE = 4
18
+ EDM = 5
19
+
20
+
21
+ from comfy.model_sampling import EPS, V_PREDICTION, EDM, ModelSamplingDiscrete, ModelSamplingContinuousEDM, StableCascadeSampling
22
+
23
+
24
+ def model_sampling(model_config, model_type):
25
+ s = ModelSamplingDiscrete
26
+
27
+ if model_type == ModelType.EPS:
28
+ c = EPS
29
+ elif model_type == ModelType.V_PREDICTION:
30
+ c = V_PREDICTION
31
+ elif model_type == ModelType.V_PREDICTION_EDM:
32
+ c = V_PREDICTION
33
+ s = ModelSamplingContinuousEDM
34
+ elif model_type == ModelType.STABLE_CASCADE:
35
+ c = EPS
36
+ s = StableCascadeSampling
37
+ elif model_type == ModelType.EDM:
38
+ c = EDM
39
+ s = ModelSamplingContinuousEDM
40
+
41
+ class ModelSampling(s, c):
42
+ pass
43
+
44
+ return ModelSampling(model_config)
45
+
46
+
47
+ class BaseModel(torch.nn.Module):
48
+ def __init__(self, model_config, model_type=ModelType.EPS, device=None, unet_model=UNetModel):
49
+ super().__init__()
50
+
51
+ unet_config = model_config.unet_config
52
+ self.latent_format = model_config.latent_format
53
+ self.model_config = model_config
54
+ self.manual_cast_dtype = model_config.manual_cast_dtype
55
+
56
+ if not unet_config.get("disable_unet_model_creation", False):
57
+ if self.manual_cast_dtype is not None:
58
+ operations = comfy.ops.manual_cast
59
+ else:
60
+ operations = comfy.ops.disable_weight_init
61
+ self.diffusion_model = unet_model(**unet_config, device=device, operations=operations)
62
+ self.model_type = model_type
63
+ self.model_sampling = model_sampling(model_config, model_type)
64
+
65
+ self.adm_channels = unet_config.get("adm_in_channels", None)
66
+ if self.adm_channels is None:
67
+ self.adm_channels = 0
68
+ self.inpaint_model = False
69
+ print("model_type", model_type.name)
70
+ print("adm", self.adm_channels)
71
+
72
+ def apply_model(self, x, t, c_concat=None, c_crossattn=None, control=None, transformer_options={}, **kwargs):
73
+ sigma = t
74
+ xc = self.model_sampling.calculate_input(sigma, x)
75
+ if c_concat is not None:
76
+ xc = torch.cat([xc] + [c_concat], dim=1)
77
+
78
+ context = c_crossattn
79
+ dtype = self.get_dtype()
80
+
81
+ if self.manual_cast_dtype is not None:
82
+ dtype = self.manual_cast_dtype
83
+
84
+ xc = xc.to(dtype)
85
+ t = self.model_sampling.timestep(t).float()
86
+ context = context.to(dtype)
87
+ extra_conds = {}
88
+ for o in kwargs:
89
+ extra = kwargs[o]
90
+ if hasattr(extra, "dtype"):
91
+ if extra.dtype != torch.int and extra.dtype != torch.long:
92
+ extra = extra.to(dtype)
93
+ extra_conds[o] = extra
94
+
95
+ model_output = self.diffusion_model(xc, t, context=context, control=control, transformer_options=transformer_options, **extra_conds).float()
96
+ return self.model_sampling.calculate_denoised(sigma, model_output, x)
97
+
98
+ def get_dtype(self):
99
+ return self.diffusion_model.dtype
100
+
101
+ def is_adm(self):
102
+ return self.adm_channels > 0
103
+
104
+ def encode_adm(self, **kwargs):
105
+ return None
106
+
107
+ def extra_conds(self, **kwargs):
108
+ out = {}
109
+ if self.inpaint_model:
110
+ concat_keys = ("mask", "masked_image")
111
+ cond_concat = []
112
+ denoise_mask = kwargs.get("concat_mask", kwargs.get("denoise_mask", None))
113
+ concat_latent_image = kwargs.get("concat_latent_image", None)
114
+ if concat_latent_image is None:
115
+ concat_latent_image = kwargs.get("latent_image", None)
116
+ else:
117
+ concat_latent_image = self.process_latent_in(concat_latent_image)
118
+
119
+ noise = kwargs.get("noise", None)
120
+ device = kwargs["device"]
121
+
122
+ if concat_latent_image.shape[1:] != noise.shape[1:]:
123
+ concat_latent_image = utils.common_upscale(concat_latent_image, noise.shape[-1], noise.shape[-2], "bilinear", "center")
124
+
125
+ concat_latent_image = utils.resize_to_batch_size(concat_latent_image, noise.shape[0])
126
+
127
+ if len(denoise_mask.shape) == len(noise.shape):
128
+ denoise_mask = denoise_mask[:,:1]
129
+
130
+ denoise_mask = denoise_mask.reshape((-1, 1, denoise_mask.shape[-2], denoise_mask.shape[-1]))
131
+ if denoise_mask.shape[-2:] != noise.shape[-2:]:
132
+ denoise_mask = utils.common_upscale(denoise_mask, noise.shape[-1], noise.shape[-2], "bilinear", "center")
133
+ denoise_mask = utils.resize_to_batch_size(denoise_mask.round(), noise.shape[0])
134
+
135
+ def blank_inpaint_image_like(latent_image):
136
+ blank_image = torch.ones_like(latent_image)
137
+ # these are the values for "zero" in pixel space translated to latent space
138
+ blank_image[:,0] *= 0.8223
139
+ blank_image[:,1] *= -0.6876
140
+ blank_image[:,2] *= 0.6364
141
+ blank_image[:,3] *= 0.1380
142
+ return blank_image
143
+
144
+ for ck in concat_keys:
145
+ if denoise_mask is not None:
146
+ if ck == "mask":
147
+ cond_concat.append(denoise_mask.to(device))
148
+ elif ck == "masked_image":
149
+ cond_concat.append(concat_latent_image.to(device)) #NOTE: the latent_image should be masked by the mask in pixel space
150
+ else:
151
+ if ck == "mask":
152
+ cond_concat.append(torch.ones_like(noise)[:,:1])
153
+ elif ck == "masked_image":
154
+ cond_concat.append(blank_inpaint_image_like(noise))
155
+ data = torch.cat(cond_concat, dim=1)
156
+ out['c_concat'] = comfy.conds.CONDNoiseShape(data)
157
+
158
+ adm = self.encode_adm(**kwargs)
159
+ if adm is not None:
160
+ out['y'] = comfy.conds.CONDRegular(adm)
161
+
162
+ cross_attn = kwargs.get("cross_attn", None)
163
+ if cross_attn is not None:
164
+ out['c_crossattn'] = comfy.conds.CONDCrossAttn(cross_attn)
165
+
166
+ cross_attn_cnet = kwargs.get("cross_attn_controlnet", None)
167
+ if cross_attn_cnet is not None:
168
+ out['crossattn_controlnet'] = comfy.conds.CONDCrossAttn(cross_attn_cnet)
169
+
170
+ c_concat = kwargs.get("noise_concat", None)
171
+ if c_concat is not None:
172
+ out['c_concat'] = comfy.conds.CONDNoiseShape(data)
173
+
174
+ return out
175
+
176
+ def load_model_weights(self, sd, unet_prefix=""):
177
+ to_load = {}
178
+ keys = list(sd.keys())
179
+ for k in keys:
180
+ if k.startswith(unet_prefix):
181
+ to_load[k[len(unet_prefix):]] = sd.pop(k)
182
+
183
+ to_load = self.model_config.process_unet_state_dict(to_load)
184
+ m, u = self.diffusion_model.load_state_dict(to_load, strict=False)
185
+ if len(m) > 0:
186
+ print("unet missing:", m)
187
+
188
+ if len(u) > 0:
189
+ print("unet unexpected:", u)
190
+ del to_load
191
+ return self
192
+
193
+ def process_latent_in(self, latent):
194
+ return self.latent_format.process_in(latent)
195
+
196
+ def process_latent_out(self, latent):
197
+ return self.latent_format.process_out(latent)
198
+
199
+ def state_dict_for_saving(self, clip_state_dict=None, vae_state_dict=None, clip_vision_state_dict=None):
200
+ extra_sds = []
201
+ if clip_state_dict is not None:
202
+ extra_sds.append(self.model_config.process_clip_state_dict_for_saving(clip_state_dict))
203
+ if vae_state_dict is not None:
204
+ extra_sds.append(self.model_config.process_vae_state_dict_for_saving(vae_state_dict))
205
+ if clip_vision_state_dict is not None:
206
+ extra_sds.append(self.model_config.process_clip_vision_state_dict_for_saving(clip_vision_state_dict))
207
+
208
+ unet_state_dict = self.diffusion_model.state_dict()
209
+ unet_state_dict = self.model_config.process_unet_state_dict_for_saving(unet_state_dict)
210
+
211
+ if self.get_dtype() == torch.float16:
212
+ extra_sds = map(lambda sd: utils.convert_sd_to(sd, torch.float16), extra_sds)
213
+
214
+ if self.model_type == ModelType.V_PREDICTION:
215
+ unet_state_dict["v_pred"] = torch.tensor([])
216
+
217
+ for sd in extra_sds:
218
+ unet_state_dict.update(sd)
219
+
220
+ return unet_state_dict
221
+
222
+ def set_inpaint(self):
223
+ self.inpaint_model = True
224
+
225
+ def memory_required(self, input_shape):
226
+ if comfy.model_management.xformers_enabled() or comfy.model_management.pytorch_attention_flash_attention():
227
+ dtype = self.get_dtype()
228
+ if self.manual_cast_dtype is not None:
229
+ dtype = self.manual_cast_dtype
230
+ #TODO: this needs to be tweaked
231
+ area = input_shape[0] * input_shape[2] * input_shape[3]
232
+ return (area * comfy.model_management.dtype_size(dtype) / 50) * (1024 * 1024)
233
+ else:
234
+ #TODO: this formula might be too aggressive since I tweaked the sub-quad and split algorithms to use less memory.
235
+ area = input_shape[0] * input_shape[2] * input_shape[3]
236
+ return (((area * 0.6) / 0.9) + 1024) * (1024 * 1024)
237
+
238
+
239
+ def unclip_adm(unclip_conditioning, device, noise_augmentor, noise_augment_merge=0.0, seed=None):
240
+ adm_inputs = []
241
+ weights = []
242
+ noise_aug = []
243
+ for unclip_cond in unclip_conditioning:
244
+ for adm_cond in unclip_cond["clip_vision_output"].image_embeds:
245
+ weight = unclip_cond["strength"]
246
+ noise_augment = unclip_cond["noise_augmentation"]
247
+ noise_level = round((noise_augmentor.max_noise_level - 1) * noise_augment)
248
+ c_adm, noise_level_emb = noise_augmentor(adm_cond.to(device), noise_level=torch.tensor([noise_level], device=device), seed=seed)
249
+ adm_out = torch.cat((c_adm, noise_level_emb), 1) * weight
250
+ weights.append(weight)
251
+ noise_aug.append(noise_augment)
252
+ adm_inputs.append(adm_out)
253
+
254
+ if len(noise_aug) > 1:
255
+ adm_out = torch.stack(adm_inputs).sum(0)
256
+ noise_augment = noise_augment_merge
257
+ noise_level = round((noise_augmentor.max_noise_level - 1) * noise_augment)
258
+ c_adm, noise_level_emb = noise_augmentor(adm_out[:, :noise_augmentor.time_embed.dim], noise_level=torch.tensor([noise_level], device=device))
259
+ adm_out = torch.cat((c_adm, noise_level_emb), 1)
260
+
261
+ return adm_out
262
+
263
+ class SD21UNCLIP(BaseModel):
264
+ def __init__(self, model_config, noise_aug_config, model_type=ModelType.V_PREDICTION, device=None):
265
+ super().__init__(model_config, model_type, device=device)
266
+ self.noise_augmentor = CLIPEmbeddingNoiseAugmentation(**noise_aug_config)
267
+
268
+ def encode_adm(self, **kwargs):
269
+ unclip_conditioning = kwargs.get("unclip_conditioning", None)
270
+ device = kwargs["device"]
271
+ if unclip_conditioning is None:
272
+ return torch.zeros((1, self.adm_channels))
273
+ else:
274
+ return unclip_adm(unclip_conditioning, device, self.noise_augmentor, kwargs.get("unclip_noise_augment_merge", 0.05), kwargs.get("seed", 0) - 10)
275
+
276
+ def sdxl_pooled(args, noise_augmentor):
277
+ if "unclip_conditioning" in args:
278
+ return unclip_adm(args.get("unclip_conditioning", None), args["device"], noise_augmentor, seed=args.get("seed", 0) - 10)[:,:1280]
279
+ else:
280
+ return args["pooled_output"]
281
+
282
+ class SDXLRefiner(BaseModel):
283
+ def __init__(self, model_config, model_type=ModelType.EPS, device=None):
284
+ super().__init__(model_config, model_type, device=device)
285
+ self.embedder = Timestep(256)
286
+ self.noise_augmentor = CLIPEmbeddingNoiseAugmentation(**{"noise_schedule_config": {"timesteps": 1000, "beta_schedule": "squaredcos_cap_v2"}, "timestep_dim": 1280})
287
+
288
+ def encode_adm(self, **kwargs):
289
+ clip_pooled = sdxl_pooled(kwargs, self.noise_augmentor)
290
+ width = kwargs.get("width", 768)
291
+ height = kwargs.get("height", 768)
292
+ crop_w = kwargs.get("crop_w", 0)
293
+ crop_h = kwargs.get("crop_h", 0)
294
+
295
+ if kwargs.get("prompt_type", "") == "negative":
296
+ aesthetic_score = kwargs.get("aesthetic_score", 2.5)
297
+ else:
298
+ aesthetic_score = kwargs.get("aesthetic_score", 6)
299
+
300
+ out = []
301
+ out.append(self.embedder(torch.Tensor([height])))
302
+ out.append(self.embedder(torch.Tensor([width])))
303
+ out.append(self.embedder(torch.Tensor([crop_h])))
304
+ out.append(self.embedder(torch.Tensor([crop_w])))
305
+ out.append(self.embedder(torch.Tensor([aesthetic_score])))
306
+ flat = torch.flatten(torch.cat(out)).unsqueeze(dim=0).repeat(clip_pooled.shape[0], 1)
307
+ return torch.cat((clip_pooled.to(flat.device), flat), dim=1)
308
+
309
+ class SDXL(BaseModel):
310
+ def __init__(self, model_config, model_type=ModelType.EPS, device=None):
311
+ super().__init__(model_config, model_type, device=device)
312
+ self.embedder = Timestep(256)
313
+ self.noise_augmentor = CLIPEmbeddingNoiseAugmentation(**{"noise_schedule_config": {"timesteps": 1000, "beta_schedule": "squaredcos_cap_v2"}, "timestep_dim": 1280})
314
+
315
+ def encode_adm(self, **kwargs):
316
+ clip_pooled = sdxl_pooled(kwargs, self.noise_augmentor)
317
+ width = kwargs.get("width", 768)
318
+ height = kwargs.get("height", 768)
319
+ crop_w = kwargs.get("crop_w", 0)
320
+ crop_h = kwargs.get("crop_h", 0)
321
+ target_width = kwargs.get("target_width", width)
322
+ target_height = kwargs.get("target_height", height)
323
+
324
+ out = []
325
+ out.append(self.embedder(torch.Tensor([height])))
326
+ out.append(self.embedder(torch.Tensor([width])))
327
+ out.append(self.embedder(torch.Tensor([crop_h])))
328
+ out.append(self.embedder(torch.Tensor([crop_w])))
329
+ out.append(self.embedder(torch.Tensor([target_height])))
330
+ out.append(self.embedder(torch.Tensor([target_width])))
331
+ flat = torch.flatten(torch.cat(out)).unsqueeze(dim=0).repeat(clip_pooled.shape[0], 1)
332
+ return torch.cat((clip_pooled.to(flat.device), flat), dim=1)
333
+
334
+ class SVD_img2vid(BaseModel):
335
+ def __init__(self, model_config, model_type=ModelType.V_PREDICTION_EDM, device=None):
336
+ super().__init__(model_config, model_type, device=device)
337
+ self.embedder = Timestep(256)
338
+
339
+ def encode_adm(self, **kwargs):
340
+ fps_id = kwargs.get("fps", 6) - 1
341
+ motion_bucket_id = kwargs.get("motion_bucket_id", 127)
342
+ augmentation = kwargs.get("augmentation_level", 0)
343
+
344
+ out = []
345
+ out.append(self.embedder(torch.Tensor([fps_id])))
346
+ out.append(self.embedder(torch.Tensor([motion_bucket_id])))
347
+ out.append(self.embedder(torch.Tensor([augmentation])))
348
+
349
+ flat = torch.flatten(torch.cat(out)).unsqueeze(dim=0)
350
+ return flat
351
+
352
+ def extra_conds(self, **kwargs):
353
+ out = {}
354
+ adm = self.encode_adm(**kwargs)
355
+ if adm is not None:
356
+ out['y'] = comfy.conds.CONDRegular(adm)
357
+
358
+ latent_image = kwargs.get("concat_latent_image", None)
359
+ noise = kwargs.get("noise", None)
360
+ device = kwargs["device"]
361
+
362
+ if latent_image is None:
363
+ latent_image = torch.zeros_like(noise)
364
+
365
+ if latent_image.shape[1:] != noise.shape[1:]:
366
+ latent_image = utils.common_upscale(latent_image, noise.shape[-1], noise.shape[-2], "bilinear", "center")
367
+
368
+ latent_image = utils.resize_to_batch_size(latent_image, noise.shape[0])
369
+
370
+ out['c_concat'] = comfy.conds.CONDNoiseShape(latent_image)
371
+
372
+ cross_attn = kwargs.get("cross_attn", None)
373
+ if cross_attn is not None:
374
+ out['c_crossattn'] = comfy.conds.CONDCrossAttn(cross_attn)
375
+
376
+ if "time_conditioning" in kwargs:
377
+ out["time_context"] = comfy.conds.CONDCrossAttn(kwargs["time_conditioning"])
378
+
379
+ out['num_video_frames'] = comfy.conds.CONDConstant(noise.shape[0])
380
+ return out
381
+
382
+ class Stable_Zero123(BaseModel):
383
+ def __init__(self, model_config, model_type=ModelType.EPS, device=None, cc_projection_weight=None, cc_projection_bias=None):
384
+ super().__init__(model_config, model_type, device=device)
385
+ self.cc_projection = comfy.ops.manual_cast.Linear(cc_projection_weight.shape[1], cc_projection_weight.shape[0], dtype=self.get_dtype(), device=device)
386
+ self.cc_projection.weight.copy_(cc_projection_weight)
387
+ self.cc_projection.bias.copy_(cc_projection_bias)
388
+
389
+ def extra_conds(self, **kwargs):
390
+ out = {}
391
+
392
+ latent_image = kwargs.get("concat_latent_image", None)
393
+ noise = kwargs.get("noise", None)
394
+
395
+ if latent_image is None:
396
+ latent_image = torch.zeros_like(noise)
397
+
398
+ if latent_image.shape[1:] != noise.shape[1:]:
399
+ latent_image = utils.common_upscale(latent_image, noise.shape[-1], noise.shape[-2], "bilinear", "center")
400
+
401
+ latent_image = utils.resize_to_batch_size(latent_image, noise.shape[0])
402
+
403
+ out['c_concat'] = comfy.conds.CONDNoiseShape(latent_image)
404
+
405
+ cross_attn = kwargs.get("cross_attn", None)
406
+ if cross_attn is not None:
407
+ if cross_attn.shape[-1] != 768:
408
+ cross_attn = self.cc_projection(cross_attn)
409
+ out['c_crossattn'] = comfy.conds.CONDCrossAttn(cross_attn)
410
+ return out
411
+
412
+ class SD_X4Upscaler(BaseModel):
413
+ def __init__(self, model_config, model_type=ModelType.V_PREDICTION, device=None):
414
+ super().__init__(model_config, model_type, device=device)
415
+ self.noise_augmentor = ImageConcatWithNoiseAugmentation(noise_schedule_config={"linear_start": 0.0001, "linear_end": 0.02}, max_noise_level=350)
416
+
417
+ def extra_conds(self, **kwargs):
418
+ out = {}
419
+
420
+ image = kwargs.get("concat_image", None)
421
+ noise = kwargs.get("noise", None)
422
+ noise_augment = kwargs.get("noise_augmentation", 0.0)
423
+ device = kwargs["device"]
424
+ seed = kwargs["seed"] - 10
425
+
426
+ noise_level = round((self.noise_augmentor.max_noise_level) * noise_augment)
427
+
428
+ if image is None:
429
+ image = torch.zeros_like(noise)[:,:3]
430
+
431
+ if image.shape[1:] != noise.shape[1:]:
432
+ image = utils.common_upscale(image.to(device), noise.shape[-1], noise.shape[-2], "bilinear", "center")
433
+
434
+ noise_level = torch.tensor([noise_level], device=device)
435
+ if noise_augment > 0:
436
+ image, noise_level = self.noise_augmentor(image.to(device), noise_level=noise_level, seed=seed)
437
+
438
+ image = utils.resize_to_batch_size(image, noise.shape[0])
439
+
440
+ out['c_concat'] = comfy.conds.CONDNoiseShape(image)
441
+ out['y'] = comfy.conds.CONDRegular(noise_level)
442
+ return out
443
+
444
+ class StableCascade_C(BaseModel):
445
+ def __init__(self, model_config, model_type=ModelType.STABLE_CASCADE, device=None):
446
+ super().__init__(model_config, model_type, device=device, unet_model=StageC)
447
+ self.diffusion_model.eval().requires_grad_(False)
448
+
449
+ def extra_conds(self, **kwargs):
450
+ out = {}
451
+ clip_text_pooled = kwargs["pooled_output"]
452
+ if clip_text_pooled is not None:
453
+ out['clip_text_pooled'] = comfy.conds.CONDRegular(clip_text_pooled)
454
+
455
+ if "unclip_conditioning" in kwargs:
456
+ embeds = []
457
+ for unclip_cond in kwargs["unclip_conditioning"]:
458
+ weight = unclip_cond["strength"]
459
+ embeds.append(unclip_cond["clip_vision_output"].image_embeds.unsqueeze(0) * weight)
460
+ clip_img = torch.cat(embeds, dim=1)
461
+ else:
462
+ clip_img = torch.zeros((1, 1, 768))
463
+ out["clip_img"] = comfy.conds.CONDRegular(clip_img)
464
+ out["sca"] = comfy.conds.CONDRegular(torch.zeros((1,)))
465
+ out["crp"] = comfy.conds.CONDRegular(torch.zeros((1,)))
466
+
467
+ cross_attn = kwargs.get("cross_attn", None)
468
+ if cross_attn is not None:
469
+ out['clip_text'] = comfy.conds.CONDCrossAttn(cross_attn)
470
+ return out
471
+
472
+
473
+ class StableCascade_B(BaseModel):
474
+ def __init__(self, model_config, model_type=ModelType.STABLE_CASCADE, device=None):
475
+ super().__init__(model_config, model_type, device=device, unet_model=StageB)
476
+ self.diffusion_model.eval().requires_grad_(False)
477
+
478
+ def extra_conds(self, **kwargs):
479
+ out = {}
480
+ noise = kwargs.get("noise", None)
481
+
482
+ clip_text_pooled = kwargs["pooled_output"]
483
+ if clip_text_pooled is not None:
484
+ out['clip'] = comfy.conds.CONDRegular(clip_text_pooled)
485
+
486
+ #size of prior doesn't really matter if zeros because it gets resized but I still want it to get batched
487
+ prior = kwargs.get("stable_cascade_prior", torch.zeros((1, 16, (noise.shape[2] * 4) // 42, (noise.shape[3] * 4) // 42), dtype=noise.dtype, layout=noise.layout, device=noise.device))
488
+
489
+ out["effnet"] = comfy.conds.CONDRegular(prior)
490
+ out["sca"] = comfy.conds.CONDRegular(torch.zeros((1,)))
491
+ return out
comfy/model_detection.py ADDED
@@ -0,0 +1,363 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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):
32
+ state_dict_keys = list(state_dict.keys())
33
+
34
+ if '{}clf.1.weight'.format(key_prefix) in state_dict_keys: #stable cascade
35
+ unet_config = {}
36
+ text_mapper_name = '{}clip_txt_mapper.weight'.format(key_prefix)
37
+ if text_mapper_name in state_dict_keys:
38
+ unet_config['stable_cascade_stage'] = 'c'
39
+ w = state_dict[text_mapper_name]
40
+ if w.shape[0] == 1536: #stage c lite
41
+ unet_config['c_cond'] = 1536
42
+ unet_config['c_hidden'] = [1536, 1536]
43
+ unet_config['nhead'] = [24, 24]
44
+ unet_config['blocks'] = [[4, 12], [12, 4]]
45
+ elif w.shape[0] == 2048: #stage c full
46
+ unet_config['c_cond'] = 2048
47
+ elif '{}clip_mapper.weight'.format(key_prefix) in state_dict_keys:
48
+ unet_config['stable_cascade_stage'] = 'b'
49
+ w = state_dict['{}down_blocks.1.0.channelwise.0.weight'.format(key_prefix)]
50
+ if w.shape[-1] == 640:
51
+ unet_config['c_hidden'] = [320, 640, 1280, 1280]
52
+ unet_config['nhead'] = [-1, -1, 20, 20]
53
+ unet_config['blocks'] = [[2, 6, 28, 6], [6, 28, 6, 2]]
54
+ unet_config['block_repeat'] = [[1, 1, 1, 1], [3, 3, 2, 2]]
55
+ elif w.shape[-1] == 576: #stage b lite
56
+ unet_config['c_hidden'] = [320, 576, 1152, 1152]
57
+ unet_config['nhead'] = [-1, 9, 18, 18]
58
+ unet_config['blocks'] = [[2, 4, 14, 4], [4, 14, 4, 2]]
59
+ unet_config['block_repeat'] = [[1, 1, 1, 1], [2, 2, 2, 2]]
60
+
61
+ return unet_config
62
+
63
+ unet_config = {
64
+ "use_checkpoint": False,
65
+ "image_size": 32,
66
+ "use_spatial_transformer": True,
67
+ "legacy": False
68
+ }
69
+
70
+ y_input = '{}label_emb.0.0.weight'.format(key_prefix)
71
+ if y_input in state_dict_keys:
72
+ unet_config["num_classes"] = "sequential"
73
+ unet_config["adm_in_channels"] = state_dict[y_input].shape[1]
74
+ else:
75
+ unet_config["adm_in_channels"] = None
76
+
77
+ model_channels = state_dict['{}input_blocks.0.0.weight'.format(key_prefix)].shape[0]
78
+ in_channels = state_dict['{}input_blocks.0.0.weight'.format(key_prefix)].shape[1]
79
+
80
+ out_key = '{}out.2.weight'.format(key_prefix)
81
+ if out_key in state_dict:
82
+ out_channels = state_dict[out_key].shape[0]
83
+ else:
84
+ out_channels = 4
85
+
86
+ num_res_blocks = []
87
+ channel_mult = []
88
+ attention_resolutions = []
89
+ transformer_depth = []
90
+ transformer_depth_output = []
91
+ context_dim = None
92
+ use_linear_in_transformer = False
93
+
94
+ video_model = False
95
+
96
+ current_res = 1
97
+ count = 0
98
+
99
+ last_res_blocks = 0
100
+ last_channel_mult = 0
101
+
102
+ input_block_count = count_blocks(state_dict_keys, '{}input_blocks'.format(key_prefix) + '.{}.')
103
+ for count in range(input_block_count):
104
+ prefix = '{}input_blocks.{}.'.format(key_prefix, count)
105
+ prefix_output = '{}output_blocks.{}.'.format(key_prefix, input_block_count - count - 1)
106
+
107
+ block_keys = sorted(list(filter(lambda a: a.startswith(prefix), state_dict_keys)))
108
+ if len(block_keys) == 0:
109
+ break
110
+
111
+ block_keys_output = sorted(list(filter(lambda a: a.startswith(prefix_output), state_dict_keys)))
112
+
113
+ if "{}0.op.weight".format(prefix) in block_keys: #new layer
114
+ num_res_blocks.append(last_res_blocks)
115
+ channel_mult.append(last_channel_mult)
116
+
117
+ current_res *= 2
118
+ last_res_blocks = 0
119
+ last_channel_mult = 0
120
+ out = calculate_transformer_depth(prefix_output, state_dict_keys, state_dict)
121
+ if out is not None:
122
+ transformer_depth_output.append(out[0])
123
+ else:
124
+ transformer_depth_output.append(0)
125
+ else:
126
+ res_block_prefix = "{}0.in_layers.0.weight".format(prefix)
127
+ if res_block_prefix in block_keys:
128
+ last_res_blocks += 1
129
+ last_channel_mult = state_dict["{}0.out_layers.3.weight".format(prefix)].shape[0] // model_channels
130
+
131
+ out = calculate_transformer_depth(prefix, state_dict_keys, state_dict)
132
+ if out is not None:
133
+ transformer_depth.append(out[0])
134
+ if context_dim is None:
135
+ context_dim = out[1]
136
+ use_linear_in_transformer = out[2]
137
+ video_model = out[3]
138
+ else:
139
+ transformer_depth.append(0)
140
+
141
+ res_block_prefix = "{}0.in_layers.0.weight".format(prefix_output)
142
+ if res_block_prefix in block_keys_output:
143
+ out = calculate_transformer_depth(prefix_output, state_dict_keys, state_dict)
144
+ if out is not None:
145
+ transformer_depth_output.append(out[0])
146
+ else:
147
+ transformer_depth_output.append(0)
148
+
149
+
150
+ num_res_blocks.append(last_res_blocks)
151
+ channel_mult.append(last_channel_mult)
152
+ if "{}middle_block.1.proj_in.weight".format(key_prefix) in state_dict_keys:
153
+ transformer_depth_middle = count_blocks(state_dict_keys, '{}middle_block.1.transformer_blocks.'.format(key_prefix) + '{}')
154
+ elif "{}middle_block.0.in_layers.0.weight".format(key_prefix) in state_dict_keys:
155
+ transformer_depth_middle = -1
156
+ else:
157
+ transformer_depth_middle = -2
158
+
159
+ unet_config["in_channels"] = in_channels
160
+ unet_config["out_channels"] = out_channels
161
+ unet_config["model_channels"] = model_channels
162
+ unet_config["num_res_blocks"] = num_res_blocks
163
+ unet_config["transformer_depth"] = transformer_depth
164
+ unet_config["transformer_depth_output"] = transformer_depth_output
165
+ unet_config["channel_mult"] = channel_mult
166
+ unet_config["transformer_depth_middle"] = transformer_depth_middle
167
+ unet_config['use_linear_in_transformer'] = use_linear_in_transformer
168
+ unet_config["context_dim"] = context_dim
169
+
170
+ if video_model:
171
+ unet_config["extra_ff_mix_layer"] = True
172
+ unet_config["use_spatial_context"] = True
173
+ unet_config["merge_strategy"] = "learned_with_images"
174
+ unet_config["merge_factor"] = 0.0
175
+ unet_config["video_kernel_size"] = [3, 1, 1]
176
+ unet_config["use_temporal_resblock"] = True
177
+ unet_config["use_temporal_attention"] = True
178
+ else:
179
+ unet_config["use_temporal_resblock"] = False
180
+ unet_config["use_temporal_attention"] = False
181
+
182
+ return unet_config
183
+
184
+ def model_config_from_unet_config(unet_config):
185
+ for model_config in comfy.supported_models.models:
186
+ if model_config.matches(unet_config):
187
+ return model_config(unet_config)
188
+
189
+ print("no match", unet_config)
190
+ return None
191
+
192
+ def model_config_from_unet(state_dict, unet_key_prefix, use_base_if_no_match=False):
193
+ unet_config = detect_unet_config(state_dict, unet_key_prefix)
194
+ model_config = model_config_from_unet_config(unet_config)
195
+ if model_config is None and use_base_if_no_match:
196
+ return comfy.supported_models_base.BASE(unet_config)
197
+ else:
198
+ return model_config
199
+
200
+ def convert_config(unet_config):
201
+ new_config = unet_config.copy()
202
+ num_res_blocks = new_config.get("num_res_blocks", None)
203
+ channel_mult = new_config.get("channel_mult", None)
204
+
205
+ if isinstance(num_res_blocks, int):
206
+ num_res_blocks = len(channel_mult) * [num_res_blocks]
207
+
208
+ if "attention_resolutions" in new_config:
209
+ attention_resolutions = new_config.pop("attention_resolutions")
210
+ transformer_depth = new_config.get("transformer_depth", None)
211
+ transformer_depth_middle = new_config.get("transformer_depth_middle", None)
212
+
213
+ if isinstance(transformer_depth, int):
214
+ transformer_depth = len(channel_mult) * [transformer_depth]
215
+ if transformer_depth_middle is None:
216
+ transformer_depth_middle = transformer_depth[-1]
217
+ t_in = []
218
+ t_out = []
219
+ s = 1
220
+ for i in range(len(num_res_blocks)):
221
+ res = num_res_blocks[i]
222
+ d = 0
223
+ if s in attention_resolutions:
224
+ d = transformer_depth[i]
225
+
226
+ t_in += [d] * res
227
+ t_out += [d] * (res + 1)
228
+ s *= 2
229
+ transformer_depth = t_in
230
+ transformer_depth_output = t_out
231
+ new_config["transformer_depth"] = t_in
232
+ new_config["transformer_depth_output"] = t_out
233
+ new_config["transformer_depth_middle"] = transformer_depth_middle
234
+
235
+ new_config["num_res_blocks"] = num_res_blocks
236
+ return new_config
237
+
238
+
239
+ def unet_config_from_diffusers_unet(state_dict, dtype=None):
240
+ match = {}
241
+ transformer_depth = []
242
+
243
+ attn_res = 1
244
+ down_blocks = count_blocks(state_dict, "down_blocks.{}")
245
+ for i in range(down_blocks):
246
+ attn_blocks = count_blocks(state_dict, "down_blocks.{}.attentions.".format(i) + '{}')
247
+ res_blocks = count_blocks(state_dict, "down_blocks.{}.resnets.".format(i) + '{}')
248
+ for ab in range(attn_blocks):
249
+ transformer_count = count_blocks(state_dict, "down_blocks.{}.attentions.{}.transformer_blocks.".format(i, ab) + '{}')
250
+ transformer_depth.append(transformer_count)
251
+ if transformer_count > 0:
252
+ match["context_dim"] = state_dict["down_blocks.{}.attentions.{}.transformer_blocks.0.attn2.to_k.weight".format(i, ab)].shape[1]
253
+
254
+ attn_res *= 2
255
+ if attn_blocks == 0:
256
+ for i in range(res_blocks):
257
+ transformer_depth.append(0)
258
+
259
+ match["transformer_depth"] = transformer_depth
260
+
261
+ match["model_channels"] = state_dict["conv_in.weight"].shape[0]
262
+ match["in_channels"] = state_dict["conv_in.weight"].shape[1]
263
+ match["adm_in_channels"] = None
264
+ if "class_embedding.linear_1.weight" in state_dict:
265
+ match["adm_in_channels"] = state_dict["class_embedding.linear_1.weight"].shape[1]
266
+ elif "add_embedding.linear_1.weight" in state_dict:
267
+ match["adm_in_channels"] = state_dict["add_embedding.linear_1.weight"].shape[1]
268
+
269
+ SDXL = {'use_checkpoint': False, 'image_size': 32, 'out_channels': 4, 'use_spatial_transformer': True, 'legacy': False,
270
+ 'num_classes': 'sequential', 'adm_in_channels': 2816, 'dtype': dtype, 'in_channels': 4, 'model_channels': 320,
271
+ 'num_res_blocks': [2, 2, 2], 'transformer_depth': [0, 0, 2, 2, 10, 10], 'channel_mult': [1, 2, 4], 'transformer_depth_middle': 10,
272
+ 'use_linear_in_transformer': True, 'context_dim': 2048, 'num_head_channels': 64, 'transformer_depth_output': [0, 0, 0, 2, 2, 2, 10, 10, 10],
273
+ 'use_temporal_attention': False, 'use_temporal_resblock': False}
274
+
275
+ SDXL_refiner = {'use_checkpoint': False, 'image_size': 32, 'out_channels': 4, 'use_spatial_transformer': True, 'legacy': False,
276
+ 'num_classes': 'sequential', 'adm_in_channels': 2560, 'dtype': dtype, 'in_channels': 4, 'model_channels': 384,
277
+ '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,
278
+ '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],
279
+ 'use_temporal_attention': False, 'use_temporal_resblock': False}
280
+
281
+ SD21 = {'use_checkpoint': False, 'image_size': 32, 'out_channels': 4, 'use_spatial_transformer': True, 'legacy': False,
282
+ 'adm_in_channels': None, 'dtype': dtype, 'in_channels': 4, 'model_channels': 320, 'num_res_blocks': [2, 2, 2, 2],
283
+ '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,
284
+ 'context_dim': 1024, 'num_head_channels': 64, 'transformer_depth_output': [1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0],
285
+ 'use_temporal_attention': False, 'use_temporal_resblock': False}
286
+
287
+ SD21_uncliph = {'use_checkpoint': False, 'image_size': 32, 'out_channels': 4, 'use_spatial_transformer': True, 'legacy': False,
288
+ 'num_classes': 'sequential', 'adm_in_channels': 2048, 'dtype': dtype, 'in_channels': 4, 'model_channels': 320,
289
+ '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,
290
+ '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],
291
+ 'use_temporal_attention': False, 'use_temporal_resblock': False}
292
+
293
+ SD21_unclipl = {'use_checkpoint': False, 'image_size': 32, 'out_channels': 4, 'use_spatial_transformer': True, 'legacy': False,
294
+ 'num_classes': 'sequential', 'adm_in_channels': 1536, 'dtype': dtype, 'in_channels': 4, 'model_channels': 320,
295
+ '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,
296
+ '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],
297
+ 'use_temporal_attention': False, 'use_temporal_resblock': False}
298
+
299
+ SD15 = {'use_checkpoint': False, 'image_size': 32, 'out_channels': 4, 'use_spatial_transformer': True, 'legacy': False, 'adm_in_channels': None,
300
+ '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],
301
+ 'channel_mult': [1, 2, 4, 4], 'transformer_depth_middle': 1, 'use_linear_in_transformer': False, 'context_dim': 768, 'num_heads': 8,
302
+ 'transformer_depth_output': [1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0],
303
+ 'use_temporal_attention': False, 'use_temporal_resblock': False}
304
+
305
+ SDXL_mid_cnet = {'use_checkpoint': False, 'image_size': 32, 'out_channels': 4, 'use_spatial_transformer': True, 'legacy': False,
306
+ 'num_classes': 'sequential', 'adm_in_channels': 2816, 'dtype': dtype, 'in_channels': 4, 'model_channels': 320,
307
+ 'num_res_blocks': [2, 2, 2], 'transformer_depth': [0, 0, 0, 0, 1, 1], 'channel_mult': [1, 2, 4], 'transformer_depth_middle': 1,
308
+ 'use_linear_in_transformer': True, 'context_dim': 2048, 'num_head_channels': 64, 'transformer_depth_output': [0, 0, 0, 0, 0, 0, 1, 1, 1],
309
+ 'use_temporal_attention': False, 'use_temporal_resblock': False}
310
+
311
+ SDXL_small_cnet = {'use_checkpoint': False, 'image_size': 32, 'out_channels': 4, 'use_spatial_transformer': True, 'legacy': False,
312
+ 'num_classes': 'sequential', 'adm_in_channels': 2816, 'dtype': dtype, 'in_channels': 4, 'model_channels': 320,
313
+ 'num_res_blocks': [2, 2, 2], 'transformer_depth': [0, 0, 0, 0, 0, 0], 'channel_mult': [1, 2, 4], 'transformer_depth_middle': 0,
314
+ 'use_linear_in_transformer': True, 'num_head_channels': 64, 'context_dim': 1, 'transformer_depth_output': [0, 0, 0, 0, 0, 0, 0, 0, 0],
315
+ 'use_temporal_attention': False, 'use_temporal_resblock': False}
316
+
317
+ SDXL_diffusers_inpaint = {'use_checkpoint': False, 'image_size': 32, 'out_channels': 4, 'use_spatial_transformer': True, 'legacy': False,
318
+ 'num_classes': 'sequential', 'adm_in_channels': 2816, 'dtype': dtype, 'in_channels': 9, 'model_channels': 320,
319
+ 'num_res_blocks': [2, 2, 2], 'transformer_depth': [0, 0, 2, 2, 10, 10], 'channel_mult': [1, 2, 4], 'transformer_depth_middle': 10,
320
+ 'use_linear_in_transformer': True, 'context_dim': 2048, 'num_head_channels': 64, 'transformer_depth_output': [0, 0, 0, 2, 2, 2, 10, 10, 10],
321
+ 'use_temporal_attention': False, 'use_temporal_resblock': False}
322
+
323
+ SSD_1B = {'use_checkpoint': False, 'image_size': 32, 'out_channels': 4, 'use_spatial_transformer': True, 'legacy': False,
324
+ 'num_classes': 'sequential', 'adm_in_channels': 2816, 'dtype': dtype, 'in_channels': 4, 'model_channels': 320,
325
+ '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],
326
+ 'channel_mult': [1, 2, 4], 'transformer_depth_middle': -1, 'use_linear_in_transformer': True, 'context_dim': 2048, 'num_head_channels': 64,
327
+ 'use_temporal_attention': False, 'use_temporal_resblock': False}
328
+
329
+ Segmind_Vega = {'use_checkpoint': False, 'image_size': 32, 'out_channels': 4, 'use_spatial_transformer': True, 'legacy': False,
330
+ 'num_classes': 'sequential', 'adm_in_channels': 2816, 'dtype': dtype, 'in_channels': 4, 'model_channels': 320,
331
+ '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],
332
+ 'channel_mult': [1, 2, 4], 'transformer_depth_middle': -1, 'use_linear_in_transformer': True, 'context_dim': 2048, 'num_head_channels': 64,
333
+ 'use_temporal_attention': False, 'use_temporal_resblock': False}
334
+
335
+ KOALA_700M = {'use_checkpoint': False, 'image_size': 32, 'out_channels': 4, 'use_spatial_transformer': True, 'legacy': False,
336
+ 'num_classes': 'sequential', 'adm_in_channels': 2816, 'dtype': dtype, 'in_channels': 4, 'model_channels': 320,
337
+ 'num_res_blocks': [1, 1, 1], 'transformer_depth': [0, 2, 5], 'transformer_depth_output': [0, 0, 2, 2, 5, 5],
338
+ 'channel_mult': [1, 2, 4], 'transformer_depth_middle': -2, 'use_linear_in_transformer': True, 'context_dim': 2048, 'num_head_channels': 64,
339
+ 'use_temporal_attention': False, 'use_temporal_resblock': False}
340
+
341
+ KOALA_1B = {'use_checkpoint': False, 'image_size': 32, 'out_channels': 4, 'use_spatial_transformer': True, 'legacy': False,
342
+ 'num_classes': 'sequential', 'adm_in_channels': 2816, 'dtype': dtype, 'in_channels': 4, 'model_channels': 320,
343
+ 'num_res_blocks': [1, 1, 1], 'transformer_depth': [0, 2, 6], 'transformer_depth_output': [0, 0, 2, 2, 6, 6],
344
+ 'channel_mult': [1, 2, 4], 'transformer_depth_middle': 6, 'use_linear_in_transformer': True, 'context_dim': 2048, 'num_head_channels': 64,
345
+ 'use_temporal_attention': False, 'use_temporal_resblock': False}
346
+
347
+ supported_models = [SDXL, SDXL_refiner, SD21, SD15, SD21_uncliph, SD21_unclipl, SDXL_mid_cnet, SDXL_small_cnet, SDXL_diffusers_inpaint, SSD_1B, Segmind_Vega, KOALA_700M, KOALA_1B]
348
+
349
+ for unet_config in supported_models:
350
+ matches = True
351
+ for k in match:
352
+ if match[k] != unet_config[k]:
353
+ matches = False
354
+ break
355
+ if matches:
356
+ return convert_config(unet_config)
357
+ return None
358
+
359
+ def model_config_from_diffusers_unet(state_dict):
360
+ unet_config = unet_config_from_diffusers_unet(state_dict)
361
+ if unet_config is not None:
362
+ return model_config_from_unet_config(unet_config)
363
+ return None
comfy/model_management.py ADDED
@@ -0,0 +1,859 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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, supported_dtypes=[torch.float16, torch.bfloat16, torch.float32]):
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
+ if torch.float16 in supported_dtypes:
501
+ return torch.float16
502
+ if should_use_bf16(device, model_params=model_params, manual_cast=True):
503
+ if torch.bfloat16 in supported_dtypes:
504
+ return torch.bfloat16
505
+ return torch.float32
506
+
507
+ # None means no manual cast
508
+ def unet_manual_cast(weight_dtype, inference_device, supported_dtypes=[torch.float16, torch.bfloat16, torch.float32]):
509
+ if weight_dtype == torch.float32:
510
+ return None
511
+
512
+ fp16_supported = should_use_fp16(inference_device, prioritize_performance=False)
513
+ if fp16_supported and weight_dtype == torch.float16:
514
+ return None
515
+
516
+ bf16_supported = should_use_bf16(inference_device)
517
+ if bf16_supported and weight_dtype == torch.bfloat16:
518
+ return None
519
+
520
+ if fp16_supported and torch.float16 in supported_dtypes:
521
+ return torch.float16
522
+
523
+ elif bf16_supported and torch.bfloat16 in supported_dtypes:
524
+ return torch.bfloat16
525
+ else:
526
+ return torch.float32
527
+
528
+ def text_encoder_offload_device():
529
+ if args.gpu_only:
530
+ return get_torch_device()
531
+ else:
532
+ return torch.device("cpu")
533
+
534
+ def text_encoder_device():
535
+ if args.gpu_only:
536
+ return get_torch_device()
537
+ elif vram_state == VRAMState.HIGH_VRAM or vram_state == VRAMState.NORMAL_VRAM:
538
+ if is_intel_xpu():
539
+ return torch.device("cpu")
540
+ if should_use_fp16(prioritize_performance=False):
541
+ return get_torch_device()
542
+ else:
543
+ return torch.device("cpu")
544
+ else:
545
+ return torch.device("cpu")
546
+
547
+ def text_encoder_dtype(device=None):
548
+ if args.fp8_e4m3fn_text_enc:
549
+ return torch.float8_e4m3fn
550
+ elif args.fp8_e5m2_text_enc:
551
+ return torch.float8_e5m2
552
+ elif args.fp16_text_enc:
553
+ return torch.float16
554
+ elif args.fp32_text_enc:
555
+ return torch.float32
556
+
557
+ if is_device_cpu(device):
558
+ return torch.float16
559
+
560
+ return torch.float16
561
+
562
+
563
+ def intermediate_device():
564
+ if args.gpu_only:
565
+ return get_torch_device()
566
+ else:
567
+ return torch.device("cpu")
568
+
569
+ def vae_device():
570
+ if args.cpu_vae:
571
+ return torch.device("cpu")
572
+ return get_torch_device()
573
+
574
+ def vae_offload_device():
575
+ if args.gpu_only:
576
+ return get_torch_device()
577
+ else:
578
+ return torch.device("cpu")
579
+
580
+ def vae_dtype():
581
+ global VAE_DTYPE
582
+ return VAE_DTYPE
583
+
584
+ def get_autocast_device(dev):
585
+ if hasattr(dev, 'type'):
586
+ return dev.type
587
+ return "cuda"
588
+
589
+ def supports_dtype(device, dtype): #TODO
590
+ if dtype == torch.float32:
591
+ return True
592
+ if is_device_cpu(device):
593
+ return False
594
+ if dtype == torch.float16:
595
+ return True
596
+ if dtype == torch.bfloat16:
597
+ return True
598
+ return False
599
+
600
+ def device_supports_non_blocking(device):
601
+ if is_device_mps(device):
602
+ return False #pytorch bug? mps doesn't support non blocking
603
+ return True
604
+
605
+ def cast_to_device(tensor, device, dtype, copy=False):
606
+ device_supports_cast = False
607
+ if tensor.dtype == torch.float32 or tensor.dtype == torch.float16:
608
+ device_supports_cast = True
609
+ elif tensor.dtype == torch.bfloat16:
610
+ if hasattr(device, 'type') and device.type.startswith("cuda"):
611
+ device_supports_cast = True
612
+ elif is_intel_xpu():
613
+ device_supports_cast = True
614
+
615
+ non_blocking = device_supports_non_blocking(device)
616
+
617
+ if device_supports_cast:
618
+ if copy:
619
+ if tensor.device == device:
620
+ return tensor.to(dtype, copy=copy, non_blocking=non_blocking)
621
+ return tensor.to(device, copy=copy, non_blocking=non_blocking).to(dtype, non_blocking=non_blocking)
622
+ else:
623
+ return tensor.to(device, non_blocking=non_blocking).to(dtype, non_blocking=non_blocking)
624
+ else:
625
+ return tensor.to(device, dtype, copy=copy, non_blocking=non_blocking)
626
+
627
+ def xformers_enabled():
628
+ global directml_enabled
629
+ global cpu_state
630
+ if cpu_state != CPUState.GPU:
631
+ return False
632
+ if is_intel_xpu():
633
+ return False
634
+ if directml_enabled:
635
+ return False
636
+ return XFORMERS_IS_AVAILABLE
637
+
638
+
639
+ def xformers_enabled_vae():
640
+ enabled = xformers_enabled()
641
+ if not enabled:
642
+ return False
643
+
644
+ return XFORMERS_ENABLED_VAE
645
+
646
+ def pytorch_attention_enabled():
647
+ global ENABLE_PYTORCH_ATTENTION
648
+ return ENABLE_PYTORCH_ATTENTION
649
+
650
+ def pytorch_attention_flash_attention():
651
+ global ENABLE_PYTORCH_ATTENTION
652
+ if ENABLE_PYTORCH_ATTENTION:
653
+ #TODO: more reliable way of checking for flash attention?
654
+ if is_nvidia(): #pytorch flash attention only works on Nvidia
655
+ return True
656
+ return False
657
+
658
+ def get_free_memory(dev=None, torch_free_too=False):
659
+ global directml_enabled
660
+ if dev is None:
661
+ dev = get_torch_device()
662
+
663
+ if hasattr(dev, 'type') and (dev.type == 'cpu' or dev.type == 'mps'):
664
+ mem_free_total = psutil.virtual_memory().available
665
+ mem_free_torch = mem_free_total
666
+ else:
667
+ if directml_enabled:
668
+ mem_free_total = 1024 * 1024 * 1024 #TODO
669
+ mem_free_torch = mem_free_total
670
+ elif is_intel_xpu():
671
+ stats = torch.xpu.memory_stats(dev)
672
+ mem_active = stats['active_bytes.all.current']
673
+ mem_allocated = stats['allocated_bytes.all.current']
674
+ mem_reserved = stats['reserved_bytes.all.current']
675
+ mem_free_torch = mem_reserved - mem_active
676
+ mem_free_total = torch.xpu.get_device_properties(dev).total_memory - mem_allocated
677
+ else:
678
+ stats = torch.cuda.memory_stats(dev)
679
+ mem_active = stats['active_bytes.all.current']
680
+ mem_reserved = stats['reserved_bytes.all.current']
681
+ mem_free_cuda, _ = torch.cuda.mem_get_info(dev)
682
+ mem_free_torch = mem_reserved - mem_active
683
+ mem_free_total = mem_free_cuda + mem_free_torch
684
+
685
+ if torch_free_too:
686
+ return (mem_free_total, mem_free_torch)
687
+ else:
688
+ return mem_free_total
689
+
690
+ def cpu_mode():
691
+ global cpu_state
692
+ return cpu_state == CPUState.CPU
693
+
694
+ def mps_mode():
695
+ global cpu_state
696
+ return cpu_state == CPUState.MPS
697
+
698
+ def is_device_type(device, type):
699
+ if hasattr(device, 'type'):
700
+ if (device.type == type):
701
+ return True
702
+ return False
703
+
704
+ def is_device_cpu(device):
705
+ return is_device_type(device, 'cpu')
706
+
707
+ def is_device_mps(device):
708
+ return is_device_type(device, 'mps')
709
+
710
+ def is_device_cuda(device):
711
+ return is_device_type(device, 'cuda')
712
+
713
+ def should_use_fp16(device=None, model_params=0, prioritize_performance=True, manual_cast=False):
714
+ global directml_enabled
715
+
716
+ if device is not None:
717
+ if is_device_cpu(device):
718
+ return False
719
+
720
+ if FORCE_FP16:
721
+ return True
722
+
723
+ if device is not None:
724
+ if is_device_mps(device):
725
+ return True
726
+
727
+ if FORCE_FP32:
728
+ return False
729
+
730
+ if directml_enabled:
731
+ return False
732
+
733
+ if mps_mode():
734
+ return True
735
+
736
+ if cpu_mode():
737
+ return False
738
+
739
+ if is_intel_xpu():
740
+ return True
741
+
742
+ if torch.version.hip:
743
+ return True
744
+
745
+ props = torch.cuda.get_device_properties("cuda")
746
+ if props.major >= 8:
747
+ return True
748
+
749
+ if props.major < 6:
750
+ return False
751
+
752
+ fp16_works = False
753
+ #FP16 is confirmed working on a 1080 (GP104) but it's a bit slower than FP32 so it should only be enabled
754
+ #when the model doesn't actually fit on the card
755
+ #TODO: actually test if GP106 and others have the same type of behavior
756
+ nvidia_10_series = ["1080", "1070", "titan x", "p3000", "p3200", "p4000", "p4200", "p5000", "p5200", "p6000", "1060", "1050", "p40", "p100", "p6", "p4"]
757
+ for x in nvidia_10_series:
758
+ if x in props.name.lower():
759
+ fp16_works = True
760
+
761
+ if fp16_works or manual_cast:
762
+ free_model_memory = (get_free_memory() * 0.9 - minimum_inference_memory())
763
+ if (not prioritize_performance) or model_params * 4 > free_model_memory:
764
+ return True
765
+
766
+ if props.major < 7:
767
+ return False
768
+
769
+ #FP16 is just broken on these cards
770
+ nvidia_16_series = ["1660", "1650", "1630", "T500", "T550", "T600", "MX550", "MX450", "CMP 30HX", "T2000", "T1000", "T1200"]
771
+ for x in nvidia_16_series:
772
+ if x in props.name:
773
+ return False
774
+
775
+ return True
776
+
777
+ def should_use_bf16(device=None, model_params=0, prioritize_performance=True, manual_cast=False):
778
+ if device is not None:
779
+ if is_device_cpu(device): #TODO ? bf16 works on CPU but is extremely slow
780
+ return False
781
+
782
+ if device is not None: #TODO not sure about mps bf16 support
783
+ if is_device_mps(device):
784
+ return False
785
+
786
+ if FORCE_FP32:
787
+ return False
788
+
789
+ if directml_enabled:
790
+ return False
791
+
792
+ if cpu_mode() or mps_mode():
793
+ return False
794
+
795
+ if is_intel_xpu():
796
+ return True
797
+
798
+ if device is None:
799
+ device = torch.device("cuda")
800
+
801
+ props = torch.cuda.get_device_properties(device)
802
+ if props.major >= 8:
803
+ return True
804
+
805
+ bf16_works = torch.cuda.is_bf16_supported()
806
+
807
+ if bf16_works or manual_cast:
808
+ free_model_memory = (get_free_memory() * 0.9 - minimum_inference_memory())
809
+ if (not prioritize_performance) or model_params * 4 > free_model_memory:
810
+ return True
811
+
812
+ return False
813
+
814
+ def soft_empty_cache(force=False):
815
+ global cpu_state
816
+ if cpu_state == CPUState.MPS:
817
+ torch.mps.empty_cache()
818
+ elif is_intel_xpu():
819
+ torch.xpu.empty_cache()
820
+ elif torch.cuda.is_available():
821
+ if force or is_nvidia(): #This seems to make things worse on ROCm so I only do it for cuda
822
+ torch.cuda.empty_cache()
823
+ torch.cuda.ipc_collect()
824
+
825
+ def unload_all_models():
826
+ free_memory(1e30, get_torch_device())
827
+
828
+
829
+ def resolve_lowvram_weight(weight, model, key): #TODO: remove
830
+ return weight
831
+
832
+ #TODO: might be cleaner to put this somewhere else
833
+ import threading
834
+
835
+ class InterruptProcessingException(Exception):
836
+ pass
837
+
838
+ interrupt_processing_mutex = threading.RLock()
839
+
840
+ interrupt_processing = False
841
+ def interrupt_current_processing(value=True):
842
+ global interrupt_processing
843
+ global interrupt_processing_mutex
844
+ with interrupt_processing_mutex:
845
+ interrupt_processing = value
846
+
847
+ def processing_interrupted():
848
+ global interrupt_processing
849
+ global interrupt_processing_mutex
850
+ with interrupt_processing_mutex:
851
+ return interrupt_processing
852
+
853
+ def throw_exception_if_processing_interrupted():
854
+ global interrupt_processing
855
+ global interrupt_processing_mutex
856
+ with interrupt_processing_mutex:
857
+ if interrupt_processing:
858
+ interrupt_processing = False
859
+ raise InterruptProcessingException()
comfy/model_patcher.py ADDED
@@ -0,0 +1,359 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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_denoise_mask_function(self, denoise_mask_function):
71
+ self.model_options["denoise_mask_function"] = denoise_mask_function
72
+
73
+ def set_model_patch(self, patch, name):
74
+ to = self.model_options["transformer_options"]
75
+ if "patches" not in to:
76
+ to["patches"] = {}
77
+ to["patches"][name] = to["patches"].get(name, []) + [patch]
78
+
79
+ def set_model_patch_replace(self, patch, name, block_name, number, transformer_index=None):
80
+ to = self.model_options["transformer_options"]
81
+ if "patches_replace" not in to:
82
+ to["patches_replace"] = {}
83
+ if name not in to["patches_replace"]:
84
+ to["patches_replace"][name] = {}
85
+ if transformer_index is not None:
86
+ block = (block_name, number, transformer_index)
87
+ else:
88
+ block = (block_name, number)
89
+ to["patches_replace"][name][block] = patch
90
+
91
+ def set_model_attn1_patch(self, patch):
92
+ self.set_model_patch(patch, "attn1_patch")
93
+
94
+ def set_model_attn2_patch(self, patch):
95
+ self.set_model_patch(patch, "attn2_patch")
96
+
97
+ def set_model_attn1_replace(self, patch, block_name, number, transformer_index=None):
98
+ self.set_model_patch_replace(patch, "attn1", block_name, number, transformer_index)
99
+
100
+ def set_model_attn2_replace(self, patch, block_name, number, transformer_index=None):
101
+ self.set_model_patch_replace(patch, "attn2", block_name, number, transformer_index)
102
+
103
+ def set_model_attn1_output_patch(self, patch):
104
+ self.set_model_patch(patch, "attn1_output_patch")
105
+
106
+ def set_model_attn2_output_patch(self, patch):
107
+ self.set_model_patch(patch, "attn2_output_patch")
108
+
109
+ def set_model_input_block_patch(self, patch):
110
+ self.set_model_patch(patch, "input_block_patch")
111
+
112
+ def set_model_input_block_patch_after_skip(self, patch):
113
+ self.set_model_patch(patch, "input_block_patch_after_skip")
114
+
115
+ def set_model_output_block_patch(self, patch):
116
+ self.set_model_patch(patch, "output_block_patch")
117
+
118
+ def add_object_patch(self, name, obj):
119
+ self.object_patches[name] = obj
120
+
121
+ def model_patches_to(self, device):
122
+ to = self.model_options["transformer_options"]
123
+ if "patches" in to:
124
+ patches = to["patches"]
125
+ for name in patches:
126
+ patch_list = patches[name]
127
+ for i in range(len(patch_list)):
128
+ if hasattr(patch_list[i], "to"):
129
+ patch_list[i] = patch_list[i].to(device)
130
+ if "patches_replace" in to:
131
+ patches = to["patches_replace"]
132
+ for name in patches:
133
+ patch_list = patches[name]
134
+ for k in patch_list:
135
+ if hasattr(patch_list[k], "to"):
136
+ patch_list[k] = patch_list[k].to(device)
137
+ if "model_function_wrapper" in self.model_options:
138
+ wrap_func = self.model_options["model_function_wrapper"]
139
+ if hasattr(wrap_func, "to"):
140
+ self.model_options["model_function_wrapper"] = wrap_func.to(device)
141
+
142
+ def model_dtype(self):
143
+ if hasattr(self.model, "get_dtype"):
144
+ return self.model.get_dtype()
145
+
146
+ def add_patches(self, patches, strength_patch=1.0, strength_model=1.0):
147
+ p = set()
148
+ for k in patches:
149
+ if k in self.model_keys:
150
+ p.add(k)
151
+ current_patches = self.patches.get(k, [])
152
+ current_patches.append((strength_patch, patches[k], strength_model))
153
+ self.patches[k] = current_patches
154
+
155
+ return list(p)
156
+
157
+ def get_key_patches(self, filter_prefix=None):
158
+ comfy.model_management.unload_model_clones(self)
159
+ model_sd = self.model_state_dict()
160
+ p = {}
161
+ for k in model_sd:
162
+ if filter_prefix is not None:
163
+ if not k.startswith(filter_prefix):
164
+ continue
165
+ if k in self.patches:
166
+ p[k] = [model_sd[k]] + self.patches[k]
167
+ else:
168
+ p[k] = (model_sd[k],)
169
+ return p
170
+
171
+ def model_state_dict(self, filter_prefix=None):
172
+ sd = self.model.state_dict()
173
+ keys = list(sd.keys())
174
+ if filter_prefix is not None:
175
+ for k in keys:
176
+ if not k.startswith(filter_prefix):
177
+ sd.pop(k)
178
+ return sd
179
+
180
+ def patch_model(self, device_to=None, patch_weights=True):
181
+ for k in self.object_patches:
182
+ old = comfy.utils.set_attr(self.model, k, self.object_patches[k])
183
+ if k not in self.object_patches_backup:
184
+ self.object_patches_backup[k] = old
185
+
186
+ if patch_weights:
187
+ model_sd = self.model_state_dict()
188
+ for key in self.patches:
189
+ if key not in model_sd:
190
+ print("could not patch. key doesn't exist in model:", key)
191
+ continue
192
+
193
+ weight = model_sd[key]
194
+
195
+ inplace_update = self.weight_inplace_update
196
+
197
+ if key not in self.backup:
198
+ self.backup[key] = weight.to(device=self.offload_device, copy=inplace_update)
199
+
200
+ if device_to is not None:
201
+ temp_weight = comfy.model_management.cast_to_device(weight, device_to, torch.float32, copy=True)
202
+ else:
203
+ temp_weight = weight.to(torch.float32, copy=True)
204
+ out_weight = self.calculate_weight(self.patches[key], temp_weight, key).to(weight.dtype)
205
+ if inplace_update:
206
+ comfy.utils.copy_to_param(self.model, key, out_weight)
207
+ else:
208
+ comfy.utils.set_attr_param(self.model, key, out_weight)
209
+ del temp_weight
210
+
211
+ if device_to is not None:
212
+ self.model.to(device_to)
213
+ self.current_device = device_to
214
+
215
+ return self.model
216
+
217
+ def calculate_weight(self, patches, weight, key):
218
+ for p in patches:
219
+ alpha = p[0]
220
+ v = p[1]
221
+ strength_model = p[2]
222
+
223
+ if strength_model != 1.0:
224
+ weight *= strength_model
225
+
226
+ if isinstance(v, list):
227
+ v = (self.calculate_weight(v[1:], v[0].clone(), key), )
228
+
229
+ if len(v) == 1:
230
+ patch_type = "diff"
231
+ elif len(v) == 2:
232
+ patch_type = v[0]
233
+ v = v[1]
234
+
235
+ if patch_type == "diff":
236
+ w1 = v[0]
237
+ if alpha != 0.0:
238
+ if w1.shape != weight.shape:
239
+ print("WARNING SHAPE MISMATCH {} WEIGHT NOT MERGED {} != {}".format(key, w1.shape, weight.shape))
240
+ else:
241
+ weight += alpha * comfy.model_management.cast_to_device(w1, weight.device, weight.dtype)
242
+ elif patch_type == "lora": #lora/locon
243
+ mat1 = comfy.model_management.cast_to_device(v[0], weight.device, torch.float32)
244
+ mat2 = comfy.model_management.cast_to_device(v[1], weight.device, torch.float32)
245
+ if v[2] is not None:
246
+ alpha *= v[2] / mat2.shape[0]
247
+ if v[3] is not None:
248
+ #locon mid weights, hopefully the math is fine because I didn't properly test it
249
+ mat3 = comfy.model_management.cast_to_device(v[3], weight.device, torch.float32)
250
+ final_shape = [mat2.shape[1], mat2.shape[0], mat3.shape[2], mat3.shape[3]]
251
+ 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)
252
+ try:
253
+ weight += (alpha * torch.mm(mat1.flatten(start_dim=1), mat2.flatten(start_dim=1))).reshape(weight.shape).type(weight.dtype)
254
+ except Exception as e:
255
+ print("ERROR", key, e)
256
+ elif patch_type == "lokr":
257
+ w1 = v[0]
258
+ w2 = v[1]
259
+ w1_a = v[3]
260
+ w1_b = v[4]
261
+ w2_a = v[5]
262
+ w2_b = v[6]
263
+ t2 = v[7]
264
+ dim = None
265
+
266
+ if w1 is None:
267
+ dim = w1_b.shape[0]
268
+ w1 = torch.mm(comfy.model_management.cast_to_device(w1_a, weight.device, torch.float32),
269
+ comfy.model_management.cast_to_device(w1_b, weight.device, torch.float32))
270
+ else:
271
+ w1 = comfy.model_management.cast_to_device(w1, weight.device, torch.float32)
272
+
273
+ if w2 is None:
274
+ dim = w2_b.shape[0]
275
+ if t2 is None:
276
+ w2 = torch.mm(comfy.model_management.cast_to_device(w2_a, weight.device, torch.float32),
277
+ comfy.model_management.cast_to_device(w2_b, weight.device, torch.float32))
278
+ else:
279
+ w2 = torch.einsum('i j k l, j r, i p -> p r k l',
280
+ comfy.model_management.cast_to_device(t2, weight.device, torch.float32),
281
+ comfy.model_management.cast_to_device(w2_b, weight.device, torch.float32),
282
+ comfy.model_management.cast_to_device(w2_a, weight.device, torch.float32))
283
+ else:
284
+ w2 = comfy.model_management.cast_to_device(w2, weight.device, torch.float32)
285
+
286
+ if len(w2.shape) == 4:
287
+ w1 = w1.unsqueeze(2).unsqueeze(2)
288
+ if v[2] is not None and dim is not None:
289
+ alpha *= v[2] / dim
290
+
291
+ try:
292
+ weight += alpha * torch.kron(w1, w2).reshape(weight.shape).type(weight.dtype)
293
+ except Exception as e:
294
+ print("ERROR", key, e)
295
+ elif patch_type == "loha":
296
+ w1a = v[0]
297
+ w1b = v[1]
298
+ if v[2] is not None:
299
+ alpha *= v[2] / w1b.shape[0]
300
+ w2a = v[3]
301
+ w2b = v[4]
302
+ if v[5] is not None: #cp decomposition
303
+ t1 = v[5]
304
+ t2 = v[6]
305
+ m1 = torch.einsum('i j k l, j r, i p -> p r k l',
306
+ comfy.model_management.cast_to_device(t1, weight.device, torch.float32),
307
+ comfy.model_management.cast_to_device(w1b, weight.device, torch.float32),
308
+ comfy.model_management.cast_to_device(w1a, weight.device, torch.float32))
309
+
310
+ m2 = torch.einsum('i j k l, j r, i p -> p r k l',
311
+ comfy.model_management.cast_to_device(t2, weight.device, torch.float32),
312
+ comfy.model_management.cast_to_device(w2b, weight.device, torch.float32),
313
+ comfy.model_management.cast_to_device(w2a, weight.device, torch.float32))
314
+ else:
315
+ m1 = torch.mm(comfy.model_management.cast_to_device(w1a, weight.device, torch.float32),
316
+ comfy.model_management.cast_to_device(w1b, weight.device, torch.float32))
317
+ m2 = torch.mm(comfy.model_management.cast_to_device(w2a, weight.device, torch.float32),
318
+ comfy.model_management.cast_to_device(w2b, weight.device, torch.float32))
319
+
320
+ try:
321
+ weight += (alpha * m1 * m2).reshape(weight.shape).type(weight.dtype)
322
+ except Exception as e:
323
+ print("ERROR", key, e)
324
+ elif patch_type == "glora":
325
+ if v[4] is not None:
326
+ alpha *= v[4] / v[0].shape[0]
327
+
328
+ a1 = comfy.model_management.cast_to_device(v[0].flatten(start_dim=1), weight.device, torch.float32)
329
+ a2 = comfy.model_management.cast_to_device(v[1].flatten(start_dim=1), weight.device, torch.float32)
330
+ b1 = comfy.model_management.cast_to_device(v[2].flatten(start_dim=1), weight.device, torch.float32)
331
+ b2 = comfy.model_management.cast_to_device(v[3].flatten(start_dim=1), weight.device, torch.float32)
332
+
333
+ weight += ((torch.mm(b2, b1) + torch.mm(torch.mm(weight.flatten(start_dim=1), a2), a1)) * alpha).reshape(weight.shape).type(weight.dtype)
334
+ else:
335
+ print("patch type not recognized", patch_type, key)
336
+
337
+ return weight
338
+
339
+ def unpatch_model(self, device_to=None):
340
+ keys = list(self.backup.keys())
341
+
342
+ if self.weight_inplace_update:
343
+ for k in keys:
344
+ comfy.utils.copy_to_param(self.model, k, self.backup[k])
345
+ else:
346
+ for k in keys:
347
+ comfy.utils.set_attr_param(self.model, k, self.backup[k])
348
+
349
+ self.backup = {}
350
+
351
+ if device_to is not None:
352
+ self.model.to(device_to)
353
+ self.current_device = device_to
354
+
355
+ keys = list(self.object_patches_backup.keys())
356
+ for k in keys:
357
+ comfy.utils.set_attr(self.model, k, self.object_patches_backup[k])
358
+
359
+ self.object_patches_backup = {}
comfy/model_sampling.py ADDED
@@ -0,0 +1,200 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ def noise_scaling(self, sigma, noise, latent_image, max_denoise=False):
15
+ if max_denoise:
16
+ noise = noise * torch.sqrt(1.0 + sigma ** 2.0)
17
+ else:
18
+ noise = noise * sigma
19
+
20
+ noise += latent_image
21
+ return noise
22
+
23
+ class V_PREDICTION(EPS):
24
+ def calculate_denoised(self, sigma, model_output, model_input):
25
+ sigma = sigma.view(sigma.shape[:1] + (1,) * (model_output.ndim - 1))
26
+ 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
27
+
28
+ class EDM(V_PREDICTION):
29
+ def calculate_denoised(self, sigma, model_output, model_input):
30
+ sigma = sigma.view(sigma.shape[:1] + (1,) * (model_output.ndim - 1))
31
+ 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
32
+
33
+
34
+ class ModelSamplingDiscrete(torch.nn.Module):
35
+ def __init__(self, model_config=None):
36
+ super().__init__()
37
+
38
+ if model_config is not None:
39
+ sampling_settings = model_config.sampling_settings
40
+ else:
41
+ sampling_settings = {}
42
+
43
+ beta_schedule = sampling_settings.get("beta_schedule", "linear")
44
+ linear_start = sampling_settings.get("linear_start", 0.00085)
45
+ linear_end = sampling_settings.get("linear_end", 0.012)
46
+
47
+ self._register_schedule(given_betas=None, beta_schedule=beta_schedule, timesteps=1000, linear_start=linear_start, linear_end=linear_end, cosine_s=8e-3)
48
+ self.sigma_data = 1.0
49
+
50
+ def _register_schedule(self, given_betas=None, beta_schedule="linear", timesteps=1000,
51
+ linear_start=1e-4, linear_end=2e-2, cosine_s=8e-3):
52
+ if given_betas is not None:
53
+ betas = given_betas
54
+ else:
55
+ betas = make_beta_schedule(beta_schedule, timesteps, linear_start=linear_start, linear_end=linear_end, cosine_s=cosine_s)
56
+ alphas = 1. - betas
57
+ alphas_cumprod = torch.cumprod(alphas, dim=0)
58
+
59
+ timesteps, = betas.shape
60
+ self.num_timesteps = int(timesteps)
61
+ self.linear_start = linear_start
62
+ self.linear_end = linear_end
63
+
64
+ # self.register_buffer('betas', torch.tensor(betas, dtype=torch.float32))
65
+ # self.register_buffer('alphas_cumprod', torch.tensor(alphas_cumprod, dtype=torch.float32))
66
+ # self.register_buffer('alphas_cumprod_prev', torch.tensor(alphas_cumprod_prev, dtype=torch.float32))
67
+
68
+ sigmas = ((1 - alphas_cumprod) / alphas_cumprod) ** 0.5
69
+ self.set_sigmas(sigmas)
70
+
71
+ def set_sigmas(self, sigmas):
72
+ self.register_buffer('sigmas', sigmas.float())
73
+ self.register_buffer('log_sigmas', sigmas.log().float())
74
+
75
+ @property
76
+ def sigma_min(self):
77
+ return self.sigmas[0]
78
+
79
+ @property
80
+ def sigma_max(self):
81
+ return self.sigmas[-1]
82
+
83
+ def timestep(self, sigma):
84
+ log_sigma = sigma.log()
85
+ dists = log_sigma.to(self.log_sigmas.device) - self.log_sigmas[:, None]
86
+ return dists.abs().argmin(dim=0).view(sigma.shape).to(sigma.device)
87
+
88
+ def sigma(self, timestep):
89
+ t = torch.clamp(timestep.float().to(self.log_sigmas.device), min=0, max=(len(self.sigmas) - 1))
90
+ low_idx = t.floor().long()
91
+ high_idx = t.ceil().long()
92
+ w = t.frac()
93
+ log_sigma = (1 - w) * self.log_sigmas[low_idx] + w * self.log_sigmas[high_idx]
94
+ return log_sigma.exp().to(timestep.device)
95
+
96
+ def percent_to_sigma(self, percent):
97
+ if percent <= 0.0:
98
+ return 999999999.9
99
+ if percent >= 1.0:
100
+ return 0.0
101
+ percent = 1.0 - percent
102
+ return self.sigma(torch.tensor(percent * 999.0)).item()
103
+
104
+
105
+ class ModelSamplingContinuousEDM(torch.nn.Module):
106
+ def __init__(self, model_config=None):
107
+ super().__init__()
108
+ if model_config is not None:
109
+ sampling_settings = model_config.sampling_settings
110
+ else:
111
+ sampling_settings = {}
112
+
113
+ sigma_min = sampling_settings.get("sigma_min", 0.002)
114
+ sigma_max = sampling_settings.get("sigma_max", 120.0)
115
+ sigma_data = sampling_settings.get("sigma_data", 1.0)
116
+ self.set_parameters(sigma_min, sigma_max, sigma_data)
117
+
118
+ def set_parameters(self, sigma_min, sigma_max, sigma_data):
119
+ self.sigma_data = sigma_data
120
+ sigmas = torch.linspace(math.log(sigma_min), math.log(sigma_max), 1000).exp()
121
+
122
+ self.register_buffer('sigmas', sigmas) #for compatibility with some schedulers
123
+ self.register_buffer('log_sigmas', sigmas.log())
124
+
125
+ @property
126
+ def sigma_min(self):
127
+ return self.sigmas[0]
128
+
129
+ @property
130
+ def sigma_max(self):
131
+ return self.sigmas[-1]
132
+
133
+ def timestep(self, sigma):
134
+ return 0.25 * sigma.log()
135
+
136
+ def sigma(self, timestep):
137
+ return (timestep / 0.25).exp()
138
+
139
+ def percent_to_sigma(self, percent):
140
+ if percent <= 0.0:
141
+ return 999999999.9
142
+ if percent >= 1.0:
143
+ return 0.0
144
+ percent = 1.0 - percent
145
+
146
+ log_sigma_min = math.log(self.sigma_min)
147
+ return math.exp((math.log(self.sigma_max) - log_sigma_min) * percent + log_sigma_min)
148
+
149
+ class StableCascadeSampling(ModelSamplingDiscrete):
150
+ def __init__(self, model_config=None):
151
+ super().__init__()
152
+
153
+ if model_config is not None:
154
+ sampling_settings = model_config.sampling_settings
155
+ else:
156
+ sampling_settings = {}
157
+
158
+ self.set_parameters(sampling_settings.get("shift", 1.0))
159
+
160
+ def set_parameters(self, shift=1.0, cosine_s=8e-3):
161
+ self.shift = shift
162
+ self.cosine_s = torch.tensor(cosine_s)
163
+ self._init_alpha_cumprod = torch.cos(self.cosine_s / (1 + self.cosine_s) * torch.pi * 0.5) ** 2
164
+
165
+ #This part is just for compatibility with some schedulers in the codebase
166
+ self.num_timesteps = 10000
167
+ sigmas = torch.empty((self.num_timesteps), dtype=torch.float32)
168
+ for x in range(self.num_timesteps):
169
+ t = (x + 1) / self.num_timesteps
170
+ sigmas[x] = self.sigma(t)
171
+
172
+ self.set_sigmas(sigmas)
173
+
174
+ def sigma(self, timestep):
175
+ alpha_cumprod = (torch.cos((timestep + self.cosine_s) / (1 + self.cosine_s) * torch.pi * 0.5) ** 2 / self._init_alpha_cumprod)
176
+
177
+ if self.shift != 1.0:
178
+ var = alpha_cumprod
179
+ logSNR = (var/(1-var)).log()
180
+ logSNR += 2 * torch.log(1.0 / torch.tensor(self.shift))
181
+ alpha_cumprod = logSNR.sigmoid()
182
+
183
+ alpha_cumprod = alpha_cumprod.clamp(0.0001, 0.9999)
184
+ return ((1 - alpha_cumprod) / alpha_cumprod) ** 0.5
185
+
186
+ def timestep(self, sigma):
187
+ var = 1 / ((sigma * sigma) + 1)
188
+ var = var.clamp(0, 1.0)
189
+ s, min_var = self.cosine_s.to(var.device), self._init_alpha_cumprod.to(var.device)
190
+ t = (((var * min_var) ** 0.5).acos() / (torch.pi * 0.5)) * (1 + s) - s
191
+ return t
192
+
193
+ def percent_to_sigma(self, percent):
194
+ if percent <= 0.0:
195
+ return 999999999.9
196
+ if percent >= 1.0:
197
+ return 0.0
198
+
199
+ percent = 1.0 - percent
200
+ return self.sigma(torch.tensor(percent))
comfy/ops.py ADDED
@@ -0,0 +1,161 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ This file is part of ComfyUI.
3
+ Copyright (C) 2024 Stability AI
4
+
5
+ This program is free software: you can redistribute it and/or modify
6
+ it under the terms of the GNU General Public License as published by
7
+ the Free Software Foundation, either version 3 of the License, or
8
+ (at your option) any later version.
9
+
10
+ This program is distributed in the hope that it will be useful,
11
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
12
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13
+ GNU General Public License for more details.
14
+
15
+ You should have received a copy of the GNU General Public License
16
+ along with this program. If not, see <https://www.gnu.org/licenses/>.
17
+ """
18
+
19
+ import torch
20
+ import comfy.model_management
21
+
22
+ def cast_bias_weight(s, input):
23
+ bias = None
24
+ non_blocking = comfy.model_management.device_supports_non_blocking(input.device)
25
+ if s.bias is not None:
26
+ bias = s.bias.to(device=input.device, dtype=input.dtype, non_blocking=non_blocking)
27
+ weight = s.weight.to(device=input.device, dtype=input.dtype, non_blocking=non_blocking)
28
+ return weight, bias
29
+
30
+
31
+ class disable_weight_init:
32
+ class Linear(torch.nn.Linear):
33
+ comfy_cast_weights = False
34
+ def reset_parameters(self):
35
+ return None
36
+
37
+ def forward_comfy_cast_weights(self, input):
38
+ weight, bias = cast_bias_weight(self, input)
39
+ return torch.nn.functional.linear(input, weight, bias)
40
+
41
+ def forward(self, *args, **kwargs):
42
+ if self.comfy_cast_weights:
43
+ return self.forward_comfy_cast_weights(*args, **kwargs)
44
+ else:
45
+ return super().forward(*args, **kwargs)
46
+
47
+ class Conv2d(torch.nn.Conv2d):
48
+ comfy_cast_weights = False
49
+ def reset_parameters(self):
50
+ return None
51
+
52
+ def forward_comfy_cast_weights(self, input):
53
+ weight, bias = cast_bias_weight(self, input)
54
+ return self._conv_forward(input, weight, bias)
55
+
56
+ def forward(self, *args, **kwargs):
57
+ if self.comfy_cast_weights:
58
+ return self.forward_comfy_cast_weights(*args, **kwargs)
59
+ else:
60
+ return super().forward(*args, **kwargs)
61
+
62
+ class Conv3d(torch.nn.Conv3d):
63
+ comfy_cast_weights = False
64
+ def reset_parameters(self):
65
+ return None
66
+
67
+ def forward_comfy_cast_weights(self, input):
68
+ weight, bias = cast_bias_weight(self, input)
69
+ return self._conv_forward(input, weight, bias)
70
+
71
+ def forward(self, *args, **kwargs):
72
+ if self.comfy_cast_weights:
73
+ return self.forward_comfy_cast_weights(*args, **kwargs)
74
+ else:
75
+ return super().forward(*args, **kwargs)
76
+
77
+ class GroupNorm(torch.nn.GroupNorm):
78
+ comfy_cast_weights = False
79
+ def reset_parameters(self):
80
+ return None
81
+
82
+ def forward_comfy_cast_weights(self, input):
83
+ weight, bias = cast_bias_weight(self, input)
84
+ return torch.nn.functional.group_norm(input, self.num_groups, weight, bias, self.eps)
85
+
86
+ def forward(self, *args, **kwargs):
87
+ if self.comfy_cast_weights:
88
+ return self.forward_comfy_cast_weights(*args, **kwargs)
89
+ else:
90
+ return super().forward(*args, **kwargs)
91
+
92
+
93
+ class LayerNorm(torch.nn.LayerNorm):
94
+ comfy_cast_weights = False
95
+ def reset_parameters(self):
96
+ return None
97
+
98
+ def forward_comfy_cast_weights(self, input):
99
+ if self.weight is not None:
100
+ weight, bias = cast_bias_weight(self, input)
101
+ else:
102
+ weight = None
103
+ bias = None
104
+ return torch.nn.functional.layer_norm(input, self.normalized_shape, weight, bias, self.eps)
105
+
106
+ def forward(self, *args, **kwargs):
107
+ if self.comfy_cast_weights:
108
+ return self.forward_comfy_cast_weights(*args, **kwargs)
109
+ else:
110
+ return super().forward(*args, **kwargs)
111
+
112
+ class ConvTranspose2d(torch.nn.ConvTranspose2d):
113
+ comfy_cast_weights = False
114
+ def reset_parameters(self):
115
+ return None
116
+
117
+ def forward_comfy_cast_weights(self, input, output_size=None):
118
+ num_spatial_dims = 2
119
+ output_padding = self._output_padding(
120
+ input, output_size, self.stride, self.padding, self.kernel_size,
121
+ num_spatial_dims, self.dilation)
122
+
123
+ weight, bias = cast_bias_weight(self, input)
124
+ return torch.nn.functional.conv_transpose2d(
125
+ input, weight, bias, self.stride, self.padding,
126
+ output_padding, self.groups, self.dilation)
127
+
128
+ def forward(self, *args, **kwargs):
129
+ if self.comfy_cast_weights:
130
+ return self.forward_comfy_cast_weights(*args, **kwargs)
131
+ else:
132
+ return super().forward(*args, **kwargs)
133
+
134
+ @classmethod
135
+ def conv_nd(s, dims, *args, **kwargs):
136
+ if dims == 2:
137
+ return s.Conv2d(*args, **kwargs)
138
+ elif dims == 3:
139
+ return s.Conv3d(*args, **kwargs)
140
+ else:
141
+ raise ValueError(f"unsupported dimensions: {dims}")
142
+
143
+
144
+ class manual_cast(disable_weight_init):
145
+ class Linear(disable_weight_init.Linear):
146
+ comfy_cast_weights = True
147
+
148
+ class Conv2d(disable_weight_init.Conv2d):
149
+ comfy_cast_weights = True
150
+
151
+ class Conv3d(disable_weight_init.Conv3d):
152
+ comfy_cast_weights = True
153
+
154
+ class GroupNorm(disable_weight_init.GroupNorm):
155
+ comfy_cast_weights = True
156
+
157
+ class LayerNorm(disable_weight_init.LayerNorm):
158
+ comfy_cast_weights = True
159
+
160
+ class ConvTranspose2d(disable_weight_init.ConvTranspose2d):
161
+ 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