piralocoplasticone commited on
Commit
02ebd03
β€’
1 Parent(s): 134a238

Upload 254 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. .github/CODEOWNERS +1 -0
  2. .github/ISSUE_TEMPLATE/bug_report.md +14 -0
  3. .github/ISSUE_TEMPLATE/feature_request.md +14 -0
  4. .gitignore +52 -0
  5. LICENSE +674 -0
  6. args_manager.py +33 -0
  7. auth-example.json +6 -0
  8. backend/doc +5 -0
  9. backend/headless/LICENSE +674 -0
  10. backend/headless/fcbh/checkpoint_pickle.py +13 -0
  11. backend/headless/fcbh/cldm/cldm.py +311 -0
  12. backend/headless/fcbh/cli_args.py +118 -0
  13. backend/headless/fcbh/clip_config_bigg.json +23 -0
  14. backend/headless/fcbh/clip_vision.py +116 -0
  15. backend/headless/fcbh/clip_vision_config_g.json +18 -0
  16. backend/headless/fcbh/clip_vision_config_h.json +18 -0
  17. backend/headless/fcbh/clip_vision_config_vitl.json +18 -0
  18. backend/headless/fcbh/conds.py +79 -0
  19. backend/headless/fcbh/controlnet.py +499 -0
  20. backend/headless/fcbh/diffusers_convert.py +261 -0
  21. backend/headless/fcbh/diffusers_load.py +37 -0
  22. backend/headless/fcbh/extra_samplers/uni_pc.py +894 -0
  23. backend/headless/fcbh/gligen.py +341 -0
  24. backend/headless/fcbh/k_diffusion/sampling.py +810 -0
  25. backend/headless/fcbh/k_diffusion/utils.py +313 -0
  26. backend/headless/fcbh/latent_formats.py +35 -0
  27. backend/headless/fcbh/ldm/models/autoencoder.py +227 -0
  28. backend/headless/fcbh/ldm/modules/attention.py +567 -0
  29. backend/headless/fcbh/ldm/modules/diffusionmodules/__init__.py +0 -0
  30. backend/headless/fcbh/ldm/modules/diffusionmodules/model.py +649 -0
  31. backend/headless/fcbh/ldm/modules/diffusionmodules/openaimodel.py +666 -0
  32. backend/headless/fcbh/ldm/modules/diffusionmodules/upscaling.py +81 -0
  33. backend/headless/fcbh/ldm/modules/diffusionmodules/util.py +278 -0
  34. backend/headless/fcbh/ldm/modules/distributions/__init__.py +0 -0
  35. backend/headless/fcbh/ldm/modules/distributions/distributions.py +92 -0
  36. backend/headless/fcbh/ldm/modules/ema.py +80 -0
  37. backend/headless/fcbh/ldm/modules/encoders/__init__.py +0 -0
  38. backend/headless/fcbh/ldm/modules/encoders/noise_aug_modules.py +35 -0
  39. backend/headless/fcbh/ldm/modules/sub_quadratic_attention.py +251 -0
  40. backend/headless/fcbh/ldm/util.py +197 -0
  41. backend/headless/fcbh/lora.py +213 -0
  42. backend/headless/fcbh/model_base.py +264 -0
  43. backend/headless/fcbh/model_detection.py +282 -0
  44. backend/headless/fcbh/model_management.py +724 -0
  45. backend/headless/fcbh/model_patcher.py +331 -0
  46. backend/headless/fcbh/model_sampling.py +85 -0
  47. backend/headless/fcbh/ops.py +40 -0
  48. backend/headless/fcbh/options.py +6 -0
  49. backend/headless/fcbh/sample.py +118 -0
  50. backend/headless/fcbh/samplers.py +711 -0
.github/CODEOWNERS ADDED
@@ -0,0 +1 @@
 
 
1
+ * @lllyasviel
.github/ISSUE_TEMPLATE/bug_report.md ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ name: Bug report
3
+ about: Describe a problem
4
+ title: ''
5
+ labels: ''
6
+ assignees: ''
7
+
8
+ ---
9
+
10
+ **Describe the problem**
11
+ A clear and concise description of what the bug is.
12
+
13
+ **Full Console Log**
14
+ Paste **full** console log here. You will make our job easier if you give a **full** log.
.github/ISSUE_TEMPLATE/feature_request.md ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ name: Feature request
3
+ about: Suggest an idea for this project
4
+ title: ''
5
+ labels: ''
6
+ assignees: ''
7
+
8
+ ---
9
+
10
+ **Is your feature request related to a problem? Please describe.**
11
+ A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
12
+
13
+ **Describe the idea you'd like**
14
+ A clear and concise description of what you want to happen.
.gitignore ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ __pycache__
2
+ *.ckpt
3
+ *.safetensors
4
+ *.pth
5
+ *.pt
6
+ *.bin
7
+ *.patch
8
+ *.backup
9
+ *.corrupted
10
+ sorted_styles.json
11
+ /language/default.json
12
+ lena.png
13
+ lena_result.png
14
+ lena_test.py
15
+ config.txt
16
+ config_modification_tutorial.txt
17
+ user_path_config.txt
18
+ user_path_config-deprecated.txt
19
+ build_chb.py
20
+ experiment.py
21
+ /modules/*.png
22
+ /repositories
23
+ /venv
24
+ /tmp
25
+ /ui-config.json
26
+ /outputs
27
+ /config.json
28
+ /log
29
+ /webui.settings.bat
30
+ /embeddings
31
+ /styles.csv
32
+ /params.txt
33
+ /styles.csv.bak
34
+ /webui-user.bat
35
+ /webui-user.sh
36
+ /interrogate
37
+ /user.css
38
+ /.idea
39
+ /notification.ogg
40
+ /notification.mp3
41
+ /SwinIR
42
+ /textual_inversion
43
+ .vscode
44
+ /extensions
45
+ /test/stdout.txt
46
+ /test/stderr.txt
47
+ /cache.json*
48
+ /config_states/
49
+ /node_modules
50
+ /package-lock.json
51
+ /.coverage*
52
+ /auth.json
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>.
args_manager.py ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fcbh.options import enable_args_parsing
2
+ enable_args_parsing(False)
3
+ import fcbh.cli_args as fcbh_cli
4
+
5
+
6
+ fcbh_cli.parser.add_argument("--share", action='store_true', help="Set whether to share on Gradio.")
7
+ fcbh_cli.parser.add_argument("--preset", type=str, default=None, help="Apply specified UI preset.")
8
+
9
+ fcbh_cli.parser.add_argument("--language", type=str, default='default',
10
+ help="Translate UI using json files in [language] folder. "
11
+ "For example, [--language example] will use [language/example.json] for translation.")
12
+
13
+ # For example, https://github.com/lllyasviel/Fooocus/issues/849
14
+ fcbh_cli.parser.add_argument("--enable-smart-memory", action="store_true",
15
+ help="Force loading models to vram when the unload can be avoided. "
16
+ "Some Mac users may need this.")
17
+
18
+ fcbh_cli.parser.add_argument("--theme", type=str, help="launches the UI with light or dark theme", default=None)
19
+ fcbh_cli.parser.add_argument("--disable-image-log", action='store_true',
20
+ help="Prevent writing images and logs to hard drive.")
21
+
22
+ fcbh_cli.parser.set_defaults(
23
+ disable_cuda_malloc=True,
24
+ auto_launch=True,
25
+ port=None
26
+ )
27
+
28
+ fcbh_cli.args = fcbh_cli.parser.parse_args()
29
+
30
+ # (Disable by default because of issues like https://github.com/lllyasviel/Fooocus/issues/724)
31
+ fcbh_cli.args.disable_smart_memory = not fcbh_cli.args.enable_smart_memory
32
+
33
+ args = fcbh_cli.args
auth-example.json ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ [
2
+ {
3
+ "user": "sitting-duck-1",
4
+ "pass": "very-bad-publicly-known-password-change-it"
5
+ }
6
+ ]
backend/doc ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ # Fooocus' Comfy Backend Headless (FCBH)
2
+
3
+ This is a Comfy Backend from StabilityAI. This pre-complied backend makes it easier for people who have trouble using pygit2.
4
+
5
+ FCBH is maintained by Fooocus's reviewing upon StabilityAI's changes.
backend/headless/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>.
backend/headless/fcbh/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)
backend/headless/fcbh/cldm/cldm.py ADDED
@@ -0,0 +1,311 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 fcbh.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=fcbh.ops,
57
+ ):
58
+ super().__init__()
59
+ assert use_spatial_transformer == True, "use_spatial_transformer has to be true"
60
+ if use_spatial_transformer:
61
+ assert context_dim is not None, 'Fool!! You forgot to include the dimension of your cross-attention conditioning...'
62
+
63
+ if context_dim is not None:
64
+ assert use_spatial_transformer, 'Fool!! You forgot to use the spatial transformer for your cross-attention conditioning...'
65
+ # from omegaconf.listconfig import ListConfig
66
+ # if type(context_dim) == ListConfig:
67
+ # context_dim = list(context_dim)
68
+
69
+ if num_heads_upsample == -1:
70
+ num_heads_upsample = num_heads
71
+
72
+ if num_heads == -1:
73
+ assert num_head_channels != -1, 'Either num_heads or num_head_channels has to be set'
74
+
75
+ if num_head_channels == -1:
76
+ assert num_heads != -1, 'Either num_heads or num_head_channels has to be set'
77
+
78
+ self.dims = dims
79
+ self.image_size = image_size
80
+ self.in_channels = in_channels
81
+ self.model_channels = model_channels
82
+
83
+ if isinstance(num_res_blocks, int):
84
+ self.num_res_blocks = len(channel_mult) * [num_res_blocks]
85
+ else:
86
+ if len(num_res_blocks) != len(channel_mult):
87
+ raise ValueError("provide num_res_blocks either as an int (globally constant) or "
88
+ "as a list/tuple (per-level) with the same length as channel_mult")
89
+ self.num_res_blocks = num_res_blocks
90
+
91
+ if disable_self_attentions is not None:
92
+ # should be a list of booleans, indicating whether to disable self-attention in TransformerBlocks or not
93
+ assert len(disable_self_attentions) == len(channel_mult)
94
+ if num_attention_blocks is not None:
95
+ assert len(num_attention_blocks) == len(self.num_res_blocks)
96
+ assert all(map(lambda i: self.num_res_blocks[i] >= num_attention_blocks[i], range(len(num_attention_blocks))))
97
+
98
+ transformer_depth = transformer_depth[:]
99
+
100
+ self.dropout = dropout
101
+ self.channel_mult = channel_mult
102
+ self.conv_resample = conv_resample
103
+ self.num_classes = num_classes
104
+ self.use_checkpoint = use_checkpoint
105
+ self.dtype = dtype
106
+ self.num_heads = num_heads
107
+ self.num_head_channels = num_head_channels
108
+ self.num_heads_upsample = num_heads_upsample
109
+ self.predict_codebook_ids = n_embed is not None
110
+
111
+ time_embed_dim = model_channels * 4
112
+ self.time_embed = nn.Sequential(
113
+ operations.Linear(model_channels, time_embed_dim, dtype=self.dtype, device=device),
114
+ nn.SiLU(),
115
+ operations.Linear(time_embed_dim, time_embed_dim, dtype=self.dtype, device=device),
116
+ )
117
+
118
+ if self.num_classes is not None:
119
+ if isinstance(self.num_classes, int):
120
+ self.label_emb = nn.Embedding(num_classes, time_embed_dim)
121
+ elif self.num_classes == "continuous":
122
+ print("setting up linear c_adm embedding layer")
123
+ self.label_emb = nn.Linear(1, time_embed_dim)
124
+ elif self.num_classes == "sequential":
125
+ assert adm_in_channels is not None
126
+ self.label_emb = nn.Sequential(
127
+ nn.Sequential(
128
+ operations.Linear(adm_in_channels, time_embed_dim, dtype=self.dtype, device=device),
129
+ nn.SiLU(),
130
+ operations.Linear(time_embed_dim, time_embed_dim, dtype=self.dtype, device=device),
131
+ )
132
+ )
133
+ else:
134
+ raise ValueError()
135
+
136
+ self.input_blocks = nn.ModuleList(
137
+ [
138
+ TimestepEmbedSequential(
139
+ operations.conv_nd(dims, in_channels, model_channels, 3, padding=1, dtype=self.dtype, device=device)
140
+ )
141
+ ]
142
+ )
143
+ self.zero_convs = nn.ModuleList([self.make_zero_conv(model_channels, operations=operations)])
144
+
145
+ self.input_hint_block = TimestepEmbedSequential(
146
+ operations.conv_nd(dims, hint_channels, 16, 3, padding=1),
147
+ nn.SiLU(),
148
+ operations.conv_nd(dims, 16, 16, 3, padding=1),
149
+ nn.SiLU(),
150
+ operations.conv_nd(dims, 16, 32, 3, padding=1, stride=2),
151
+ nn.SiLU(),
152
+ operations.conv_nd(dims, 32, 32, 3, padding=1),
153
+ nn.SiLU(),
154
+ operations.conv_nd(dims, 32, 96, 3, padding=1, stride=2),
155
+ nn.SiLU(),
156
+ operations.conv_nd(dims, 96, 96, 3, padding=1),
157
+ nn.SiLU(),
158
+ operations.conv_nd(dims, 96, 256, 3, padding=1, stride=2),
159
+ nn.SiLU(),
160
+ zero_module(operations.conv_nd(dims, 256, model_channels, 3, padding=1))
161
+ )
162
+
163
+ self._feature_size = model_channels
164
+ input_block_chans = [model_channels]
165
+ ch = model_channels
166
+ ds = 1
167
+ for level, mult in enumerate(channel_mult):
168
+ for nr in range(self.num_res_blocks[level]):
169
+ layers = [
170
+ ResBlock(
171
+ ch,
172
+ time_embed_dim,
173
+ dropout,
174
+ out_channels=mult * model_channels,
175
+ dims=dims,
176
+ use_checkpoint=use_checkpoint,
177
+ use_scale_shift_norm=use_scale_shift_norm,
178
+ dtype=self.dtype,
179
+ device=device,
180
+ operations=operations,
181
+ )
182
+ ]
183
+ ch = mult * model_channels
184
+ num_transformers = transformer_depth.pop(0)
185
+ if num_transformers > 0:
186
+ if num_head_channels == -1:
187
+ dim_head = ch // num_heads
188
+ else:
189
+ num_heads = ch // num_head_channels
190
+ dim_head = num_head_channels
191
+ if legacy:
192
+ #num_heads = 1
193
+ dim_head = ch // num_heads if use_spatial_transformer else num_head_channels
194
+ if exists(disable_self_attentions):
195
+ disabled_sa = disable_self_attentions[level]
196
+ else:
197
+ disabled_sa = False
198
+
199
+ if not exists(num_attention_blocks) or nr < num_attention_blocks[level]:
200
+ layers.append(
201
+ SpatialTransformer(
202
+ ch, num_heads, dim_head, depth=num_transformers, context_dim=context_dim,
203
+ disable_self_attn=disabled_sa, use_linear=use_linear_in_transformer,
204
+ use_checkpoint=use_checkpoint, dtype=self.dtype, device=device, operations=operations
205
+ )
206
+ )
207
+ self.input_blocks.append(TimestepEmbedSequential(*layers))
208
+ self.zero_convs.append(self.make_zero_conv(ch, operations=operations))
209
+ self._feature_size += ch
210
+ input_block_chans.append(ch)
211
+ if level != len(channel_mult) - 1:
212
+ out_ch = ch
213
+ self.input_blocks.append(
214
+ TimestepEmbedSequential(
215
+ ResBlock(
216
+ ch,
217
+ time_embed_dim,
218
+ dropout,
219
+ out_channels=out_ch,
220
+ dims=dims,
221
+ use_checkpoint=use_checkpoint,
222
+ use_scale_shift_norm=use_scale_shift_norm,
223
+ down=True,
224
+ dtype=self.dtype,
225
+ device=device,
226
+ operations=operations
227
+ )
228
+ if resblock_updown
229
+ else Downsample(
230
+ ch, conv_resample, dims=dims, out_channels=out_ch, dtype=self.dtype, device=device, operations=operations
231
+ )
232
+ )
233
+ )
234
+ ch = out_ch
235
+ input_block_chans.append(ch)
236
+ self.zero_convs.append(self.make_zero_conv(ch, operations=operations))
237
+ ds *= 2
238
+ self._feature_size += ch
239
+
240
+ if num_head_channels == -1:
241
+ dim_head = ch // num_heads
242
+ else:
243
+ num_heads = ch // num_head_channels
244
+ dim_head = num_head_channels
245
+ if legacy:
246
+ #num_heads = 1
247
+ dim_head = ch // num_heads if use_spatial_transformer else num_head_channels
248
+ mid_block = [
249
+ ResBlock(
250
+ ch,
251
+ time_embed_dim,
252
+ dropout,
253
+ dims=dims,
254
+ use_checkpoint=use_checkpoint,
255
+ use_scale_shift_norm=use_scale_shift_norm,
256
+ dtype=self.dtype,
257
+ device=device,
258
+ operations=operations
259
+ )]
260
+ if transformer_depth_middle >= 0:
261
+ mid_block += [SpatialTransformer( # always uses a self-attn
262
+ ch, num_heads, dim_head, depth=transformer_depth_middle, context_dim=context_dim,
263
+ disable_self_attn=disable_middle_self_attn, use_linear=use_linear_in_transformer,
264
+ use_checkpoint=use_checkpoint, dtype=self.dtype, device=device, operations=operations
265
+ ),
266
+ ResBlock(
267
+ ch,
268
+ time_embed_dim,
269
+ dropout,
270
+ dims=dims,
271
+ use_checkpoint=use_checkpoint,
272
+ use_scale_shift_norm=use_scale_shift_norm,
273
+ dtype=self.dtype,
274
+ device=device,
275
+ operations=operations
276
+ )]
277
+ self.middle_block = TimestepEmbedSequential(*mid_block)
278
+ self.middle_block_out = self.make_zero_conv(ch, operations=operations)
279
+ self._feature_size += ch
280
+
281
+ def make_zero_conv(self, channels, operations=None):
282
+ return TimestepEmbedSequential(zero_module(operations.conv_nd(self.dims, channels, channels, 1, padding=0)))
283
+
284
+ def forward(self, x, hint, timesteps, context, y=None, **kwargs):
285
+ t_emb = timestep_embedding(timesteps, self.model_channels, repeat_only=False).to(self.dtype)
286
+ emb = self.time_embed(t_emb)
287
+
288
+ guided_hint = self.input_hint_block(hint, emb, context)
289
+
290
+ outs = []
291
+
292
+ hs = []
293
+ if self.num_classes is not None:
294
+ assert y.shape[0] == x.shape[0]
295
+ emb = emb + self.label_emb(y)
296
+
297
+ h = x.type(self.dtype)
298
+ for module, zero_conv in zip(self.input_blocks, self.zero_convs):
299
+ if guided_hint is not None:
300
+ h = module(h, emb, context)
301
+ h += guided_hint
302
+ guided_hint = None
303
+ else:
304
+ h = module(h, emb, context)
305
+ outs.append(zero_conv(h, emb, context))
306
+
307
+ h = self.middle_block(h, emb, context)
308
+ outs.append(self.middle_block_out(h, emb, context))
309
+
310
+ return outs
311
+
backend/headless/fcbh/cli_args.py ADDED
@@ -0,0 +1,118 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import enum
3
+ import fcbh.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 fcbh_backend output directory.")
43
+ parser.add_argument("--temp-directory", type=str, default=None, help="Set the fcbh_backend temp directory (default is in the fcbh_backend directory).")
44
+ parser.add_argument("--input-directory", type=str, default=None, help="Set the fcbh_backend input directory.")
45
+ parser.add_argument("--auto-launch", action="store_true", help="Automatically launch fcbh_backend 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
+ parser.add_argument("--bf16-unet", action="store_true", help="Run the UNET in bf16. This should only be used for testing stuff.")
59
+
60
+ fpvae_group = parser.add_mutually_exclusive_group()
61
+ fpvae_group.add_argument("--fp16-vae", action="store_true", help="Run the VAE in fp16, might cause black images.")
62
+ fpvae_group.add_argument("--fp32-vae", action="store_true", help="Run the VAE in full precision fp32.")
63
+ fpvae_group.add_argument("--bf16-vae", action="store_true", help="Run the VAE in bf16.")
64
+
65
+ fpte_group = parser.add_mutually_exclusive_group()
66
+ fpte_group.add_argument("--fp8_e4m3fn-text-enc", action="store_true", help="Store text encoder weights in fp8 (e4m3fn variant).")
67
+ fpte_group.add_argument("--fp8_e5m2-text-enc", action="store_true", help="Store text encoder weights in fp8 (e5m2 variant).")
68
+ fpte_group.add_argument("--fp16-text-enc", action="store_true", help="Store text encoder weights in fp16.")
69
+ fpte_group.add_argument("--fp32-text-enc", action="store_true", help="Store text encoder weights in fp32.")
70
+
71
+
72
+ parser.add_argument("--directml", type=int, nargs="?", metavar="DIRECTML_DEVICE", const=-1, help="Use torch-directml.")
73
+
74
+ parser.add_argument("--disable-ipex-optimize", action="store_true", help="Disables ipex.optimize when loading models with Intel GPUs.")
75
+
76
+ class LatentPreviewMethod(enum.Enum):
77
+ NoPreviews = "none"
78
+ Auto = "auto"
79
+ Latent2RGB = "latent2rgb"
80
+ TAESD = "taesd"
81
+
82
+ parser.add_argument("--preview-method", type=LatentPreviewMethod, default=LatentPreviewMethod.NoPreviews, help="Default preview method for sampler nodes.", action=EnumAction)
83
+
84
+ attn_group = parser.add_mutually_exclusive_group()
85
+ attn_group.add_argument("--use-split-cross-attention", action="store_true", help="Use the split cross attention optimization. Ignored when xformers is used.")
86
+ attn_group.add_argument("--use-quad-cross-attention", action="store_true", help="Use the sub-quadratic cross attention optimization . Ignored when xformers is used.")
87
+ attn_group.add_argument("--use-pytorch-cross-attention", action="store_true", help="Use the new pytorch 2.0 cross attention function.")
88
+
89
+ parser.add_argument("--disable-xformers", action="store_true", help="Disable xformers.")
90
+
91
+ vram_group = parser.add_mutually_exclusive_group()
92
+ vram_group.add_argument("--gpu-only", action="store_true", help="Store and run everything (text encoders/CLIP models, etc... on the GPU).")
93
+ 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.")
94
+ vram_group.add_argument("--normalvram", action="store_true", help="Used to force normal vram use if lowvram gets automatically enabled.")
95
+ vram_group.add_argument("--lowvram", action="store_true", help="Split the unet in parts to use less vram.")
96
+ vram_group.add_argument("--novram", action="store_true", help="When lowvram isn't enough.")
97
+ vram_group.add_argument("--cpu", action="store_true", help="To use the CPU for everything (slow).")
98
+
99
+
100
+ parser.add_argument("--disable-smart-memory", action="store_true", help="Force fcbh_backend to agressively offload to regular ram instead of keeping models in vram when it can.")
101
+
102
+
103
+ parser.add_argument("--dont-print-server", action="store_true", help="Don't print server output.")
104
+ parser.add_argument("--quick-test-for-ci", action="store_true", help="Quick test for CI.")
105
+ 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).")
106
+
107
+ parser.add_argument("--disable-metadata", action="store_true", help="Disable saving prompt metadata in files.")
108
+
109
+ if fcbh.options.args_parsing:
110
+ args = parser.parse_args()
111
+ else:
112
+ args = parser.parse_args([])
113
+
114
+ if args.windows_standalone_build:
115
+ args.auto_launch = True
116
+
117
+ if args.disable_auto_launch:
118
+ args.auto_launch = False
backend/headless/fcbh/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
+ }
backend/headless/fcbh/clip_vision.py ADDED
@@ -0,0 +1,116 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from transformers import CLIPVisionModelWithProjection, CLIPVisionConfig, modeling_utils
2
+ from .utils import load_torch_file, transformers_convert, common_upscale
3
+ import os
4
+ import torch
5
+ import contextlib
6
+
7
+ import fcbh.ops
8
+ import fcbh.model_patcher
9
+ import fcbh.model_management
10
+ import fcbh.utils
11
+
12
+ def clip_preprocess(image, size=224):
13
+ mean = torch.tensor([ 0.48145466,0.4578275,0.40821073], device=image.device, dtype=image.dtype)
14
+ std = torch.tensor([0.26862954,0.26130258,0.27577711], device=image.device, dtype=image.dtype)
15
+ scale = (size / min(image.shape[1], image.shape[2]))
16
+ image = torch.nn.functional.interpolate(image.movedim(-1, 1), size=(round(scale * image.shape[1]), round(scale * image.shape[2])), mode="bicubic", antialias=True)
17
+ h = (image.shape[2] - size)//2
18
+ w = (image.shape[3] - size)//2
19
+ image = image[:,:,h:h+size,w:w+size]
20
+ image = torch.clip((255. * image), 0, 255).round() / 255.0
21
+ return (image - mean.view([3,1,1])) / std.view([3,1,1])
22
+
23
+ class ClipVisionModel():
24
+ def __init__(self, json_config):
25
+ config = CLIPVisionConfig.from_json_file(json_config)
26
+ self.load_device = fcbh.model_management.text_encoder_device()
27
+ offload_device = fcbh.model_management.text_encoder_offload_device()
28
+ self.dtype = torch.float32
29
+ if fcbh.model_management.should_use_fp16(self.load_device, prioritize_performance=False):
30
+ self.dtype = torch.float16
31
+
32
+ with fcbh.ops.use_fcbh_ops(offload_device, self.dtype):
33
+ with modeling_utils.no_init_weights():
34
+ self.model = CLIPVisionModelWithProjection(config)
35
+ self.model.to(self.dtype)
36
+
37
+ self.patcher = fcbh.model_patcher.ModelPatcher(self.model, load_device=self.load_device, offload_device=offload_device)
38
+ def load_sd(self, sd):
39
+ return self.model.load_state_dict(sd, strict=False)
40
+
41
+ def encode_image(self, image):
42
+ fcbh.model_management.load_model_gpu(self.patcher)
43
+ pixel_values = clip_preprocess(image.to(self.load_device))
44
+
45
+ if self.dtype != torch.float32:
46
+ precision_scope = torch.autocast
47
+ else:
48
+ precision_scope = lambda a, b: contextlib.nullcontext(a)
49
+
50
+ with precision_scope(fcbh.model_management.get_autocast_device(self.load_device), torch.float32):
51
+ outputs = self.model(pixel_values=pixel_values, output_hidden_states=True)
52
+
53
+ for k in outputs:
54
+ t = outputs[k]
55
+ if t is not None:
56
+ if k == 'hidden_states':
57
+ outputs["penultimate_hidden_states"] = t[-2].cpu()
58
+ outputs["hidden_states"] = None
59
+ else:
60
+ outputs[k] = t.cpu()
61
+
62
+ return outputs
63
+
64
+ def convert_to_transformers(sd, prefix):
65
+ sd_k = sd.keys()
66
+ if "{}transformer.resblocks.0.attn.in_proj_weight".format(prefix) in sd_k:
67
+ keys_to_replace = {
68
+ "{}class_embedding".format(prefix): "vision_model.embeddings.class_embedding",
69
+ "{}conv1.weight".format(prefix): "vision_model.embeddings.patch_embedding.weight",
70
+ "{}positional_embedding".format(prefix): "vision_model.embeddings.position_embedding.weight",
71
+ "{}ln_post.bias".format(prefix): "vision_model.post_layernorm.bias",
72
+ "{}ln_post.weight".format(prefix): "vision_model.post_layernorm.weight",
73
+ "{}ln_pre.bias".format(prefix): "vision_model.pre_layrnorm.bias",
74
+ "{}ln_pre.weight".format(prefix): "vision_model.pre_layrnorm.weight",
75
+ }
76
+
77
+ for x in keys_to_replace:
78
+ if x in sd_k:
79
+ sd[keys_to_replace[x]] = sd.pop(x)
80
+
81
+ if "{}proj".format(prefix) in sd_k:
82
+ sd['visual_projection.weight'] = sd.pop("{}proj".format(prefix)).transpose(0, 1)
83
+
84
+ sd = transformers_convert(sd, prefix, "vision_model.", 48)
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("extra keys 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)
backend/headless/fcbh/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
+ }
backend/headless/fcbh/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
+ }
backend/headless/fcbh/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
+ }
backend/headless/fcbh/conds.py ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import enum
2
+ import torch
3
+ import math
4
+ import fcbh.utils
5
+
6
+
7
+ def lcm(a, b): #TODO: eventually replace by math.lcm (added in python3.9)
8
+ return abs(a*b) // math.gcd(a, b)
9
+
10
+ class CONDRegular:
11
+ def __init__(self, cond):
12
+ self.cond = cond
13
+
14
+ def _copy_with(self, cond):
15
+ return self.__class__(cond)
16
+
17
+ def process_cond(self, batch_size, device, **kwargs):
18
+ return self._copy_with(fcbh.utils.repeat_to_batch_size(self.cond, batch_size).to(device))
19
+
20
+ def can_concat(self, other):
21
+ if self.cond.shape != other.cond.shape:
22
+ return False
23
+ return True
24
+
25
+ def concat(self, others):
26
+ conds = [self.cond]
27
+ for x in others:
28
+ conds.append(x.cond)
29
+ return torch.cat(conds)
30
+
31
+ class CONDNoiseShape(CONDRegular):
32
+ def process_cond(self, batch_size, device, area, **kwargs):
33
+ data = self.cond[:,:,area[2]:area[0] + area[2],area[3]:area[1] + area[3]]
34
+ return self._copy_with(fcbh.utils.repeat_to_batch_size(data, batch_size).to(device))
35
+
36
+
37
+ class CONDCrossAttn(CONDRegular):
38
+ def can_concat(self, other):
39
+ s1 = self.cond.shape
40
+ s2 = other.cond.shape
41
+ if s1 != s2:
42
+ if s1[0] != s2[0] or s1[2] != s2[2]: #these 2 cases should not happen
43
+ return False
44
+
45
+ mult_min = lcm(s1[1], s2[1])
46
+ diff = mult_min // min(s1[1], s2[1])
47
+ if diff > 4: #arbitrary limit on the padding because it's probably going to impact performance negatively if it's too much
48
+ return False
49
+ return True
50
+
51
+ def concat(self, others):
52
+ conds = [self.cond]
53
+ crossattn_max_len = self.cond.shape[1]
54
+ for x in others:
55
+ c = x.cond
56
+ crossattn_max_len = lcm(crossattn_max_len, c.shape[1])
57
+ conds.append(c)
58
+
59
+ out = []
60
+ for c in conds:
61
+ if c.shape[1] < crossattn_max_len:
62
+ c = c.repeat(1, crossattn_max_len // c.shape[1], 1) #padding with repeat doesn't change result
63
+ out.append(c)
64
+ return torch.cat(out)
65
+
66
+ class CONDConstant(CONDRegular):
67
+ def __init__(self, cond):
68
+ self.cond = cond
69
+
70
+ def process_cond(self, batch_size, device, **kwargs):
71
+ return self._copy_with(self.cond)
72
+
73
+ def can_concat(self, other):
74
+ if self.cond != other.cond:
75
+ return False
76
+ return True
77
+
78
+ def concat(self, others):
79
+ return self.cond
backend/headless/fcbh/controlnet.py ADDED
@@ -0,0 +1,499 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import math
3
+ import os
4
+ import fcbh.utils
5
+ import fcbh.model_management
6
+ import fcbh.model_detection
7
+ import fcbh.model_patcher
8
+
9
+ import fcbh.cldm.cldm
10
+ import fcbh.t2i_adapter.adapter
11
+
12
+
13
+ def broadcast_image_to(tensor, target_batch_size, batched_number):
14
+ current_batch_size = tensor.shape[0]
15
+ #print(current_batch_size, target_batch_size)
16
+ if current_batch_size == 1:
17
+ return tensor
18
+
19
+ per_batch = target_batch_size // batched_number
20
+ tensor = tensor[:per_batch]
21
+
22
+ if per_batch > tensor.shape[0]:
23
+ tensor = torch.cat([tensor] * (per_batch // tensor.shape[0]) + [tensor[:(per_batch % tensor.shape[0])]], dim=0)
24
+
25
+ current_batch_size = tensor.shape[0]
26
+ if current_batch_size == target_batch_size:
27
+ return tensor
28
+ else:
29
+ return torch.cat([tensor] * batched_number, dim=0)
30
+
31
+ class ControlBase:
32
+ def __init__(self, device=None):
33
+ self.cond_hint_original = None
34
+ self.cond_hint = None
35
+ self.strength = 1.0
36
+ self.timestep_percent_range = (0.0, 1.0)
37
+ self.timestep_range = None
38
+
39
+ if device is None:
40
+ device = fcbh.model_management.get_torch_device()
41
+ self.device = device
42
+ self.previous_controlnet = None
43
+ self.global_average_pooling = False
44
+
45
+ def set_cond_hint(self, cond_hint, strength=1.0, timestep_percent_range=(0.0, 1.0)):
46
+ self.cond_hint_original = cond_hint
47
+ self.strength = strength
48
+ self.timestep_percent_range = timestep_percent_range
49
+ return self
50
+
51
+ def pre_run(self, model, percent_to_timestep_function):
52
+ self.timestep_range = (percent_to_timestep_function(self.timestep_percent_range[0]), percent_to_timestep_function(self.timestep_percent_range[1]))
53
+ if self.previous_controlnet is not None:
54
+ self.previous_controlnet.pre_run(model, percent_to_timestep_function)
55
+
56
+ def set_previous_controlnet(self, controlnet):
57
+ self.previous_controlnet = controlnet
58
+ return self
59
+
60
+ def cleanup(self):
61
+ if self.previous_controlnet is not None:
62
+ self.previous_controlnet.cleanup()
63
+ if self.cond_hint is not None:
64
+ del self.cond_hint
65
+ self.cond_hint = None
66
+ self.timestep_range = None
67
+
68
+ def get_models(self):
69
+ out = []
70
+ if self.previous_controlnet is not None:
71
+ out += self.previous_controlnet.get_models()
72
+ return out
73
+
74
+ def copy_to(self, c):
75
+ c.cond_hint_original = self.cond_hint_original
76
+ c.strength = self.strength
77
+ c.timestep_percent_range = self.timestep_percent_range
78
+
79
+ def inference_memory_requirements(self, dtype):
80
+ if self.previous_controlnet is not None:
81
+ return self.previous_controlnet.inference_memory_requirements(dtype)
82
+ return 0
83
+
84
+ def control_merge(self, control_input, control_output, control_prev, output_dtype):
85
+ out = {'input':[], 'middle':[], 'output': []}
86
+
87
+ if control_input is not None:
88
+ for i in range(len(control_input)):
89
+ key = 'input'
90
+ x = control_input[i]
91
+ if x is not None:
92
+ x *= self.strength
93
+ if x.dtype != output_dtype:
94
+ x = x.to(output_dtype)
95
+ out[key].insert(0, x)
96
+
97
+ if control_output is not None:
98
+ for i in range(len(control_output)):
99
+ if i == (len(control_output) - 1):
100
+ key = 'middle'
101
+ index = 0
102
+ else:
103
+ key = 'output'
104
+ index = i
105
+ x = control_output[i]
106
+ if x is not None:
107
+ if self.global_average_pooling:
108
+ x = torch.mean(x, dim=(2, 3), keepdim=True).repeat(1, 1, x.shape[2], x.shape[3])
109
+
110
+ x *= self.strength
111
+ if x.dtype != output_dtype:
112
+ x = x.to(output_dtype)
113
+
114
+ out[key].append(x)
115
+ if control_prev is not None:
116
+ for x in ['input', 'middle', 'output']:
117
+ o = out[x]
118
+ for i in range(len(control_prev[x])):
119
+ prev_val = control_prev[x][i]
120
+ if i >= len(o):
121
+ o.append(prev_val)
122
+ elif prev_val is not None:
123
+ if o[i] is None:
124
+ o[i] = prev_val
125
+ else:
126
+ o[i] += prev_val
127
+ return out
128
+
129
+ class ControlNet(ControlBase):
130
+ def __init__(self, control_model, global_average_pooling=False, device=None):
131
+ super().__init__(device)
132
+ self.control_model = control_model
133
+ self.control_model_wrapped = fcbh.model_patcher.ModelPatcher(self.control_model, load_device=fcbh.model_management.get_torch_device(), offload_device=fcbh.model_management.unet_offload_device())
134
+ self.global_average_pooling = global_average_pooling
135
+ self.model_sampling_current = None
136
+
137
+ def get_control(self, x_noisy, t, cond, batched_number):
138
+ control_prev = None
139
+ if self.previous_controlnet is not None:
140
+ control_prev = self.previous_controlnet.get_control(x_noisy, t, cond, batched_number)
141
+
142
+ if self.timestep_range is not None:
143
+ if t[0] > self.timestep_range[0] or t[0] < self.timestep_range[1]:
144
+ if control_prev is not None:
145
+ return control_prev
146
+ else:
147
+ return None
148
+
149
+ output_dtype = x_noisy.dtype
150
+ if self.cond_hint is None or x_noisy.shape[2] * 8 != self.cond_hint.shape[2] or x_noisy.shape[3] * 8 != self.cond_hint.shape[3]:
151
+ if self.cond_hint is not None:
152
+ del self.cond_hint
153
+ self.cond_hint = None
154
+ self.cond_hint = fcbh.utils.common_upscale(self.cond_hint_original, x_noisy.shape[3] * 8, x_noisy.shape[2] * 8, 'nearest-exact', "center").to(self.control_model.dtype).to(self.device)
155
+ if x_noisy.shape[0] != self.cond_hint.shape[0]:
156
+ self.cond_hint = broadcast_image_to(self.cond_hint, x_noisy.shape[0], batched_number)
157
+
158
+
159
+ context = cond['c_crossattn']
160
+ y = cond.get('y', None)
161
+ if y is not None:
162
+ y = y.to(self.control_model.dtype)
163
+ timestep = self.model_sampling_current.timestep(t)
164
+ x_noisy = self.model_sampling_current.calculate_input(t, x_noisy)
165
+
166
+ control = self.control_model(x=x_noisy.to(self.control_model.dtype), hint=self.cond_hint, timesteps=timestep.float(), context=context.to(self.control_model.dtype), y=y)
167
+ return self.control_merge(None, control, control_prev, output_dtype)
168
+
169
+ def copy(self):
170
+ c = ControlNet(self.control_model, global_average_pooling=self.global_average_pooling)
171
+ self.copy_to(c)
172
+ return c
173
+
174
+ def get_models(self):
175
+ out = super().get_models()
176
+ out.append(self.control_model_wrapped)
177
+ return out
178
+
179
+ def pre_run(self, model, percent_to_timestep_function):
180
+ super().pre_run(model, percent_to_timestep_function)
181
+ self.model_sampling_current = model.model_sampling
182
+
183
+ def cleanup(self):
184
+ self.model_sampling_current = None
185
+ super().cleanup()
186
+
187
+ class ControlLoraOps:
188
+ class Linear(torch.nn.Module):
189
+ def __init__(self, in_features: int, out_features: int, bias: bool = True,
190
+ device=None, dtype=None) -> None:
191
+ factory_kwargs = {'device': device, 'dtype': dtype}
192
+ super().__init__()
193
+ self.in_features = in_features
194
+ self.out_features = out_features
195
+ self.weight = None
196
+ self.up = None
197
+ self.down = None
198
+ self.bias = None
199
+
200
+ def forward(self, input):
201
+ if self.up is not None:
202
+ return torch.nn.functional.linear(input, self.weight.to(input.device) + (torch.mm(self.up.flatten(start_dim=1), self.down.flatten(start_dim=1))).reshape(self.weight.shape).type(input.dtype), self.bias)
203
+ else:
204
+ return torch.nn.functional.linear(input, self.weight.to(input.device), self.bias)
205
+
206
+ class Conv2d(torch.nn.Module):
207
+ def __init__(
208
+ self,
209
+ in_channels,
210
+ out_channels,
211
+ kernel_size,
212
+ stride=1,
213
+ padding=0,
214
+ dilation=1,
215
+ groups=1,
216
+ bias=True,
217
+ padding_mode='zeros',
218
+ device=None,
219
+ dtype=None
220
+ ):
221
+ super().__init__()
222
+ self.in_channels = in_channels
223
+ self.out_channels = out_channels
224
+ self.kernel_size = kernel_size
225
+ self.stride = stride
226
+ self.padding = padding
227
+ self.dilation = dilation
228
+ self.transposed = False
229
+ self.output_padding = 0
230
+ self.groups = groups
231
+ self.padding_mode = padding_mode
232
+
233
+ self.weight = None
234
+ self.bias = None
235
+ self.up = None
236
+ self.down = None
237
+
238
+
239
+ def forward(self, input):
240
+ if self.up is not None:
241
+ return torch.nn.functional.conv2d(input, self.weight.to(input.device) + (torch.mm(self.up.flatten(start_dim=1), self.down.flatten(start_dim=1))).reshape(self.weight.shape).type(input.dtype), self.bias, self.stride, self.padding, self.dilation, self.groups)
242
+ else:
243
+ return torch.nn.functional.conv2d(input, self.weight.to(input.device), self.bias, self.stride, self.padding, self.dilation, self.groups)
244
+
245
+ def conv_nd(self, dims, *args, **kwargs):
246
+ if dims == 2:
247
+ return self.Conv2d(*args, **kwargs)
248
+ else:
249
+ raise ValueError(f"unsupported dimensions: {dims}")
250
+
251
+
252
+ class ControlLora(ControlNet):
253
+ def __init__(self, control_weights, global_average_pooling=False, device=None):
254
+ ControlBase.__init__(self, device)
255
+ self.control_weights = control_weights
256
+ self.global_average_pooling = global_average_pooling
257
+
258
+ def pre_run(self, model, percent_to_timestep_function):
259
+ super().pre_run(model, percent_to_timestep_function)
260
+ controlnet_config = model.model_config.unet_config.copy()
261
+ controlnet_config.pop("out_channels")
262
+ controlnet_config["hint_channels"] = self.control_weights["input_hint_block.0.weight"].shape[1]
263
+ controlnet_config["operations"] = ControlLoraOps()
264
+ self.control_model = fcbh.cldm.cldm.ControlNet(**controlnet_config)
265
+ dtype = model.get_dtype()
266
+ self.control_model.to(dtype)
267
+ self.control_model.to(fcbh.model_management.get_torch_device())
268
+ diffusion_model = model.diffusion_model
269
+ sd = diffusion_model.state_dict()
270
+ cm = self.control_model.state_dict()
271
+
272
+ for k in sd:
273
+ weight = fcbh.model_management.resolve_lowvram_weight(sd[k], diffusion_model, k)
274
+ try:
275
+ fcbh.utils.set_attr(self.control_model, k, weight)
276
+ except:
277
+ pass
278
+
279
+ for k in self.control_weights:
280
+ if k not in {"lora_controlnet"}:
281
+ fcbh.utils.set_attr(self.control_model, k, self.control_weights[k].to(dtype).to(fcbh.model_management.get_torch_device()))
282
+
283
+ def copy(self):
284
+ c = ControlLora(self.control_weights, global_average_pooling=self.global_average_pooling)
285
+ self.copy_to(c)
286
+ return c
287
+
288
+ def cleanup(self):
289
+ del self.control_model
290
+ self.control_model = None
291
+ super().cleanup()
292
+
293
+ def get_models(self):
294
+ out = ControlBase.get_models(self)
295
+ return out
296
+
297
+ def inference_memory_requirements(self, dtype):
298
+ return fcbh.utils.calculate_parameters(self.control_weights) * fcbh.model_management.dtype_size(dtype) + ControlBase.inference_memory_requirements(self, dtype)
299
+
300
+ def load_controlnet(ckpt_path, model=None):
301
+ controlnet_data = fcbh.utils.load_torch_file(ckpt_path, safe_load=True)
302
+ if "lora_controlnet" in controlnet_data:
303
+ return ControlLora(controlnet_data)
304
+
305
+ controlnet_config = None
306
+ if "controlnet_cond_embedding.conv_in.weight" in controlnet_data: #diffusers format
307
+ unet_dtype = fcbh.model_management.unet_dtype()
308
+ controlnet_config = fcbh.model_detection.unet_config_from_diffusers_unet(controlnet_data, unet_dtype)
309
+ diffusers_keys = fcbh.utils.unet_to_diffusers(controlnet_config)
310
+ diffusers_keys["controlnet_mid_block.weight"] = "middle_block_out.0.weight"
311
+ diffusers_keys["controlnet_mid_block.bias"] = "middle_block_out.0.bias"
312
+
313
+ count = 0
314
+ loop = True
315
+ while loop:
316
+ suffix = [".weight", ".bias"]
317
+ for s in suffix:
318
+ k_in = "controlnet_down_blocks.{}{}".format(count, s)
319
+ k_out = "zero_convs.{}.0{}".format(count, s)
320
+ if k_in not in controlnet_data:
321
+ loop = False
322
+ break
323
+ diffusers_keys[k_in] = k_out
324
+ count += 1
325
+
326
+ count = 0
327
+ loop = True
328
+ while loop:
329
+ suffix = [".weight", ".bias"]
330
+ for s in suffix:
331
+ if count == 0:
332
+ k_in = "controlnet_cond_embedding.conv_in{}".format(s)
333
+ else:
334
+ k_in = "controlnet_cond_embedding.blocks.{}{}".format(count - 1, s)
335
+ k_out = "input_hint_block.{}{}".format(count * 2, s)
336
+ if k_in not in controlnet_data:
337
+ k_in = "controlnet_cond_embedding.conv_out{}".format(s)
338
+ loop = False
339
+ diffusers_keys[k_in] = k_out
340
+ count += 1
341
+
342
+ new_sd = {}
343
+ for k in diffusers_keys:
344
+ if k in controlnet_data:
345
+ new_sd[diffusers_keys[k]] = controlnet_data.pop(k)
346
+
347
+ leftover_keys = controlnet_data.keys()
348
+ if len(leftover_keys) > 0:
349
+ print("leftover keys:", leftover_keys)
350
+ controlnet_data = new_sd
351
+
352
+ pth_key = 'control_model.zero_convs.0.0.weight'
353
+ pth = False
354
+ key = 'zero_convs.0.0.weight'
355
+ if pth_key in controlnet_data:
356
+ pth = True
357
+ key = pth_key
358
+ prefix = "control_model."
359
+ elif key in controlnet_data:
360
+ prefix = ""
361
+ else:
362
+ net = load_t2i_adapter(controlnet_data)
363
+ if net is None:
364
+ print("error checkpoint does not contain controlnet or t2i adapter data", ckpt_path)
365
+ return net
366
+
367
+ if controlnet_config is None:
368
+ unet_dtype = fcbh.model_management.unet_dtype()
369
+ controlnet_config = fcbh.model_detection.model_config_from_unet(controlnet_data, prefix, unet_dtype, True).unet_config
370
+ controlnet_config.pop("out_channels")
371
+ controlnet_config["hint_channels"] = controlnet_data["{}input_hint_block.0.weight".format(prefix)].shape[1]
372
+ control_model = fcbh.cldm.cldm.ControlNet(**controlnet_config)
373
+
374
+ if pth:
375
+ if 'difference' in controlnet_data:
376
+ if model is not None:
377
+ fcbh.model_management.load_models_gpu([model])
378
+ model_sd = model.model_state_dict()
379
+ for x in controlnet_data:
380
+ c_m = "control_model."
381
+ if x.startswith(c_m):
382
+ sd_key = "diffusion_model.{}".format(x[len(c_m):])
383
+ if sd_key in model_sd:
384
+ cd = controlnet_data[x]
385
+ cd += model_sd[sd_key].type(cd.dtype).to(cd.device)
386
+ else:
387
+ print("WARNING: Loaded a diff controlnet without a model. It will very likely not work.")
388
+
389
+ class WeightsLoader(torch.nn.Module):
390
+ pass
391
+ w = WeightsLoader()
392
+ w.control_model = control_model
393
+ missing, unexpected = w.load_state_dict(controlnet_data, strict=False)
394
+ else:
395
+ missing, unexpected = control_model.load_state_dict(controlnet_data, strict=False)
396
+ print(missing, unexpected)
397
+
398
+ control_model = control_model.to(unet_dtype)
399
+
400
+ global_average_pooling = False
401
+ filename = os.path.splitext(ckpt_path)[0]
402
+ if filename.endswith("_shuffle") or filename.endswith("_shuffle_fp16"): #TODO: smarter way of enabling global_average_pooling
403
+ global_average_pooling = True
404
+
405
+ control = ControlNet(control_model, global_average_pooling=global_average_pooling)
406
+ return control
407
+
408
+ class T2IAdapter(ControlBase):
409
+ def __init__(self, t2i_model, channels_in, device=None):
410
+ super().__init__(device)
411
+ self.t2i_model = t2i_model
412
+ self.channels_in = channels_in
413
+ self.control_input = None
414
+
415
+ def scale_image_to(self, width, height):
416
+ unshuffle_amount = self.t2i_model.unshuffle_amount
417
+ width = math.ceil(width / unshuffle_amount) * unshuffle_amount
418
+ height = math.ceil(height / unshuffle_amount) * unshuffle_amount
419
+ return width, height
420
+
421
+ def get_control(self, x_noisy, t, cond, batched_number):
422
+ control_prev = None
423
+ if self.previous_controlnet is not None:
424
+ control_prev = self.previous_controlnet.get_control(x_noisy, t, cond, batched_number)
425
+
426
+ if self.timestep_range is not None:
427
+ if t[0] > self.timestep_range[0] or t[0] < self.timestep_range[1]:
428
+ if control_prev is not None:
429
+ return control_prev
430
+ else:
431
+ return None
432
+
433
+ if self.cond_hint is None or x_noisy.shape[2] * 8 != self.cond_hint.shape[2] or x_noisy.shape[3] * 8 != self.cond_hint.shape[3]:
434
+ if self.cond_hint is not None:
435
+ del self.cond_hint
436
+ self.control_input = None
437
+ self.cond_hint = None
438
+ width, height = self.scale_image_to(x_noisy.shape[3] * 8, x_noisy.shape[2] * 8)
439
+ self.cond_hint = fcbh.utils.common_upscale(self.cond_hint_original, width, height, 'nearest-exact', "center").float().to(self.device)
440
+ if self.channels_in == 1 and self.cond_hint.shape[1] > 1:
441
+ self.cond_hint = torch.mean(self.cond_hint, 1, keepdim=True)
442
+ if x_noisy.shape[0] != self.cond_hint.shape[0]:
443
+ self.cond_hint = broadcast_image_to(self.cond_hint, x_noisy.shape[0], batched_number)
444
+ if self.control_input is None:
445
+ self.t2i_model.to(x_noisy.dtype)
446
+ self.t2i_model.to(self.device)
447
+ self.control_input = self.t2i_model(self.cond_hint.to(x_noisy.dtype))
448
+ self.t2i_model.cpu()
449
+
450
+ control_input = list(map(lambda a: None if a is None else a.clone(), self.control_input))
451
+ mid = None
452
+ if self.t2i_model.xl == True:
453
+ mid = control_input[-1:]
454
+ control_input = control_input[:-1]
455
+ return self.control_merge(control_input, mid, control_prev, x_noisy.dtype)
456
+
457
+ def copy(self):
458
+ c = T2IAdapter(self.t2i_model, self.channels_in)
459
+ self.copy_to(c)
460
+ return c
461
+
462
+ def load_t2i_adapter(t2i_data):
463
+ if 'adapter' in t2i_data:
464
+ t2i_data = t2i_data['adapter']
465
+ if 'adapter.body.0.resnets.0.block1.weight' in t2i_data: #diffusers format
466
+ prefix_replace = {}
467
+ for i in range(4):
468
+ for j in range(2):
469
+ prefix_replace["adapter.body.{}.resnets.{}.".format(i, j)] = "body.{}.".format(i * 2 + j)
470
+ prefix_replace["adapter.body.{}.".format(i, j)] = "body.{}.".format(i * 2)
471
+ prefix_replace["adapter."] = ""
472
+ t2i_data = fcbh.utils.state_dict_prefix_replace(t2i_data, prefix_replace)
473
+ keys = t2i_data.keys()
474
+
475
+ if "body.0.in_conv.weight" in keys:
476
+ cin = t2i_data['body.0.in_conv.weight'].shape[1]
477
+ model_ad = fcbh.t2i_adapter.adapter.Adapter_light(cin=cin, channels=[320, 640, 1280, 1280], nums_rb=4)
478
+ elif 'conv_in.weight' in keys:
479
+ cin = t2i_data['conv_in.weight'].shape[1]
480
+ channel = t2i_data['conv_in.weight'].shape[0]
481
+ ksize = t2i_data['body.0.block2.weight'].shape[2]
482
+ use_conv = False
483
+ down_opts = list(filter(lambda a: a.endswith("down_opt.op.weight"), keys))
484
+ if len(down_opts) > 0:
485
+ use_conv = True
486
+ xl = False
487
+ if cin == 256 or cin == 768:
488
+ xl = True
489
+ model_ad = fcbh.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)
490
+ else:
491
+ return None
492
+ missing, unexpected = model_ad.load_state_dict(t2i_data)
493
+ if len(missing) > 0:
494
+ print("t2i missing", missing)
495
+
496
+ if len(unexpected) > 0:
497
+ print("t2i unexpected", unexpected)
498
+
499
+ return T2IAdapter(model_ad, model_ad.input_channels)
backend/headless/fcbh/diffusers_convert.py ADDED
@@ -0,0 +1,261 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import re
2
+ import torch
3
+
4
+ # conversion code from https://github.com/huggingface/diffusers/blob/main/scripts/convert_diffusers_to_original_stable_diffusion.py
5
+
6
+ # =================#
7
+ # UNet Conversion #
8
+ # =================#
9
+
10
+ unet_conversion_map = [
11
+ # (stable-diffusion, HF Diffusers)
12
+ ("time_embed.0.weight", "time_embedding.linear_1.weight"),
13
+ ("time_embed.0.bias", "time_embedding.linear_1.bias"),
14
+ ("time_embed.2.weight", "time_embedding.linear_2.weight"),
15
+ ("time_embed.2.bias", "time_embedding.linear_2.bias"),
16
+ ("input_blocks.0.0.weight", "conv_in.weight"),
17
+ ("input_blocks.0.0.bias", "conv_in.bias"),
18
+ ("out.0.weight", "conv_norm_out.weight"),
19
+ ("out.0.bias", "conv_norm_out.bias"),
20
+ ("out.2.weight", "conv_out.weight"),
21
+ ("out.2.bias", "conv_out.bias"),
22
+ ]
23
+
24
+ unet_conversion_map_resnet = [
25
+ # (stable-diffusion, HF Diffusers)
26
+ ("in_layers.0", "norm1"),
27
+ ("in_layers.2", "conv1"),
28
+ ("out_layers.0", "norm2"),
29
+ ("out_layers.3", "conv2"),
30
+ ("emb_layers.1", "time_emb_proj"),
31
+ ("skip_connection", "conv_shortcut"),
32
+ ]
33
+
34
+ unet_conversion_map_layer = []
35
+ # hardcoded number of downblocks and resnets/attentions...
36
+ # would need smarter logic for other networks.
37
+ for i in range(4):
38
+ # loop over downblocks/upblocks
39
+
40
+ for j in range(2):
41
+ # loop over resnets/attentions for downblocks
42
+ hf_down_res_prefix = f"down_blocks.{i}.resnets.{j}."
43
+ sd_down_res_prefix = f"input_blocks.{3 * i + j + 1}.0."
44
+ unet_conversion_map_layer.append((sd_down_res_prefix, hf_down_res_prefix))
45
+
46
+ if i < 3:
47
+ # no attention layers in down_blocks.3
48
+ hf_down_atn_prefix = f"down_blocks.{i}.attentions.{j}."
49
+ sd_down_atn_prefix = f"input_blocks.{3 * i + j + 1}.1."
50
+ unet_conversion_map_layer.append((sd_down_atn_prefix, hf_down_atn_prefix))
51
+
52
+ for j in range(3):
53
+ # loop over resnets/attentions for upblocks
54
+ hf_up_res_prefix = f"up_blocks.{i}.resnets.{j}."
55
+ sd_up_res_prefix = f"output_blocks.{3 * i + j}.0."
56
+ unet_conversion_map_layer.append((sd_up_res_prefix, hf_up_res_prefix))
57
+
58
+ if i > 0:
59
+ # no attention layers in up_blocks.0
60
+ hf_up_atn_prefix = f"up_blocks.{i}.attentions.{j}."
61
+ sd_up_atn_prefix = f"output_blocks.{3 * i + j}.1."
62
+ unet_conversion_map_layer.append((sd_up_atn_prefix, hf_up_atn_prefix))
63
+
64
+ if i < 3:
65
+ # no downsample in down_blocks.3
66
+ hf_downsample_prefix = f"down_blocks.{i}.downsamplers.0.conv."
67
+ sd_downsample_prefix = f"input_blocks.{3 * (i + 1)}.0.op."
68
+ unet_conversion_map_layer.append((sd_downsample_prefix, hf_downsample_prefix))
69
+
70
+ # no upsample in up_blocks.3
71
+ hf_upsample_prefix = f"up_blocks.{i}.upsamplers.0."
72
+ sd_upsample_prefix = f"output_blocks.{3 * i + 2}.{1 if i == 0 else 2}."
73
+ unet_conversion_map_layer.append((sd_upsample_prefix, hf_upsample_prefix))
74
+
75
+ hf_mid_atn_prefix = "mid_block.attentions.0."
76
+ sd_mid_atn_prefix = "middle_block.1."
77
+ unet_conversion_map_layer.append((sd_mid_atn_prefix, hf_mid_atn_prefix))
78
+
79
+ for j in range(2):
80
+ hf_mid_res_prefix = f"mid_block.resnets.{j}."
81
+ sd_mid_res_prefix = f"middle_block.{2 * j}."
82
+ unet_conversion_map_layer.append((sd_mid_res_prefix, hf_mid_res_prefix))
83
+
84
+
85
+ def convert_unet_state_dict(unet_state_dict):
86
+ # buyer beware: this is a *brittle* function,
87
+ # and correct output requires that all of these pieces interact in
88
+ # the exact order in which I have arranged them.
89
+ mapping = {k: k for k in unet_state_dict.keys()}
90
+ for sd_name, hf_name in unet_conversion_map:
91
+ mapping[hf_name] = sd_name
92
+ for k, v in mapping.items():
93
+ if "resnets" in k:
94
+ for sd_part, hf_part in unet_conversion_map_resnet:
95
+ v = v.replace(hf_part, sd_part)
96
+ mapping[k] = v
97
+ for k, v in mapping.items():
98
+ for sd_part, hf_part in unet_conversion_map_layer:
99
+ v = v.replace(hf_part, sd_part)
100
+ mapping[k] = v
101
+ new_state_dict = {v: unet_state_dict[k] for k, v in mapping.items()}
102
+ return new_state_dict
103
+
104
+
105
+ # ================#
106
+ # VAE Conversion #
107
+ # ================#
108
+
109
+ vae_conversion_map = [
110
+ # (stable-diffusion, HF Diffusers)
111
+ ("nin_shortcut", "conv_shortcut"),
112
+ ("norm_out", "conv_norm_out"),
113
+ ("mid.attn_1.", "mid_block.attentions.0."),
114
+ ]
115
+
116
+ for i in range(4):
117
+ # down_blocks have two resnets
118
+ for j in range(2):
119
+ hf_down_prefix = f"encoder.down_blocks.{i}.resnets.{j}."
120
+ sd_down_prefix = f"encoder.down.{i}.block.{j}."
121
+ vae_conversion_map.append((sd_down_prefix, hf_down_prefix))
122
+
123
+ if i < 3:
124
+ hf_downsample_prefix = f"down_blocks.{i}.downsamplers.0."
125
+ sd_downsample_prefix = f"down.{i}.downsample."
126
+ vae_conversion_map.append((sd_downsample_prefix, hf_downsample_prefix))
127
+
128
+ hf_upsample_prefix = f"up_blocks.{i}.upsamplers.0."
129
+ sd_upsample_prefix = f"up.{3 - i}.upsample."
130
+ vae_conversion_map.append((sd_upsample_prefix, hf_upsample_prefix))
131
+
132
+ # up_blocks have three resnets
133
+ # also, up blocks in hf are numbered in reverse from sd
134
+ for j in range(3):
135
+ hf_up_prefix = f"decoder.up_blocks.{i}.resnets.{j}."
136
+ sd_up_prefix = f"decoder.up.{3 - i}.block.{j}."
137
+ vae_conversion_map.append((sd_up_prefix, hf_up_prefix))
138
+
139
+ # this part accounts for mid blocks in both the encoder and the decoder
140
+ for i in range(2):
141
+ hf_mid_res_prefix = f"mid_block.resnets.{i}."
142
+ sd_mid_res_prefix = f"mid.block_{i + 1}."
143
+ vae_conversion_map.append((sd_mid_res_prefix, hf_mid_res_prefix))
144
+
145
+ vae_conversion_map_attn = [
146
+ # (stable-diffusion, HF Diffusers)
147
+ ("norm.", "group_norm."),
148
+ ("q.", "query."),
149
+ ("k.", "key."),
150
+ ("v.", "value."),
151
+ ("q.", "to_q."),
152
+ ("k.", "to_k."),
153
+ ("v.", "to_v."),
154
+ ("proj_out.", "to_out.0."),
155
+ ("proj_out.", "proj_attn."),
156
+ ]
157
+
158
+
159
+ def reshape_weight_for_sd(w):
160
+ # convert HF linear weights to SD conv2d weights
161
+ return w.reshape(*w.shape, 1, 1)
162
+
163
+
164
+ def convert_vae_state_dict(vae_state_dict):
165
+ mapping = {k: k for k in vae_state_dict.keys()}
166
+ for k, v in mapping.items():
167
+ for sd_part, hf_part in vae_conversion_map:
168
+ v = v.replace(hf_part, sd_part)
169
+ mapping[k] = v
170
+ for k, v in mapping.items():
171
+ if "attentions" in k:
172
+ for sd_part, hf_part in vae_conversion_map_attn:
173
+ v = v.replace(hf_part, sd_part)
174
+ mapping[k] = v
175
+ new_state_dict = {v: vae_state_dict[k] for k, v in mapping.items()}
176
+ weights_to_convert = ["q", "k", "v", "proj_out"]
177
+ for k, v in new_state_dict.items():
178
+ for weight_name in weights_to_convert:
179
+ if f"mid.attn_1.{weight_name}.weight" in k:
180
+ print(f"Reshaping {k} for SD format")
181
+ new_state_dict[k] = reshape_weight_for_sd(v)
182
+ return new_state_dict
183
+
184
+
185
+ # =========================#
186
+ # Text Encoder Conversion #
187
+ # =========================#
188
+
189
+
190
+ textenc_conversion_lst = [
191
+ # (stable-diffusion, HF Diffusers)
192
+ ("resblocks.", "text_model.encoder.layers."),
193
+ ("ln_1", "layer_norm1"),
194
+ ("ln_2", "layer_norm2"),
195
+ (".c_fc.", ".fc1."),
196
+ (".c_proj.", ".fc2."),
197
+ (".attn", ".self_attn"),
198
+ ("ln_final.", "transformer.text_model.final_layer_norm."),
199
+ ("token_embedding.weight", "transformer.text_model.embeddings.token_embedding.weight"),
200
+ ("positional_embedding", "transformer.text_model.embeddings.position_embedding.weight"),
201
+ ]
202
+ protected = {re.escape(x[1]): x[0] for x in textenc_conversion_lst}
203
+ textenc_pattern = re.compile("|".join(protected.keys()))
204
+
205
+ # Ordering is from https://github.com/pytorch/pytorch/blob/master/test/cpp/api/modules.cpp
206
+ code2idx = {"q": 0, "k": 1, "v": 2}
207
+
208
+
209
+ def convert_text_enc_state_dict_v20(text_enc_dict, prefix=""):
210
+ new_state_dict = {}
211
+ capture_qkv_weight = {}
212
+ capture_qkv_bias = {}
213
+ for k, v in text_enc_dict.items():
214
+ if not k.startswith(prefix):
215
+ continue
216
+ if (
217
+ k.endswith(".self_attn.q_proj.weight")
218
+ or k.endswith(".self_attn.k_proj.weight")
219
+ or k.endswith(".self_attn.v_proj.weight")
220
+ ):
221
+ k_pre = k[: -len(".q_proj.weight")]
222
+ k_code = k[-len("q_proj.weight")]
223
+ if k_pre not in capture_qkv_weight:
224
+ capture_qkv_weight[k_pre] = [None, None, None]
225
+ capture_qkv_weight[k_pre][code2idx[k_code]] = v
226
+ continue
227
+
228
+ if (
229
+ k.endswith(".self_attn.q_proj.bias")
230
+ or k.endswith(".self_attn.k_proj.bias")
231
+ or k.endswith(".self_attn.v_proj.bias")
232
+ ):
233
+ k_pre = k[: -len(".q_proj.bias")]
234
+ k_code = k[-len("q_proj.bias")]
235
+ if k_pre not in capture_qkv_bias:
236
+ capture_qkv_bias[k_pre] = [None, None, None]
237
+ capture_qkv_bias[k_pre][code2idx[k_code]] = v
238
+ continue
239
+
240
+ relabelled_key = textenc_pattern.sub(lambda m: protected[re.escape(m.group(0))], k)
241
+ new_state_dict[relabelled_key] = v
242
+
243
+ for k_pre, tensors in capture_qkv_weight.items():
244
+ if None in tensors:
245
+ raise Exception("CORRUPTED MODEL: one of the q-k-v values for the text encoder was missing")
246
+ relabelled_key = textenc_pattern.sub(lambda m: protected[re.escape(m.group(0))], k_pre)
247
+ new_state_dict[relabelled_key + ".in_proj_weight"] = torch.cat(tensors)
248
+
249
+ for k_pre, tensors in capture_qkv_bias.items():
250
+ if None in tensors:
251
+ raise Exception("CORRUPTED MODEL: one of the q-k-v values for the text encoder was missing")
252
+ relabelled_key = textenc_pattern.sub(lambda m: protected[re.escape(m.group(0))], k_pre)
253
+ new_state_dict[relabelled_key + ".in_proj_bias"] = torch.cat(tensors)
254
+
255
+ return new_state_dict
256
+
257
+
258
+ def convert_text_enc_state_dict(text_enc_dict):
259
+ return text_enc_dict
260
+
261
+
backend/headless/fcbh/diffusers_load.py ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import os
3
+
4
+ import fcbh.sd
5
+
6
+ def first_file(path, filenames):
7
+ for f in filenames:
8
+ p = os.path.join(path, f)
9
+ if os.path.exists(p):
10
+ return p
11
+ return None
12
+
13
+ def load_diffusers(model_path, output_vae=True, output_clip=True, embedding_directory=None):
14
+ diffusion_model_names = ["diffusion_pytorch_model.fp16.safetensors", "diffusion_pytorch_model.safetensors", "diffusion_pytorch_model.fp16.bin", "diffusion_pytorch_model.bin"]
15
+ unet_path = first_file(os.path.join(model_path, "unet"), diffusion_model_names)
16
+ vae_path = first_file(os.path.join(model_path, "vae"), diffusion_model_names)
17
+
18
+ text_encoder_model_names = ["model.fp16.safetensors", "model.safetensors", "pytorch_model.fp16.bin", "pytorch_model.bin"]
19
+ text_encoder1_path = first_file(os.path.join(model_path, "text_encoder"), text_encoder_model_names)
20
+ text_encoder2_path = first_file(os.path.join(model_path, "text_encoder_2"), text_encoder_model_names)
21
+
22
+ text_encoder_paths = [text_encoder1_path]
23
+ if text_encoder2_path is not None:
24
+ text_encoder_paths.append(text_encoder2_path)
25
+
26
+ unet = fcbh.sd.load_unet(unet_path)
27
+
28
+ clip = None
29
+ if output_clip:
30
+ clip = fcbh.sd.load_clip(text_encoder_paths, embedding_directory=embedding_directory)
31
+
32
+ vae = None
33
+ if output_vae:
34
+ sd = fcbh.utils.load_torch_file(vae_path)
35
+ vae = fcbh.sd.VAE(sd=sd)
36
+
37
+ return (unet, clip, vae)
backend/headless/fcbh/extra_samplers/uni_pc.py ADDED
@@ -0,0 +1,894 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #code taken from: https://github.com/wl-zhao/UniPC and modified
2
+
3
+ import torch
4
+ import torch.nn.functional as F
5
+ import math
6
+
7
+ from tqdm.auto import trange, tqdm
8
+
9
+
10
+ class NoiseScheduleVP:
11
+ def __init__(
12
+ self,
13
+ schedule='discrete',
14
+ betas=None,
15
+ alphas_cumprod=None,
16
+ continuous_beta_0=0.1,
17
+ continuous_beta_1=20.,
18
+ ):
19
+ """Create a wrapper class for the forward SDE (VP type).
20
+
21
+ ***
22
+ Update: We support discrete-time diffusion models by implementing a picewise linear interpolation for log_alpha_t.
23
+ We recommend to use schedule='discrete' for the discrete-time diffusion models, especially for high-resolution images.
24
+ ***
25
+
26
+ The forward SDE ensures that the condition distribution q_{t|0}(x_t | x_0) = N ( alpha_t * x_0, sigma_t^2 * I ).
27
+ We further define lambda_t = log(alpha_t) - log(sigma_t), which is the half-logSNR (described in the DPM-Solver paper).
28
+ Therefore, we implement the functions for computing alpha_t, sigma_t and lambda_t. For t in [0, T], we have:
29
+
30
+ log_alpha_t = self.marginal_log_mean_coeff(t)
31
+ sigma_t = self.marginal_std(t)
32
+ lambda_t = self.marginal_lambda(t)
33
+
34
+ Moreover, as lambda(t) is an invertible function, we also support its inverse function:
35
+
36
+ t = self.inverse_lambda(lambda_t)
37
+
38
+ ===============================================================
39
+
40
+ We support both discrete-time DPMs (trained on n = 0, 1, ..., N-1) and continuous-time DPMs (trained on t in [t_0, T]).
41
+
42
+ 1. For discrete-time DPMs:
43
+
44
+ For discrete-time DPMs trained on n = 0, 1, ..., N-1, we convert the discrete steps to continuous time steps by:
45
+ t_i = (i + 1) / N
46
+ e.g. for N = 1000, we have t_0 = 1e-3 and T = t_{N-1} = 1.
47
+ We solve the corresponding diffusion ODE from time T = 1 to time t_0 = 1e-3.
48
+
49
+ Args:
50
+ betas: A `torch.Tensor`. The beta array for the discrete-time DPM. (See the original DDPM paper for details)
51
+ alphas_cumprod: A `torch.Tensor`. The cumprod alphas for the discrete-time DPM. (See the original DDPM paper for details)
52
+
53
+ Note that we always have alphas_cumprod = cumprod(betas). Therefore, we only need to set one of `betas` and `alphas_cumprod`.
54
+
55
+ **Important**: Please pay special attention for the args for `alphas_cumprod`:
56
+ The `alphas_cumprod` is the \hat{alpha_n} arrays in the notations of DDPM. Specifically, DDPMs assume that
57
+ q_{t_n | 0}(x_{t_n} | x_0) = N ( \sqrt{\hat{alpha_n}} * x_0, (1 - \hat{alpha_n}) * I ).
58
+ Therefore, the notation \hat{alpha_n} is different from the notation alpha_t in DPM-Solver. In fact, we have
59
+ alpha_{t_n} = \sqrt{\hat{alpha_n}},
60
+ and
61
+ log(alpha_{t_n}) = 0.5 * log(\hat{alpha_n}).
62
+
63
+
64
+ 2. For continuous-time DPMs:
65
+
66
+ We support two types of VPSDEs: linear (DDPM) and cosine (improved-DDPM). The hyperparameters for the noise
67
+ schedule are the default settings in DDPM and improved-DDPM:
68
+
69
+ Args:
70
+ beta_min: A `float` number. The smallest beta for the linear schedule.
71
+ beta_max: A `float` number. The largest beta for the linear schedule.
72
+ cosine_s: A `float` number. The hyperparameter in the cosine schedule.
73
+ cosine_beta_max: A `float` number. The hyperparameter in the cosine schedule.
74
+ T: A `float` number. The ending time of the forward process.
75
+
76
+ ===============================================================
77
+
78
+ Args:
79
+ schedule: A `str`. The noise schedule of the forward SDE. 'discrete' for discrete-time DPMs,
80
+ 'linear' or 'cosine' for continuous-time DPMs.
81
+ Returns:
82
+ A wrapper object of the forward SDE (VP type).
83
+
84
+ ===============================================================
85
+
86
+ Example:
87
+
88
+ # For discrete-time DPMs, given betas (the beta array for n = 0, 1, ..., N - 1):
89
+ >>> ns = NoiseScheduleVP('discrete', betas=betas)
90
+
91
+ # For discrete-time DPMs, given alphas_cumprod (the \hat{alpha_n} array for n = 0, 1, ..., N - 1):
92
+ >>> ns = NoiseScheduleVP('discrete', alphas_cumprod=alphas_cumprod)
93
+
94
+ # For continuous-time DPMs (VPSDE), linear schedule:
95
+ >>> ns = NoiseScheduleVP('linear', continuous_beta_0=0.1, continuous_beta_1=20.)
96
+
97
+ """
98
+
99
+ if schedule not in ['discrete', 'linear', 'cosine']:
100
+ raise ValueError("Unsupported noise schedule {}. The schedule needs to be 'discrete' or 'linear' or 'cosine'".format(schedule))
101
+
102
+ self.schedule = schedule
103
+ if schedule == 'discrete':
104
+ if betas is not None:
105
+ log_alphas = 0.5 * torch.log(1 - betas).cumsum(dim=0)
106
+ else:
107
+ assert alphas_cumprod is not None
108
+ log_alphas = 0.5 * torch.log(alphas_cumprod)
109
+ self.total_N = len(log_alphas)
110
+ self.T = 1.
111
+ self.t_array = torch.linspace(0., 1., self.total_N + 1)[1:].reshape((1, -1))
112
+ self.log_alpha_array = log_alphas.reshape((1, -1,))
113
+ else:
114
+ self.total_N = 1000
115
+ self.beta_0 = continuous_beta_0
116
+ self.beta_1 = continuous_beta_1
117
+ self.cosine_s = 0.008
118
+ self.cosine_beta_max = 999.
119
+ self.cosine_t_max = math.atan(self.cosine_beta_max * (1. + self.cosine_s) / math.pi) * 2. * (1. + self.cosine_s) / math.pi - self.cosine_s
120
+ self.cosine_log_alpha_0 = math.log(math.cos(self.cosine_s / (1. + self.cosine_s) * math.pi / 2.))
121
+ self.schedule = schedule
122
+ if schedule == 'cosine':
123
+ # For the cosine schedule, T = 1 will have numerical issues. So we manually set the ending time T.
124
+ # Note that T = 0.9946 may be not the optimal setting. However, we find it works well.
125
+ self.T = 0.9946
126
+ else:
127
+ self.T = 1.
128
+
129
+ def marginal_log_mean_coeff(self, t):
130
+ """
131
+ Compute log(alpha_t) of a given continuous-time label t in [0, T].
132
+ """
133
+ if self.schedule == 'discrete':
134
+ return interpolate_fn(t.reshape((-1, 1)), self.t_array.to(t.device), self.log_alpha_array.to(t.device)).reshape((-1))
135
+ elif self.schedule == 'linear':
136
+ return -0.25 * t ** 2 * (self.beta_1 - self.beta_0) - 0.5 * t * self.beta_0
137
+ elif self.schedule == 'cosine':
138
+ log_alpha_fn = lambda s: torch.log(torch.cos((s + self.cosine_s) / (1. + self.cosine_s) * math.pi / 2.))
139
+ log_alpha_t = log_alpha_fn(t) - self.cosine_log_alpha_0
140
+ return log_alpha_t
141
+
142
+ def marginal_alpha(self, t):
143
+ """
144
+ Compute alpha_t of a given continuous-time label t in [0, T].
145
+ """
146
+ return torch.exp(self.marginal_log_mean_coeff(t))
147
+
148
+ def marginal_std(self, t):
149
+ """
150
+ Compute sigma_t of a given continuous-time label t in [0, T].
151
+ """
152
+ return torch.sqrt(1. - torch.exp(2. * self.marginal_log_mean_coeff(t)))
153
+
154
+ def marginal_lambda(self, t):
155
+ """
156
+ Compute lambda_t = log(alpha_t) - log(sigma_t) of a given continuous-time label t in [0, T].
157
+ """
158
+ log_mean_coeff = self.marginal_log_mean_coeff(t)
159
+ log_std = 0.5 * torch.log(1. - torch.exp(2. * log_mean_coeff))
160
+ return log_mean_coeff - log_std
161
+
162
+ def inverse_lambda(self, lamb):
163
+ """
164
+ Compute the continuous-time label t in [0, T] of a given half-logSNR lambda_t.
165
+ """
166
+ if self.schedule == 'linear':
167
+ tmp = 2. * (self.beta_1 - self.beta_0) * torch.logaddexp(-2. * lamb, torch.zeros((1,)).to(lamb))
168
+ Delta = self.beta_0**2 + tmp
169
+ return tmp / (torch.sqrt(Delta) + self.beta_0) / (self.beta_1 - self.beta_0)
170
+ elif self.schedule == 'discrete':
171
+ log_alpha = -0.5 * torch.logaddexp(torch.zeros((1,)).to(lamb.device), -2. * lamb)
172
+ t = interpolate_fn(log_alpha.reshape((-1, 1)), torch.flip(self.log_alpha_array.to(lamb.device), [1]), torch.flip(self.t_array.to(lamb.device), [1]))
173
+ return t.reshape((-1,))
174
+ else:
175
+ log_alpha = -0.5 * torch.logaddexp(-2. * lamb, torch.zeros((1,)).to(lamb))
176
+ t_fn = lambda log_alpha_t: torch.arccos(torch.exp(log_alpha_t + self.cosine_log_alpha_0)) * 2. * (1. + self.cosine_s) / math.pi - self.cosine_s
177
+ t = t_fn(log_alpha)
178
+ return t
179
+
180
+
181
+ def model_wrapper(
182
+ model,
183
+ noise_schedule,
184
+ model_type="noise",
185
+ model_kwargs={},
186
+ guidance_type="uncond",
187
+ condition=None,
188
+ unconditional_condition=None,
189
+ guidance_scale=1.,
190
+ classifier_fn=None,
191
+ classifier_kwargs={},
192
+ ):
193
+ """Create a wrapper function for the noise prediction model.
194
+
195
+ DPM-Solver needs to solve the continuous-time diffusion ODEs. For DPMs trained on discrete-time labels, we need to
196
+ firstly wrap the model function to a noise prediction model that accepts the continuous time as the input.
197
+
198
+ We support four types of the diffusion model by setting `model_type`:
199
+
200
+ 1. "noise": noise prediction model. (Trained by predicting noise).
201
+
202
+ 2. "x_start": data prediction model. (Trained by predicting the data x_0 at time 0).
203
+
204
+ 3. "v": velocity prediction model. (Trained by predicting the velocity).
205
+ The "v" prediction is derivation detailed in Appendix D of [1], and is used in Imagen-Video [2].
206
+
207
+ [1] Salimans, Tim, and Jonathan Ho. "Progressive distillation for fast sampling of diffusion models."
208
+ arXiv preprint arXiv:2202.00512 (2022).
209
+ [2] Ho, Jonathan, et al. "Imagen Video: High Definition Video Generation with Diffusion Models."
210
+ arXiv preprint arXiv:2210.02303 (2022).
211
+
212
+ 4. "score": marginal score function. (Trained by denoising score matching).
213
+ Note that the score function and the noise prediction model follows a simple relationship:
214
+ ```
215
+ noise(x_t, t) = -sigma_t * score(x_t, t)
216
+ ```
217
+
218
+ We support three types of guided sampling by DPMs by setting `guidance_type`:
219
+ 1. "uncond": unconditional sampling by DPMs.
220
+ The input `model` has the following format:
221
+ ``
222
+ model(x, t_input, **model_kwargs) -> noise | x_start | v | score
223
+ ``
224
+
225
+ 2. "classifier": classifier guidance sampling [3] by DPMs and another classifier.
226
+ The input `model` has the following format:
227
+ ``
228
+ model(x, t_input, **model_kwargs) -> noise | x_start | v | score
229
+ ``
230
+
231
+ The input `classifier_fn` has the following format:
232
+ ``
233
+ classifier_fn(x, t_input, cond, **classifier_kwargs) -> logits(x, t_input, cond)
234
+ ``
235
+
236
+ [3] P. Dhariwal and A. Q. Nichol, "Diffusion models beat GANs on image synthesis,"
237
+ in Advances in Neural Information Processing Systems, vol. 34, 2021, pp. 8780-8794.
238
+
239
+ 3. "classifier-free": classifier-free guidance sampling by conditional DPMs.
240
+ The input `model` has the following format:
241
+ ``
242
+ model(x, t_input, cond, **model_kwargs) -> noise | x_start | v | score
243
+ ``
244
+ And if cond == `unconditional_condition`, the model output is the unconditional DPM output.
245
+
246
+ [4] Ho, Jonathan, and Tim Salimans. "Classifier-free diffusion guidance."
247
+ arXiv preprint arXiv:2207.12598 (2022).
248
+
249
+
250
+ The `t_input` is the time label of the model, which may be discrete-time labels (i.e. 0 to 999)
251
+ or continuous-time labels (i.e. epsilon to T).
252
+
253
+ We wrap the model function to accept only `x` and `t_continuous` as inputs, and outputs the predicted noise:
254
+ ``
255
+ def model_fn(x, t_continuous) -> noise:
256
+ t_input = get_model_input_time(t_continuous)
257
+ return noise_pred(model, x, t_input, **model_kwargs)
258
+ ``
259
+ where `t_continuous` is the continuous time labels (i.e. epsilon to T). And we use `model_fn` for DPM-Solver.
260
+
261
+ ===============================================================
262
+
263
+ Args:
264
+ model: A diffusion model with the corresponding format described above.
265
+ noise_schedule: A noise schedule object, such as NoiseScheduleVP.
266
+ model_type: A `str`. The parameterization type of the diffusion model.
267
+ "noise" or "x_start" or "v" or "score".
268
+ model_kwargs: A `dict`. A dict for the other inputs of the model function.
269
+ guidance_type: A `str`. The type of the guidance for sampling.
270
+ "uncond" or "classifier" or "classifier-free".
271
+ condition: A pytorch tensor. The condition for the guided sampling.
272
+ Only used for "classifier" or "classifier-free" guidance type.
273
+ unconditional_condition: A pytorch tensor. The condition for the unconditional sampling.
274
+ Only used for "classifier-free" guidance type.
275
+ guidance_scale: A `float`. The scale for the guided sampling.
276
+ classifier_fn: A classifier function. Only used for the classifier guidance.
277
+ classifier_kwargs: A `dict`. A dict for the other inputs of the classifier function.
278
+ Returns:
279
+ A noise prediction model that accepts the noised data and the continuous time as the inputs.
280
+ """
281
+
282
+ def get_model_input_time(t_continuous):
283
+ """
284
+ Convert the continuous-time `t_continuous` (in [epsilon, T]) to the model input time.
285
+ For discrete-time DPMs, we convert `t_continuous` in [1 / N, 1] to `t_input` in [0, 1000 * (N - 1) / N].
286
+ For continuous-time DPMs, we just use `t_continuous`.
287
+ """
288
+ if noise_schedule.schedule == 'discrete':
289
+ return (t_continuous - 1. / noise_schedule.total_N) * 1000.
290
+ else:
291
+ return t_continuous
292
+
293
+ def noise_pred_fn(x, t_continuous, cond=None):
294
+ if t_continuous.reshape((-1,)).shape[0] == 1:
295
+ t_continuous = t_continuous.expand((x.shape[0]))
296
+ t_input = get_model_input_time(t_continuous)
297
+ output = model(x, t_input, **model_kwargs)
298
+ if model_type == "noise":
299
+ return output
300
+ elif model_type == "x_start":
301
+ alpha_t, sigma_t = noise_schedule.marginal_alpha(t_continuous), noise_schedule.marginal_std(t_continuous)
302
+ dims = x.dim()
303
+ return (x - expand_dims(alpha_t, dims) * output) / expand_dims(sigma_t, dims)
304
+ elif model_type == "v":
305
+ alpha_t, sigma_t = noise_schedule.marginal_alpha(t_continuous), noise_schedule.marginal_std(t_continuous)
306
+ dims = x.dim()
307
+ return expand_dims(alpha_t, dims) * output + expand_dims(sigma_t, dims) * x
308
+ elif model_type == "score":
309
+ sigma_t = noise_schedule.marginal_std(t_continuous)
310
+ dims = x.dim()
311
+ return -expand_dims(sigma_t, dims) * output
312
+
313
+ def cond_grad_fn(x, t_input):
314
+ """
315
+ Compute the gradient of the classifier, i.e. nabla_{x} log p_t(cond | x_t).
316
+ """
317
+ with torch.enable_grad():
318
+ x_in = x.detach().requires_grad_(True)
319
+ log_prob = classifier_fn(x_in, t_input, condition, **classifier_kwargs)
320
+ return torch.autograd.grad(log_prob.sum(), x_in)[0]
321
+
322
+ def model_fn(x, t_continuous):
323
+ """
324
+ The noise predicition model function that is used for DPM-Solver.
325
+ """
326
+ if t_continuous.reshape((-1,)).shape[0] == 1:
327
+ t_continuous = t_continuous.expand((x.shape[0]))
328
+ if guidance_type == "uncond":
329
+ return noise_pred_fn(x, t_continuous)
330
+ elif guidance_type == "classifier":
331
+ assert classifier_fn is not None
332
+ t_input = get_model_input_time(t_continuous)
333
+ cond_grad = cond_grad_fn(x, t_input)
334
+ sigma_t = noise_schedule.marginal_std(t_continuous)
335
+ noise = noise_pred_fn(x, t_continuous)
336
+ return noise - guidance_scale * expand_dims(sigma_t, dims=cond_grad.dim()) * cond_grad
337
+ elif guidance_type == "classifier-free":
338
+ if guidance_scale == 1. or unconditional_condition is None:
339
+ return noise_pred_fn(x, t_continuous, cond=condition)
340
+ else:
341
+ x_in = torch.cat([x] * 2)
342
+ t_in = torch.cat([t_continuous] * 2)
343
+ c_in = torch.cat([unconditional_condition, condition])
344
+ noise_uncond, noise = noise_pred_fn(x_in, t_in, cond=c_in).chunk(2)
345
+ return noise_uncond + guidance_scale * (noise - noise_uncond)
346
+
347
+ assert model_type in ["noise", "x_start", "v"]
348
+ assert guidance_type in ["uncond", "classifier", "classifier-free"]
349
+ return model_fn
350
+
351
+
352
+ class UniPC:
353
+ def __init__(
354
+ self,
355
+ model_fn,
356
+ noise_schedule,
357
+ predict_x0=True,
358
+ thresholding=False,
359
+ max_val=1.,
360
+ variant='bh1',
361
+ noise_mask=None,
362
+ masked_image=None,
363
+ noise=None,
364
+ ):
365
+ """Construct a UniPC.
366
+
367
+ We support both data_prediction and noise_prediction.
368
+ """
369
+ self.model = model_fn
370
+ self.noise_schedule = noise_schedule
371
+ self.variant = variant
372
+ self.predict_x0 = predict_x0
373
+ self.thresholding = thresholding
374
+ self.max_val = max_val
375
+ self.noise_mask = noise_mask
376
+ self.masked_image = masked_image
377
+ self.noise = noise
378
+
379
+ def dynamic_thresholding_fn(self, x0, t=None):
380
+ """
381
+ The dynamic thresholding method.
382
+ """
383
+ dims = x0.dim()
384
+ p = self.dynamic_thresholding_ratio
385
+ s = torch.quantile(torch.abs(x0).reshape((x0.shape[0], -1)), p, dim=1)
386
+ s = expand_dims(torch.maximum(s, self.thresholding_max_val * torch.ones_like(s).to(s.device)), dims)
387
+ x0 = torch.clamp(x0, -s, s) / s
388
+ return x0
389
+
390
+ def noise_prediction_fn(self, x, t):
391
+ """
392
+ Return the noise prediction model.
393
+ """
394
+ if self.noise_mask is not None:
395
+ return self.model(x, t) * self.noise_mask
396
+ else:
397
+ return self.model(x, t)
398
+
399
+ def data_prediction_fn(self, x, t):
400
+ """
401
+ Return the data prediction model (with thresholding).
402
+ """
403
+ noise = self.noise_prediction_fn(x, t)
404
+ dims = x.dim()
405
+ alpha_t, sigma_t = self.noise_schedule.marginal_alpha(t), self.noise_schedule.marginal_std(t)
406
+ x0 = (x - expand_dims(sigma_t, dims) * noise) / expand_dims(alpha_t, dims)
407
+ if self.thresholding:
408
+ p = 0.995 # A hyperparameter in the paper of "Imagen" [1].
409
+ s = torch.quantile(torch.abs(x0).reshape((x0.shape[0], -1)), p, dim=1)
410
+ s = expand_dims(torch.maximum(s, self.max_val * torch.ones_like(s).to(s.device)), dims)
411
+ x0 = torch.clamp(x0, -s, s) / s
412
+ if self.noise_mask is not None:
413
+ x0 = x0 * self.noise_mask + (1. - self.noise_mask) * self.masked_image
414
+ return x0
415
+
416
+ def model_fn(self, x, t):
417
+ """
418
+ Convert the model to the noise prediction model or the data prediction model.
419
+ """
420
+ if self.predict_x0:
421
+ return self.data_prediction_fn(x, t)
422
+ else:
423
+ return self.noise_prediction_fn(x, t)
424
+
425
+ def get_time_steps(self, skip_type, t_T, t_0, N, device):
426
+ """Compute the intermediate time steps for sampling.
427
+ """
428
+ if skip_type == 'logSNR':
429
+ lambda_T = self.noise_schedule.marginal_lambda(torch.tensor(t_T).to(device))
430
+ lambda_0 = self.noise_schedule.marginal_lambda(torch.tensor(t_0).to(device))
431
+ logSNR_steps = torch.linspace(lambda_T.cpu().item(), lambda_0.cpu().item(), N + 1).to(device)
432
+ return self.noise_schedule.inverse_lambda(logSNR_steps)
433
+ elif skip_type == 'time_uniform':
434
+ return torch.linspace(t_T, t_0, N + 1).to(device)
435
+ elif skip_type == 'time_quadratic':
436
+ t_order = 2
437
+ t = torch.linspace(t_T**(1. / t_order), t_0**(1. / t_order), N + 1).pow(t_order).to(device)
438
+ return t
439
+ else:
440
+ raise ValueError("Unsupported skip_type {}, need to be 'logSNR' or 'time_uniform' or 'time_quadratic'".format(skip_type))
441
+
442
+ def get_orders_and_timesteps_for_singlestep_solver(self, steps, order, skip_type, t_T, t_0, device):
443
+ """
444
+ Get the order of each step for sampling by the singlestep DPM-Solver.
445
+ """
446
+ if order == 3:
447
+ K = steps // 3 + 1
448
+ if steps % 3 == 0:
449
+ orders = [3,] * (K - 2) + [2, 1]
450
+ elif steps % 3 == 1:
451
+ orders = [3,] * (K - 1) + [1]
452
+ else:
453
+ orders = [3,] * (K - 1) + [2]
454
+ elif order == 2:
455
+ if steps % 2 == 0:
456
+ K = steps // 2
457
+ orders = [2,] * K
458
+ else:
459
+ K = steps // 2 + 1
460
+ orders = [2,] * (K - 1) + [1]
461
+ elif order == 1:
462
+ K = steps
463
+ orders = [1,] * steps
464
+ else:
465
+ raise ValueError("'order' must be '1' or '2' or '3'.")
466
+ if skip_type == 'logSNR':
467
+ # To reproduce the results in DPM-Solver paper
468
+ timesteps_outer = self.get_time_steps(skip_type, t_T, t_0, K, device)
469
+ else:
470
+ timesteps_outer = self.get_time_steps(skip_type, t_T, t_0, steps, device)[torch.cumsum(torch.tensor([0,] + orders), 0).to(device)]
471
+ return timesteps_outer, orders
472
+
473
+ def denoise_to_zero_fn(self, x, s):
474
+ """
475
+ Denoise at the final step, which is equivalent to solve the ODE from lambda_s to infty by first-order discretization.
476
+ """
477
+ return self.data_prediction_fn(x, s)
478
+
479
+ def multistep_uni_pc_update(self, x, model_prev_list, t_prev_list, t, order, **kwargs):
480
+ if len(t.shape) == 0:
481
+ t = t.view(-1)
482
+ if 'bh' in self.variant:
483
+ return self.multistep_uni_pc_bh_update(x, model_prev_list, t_prev_list, t, order, **kwargs)
484
+ else:
485
+ assert self.variant == 'vary_coeff'
486
+ return self.multistep_uni_pc_vary_update(x, model_prev_list, t_prev_list, t, order, **kwargs)
487
+
488
+ def multistep_uni_pc_vary_update(self, x, model_prev_list, t_prev_list, t, order, use_corrector=True):
489
+ print(f'using unified predictor-corrector with order {order} (solver type: vary coeff)')
490
+ ns = self.noise_schedule
491
+ assert order <= len(model_prev_list)
492
+
493
+ # first compute rks
494
+ t_prev_0 = t_prev_list[-1]
495
+ lambda_prev_0 = ns.marginal_lambda(t_prev_0)
496
+ lambda_t = ns.marginal_lambda(t)
497
+ model_prev_0 = model_prev_list[-1]
498
+ sigma_prev_0, sigma_t = ns.marginal_std(t_prev_0), ns.marginal_std(t)
499
+ log_alpha_t = ns.marginal_log_mean_coeff(t)
500
+ alpha_t = torch.exp(log_alpha_t)
501
+
502
+ h = lambda_t - lambda_prev_0
503
+
504
+ rks = []
505
+ D1s = []
506
+ for i in range(1, order):
507
+ t_prev_i = t_prev_list[-(i + 1)]
508
+ model_prev_i = model_prev_list[-(i + 1)]
509
+ lambda_prev_i = ns.marginal_lambda(t_prev_i)
510
+ rk = (lambda_prev_i - lambda_prev_0) / h
511
+ rks.append(rk)
512
+ D1s.append((model_prev_i - model_prev_0) / rk)
513
+
514
+ rks.append(1.)
515
+ rks = torch.tensor(rks, device=x.device)
516
+
517
+ K = len(rks)
518
+ # build C matrix
519
+ C = []
520
+
521
+ col = torch.ones_like(rks)
522
+ for k in range(1, K + 1):
523
+ C.append(col)
524
+ col = col * rks / (k + 1)
525
+ C = torch.stack(C, dim=1)
526
+
527
+ if len(D1s) > 0:
528
+ D1s = torch.stack(D1s, dim=1) # (B, K)
529
+ C_inv_p = torch.linalg.inv(C[:-1, :-1])
530
+ A_p = C_inv_p
531
+
532
+ if use_corrector:
533
+ print('using corrector')
534
+ C_inv = torch.linalg.inv(C)
535
+ A_c = C_inv
536
+
537
+ hh = -h if self.predict_x0 else h
538
+ h_phi_1 = torch.expm1(hh)
539
+ h_phi_ks = []
540
+ factorial_k = 1
541
+ h_phi_k = h_phi_1
542
+ for k in range(1, K + 2):
543
+ h_phi_ks.append(h_phi_k)
544
+ h_phi_k = h_phi_k / hh - 1 / factorial_k
545
+ factorial_k *= (k + 1)
546
+
547
+ model_t = None
548
+ if self.predict_x0:
549
+ x_t_ = (
550
+ sigma_t / sigma_prev_0 * x
551
+ - alpha_t * h_phi_1 * model_prev_0
552
+ )
553
+ # now predictor
554
+ x_t = x_t_
555
+ if len(D1s) > 0:
556
+ # compute the residuals for predictor
557
+ for k in range(K - 1):
558
+ x_t = x_t - alpha_t * h_phi_ks[k + 1] * torch.einsum('bkchw,k->bchw', D1s, A_p[k])
559
+ # now corrector
560
+ if use_corrector:
561
+ model_t = self.model_fn(x_t, t)
562
+ D1_t = (model_t - model_prev_0)
563
+ x_t = x_t_
564
+ k = 0
565
+ for k in range(K - 1):
566
+ x_t = x_t - alpha_t * h_phi_ks[k + 1] * torch.einsum('bkchw,k->bchw', D1s, A_c[k][:-1])
567
+ x_t = x_t - alpha_t * h_phi_ks[K] * (D1_t * A_c[k][-1])
568
+ else:
569
+ log_alpha_prev_0, log_alpha_t = ns.marginal_log_mean_coeff(t_prev_0), ns.marginal_log_mean_coeff(t)
570
+ x_t_ = (
571
+ (torch.exp(log_alpha_t - log_alpha_prev_0)) * x
572
+ - (sigma_t * h_phi_1) * model_prev_0
573
+ )
574
+ # now predictor
575
+ x_t = x_t_
576
+ if len(D1s) > 0:
577
+ # compute the residuals for predictor
578
+ for k in range(K - 1):
579
+ x_t = x_t - sigma_t * h_phi_ks[k + 1] * torch.einsum('bkchw,k->bchw', D1s, A_p[k])
580
+ # now corrector
581
+ if use_corrector:
582
+ model_t = self.model_fn(x_t, t)
583
+ D1_t = (model_t - model_prev_0)
584
+ x_t = x_t_
585
+ k = 0
586
+ for k in range(K - 1):
587
+ x_t = x_t - sigma_t * h_phi_ks[k + 1] * torch.einsum('bkchw,k->bchw', D1s, A_c[k][:-1])
588
+ x_t = x_t - sigma_t * h_phi_ks[K] * (D1_t * A_c[k][-1])
589
+ return x_t, model_t
590
+
591
+ def multistep_uni_pc_bh_update(self, x, model_prev_list, t_prev_list, t, order, x_t=None, use_corrector=True):
592
+ # print(f'using unified predictor-corrector with order {order} (solver type: B(h))')
593
+ ns = self.noise_schedule
594
+ assert order <= len(model_prev_list)
595
+ dims = x.dim()
596
+
597
+ # first compute rks
598
+ t_prev_0 = t_prev_list[-1]
599
+ lambda_prev_0 = ns.marginal_lambda(t_prev_0)
600
+ lambda_t = ns.marginal_lambda(t)
601
+ model_prev_0 = model_prev_list[-1]
602
+ sigma_prev_0, sigma_t = ns.marginal_std(t_prev_0), ns.marginal_std(t)
603
+ log_alpha_prev_0, log_alpha_t = ns.marginal_log_mean_coeff(t_prev_0), ns.marginal_log_mean_coeff(t)
604
+ alpha_t = torch.exp(log_alpha_t)
605
+
606
+ h = lambda_t - lambda_prev_0
607
+
608
+ rks = []
609
+ D1s = []
610
+ for i in range(1, order):
611
+ t_prev_i = t_prev_list[-(i + 1)]
612
+ model_prev_i = model_prev_list[-(i + 1)]
613
+ lambda_prev_i = ns.marginal_lambda(t_prev_i)
614
+ rk = ((lambda_prev_i - lambda_prev_0) / h)[0]
615
+ rks.append(rk)
616
+ D1s.append((model_prev_i - model_prev_0) / rk)
617
+
618
+ rks.append(1.)
619
+ rks = torch.tensor(rks, device=x.device)
620
+
621
+ R = []
622
+ b = []
623
+
624
+ hh = -h[0] if self.predict_x0 else h[0]
625
+ h_phi_1 = torch.expm1(hh) # h\phi_1(h) = e^h - 1
626
+ h_phi_k = h_phi_1 / hh - 1
627
+
628
+ factorial_i = 1
629
+
630
+ if self.variant == 'bh1':
631
+ B_h = hh
632
+ elif self.variant == 'bh2':
633
+ B_h = torch.expm1(hh)
634
+ else:
635
+ raise NotImplementedError()
636
+
637
+ for i in range(1, order + 1):
638
+ R.append(torch.pow(rks, i - 1))
639
+ b.append(h_phi_k * factorial_i / B_h)
640
+ factorial_i *= (i + 1)
641
+ h_phi_k = h_phi_k / hh - 1 / factorial_i
642
+
643
+ R = torch.stack(R)
644
+ b = torch.tensor(b, device=x.device)
645
+
646
+ # now predictor
647
+ use_predictor = len(D1s) > 0 and x_t is None
648
+ if len(D1s) > 0:
649
+ D1s = torch.stack(D1s, dim=1) # (B, K)
650
+ if x_t is None:
651
+ # for order 2, we use a simplified version
652
+ if order == 2:
653
+ rhos_p = torch.tensor([0.5], device=b.device)
654
+ else:
655
+ rhos_p = torch.linalg.solve(R[:-1, :-1], b[:-1])
656
+ else:
657
+ D1s = None
658
+
659
+ if use_corrector:
660
+ # print('using corrector')
661
+ # for order 1, we use a simplified version
662
+ if order == 1:
663
+ rhos_c = torch.tensor([0.5], device=b.device)
664
+ else:
665
+ rhos_c = torch.linalg.solve(R, b)
666
+
667
+ model_t = None
668
+ if self.predict_x0:
669
+ x_t_ = (
670
+ expand_dims(sigma_t / sigma_prev_0, dims) * x
671
+ - expand_dims(alpha_t * h_phi_1, dims)* model_prev_0
672
+ )
673
+
674
+ if x_t is None:
675
+ if use_predictor:
676
+ pred_res = torch.einsum('k,bkchw->bchw', rhos_p, D1s)
677
+ else:
678
+ pred_res = 0
679
+ x_t = x_t_ - expand_dims(alpha_t * B_h, dims) * pred_res
680
+
681
+ if use_corrector:
682
+ model_t = self.model_fn(x_t, t)
683
+ if D1s is not None:
684
+ corr_res = torch.einsum('k,bkchw->bchw', rhos_c[:-1], D1s)
685
+ else:
686
+ corr_res = 0
687
+ D1_t = (model_t - model_prev_0)
688
+ x_t = x_t_ - expand_dims(alpha_t * B_h, dims) * (corr_res + rhos_c[-1] * D1_t)
689
+ else:
690
+ x_t_ = (
691
+ expand_dims(torch.exp(log_alpha_t - log_alpha_prev_0), dims) * x
692
+ - expand_dims(sigma_t * h_phi_1, dims) * model_prev_0
693
+ )
694
+ if x_t is None:
695
+ if use_predictor:
696
+ pred_res = torch.einsum('k,bkchw->bchw', rhos_p, D1s)
697
+ else:
698
+ pred_res = 0
699
+ x_t = x_t_ - expand_dims(sigma_t * B_h, dims) * pred_res
700
+
701
+ if use_corrector:
702
+ model_t = self.model_fn(x_t, t)
703
+ if D1s is not None:
704
+ corr_res = torch.einsum('k,bkchw->bchw', rhos_c[:-1], D1s)
705
+ else:
706
+ corr_res = 0
707
+ D1_t = (model_t - model_prev_0)
708
+ x_t = x_t_ - expand_dims(sigma_t * B_h, dims) * (corr_res + rhos_c[-1] * D1_t)
709
+ return x_t, model_t
710
+
711
+
712
+ def sample(self, x, timesteps, t_start=None, t_end=None, order=3, skip_type='time_uniform',
713
+ method='singlestep', lower_order_final=True, denoise_to_zero=False, solver_type='dpm_solver',
714
+ atol=0.0078, rtol=0.05, corrector=False, callback=None, disable_pbar=False
715
+ ):
716
+ # t_0 = 1. / self.noise_schedule.total_N if t_end is None else t_end
717
+ # t_T = self.noise_schedule.T if t_start is None else t_start
718
+ device = x.device
719
+ steps = len(timesteps) - 1
720
+ if method == 'multistep':
721
+ assert steps >= order
722
+ # timesteps = self.get_time_steps(skip_type=skip_type, t_T=t_T, t_0=t_0, N=steps, device=device)
723
+ assert timesteps.shape[0] - 1 == steps
724
+ # with torch.no_grad():
725
+ for step_index in trange(steps, disable=disable_pbar):
726
+ if self.noise_mask is not None:
727
+ x = x * self.noise_mask + (1. - self.noise_mask) * (self.masked_image * self.noise_schedule.marginal_alpha(timesteps[step_index]) + self.noise * self.noise_schedule.marginal_std(timesteps[step_index]))
728
+ if step_index == 0:
729
+ vec_t = timesteps[0].expand((x.shape[0]))
730
+ model_prev_list = [self.model_fn(x, vec_t)]
731
+ t_prev_list = [vec_t]
732
+ elif step_index < order:
733
+ init_order = step_index
734
+ # Init the first `order` values by lower order multistep DPM-Solver.
735
+ # for init_order in range(1, order):
736
+ vec_t = timesteps[init_order].expand(x.shape[0])
737
+ x, model_x = self.multistep_uni_pc_update(x, model_prev_list, t_prev_list, vec_t, init_order, use_corrector=True)
738
+ if model_x is None:
739
+ model_x = self.model_fn(x, vec_t)
740
+ model_prev_list.append(model_x)
741
+ t_prev_list.append(vec_t)
742
+ else:
743
+ extra_final_step = 0
744
+ if step_index == (steps - 1):
745
+ extra_final_step = 1
746
+ for step in range(step_index, step_index + 1 + extra_final_step):
747
+ vec_t = timesteps[step].expand(x.shape[0])
748
+ if lower_order_final:
749
+ step_order = min(order, steps + 1 - step)
750
+ else:
751
+ step_order = order
752
+ # print('this step order:', step_order)
753
+ if step == steps:
754
+ # print('do not run corrector at the last step')
755
+ use_corrector = False
756
+ else:
757
+ use_corrector = True
758
+ x, model_x = self.multistep_uni_pc_update(x, model_prev_list, t_prev_list, vec_t, step_order, use_corrector=use_corrector)
759
+ for i in range(order - 1):
760
+ t_prev_list[i] = t_prev_list[i + 1]
761
+ model_prev_list[i] = model_prev_list[i + 1]
762
+ t_prev_list[-1] = vec_t
763
+ # We do not need to evaluate the final model value.
764
+ if step < steps:
765
+ if model_x is None:
766
+ model_x = self.model_fn(x, vec_t)
767
+ model_prev_list[-1] = model_x
768
+ if callback is not None:
769
+ callback(step_index, model_prev_list[-1], x, steps)
770
+ else:
771
+ raise NotImplementedError()
772
+ # if denoise_to_zero:
773
+ # x = self.denoise_to_zero_fn(x, torch.ones((x.shape[0],)).to(device) * t_0)
774
+ return x
775
+
776
+
777
+ #############################################################
778
+ # other utility functions
779
+ #############################################################
780
+
781
+ def interpolate_fn(x, xp, yp):
782
+ """
783
+ A piecewise linear function y = f(x), using xp and yp as keypoints.
784
+ We implement f(x) in a differentiable way (i.e. applicable for autograd).
785
+ The function f(x) is well-defined for all x-axis. (For x beyond the bounds of xp, we use the outmost points of xp to define the linear function.)
786
+
787
+ Args:
788
+ x: PyTorch tensor with shape [N, C], where N is the batch size, C is the number of channels (we use C = 1 for DPM-Solver).
789
+ xp: PyTorch tensor with shape [C, K], where K is the number of keypoints.
790
+ yp: PyTorch tensor with shape [C, K].
791
+ Returns:
792
+ The function values f(x), with shape [N, C].
793
+ """
794
+ N, K = x.shape[0], xp.shape[1]
795
+ all_x = torch.cat([x.unsqueeze(2), xp.unsqueeze(0).repeat((N, 1, 1))], dim=2)
796
+ sorted_all_x, x_indices = torch.sort(all_x, dim=2)
797
+ x_idx = torch.argmin(x_indices, dim=2)
798
+ cand_start_idx = x_idx - 1
799
+ start_idx = torch.where(
800
+ torch.eq(x_idx, 0),
801
+ torch.tensor(1, device=x.device),
802
+ torch.where(
803
+ torch.eq(x_idx, K), torch.tensor(K - 2, device=x.device), cand_start_idx,
804
+ ),
805
+ )
806
+ end_idx = torch.where(torch.eq(start_idx, cand_start_idx), start_idx + 2, start_idx + 1)
807
+ start_x = torch.gather(sorted_all_x, dim=2, index=start_idx.unsqueeze(2)).squeeze(2)
808
+ end_x = torch.gather(sorted_all_x, dim=2, index=end_idx.unsqueeze(2)).squeeze(2)
809
+ start_idx2 = torch.where(
810
+ torch.eq(x_idx, 0),
811
+ torch.tensor(0, device=x.device),
812
+ torch.where(
813
+ torch.eq(x_idx, K), torch.tensor(K - 2, device=x.device), cand_start_idx,
814
+ ),
815
+ )
816
+ y_positions_expanded = yp.unsqueeze(0).expand(N, -1, -1)
817
+ start_y = torch.gather(y_positions_expanded, dim=2, index=start_idx2.unsqueeze(2)).squeeze(2)
818
+ end_y = torch.gather(y_positions_expanded, dim=2, index=(start_idx2 + 1).unsqueeze(2)).squeeze(2)
819
+ cand = start_y + (x - start_x) * (end_y - start_y) / (end_x - start_x)
820
+ return cand
821
+
822
+
823
+ def expand_dims(v, dims):
824
+ """
825
+ Expand the tensor `v` to the dim `dims`.
826
+
827
+ Args:
828
+ `v`: a PyTorch tensor with shape [N].
829
+ `dim`: a `int`.
830
+ Returns:
831
+ a PyTorch tensor with shape [N, 1, 1, ..., 1] and the total dimension is `dims`.
832
+ """
833
+ return v[(...,) + (None,)*(dims - 1)]
834
+
835
+
836
+ class SigmaConvert:
837
+ schedule = ""
838
+ def marginal_log_mean_coeff(self, sigma):
839
+ return 0.5 * torch.log(1 / ((sigma * sigma) + 1))
840
+
841
+ def marginal_alpha(self, t):
842
+ return torch.exp(self.marginal_log_mean_coeff(t))
843
+
844
+ def marginal_std(self, t):
845
+ return torch.sqrt(1. - torch.exp(2. * self.marginal_log_mean_coeff(t)))
846
+
847
+ def marginal_lambda(self, t):
848
+ """
849
+ Compute lambda_t = log(alpha_t) - log(sigma_t) of a given continuous-time label t in [0, T].
850
+ """
851
+ log_mean_coeff = self.marginal_log_mean_coeff(t)
852
+ log_std = 0.5 * torch.log(1. - torch.exp(2. * log_mean_coeff))
853
+ return log_mean_coeff - log_std
854
+
855
+ def predict_eps_sigma(model, input, sigma_in, **kwargs):
856
+ sigma = sigma_in.view(sigma_in.shape[:1] + (1,) * (input.ndim - 1))
857
+ input = input * ((sigma ** 2 + 1.0) ** 0.5)
858
+ return (input - model(input, sigma_in, **kwargs)) / sigma
859
+
860
+
861
+ def sample_unipc(model, noise, image, sigmas, max_denoise, extra_args=None, callback=None, disable=False, noise_mask=None, variant='bh1'):
862
+ timesteps = sigmas.clone()
863
+ if sigmas[-1] == 0:
864
+ timesteps = sigmas[:]
865
+ timesteps[-1] = 0.001
866
+ else:
867
+ timesteps = sigmas.clone()
868
+ ns = SigmaConvert()
869
+
870
+ if image is not None:
871
+ img = image * ns.marginal_alpha(timesteps[0])
872
+ if max_denoise:
873
+ noise_mult = 1.0
874
+ else:
875
+ noise_mult = ns.marginal_std(timesteps[0])
876
+ img += noise * noise_mult
877
+ else:
878
+ img = noise
879
+
880
+ model_type = "noise"
881
+
882
+ model_fn = model_wrapper(
883
+ lambda input, sigma, **kwargs: predict_eps_sigma(model, input, sigma, **kwargs),
884
+ ns,
885
+ model_type=model_type,
886
+ guidance_type="uncond",
887
+ model_kwargs=extra_args,
888
+ )
889
+
890
+ order = min(3, len(timesteps) - 2)
891
+ uni_pc = UniPC(model_fn, ns, predict_x0=True, thresholding=False, noise_mask=noise_mask, masked_image=image, noise=noise, variant=variant)
892
+ x = uni_pc.sample(img, timesteps=timesteps, skip_type="time_uniform", method="multistep", order=order, lower_order_final=True, callback=callback, disable_pbar=disable)
893
+ x /= ns.marginal_alpha(timesteps[-1])
894
+ return x
backend/headless/fcbh/gligen.py ADDED
@@ -0,0 +1,341 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from torch import nn, einsum
3
+ from .ldm.modules.attention import CrossAttention
4
+ from inspect import isfunction
5
+
6
+
7
+ def exists(val):
8
+ return val is not None
9
+
10
+
11
+ def uniq(arr):
12
+ return{el: True for el in arr}.keys()
13
+
14
+
15
+ def default(val, d):
16
+ if exists(val):
17
+ return val
18
+ return d() if isfunction(d) else d
19
+
20
+
21
+ # feedforward
22
+ class GEGLU(nn.Module):
23
+ def __init__(self, dim_in, dim_out):
24
+ super().__init__()
25
+ self.proj = nn.Linear(dim_in, dim_out * 2)
26
+
27
+ def forward(self, x):
28
+ x, gate = self.proj(x).chunk(2, dim=-1)
29
+ return x * torch.nn.functional.gelu(gate)
30
+
31
+
32
+ class FeedForward(nn.Module):
33
+ def __init__(self, dim, dim_out=None, mult=4, glu=False, dropout=0.):
34
+ super().__init__()
35
+ inner_dim = int(dim * mult)
36
+ dim_out = default(dim_out, dim)
37
+ project_in = nn.Sequential(
38
+ nn.Linear(dim, inner_dim),
39
+ nn.GELU()
40
+ ) if not glu else GEGLU(dim, inner_dim)
41
+
42
+ self.net = nn.Sequential(
43
+ project_in,
44
+ nn.Dropout(dropout),
45
+ nn.Linear(inner_dim, dim_out)
46
+ )
47
+
48
+ def forward(self, x):
49
+ return self.net(x)
50
+
51
+
52
+ class GatedCrossAttentionDense(nn.Module):
53
+ def __init__(self, query_dim, context_dim, n_heads, d_head):
54
+ super().__init__()
55
+
56
+ self.attn = CrossAttention(
57
+ query_dim=query_dim,
58
+ context_dim=context_dim,
59
+ heads=n_heads,
60
+ dim_head=d_head)
61
+ self.ff = FeedForward(query_dim, glu=True)
62
+
63
+ self.norm1 = nn.LayerNorm(query_dim)
64
+ self.norm2 = nn.LayerNorm(query_dim)
65
+
66
+ self.register_parameter('alpha_attn', nn.Parameter(torch.tensor(0.)))
67
+ self.register_parameter('alpha_dense', nn.Parameter(torch.tensor(0.)))
68
+
69
+ # this can be useful: we can externally change magnitude of tanh(alpha)
70
+ # for example, when it is set to 0, then the entire model is same as
71
+ # original one
72
+ self.scale = 1
73
+
74
+ def forward(self, x, objs):
75
+
76
+ x = x + self.scale * \
77
+ torch.tanh(self.alpha_attn) * self.attn(self.norm1(x), objs, objs)
78
+ x = x + self.scale * \
79
+ torch.tanh(self.alpha_dense) * self.ff(self.norm2(x))
80
+
81
+ return x
82
+
83
+
84
+ class GatedSelfAttentionDense(nn.Module):
85
+ def __init__(self, query_dim, context_dim, n_heads, d_head):
86
+ super().__init__()
87
+
88
+ # we need a linear projection since we need cat visual feature and obj
89
+ # feature
90
+ self.linear = nn.Linear(context_dim, query_dim)
91
+
92
+ self.attn = CrossAttention(
93
+ query_dim=query_dim,
94
+ context_dim=query_dim,
95
+ heads=n_heads,
96
+ dim_head=d_head)
97
+ self.ff = FeedForward(query_dim, glu=True)
98
+
99
+ self.norm1 = nn.LayerNorm(query_dim)
100
+ self.norm2 = nn.LayerNorm(query_dim)
101
+
102
+ self.register_parameter('alpha_attn', nn.Parameter(torch.tensor(0.)))
103
+ self.register_parameter('alpha_dense', nn.Parameter(torch.tensor(0.)))
104
+
105
+ # this can be useful: we can externally change magnitude of tanh(alpha)
106
+ # for example, when it is set to 0, then the entire model is same as
107
+ # original one
108
+ self.scale = 1
109
+
110
+ def forward(self, x, objs):
111
+
112
+ N_visual = x.shape[1]
113
+ objs = self.linear(objs)
114
+
115
+ x = x + self.scale * torch.tanh(self.alpha_attn) * self.attn(
116
+ self.norm1(torch.cat([x, objs], dim=1)))[:, 0:N_visual, :]
117
+ x = x + self.scale * \
118
+ torch.tanh(self.alpha_dense) * self.ff(self.norm2(x))
119
+
120
+ return x
121
+
122
+
123
+ class GatedSelfAttentionDense2(nn.Module):
124
+ def __init__(self, query_dim, context_dim, n_heads, d_head):
125
+ super().__init__()
126
+
127
+ # we need a linear projection since we need cat visual feature and obj
128
+ # feature
129
+ self.linear = nn.Linear(context_dim, query_dim)
130
+
131
+ self.attn = CrossAttention(
132
+ query_dim=query_dim, context_dim=query_dim, dim_head=d_head)
133
+ self.ff = FeedForward(query_dim, glu=True)
134
+
135
+ self.norm1 = nn.LayerNorm(query_dim)
136
+ self.norm2 = nn.LayerNorm(query_dim)
137
+
138
+ self.register_parameter('alpha_attn', nn.Parameter(torch.tensor(0.)))
139
+ self.register_parameter('alpha_dense', nn.Parameter(torch.tensor(0.)))
140
+
141
+ # this can be useful: we can externally change magnitude of tanh(alpha)
142
+ # for example, when it is set to 0, then the entire model is same as
143
+ # original one
144
+ self.scale = 1
145
+
146
+ def forward(self, x, objs):
147
+
148
+ B, N_visual, _ = x.shape
149
+ B, N_ground, _ = objs.shape
150
+
151
+ objs = self.linear(objs)
152
+
153
+ # sanity check
154
+ size_v = math.sqrt(N_visual)
155
+ size_g = math.sqrt(N_ground)
156
+ assert int(size_v) == size_v, "Visual tokens must be square rootable"
157
+ assert int(size_g) == size_g, "Grounding tokens must be square rootable"
158
+ size_v = int(size_v)
159
+ size_g = int(size_g)
160
+
161
+ # select grounding token and resize it to visual token size as residual
162
+ out = self.attn(self.norm1(torch.cat([x, objs], dim=1)))[
163
+ :, N_visual:, :]
164
+ out = out.permute(0, 2, 1).reshape(B, -1, size_g, size_g)
165
+ out = torch.nn.functional.interpolate(
166
+ out, (size_v, size_v), mode='bicubic')
167
+ residual = out.reshape(B, -1, N_visual).permute(0, 2, 1)
168
+
169
+ # add residual to visual feature
170
+ x = x + self.scale * torch.tanh(self.alpha_attn) * residual
171
+ x = x + self.scale * \
172
+ torch.tanh(self.alpha_dense) * self.ff(self.norm2(x))
173
+
174
+ return x
175
+
176
+
177
+ class FourierEmbedder():
178
+ def __init__(self, num_freqs=64, temperature=100):
179
+
180
+ self.num_freqs = num_freqs
181
+ self.temperature = temperature
182
+ self.freq_bands = temperature ** (torch.arange(num_freqs) / num_freqs)
183
+
184
+ @torch.no_grad()
185
+ def __call__(self, x, cat_dim=-1):
186
+ "x: arbitrary shape of tensor. dim: cat dim"
187
+ out = []
188
+ for freq in self.freq_bands:
189
+ out.append(torch.sin(freq * x))
190
+ out.append(torch.cos(freq * x))
191
+ return torch.cat(out, cat_dim)
192
+
193
+
194
+ class PositionNet(nn.Module):
195
+ def __init__(self, in_dim, out_dim, fourier_freqs=8):
196
+ super().__init__()
197
+ self.in_dim = in_dim
198
+ self.out_dim = out_dim
199
+
200
+ self.fourier_embedder = FourierEmbedder(num_freqs=fourier_freqs)
201
+ self.position_dim = fourier_freqs * 2 * 4 # 2 is sin&cos, 4 is xyxy
202
+
203
+ self.linears = nn.Sequential(
204
+ nn.Linear(self.in_dim + self.position_dim, 512),
205
+ nn.SiLU(),
206
+ nn.Linear(512, 512),
207
+ nn.SiLU(),
208
+ nn.Linear(512, out_dim),
209
+ )
210
+
211
+ self.null_positive_feature = torch.nn.Parameter(
212
+ torch.zeros([self.in_dim]))
213
+ self.null_position_feature = torch.nn.Parameter(
214
+ torch.zeros([self.position_dim]))
215
+
216
+ def forward(self, boxes, masks, positive_embeddings):
217
+ B, N, _ = boxes.shape
218
+ dtype = self.linears[0].weight.dtype
219
+ masks = masks.unsqueeze(-1).to(dtype)
220
+ positive_embeddings = positive_embeddings.to(dtype)
221
+
222
+ # embedding position (it may includes padding as placeholder)
223
+ xyxy_embedding = self.fourier_embedder(boxes.to(dtype)) # B*N*4 --> B*N*C
224
+
225
+ # learnable null embedding
226
+ positive_null = self.null_positive_feature.view(1, 1, -1)
227
+ xyxy_null = self.null_position_feature.view(1, 1, -1)
228
+
229
+ # replace padding with learnable null embedding
230
+ positive_embeddings = positive_embeddings * \
231
+ masks + (1 - masks) * positive_null
232
+ xyxy_embedding = xyxy_embedding * masks + (1 - masks) * xyxy_null
233
+
234
+ objs = self.linears(
235
+ torch.cat([positive_embeddings, xyxy_embedding], dim=-1))
236
+ assert objs.shape == torch.Size([B, N, self.out_dim])
237
+ return objs
238
+
239
+
240
+ class Gligen(nn.Module):
241
+ def __init__(self, modules, position_net, key_dim):
242
+ super().__init__()
243
+ self.module_list = nn.ModuleList(modules)
244
+ self.position_net = position_net
245
+ self.key_dim = key_dim
246
+ self.max_objs = 30
247
+ self.current_device = torch.device("cpu")
248
+
249
+ def _set_position(self, boxes, masks, positive_embeddings):
250
+ objs = self.position_net(boxes, masks, positive_embeddings)
251
+ def func(x, extra_options):
252
+ key = extra_options["transformer_index"]
253
+ module = self.module_list[key]
254
+ return module(x, objs)
255
+ return func
256
+
257
+ def set_position(self, latent_image_shape, position_params, device):
258
+ batch, c, h, w = latent_image_shape
259
+ masks = torch.zeros([self.max_objs], device="cpu")
260
+ boxes = []
261
+ positive_embeddings = []
262
+ for p in position_params:
263
+ x1 = (p[4]) / w
264
+ y1 = (p[3]) / h
265
+ x2 = (p[4] + p[2]) / w
266
+ y2 = (p[3] + p[1]) / h
267
+ masks[len(boxes)] = 1.0
268
+ boxes += [torch.tensor((x1, y1, x2, y2)).unsqueeze(0)]
269
+ positive_embeddings += [p[0]]
270
+ append_boxes = []
271
+ append_conds = []
272
+ if len(boxes) < self.max_objs:
273
+ append_boxes = [torch.zeros(
274
+ [self.max_objs - len(boxes), 4], device="cpu")]
275
+ append_conds = [torch.zeros(
276
+ [self.max_objs - len(boxes), self.key_dim], device="cpu")]
277
+
278
+ box_out = torch.cat(
279
+ boxes + append_boxes).unsqueeze(0).repeat(batch, 1, 1)
280
+ masks = masks.unsqueeze(0).repeat(batch, 1)
281
+ conds = torch.cat(positive_embeddings +
282
+ append_conds).unsqueeze(0).repeat(batch, 1, 1)
283
+ return self._set_position(
284
+ box_out.to(device),
285
+ masks.to(device),
286
+ conds.to(device))
287
+
288
+ def set_empty(self, latent_image_shape, device):
289
+ batch, c, h, w = latent_image_shape
290
+ masks = torch.zeros([self.max_objs], device="cpu").repeat(batch, 1)
291
+ box_out = torch.zeros([self.max_objs, 4],
292
+ device="cpu").repeat(batch, 1, 1)
293
+ conds = torch.zeros([self.max_objs, self.key_dim],
294
+ device="cpu").repeat(batch, 1, 1)
295
+ return self._set_position(
296
+ box_out.to(device),
297
+ masks.to(device),
298
+ conds.to(device))
299
+
300
+
301
+ def load_gligen(sd):
302
+ sd_k = sd.keys()
303
+ output_list = []
304
+ key_dim = 768
305
+ for a in ["input_blocks", "middle_block", "output_blocks"]:
306
+ for b in range(20):
307
+ k_temp = filter(lambda k: "{}.{}.".format(a, b)
308
+ in k and ".fuser." in k, sd_k)
309
+ k_temp = map(lambda k: (k, k.split(".fuser.")[-1]), k_temp)
310
+
311
+ n_sd = {}
312
+ for k in k_temp:
313
+ n_sd[k[1]] = sd[k[0]]
314
+ if len(n_sd) > 0:
315
+ query_dim = n_sd["linear.weight"].shape[0]
316
+ key_dim = n_sd["linear.weight"].shape[1]
317
+
318
+ if key_dim == 768: # SD1.x
319
+ n_heads = 8
320
+ d_head = query_dim // n_heads
321
+ else:
322
+ d_head = 64
323
+ n_heads = query_dim // d_head
324
+
325
+ gated = GatedSelfAttentionDense(
326
+ query_dim, key_dim, n_heads, d_head)
327
+ gated.load_state_dict(n_sd, strict=False)
328
+ output_list.append(gated)
329
+
330
+ if "position_net.null_positive_feature" in sd_k:
331
+ in_dim = sd["position_net.null_positive_feature"].shape[0]
332
+ out_dim = sd["position_net.linears.4.weight"].shape[0]
333
+
334
+ class WeightsLoader(torch.nn.Module):
335
+ pass
336
+ w = WeightsLoader()
337
+ w.position_net = PositionNet(in_dim, out_dim)
338
+ w.load_state_dict(sd, strict=False)
339
+
340
+ gligen = Gligen(output_list, w.position_net, key_dim)
341
+ return gligen
backend/headless/fcbh/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
backend/headless/fcbh/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
backend/headless/fcbh/latent_formats.py ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ class LatentFormat:
3
+ scale_factor = 1.0
4
+ latent_rgb_factors = None
5
+ taesd_decoder_name = None
6
+
7
+ def process_in(self, latent):
8
+ return latent * self.scale_factor
9
+
10
+ def process_out(self, latent):
11
+ return latent / self.scale_factor
12
+
13
+ class SD15(LatentFormat):
14
+ def __init__(self, scale_factor=0.18215):
15
+ self.scale_factor = scale_factor
16
+ self.latent_rgb_factors = [
17
+ # R G B
18
+ [ 0.3512, 0.2297, 0.3227],
19
+ [ 0.3250, 0.4974, 0.2350],
20
+ [-0.2829, 0.1762, 0.2721],
21
+ [-0.2120, -0.2616, -0.7177]
22
+ ]
23
+ self.taesd_decoder_name = "taesd_decoder"
24
+
25
+ class SDXL(LatentFormat):
26
+ def __init__(self):
27
+ self.scale_factor = 0.13025
28
+ self.latent_rgb_factors = [
29
+ # R G B
30
+ [ 0.3920, 0.4054, 0.4549],
31
+ [-0.2634, -0.0196, 0.0653],
32
+ [ 0.0568, 0.1687, -0.0755],
33
+ [-0.3112, -0.2359, -0.2076]
34
+ ]
35
+ self.taesd_decoder_name = "taesdxl_decoder"
backend/headless/fcbh/ldm/models/autoencoder.py ADDED
@@ -0,0 +1,227 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 fcbh.ldm.modules.distributions.distributions import DiagonalGaussianDistribution
8
+
9
+ from fcbh.ldm.util import instantiate_from_config
10
+ from fcbh.ldm.modules.ema import LitEma
11
+
12
+ class DiagonalGaussianRegularizer(torch.nn.Module):
13
+ def __init__(self, sample: bool = True):
14
+ super().__init__()
15
+ self.sample = sample
16
+
17
+ def get_trainable_parameters(self) -> Any:
18
+ yield from ()
19
+
20
+ def forward(self, z: torch.Tensor) -> Tuple[torch.Tensor, dict]:
21
+ log = dict()
22
+ posterior = DiagonalGaussianDistribution(z)
23
+ if self.sample:
24
+ z = posterior.sample()
25
+ else:
26
+ z = posterior.mode()
27
+ kl_loss = posterior.kl()
28
+ kl_loss = torch.sum(kl_loss) / kl_loss.shape[0]
29
+ log["kl_loss"] = kl_loss
30
+ return z, log
31
+
32
+
33
+ class AbstractAutoencoder(torch.nn.Module):
34
+ """
35
+ This is the base class for all autoencoders, including image autoencoders, image autoencoders with discriminators,
36
+ unCLIP models, etc. Hence, it is fairly general, and specific features
37
+ (e.g. discriminator training, encoding, decoding) must be implemented in subclasses.
38
+ """
39
+
40
+ def __init__(
41
+ self,
42
+ ema_decay: Union[None, float] = None,
43
+ monitor: Union[None, str] = None,
44
+ input_key: str = "jpg",
45
+ **kwargs,
46
+ ):
47
+ super().__init__()
48
+
49
+ self.input_key = input_key
50
+ self.use_ema = ema_decay is not None
51
+ if monitor is not None:
52
+ self.monitor = monitor
53
+
54
+ if self.use_ema:
55
+ self.model_ema = LitEma(self, decay=ema_decay)
56
+ logpy.info(f"Keeping EMAs of {len(list(self.model_ema.buffers()))}.")
57
+
58
+ def get_input(self, batch) -> Any:
59
+ raise NotImplementedError()
60
+
61
+ def on_train_batch_end(self, *args, **kwargs):
62
+ # for EMA computation
63
+ if self.use_ema:
64
+ self.model_ema(self)
65
+
66
+ @contextmanager
67
+ def ema_scope(self, context=None):
68
+ if self.use_ema:
69
+ self.model_ema.store(self.parameters())
70
+ self.model_ema.copy_to(self)
71
+ if context is not None:
72
+ logpy.info(f"{context}: Switched to EMA weights")
73
+ try:
74
+ yield None
75
+ finally:
76
+ if self.use_ema:
77
+ self.model_ema.restore(self.parameters())
78
+ if context is not None:
79
+ logpy.info(f"{context}: Restored training weights")
80
+
81
+ def encode(self, *args, **kwargs) -> torch.Tensor:
82
+ raise NotImplementedError("encode()-method of abstract base class called")
83
+
84
+ def decode(self, *args, **kwargs) -> torch.Tensor:
85
+ raise NotImplementedError("decode()-method of abstract base class called")
86
+
87
+ def instantiate_optimizer_from_config(self, params, lr, cfg):
88
+ logpy.info(f"loading >>> {cfg['target']} <<< optimizer from config")
89
+ return get_obj_from_str(cfg["target"])(
90
+ params, lr=lr, **cfg.get("params", dict())
91
+ )
92
+
93
+ def configure_optimizers(self) -> Any:
94
+ raise NotImplementedError()
95
+
96
+
97
+ class AutoencodingEngine(AbstractAutoencoder):
98
+ """
99
+ Base class for all image autoencoders that we train, like VQGAN or AutoencoderKL
100
+ (we also restore them explicitly as special cases for legacy reasons).
101
+ Regularizations such as KL or VQ are moved to the regularizer class.
102
+ """
103
+
104
+ def __init__(
105
+ self,
106
+ *args,
107
+ encoder_config: Dict,
108
+ decoder_config: Dict,
109
+ regularizer_config: Dict,
110
+ **kwargs,
111
+ ):
112
+ super().__init__(*args, **kwargs)
113
+
114
+ self.encoder: torch.nn.Module = instantiate_from_config(encoder_config)
115
+ self.decoder: torch.nn.Module = instantiate_from_config(decoder_config)
116
+ self.regularization: AbstractRegularizer = instantiate_from_config(
117
+ regularizer_config
118
+ )
119
+
120
+ def get_last_layer(self):
121
+ return self.decoder.get_last_layer()
122
+
123
+ def encode(
124
+ self,
125
+ x: torch.Tensor,
126
+ return_reg_log: bool = False,
127
+ unregularized: bool = False,
128
+ ) -> Union[torch.Tensor, Tuple[torch.Tensor, dict]]:
129
+ z = self.encoder(x)
130
+ if unregularized:
131
+ return z, dict()
132
+ z, reg_log = self.regularization(z)
133
+ if return_reg_log:
134
+ return z, reg_log
135
+ return z
136
+
137
+ def decode(self, z: torch.Tensor, **kwargs) -> torch.Tensor:
138
+ x = self.decoder(z, **kwargs)
139
+ return x
140
+
141
+ def forward(
142
+ self, x: torch.Tensor, **additional_decode_kwargs
143
+ ) -> Tuple[torch.Tensor, torch.Tensor, dict]:
144
+ z, reg_log = self.encode(x, return_reg_log=True)
145
+ dec = self.decode(z, **additional_decode_kwargs)
146
+ return z, dec, reg_log
147
+
148
+
149
+ class AutoencodingEngineLegacy(AutoencodingEngine):
150
+ def __init__(self, embed_dim: int, **kwargs):
151
+ self.max_batch_size = kwargs.pop("max_batch_size", None)
152
+ ddconfig = kwargs.pop("ddconfig")
153
+ super().__init__(
154
+ encoder_config={
155
+ "target": "fcbh.ldm.modules.diffusionmodules.model.Encoder",
156
+ "params": ddconfig,
157
+ },
158
+ decoder_config={
159
+ "target": "fcbh.ldm.modules.diffusionmodules.model.Decoder",
160
+ "params": ddconfig,
161
+ },
162
+ **kwargs,
163
+ )
164
+ self.quant_conv = torch.nn.Conv2d(
165
+ (1 + ddconfig["double_z"]) * ddconfig["z_channels"],
166
+ (1 + ddconfig["double_z"]) * embed_dim,
167
+ 1,
168
+ )
169
+ self.post_quant_conv = torch.nn.Conv2d(embed_dim, ddconfig["z_channels"], 1)
170
+ self.embed_dim = embed_dim
171
+
172
+ def get_autoencoder_params(self) -> list:
173
+ params = super().get_autoencoder_params()
174
+ return params
175
+
176
+ def encode(
177
+ self, x: torch.Tensor, return_reg_log: bool = False
178
+ ) -> Union[torch.Tensor, Tuple[torch.Tensor, dict]]:
179
+ if self.max_batch_size is None:
180
+ z = self.encoder(x)
181
+ z = self.quant_conv(z)
182
+ else:
183
+ N = x.shape[0]
184
+ bs = self.max_batch_size
185
+ n_batches = int(math.ceil(N / bs))
186
+ z = list()
187
+ for i_batch in range(n_batches):
188
+ z_batch = self.encoder(x[i_batch * bs : (i_batch + 1) * bs])
189
+ z_batch = self.quant_conv(z_batch)
190
+ z.append(z_batch)
191
+ z = torch.cat(z, 0)
192
+
193
+ z, reg_log = self.regularization(z)
194
+ if return_reg_log:
195
+ return z, reg_log
196
+ return z
197
+
198
+ def decode(self, z: torch.Tensor, **decoder_kwargs) -> torch.Tensor:
199
+ if self.max_batch_size is None:
200
+ dec = self.post_quant_conv(z)
201
+ dec = self.decoder(dec, **decoder_kwargs)
202
+ else:
203
+ N = z.shape[0]
204
+ bs = self.max_batch_size
205
+ n_batches = int(math.ceil(N / bs))
206
+ dec = list()
207
+ for i_batch in range(n_batches):
208
+ dec_batch = self.post_quant_conv(z[i_batch * bs : (i_batch + 1) * bs])
209
+ dec_batch = self.decoder(dec_batch, **decoder_kwargs)
210
+ dec.append(dec_batch)
211
+ dec = torch.cat(dec, 0)
212
+
213
+ return dec
214
+
215
+
216
+ class AutoencoderKL(AutoencodingEngineLegacy):
217
+ def __init__(self, **kwargs):
218
+ if "lossconfig" in kwargs:
219
+ kwargs["loss_config"] = kwargs.pop("lossconfig")
220
+ super().__init__(
221
+ regularizer_config={
222
+ "target": (
223
+ "fcbh.ldm.models.autoencoder.DiagonalGaussianRegularizer"
224
+ )
225
+ },
226
+ **kwargs,
227
+ )
backend/headless/fcbh/ldm/modules/attention.py ADDED
@@ -0,0 +1,567 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from inspect import isfunction
2
+ import math
3
+ import torch
4
+ import torch.nn.functional as F
5
+ from torch import nn, einsum
6
+ from einops import rearrange, repeat
7
+ from typing import Optional, Any
8
+
9
+ from .diffusionmodules.util import checkpoint
10
+ from .sub_quadratic_attention import efficient_dot_product_attention
11
+
12
+ from fcbh import model_management
13
+
14
+ if model_management.xformers_enabled():
15
+ import xformers
16
+ import xformers.ops
17
+
18
+ from fcbh.cli_args import args
19
+ import fcbh.ops
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=fcbh.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=fcbh.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
+
85
+ def zero_module(module):
86
+ """
87
+ Zero out the parameters of a module and return it.
88
+ """
89
+ for p in module.parameters():
90
+ p.detach().zero_()
91
+ return module
92
+
93
+
94
+ def Normalize(in_channels, dtype=None, device=None):
95
+ return torch.nn.GroupNorm(num_groups=32, num_channels=in_channels, eps=1e-6, affine=True, dtype=dtype, device=device)
96
+
97
+ def attention_basic(q, k, v, heads, mask=None):
98
+ b, _, dim_head = q.shape
99
+ dim_head //= heads
100
+ scale = dim_head ** -0.5
101
+
102
+ h = heads
103
+ q, k, v = map(
104
+ lambda t: t.unsqueeze(3)
105
+ .reshape(b, -1, heads, dim_head)
106
+ .permute(0, 2, 1, 3)
107
+ .reshape(b * heads, -1, dim_head)
108
+ .contiguous(),
109
+ (q, k, v),
110
+ )
111
+
112
+ # force cast to fp32 to avoid overflowing
113
+ if _ATTN_PRECISION =="fp32":
114
+ with torch.autocast(enabled=False, device_type = 'cuda'):
115
+ q, k = q.float(), k.float()
116
+ sim = einsum('b i d, b j d -> b i j', q, k) * scale
117
+ else:
118
+ sim = einsum('b i d, b j d -> b i j', q, k) * scale
119
+
120
+ del q, k
121
+
122
+ if exists(mask):
123
+ mask = rearrange(mask, 'b ... -> b (...)')
124
+ max_neg_value = -torch.finfo(sim.dtype).max
125
+ mask = repeat(mask, 'b j -> (b h) () j', h=h)
126
+ sim.masked_fill_(~mask, max_neg_value)
127
+
128
+ # attention, what we cannot get enough of
129
+ sim = sim.softmax(dim=-1)
130
+
131
+ out = einsum('b i j, b j d -> b i d', sim.to(v.dtype), v)
132
+ out = (
133
+ out.unsqueeze(0)
134
+ .reshape(b, heads, -1, dim_head)
135
+ .permute(0, 2, 1, 3)
136
+ .reshape(b, -1, heads * dim_head)
137
+ )
138
+ return out
139
+
140
+
141
+ def attention_sub_quad(query, key, value, heads, mask=None):
142
+ b, _, dim_head = query.shape
143
+ dim_head //= heads
144
+
145
+ scale = dim_head ** -0.5
146
+ query = query.unsqueeze(3).reshape(b, -1, heads, dim_head).permute(0, 2, 1, 3).reshape(b * heads, -1, dim_head)
147
+ value = value.unsqueeze(3).reshape(b, -1, heads, dim_head).permute(0, 2, 1, 3).reshape(b * heads, -1, dim_head)
148
+
149
+ key = key.unsqueeze(3).reshape(b, -1, heads, dim_head).permute(0, 2, 3, 1).reshape(b * heads, dim_head, -1)
150
+
151
+ dtype = query.dtype
152
+ upcast_attention = _ATTN_PRECISION =="fp32" and query.dtype != torch.float32
153
+ if upcast_attention:
154
+ bytes_per_token = torch.finfo(torch.float32).bits//8
155
+ else:
156
+ bytes_per_token = torch.finfo(query.dtype).bits//8
157
+ batch_x_heads, q_tokens, _ = query.shape
158
+ _, _, k_tokens = key.shape
159
+ qk_matmul_size_bytes = batch_x_heads * bytes_per_token * q_tokens * k_tokens
160
+
161
+ mem_free_total, mem_free_torch = model_management.get_free_memory(query.device, True)
162
+
163
+ kv_chunk_size_min = None
164
+ kv_chunk_size = None
165
+ query_chunk_size = None
166
+
167
+ for x in [4096, 2048, 1024, 512, 256]:
168
+ count = mem_free_total / (batch_x_heads * bytes_per_token * x * 4.0)
169
+ if count >= k_tokens:
170
+ kv_chunk_size = k_tokens
171
+ query_chunk_size = x
172
+ break
173
+
174
+ if query_chunk_size is None:
175
+ query_chunk_size = 512
176
+
177
+ hidden_states = efficient_dot_product_attention(
178
+ query,
179
+ key,
180
+ value,
181
+ query_chunk_size=query_chunk_size,
182
+ kv_chunk_size=kv_chunk_size,
183
+ kv_chunk_size_min=kv_chunk_size_min,
184
+ use_checkpoint=False,
185
+ upcast_attention=upcast_attention,
186
+ )
187
+
188
+ hidden_states = hidden_states.to(dtype)
189
+
190
+ hidden_states = hidden_states.unflatten(0, (-1, heads)).transpose(1,2).flatten(start_dim=2)
191
+ return hidden_states
192
+
193
+ def attention_split(q, k, v, heads, mask=None):
194
+ b, _, dim_head = q.shape
195
+ dim_head //= heads
196
+ scale = dim_head ** -0.5
197
+
198
+ h = heads
199
+ q, k, v = map(
200
+ lambda t: t.unsqueeze(3)
201
+ .reshape(b, -1, heads, dim_head)
202
+ .permute(0, 2, 1, 3)
203
+ .reshape(b * heads, -1, dim_head)
204
+ .contiguous(),
205
+ (q, k, v),
206
+ )
207
+
208
+ r1 = torch.zeros(q.shape[0], q.shape[1], v.shape[2], device=q.device, dtype=q.dtype)
209
+
210
+ mem_free_total = model_management.get_free_memory(q.device)
211
+
212
+ if _ATTN_PRECISION =="fp32":
213
+ element_size = 4
214
+ else:
215
+ element_size = q.element_size()
216
+
217
+ gb = 1024 ** 3
218
+ tensor_size = q.shape[0] * q.shape[1] * k.shape[1] * element_size
219
+ modifier = 3
220
+ mem_required = tensor_size * modifier
221
+ steps = 1
222
+
223
+
224
+ if mem_required > mem_free_total:
225
+ steps = 2**(math.ceil(math.log(mem_required / mem_free_total, 2)))
226
+ # print(f"Expected tensor size:{tensor_size/gb:0.1f}GB, cuda free:{mem_free_cuda/gb:0.1f}GB "
227
+ # f"torch free:{mem_free_torch/gb:0.1f} total:{mem_free_total/gb:0.1f} steps:{steps}")
228
+
229
+ if steps > 64:
230
+ max_res = math.floor(math.sqrt(math.sqrt(mem_free_total / 2.5)) / 8) * 64
231
+ raise RuntimeError(f'Not enough memory, use lower resolution (max approx. {max_res}x{max_res}). '
232
+ f'Need: {mem_required/64/gb:0.1f}GB free, Have:{mem_free_total/gb:0.1f}GB free')
233
+
234
+ # print("steps", steps, mem_required, mem_free_total, modifier, q.element_size(), tensor_size)
235
+ first_op_done = False
236
+ cleared_cache = False
237
+ while True:
238
+ try:
239
+ slice_size = q.shape[1] // steps if (q.shape[1] % steps) == 0 else q.shape[1]
240
+ for i in range(0, q.shape[1], slice_size):
241
+ end = i + slice_size
242
+ if _ATTN_PRECISION =="fp32":
243
+ with torch.autocast(enabled=False, device_type = 'cuda'):
244
+ s1 = einsum('b i d, b j d -> b i j', q[:, i:end].float(), k.float()) * scale
245
+ else:
246
+ s1 = einsum('b i d, b j d -> b i j', q[:, i:end], k) * scale
247
+
248
+ s2 = s1.softmax(dim=-1).to(v.dtype)
249
+ del s1
250
+ first_op_done = True
251
+
252
+ r1[:, i:end] = einsum('b i j, b j d -> b i d', s2, v)
253
+ del s2
254
+ break
255
+ except model_management.OOM_EXCEPTION as e:
256
+ if first_op_done == False:
257
+ model_management.soft_empty_cache(True)
258
+ if cleared_cache == False:
259
+ cleared_cache = True
260
+ print("out of memory error, emptying cache and trying again")
261
+ continue
262
+ steps *= 2
263
+ if steps > 64:
264
+ raise e
265
+ print("out of memory error, increasing steps and trying again", steps)
266
+ else:
267
+ raise e
268
+
269
+ del q, k, v
270
+
271
+ r1 = (
272
+ r1.unsqueeze(0)
273
+ .reshape(b, heads, -1, dim_head)
274
+ .permute(0, 2, 1, 3)
275
+ .reshape(b, -1, heads * dim_head)
276
+ )
277
+ return r1
278
+
279
+ def attention_xformers(q, k, v, heads, mask=None):
280
+ b, _, dim_head = q.shape
281
+ dim_head //= heads
282
+
283
+ q, k, v = map(
284
+ lambda t: t.unsqueeze(3)
285
+ .reshape(b, -1, heads, dim_head)
286
+ .permute(0, 2, 1, 3)
287
+ .reshape(b * heads, -1, dim_head)
288
+ .contiguous(),
289
+ (q, k, v),
290
+ )
291
+
292
+ # actually compute the attention, what we cannot get enough of
293
+ out = xformers.ops.memory_efficient_attention(q, k, v, attn_bias=None)
294
+
295
+ if exists(mask):
296
+ raise NotImplementedError
297
+ out = (
298
+ out.unsqueeze(0)
299
+ .reshape(b, heads, -1, dim_head)
300
+ .permute(0, 2, 1, 3)
301
+ .reshape(b, -1, heads * dim_head)
302
+ )
303
+ return out
304
+
305
+ def attention_pytorch(q, k, v, heads, mask=None):
306
+ b, _, dim_head = q.shape
307
+ dim_head //= heads
308
+ q, k, v = map(
309
+ lambda t: t.view(b, -1, heads, dim_head).transpose(1, 2),
310
+ (q, k, v),
311
+ )
312
+
313
+ out = torch.nn.functional.scaled_dot_product_attention(q, k, v, attn_mask=mask, dropout_p=0.0, is_causal=False)
314
+ out = (
315
+ out.transpose(1, 2).reshape(b, -1, heads * dim_head)
316
+ )
317
+ return out
318
+
319
+
320
+ optimized_attention = attention_basic
321
+ optimized_attention_masked = attention_basic
322
+
323
+ if model_management.xformers_enabled():
324
+ print("Using xformers cross attention")
325
+ optimized_attention = attention_xformers
326
+ elif model_management.pytorch_attention_enabled():
327
+ print("Using pytorch cross attention")
328
+ optimized_attention = attention_pytorch
329
+ else:
330
+ if args.use_split_cross_attention:
331
+ print("Using split optimization for cross attention")
332
+ optimized_attention = attention_split
333
+ else:
334
+ print("Using sub quadratic optimization for cross attention, if you have memory or speed issues try using: --use-split-cross-attention")
335
+ optimized_attention = attention_sub_quad
336
+
337
+ if model_management.pytorch_attention_enabled():
338
+ optimized_attention_masked = attention_pytorch
339
+
340
+ class CrossAttention(nn.Module):
341
+ def __init__(self, query_dim, context_dim=None, heads=8, dim_head=64, dropout=0., dtype=None, device=None, operations=fcbh.ops):
342
+ super().__init__()
343
+ inner_dim = dim_head * heads
344
+ context_dim = default(context_dim, query_dim)
345
+
346
+ self.heads = heads
347
+ self.dim_head = dim_head
348
+
349
+ self.to_q = operations.Linear(query_dim, inner_dim, bias=False, dtype=dtype, device=device)
350
+ self.to_k = operations.Linear(context_dim, inner_dim, bias=False, dtype=dtype, device=device)
351
+ self.to_v = operations.Linear(context_dim, inner_dim, bias=False, dtype=dtype, device=device)
352
+
353
+ self.to_out = nn.Sequential(operations.Linear(inner_dim, query_dim, dtype=dtype, device=device), nn.Dropout(dropout))
354
+
355
+ def forward(self, x, context=None, value=None, mask=None):
356
+ q = self.to_q(x)
357
+ context = default(context, x)
358
+ k = self.to_k(context)
359
+ if value is not None:
360
+ v = self.to_v(value)
361
+ del value
362
+ else:
363
+ v = self.to_v(context)
364
+
365
+ if mask is None:
366
+ out = optimized_attention(q, k, v, self.heads)
367
+ else:
368
+ out = optimized_attention_masked(q, k, v, self.heads, mask)
369
+ return self.to_out(out)
370
+
371
+
372
+ class BasicTransformerBlock(nn.Module):
373
+ def __init__(self, dim, n_heads, d_head, dropout=0., context_dim=None, gated_ff=True, checkpoint=True,
374
+ disable_self_attn=False, dtype=None, device=None, operations=fcbh.ops):
375
+ super().__init__()
376
+ self.disable_self_attn = disable_self_attn
377
+ self.attn1 = CrossAttention(query_dim=dim, heads=n_heads, dim_head=d_head, dropout=dropout,
378
+ 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
379
+ self.ff = FeedForward(dim, dropout=dropout, glu=gated_ff, dtype=dtype, device=device, operations=operations)
380
+ self.attn2 = CrossAttention(query_dim=dim, context_dim=context_dim,
381
+ heads=n_heads, dim_head=d_head, dropout=dropout, dtype=dtype, device=device, operations=operations) # is self-attn if context is none
382
+ self.norm1 = nn.LayerNorm(dim, dtype=dtype, device=device)
383
+ self.norm2 = nn.LayerNorm(dim, dtype=dtype, device=device)
384
+ self.norm3 = nn.LayerNorm(dim, dtype=dtype, device=device)
385
+ self.checkpoint = checkpoint
386
+ self.n_heads = n_heads
387
+ self.d_head = d_head
388
+
389
+ def forward(self, x, context=None, transformer_options={}):
390
+ return checkpoint(self._forward, (x, context, transformer_options), self.parameters(), self.checkpoint)
391
+
392
+ def _forward(self, x, context=None, transformer_options={}):
393
+ extra_options = {}
394
+ block = None
395
+ block_index = 0
396
+ if "current_index" in transformer_options:
397
+ extra_options["transformer_index"] = transformer_options["current_index"]
398
+ if "block_index" in transformer_options:
399
+ block_index = transformer_options["block_index"]
400
+ extra_options["block_index"] = block_index
401
+ if "original_shape" in transformer_options:
402
+ extra_options["original_shape"] = transformer_options["original_shape"]
403
+ if "block" in transformer_options:
404
+ block = transformer_options["block"]
405
+ extra_options["block"] = block
406
+ if "cond_or_uncond" in transformer_options:
407
+ extra_options["cond_or_uncond"] = transformer_options["cond_or_uncond"]
408
+ if "patches" in transformer_options:
409
+ transformer_patches = transformer_options["patches"]
410
+ else:
411
+ transformer_patches = {}
412
+
413
+ extra_options["n_heads"] = self.n_heads
414
+ extra_options["dim_head"] = self.d_head
415
+
416
+ if "patches_replace" in transformer_options:
417
+ transformer_patches_replace = transformer_options["patches_replace"]
418
+ else:
419
+ transformer_patches_replace = {}
420
+
421
+ n = self.norm1(x)
422
+ if self.disable_self_attn:
423
+ context_attn1 = context
424
+ else:
425
+ context_attn1 = None
426
+ value_attn1 = None
427
+
428
+ if "attn1_patch" in transformer_patches:
429
+ patch = transformer_patches["attn1_patch"]
430
+ if context_attn1 is None:
431
+ context_attn1 = n
432
+ value_attn1 = context_attn1
433
+ for p in patch:
434
+ n, context_attn1, value_attn1 = p(n, context_attn1, value_attn1, extra_options)
435
+
436
+ if block is not None:
437
+ transformer_block = (block[0], block[1], block_index)
438
+ else:
439
+ transformer_block = None
440
+ attn1_replace_patch = transformer_patches_replace.get("attn1", {})
441
+ block_attn1 = transformer_block
442
+ if block_attn1 not in attn1_replace_patch:
443
+ block_attn1 = block
444
+
445
+ if block_attn1 in attn1_replace_patch:
446
+ if context_attn1 is None:
447
+ context_attn1 = n
448
+ value_attn1 = n
449
+ n = self.attn1.to_q(n)
450
+ context_attn1 = self.attn1.to_k(context_attn1)
451
+ value_attn1 = self.attn1.to_v(value_attn1)
452
+ n = attn1_replace_patch[block_attn1](n, context_attn1, value_attn1, extra_options)
453
+ n = self.attn1.to_out(n)
454
+ else:
455
+ n = self.attn1(n, context=context_attn1, value=value_attn1)
456
+
457
+ if "attn1_output_patch" in transformer_patches:
458
+ patch = transformer_patches["attn1_output_patch"]
459
+ for p in patch:
460
+ n = p(n, extra_options)
461
+
462
+ x += n
463
+ if "middle_patch" in transformer_patches:
464
+ patch = transformer_patches["middle_patch"]
465
+ for p in patch:
466
+ x = p(x, extra_options)
467
+
468
+ n = self.norm2(x)
469
+
470
+ context_attn2 = context
471
+ value_attn2 = None
472
+ if "attn2_patch" in transformer_patches:
473
+ patch = transformer_patches["attn2_patch"]
474
+ value_attn2 = context_attn2
475
+ for p in patch:
476
+ n, context_attn2, value_attn2 = p(n, context_attn2, value_attn2, extra_options)
477
+
478
+ attn2_replace_patch = transformer_patches_replace.get("attn2", {})
479
+ block_attn2 = transformer_block
480
+ if block_attn2 not in attn2_replace_patch:
481
+ block_attn2 = block
482
+
483
+ if block_attn2 in attn2_replace_patch:
484
+ if value_attn2 is None:
485
+ value_attn2 = context_attn2
486
+ n = self.attn2.to_q(n)
487
+ context_attn2 = self.attn2.to_k(context_attn2)
488
+ value_attn2 = self.attn2.to_v(value_attn2)
489
+ n = attn2_replace_patch[block_attn2](n, context_attn2, value_attn2, extra_options)
490
+ n = self.attn2.to_out(n)
491
+ else:
492
+ n = self.attn2(n, context=context_attn2, value=value_attn2)
493
+
494
+ if "attn2_output_patch" in transformer_patches:
495
+ patch = transformer_patches["attn2_output_patch"]
496
+ for p in patch:
497
+ n = p(n, extra_options)
498
+
499
+ x += n
500
+ x = self.ff(self.norm3(x)) + x
501
+ return x
502
+
503
+
504
+ class SpatialTransformer(nn.Module):
505
+ """
506
+ Transformer block for image-like data.
507
+ First, project the input (aka embedding)
508
+ and reshape to b, t, d.
509
+ Then apply standard transformer action.
510
+ Finally, reshape to image
511
+ NEW: use_linear for more efficiency instead of the 1x1 convs
512
+ """
513
+ def __init__(self, in_channels, n_heads, d_head,
514
+ depth=1, dropout=0., context_dim=None,
515
+ disable_self_attn=False, use_linear=False,
516
+ use_checkpoint=True, dtype=None, device=None, operations=fcbh.ops):
517
+ super().__init__()
518
+ if exists(context_dim) and not isinstance(context_dim, list):
519
+ context_dim = [context_dim] * depth
520
+ self.in_channels = in_channels
521
+ inner_dim = n_heads * d_head
522
+ self.norm = Normalize(in_channels, dtype=dtype, device=device)
523
+ if not use_linear:
524
+ self.proj_in = operations.Conv2d(in_channels,
525
+ inner_dim,
526
+ kernel_size=1,
527
+ stride=1,
528
+ padding=0, dtype=dtype, device=device)
529
+ else:
530
+ self.proj_in = operations.Linear(in_channels, inner_dim, dtype=dtype, device=device)
531
+
532
+ self.transformer_blocks = nn.ModuleList(
533
+ [BasicTransformerBlock(inner_dim, n_heads, d_head, dropout=dropout, context_dim=context_dim[d],
534
+ disable_self_attn=disable_self_attn, checkpoint=use_checkpoint, dtype=dtype, device=device, operations=operations)
535
+ for d in range(depth)]
536
+ )
537
+ if not use_linear:
538
+ self.proj_out = operations.Conv2d(inner_dim,in_channels,
539
+ kernel_size=1,
540
+ stride=1,
541
+ padding=0, dtype=dtype, device=device)
542
+ else:
543
+ self.proj_out = operations.Linear(in_channels, inner_dim, dtype=dtype, device=device)
544
+ self.use_linear = use_linear
545
+
546
+ def forward(self, x, context=None, transformer_options={}):
547
+ # note: if no context is given, cross-attention defaults to self-attention
548
+ if not isinstance(context, list):
549
+ context = [context] * len(self.transformer_blocks)
550
+ b, c, h, w = x.shape
551
+ x_in = x
552
+ x = self.norm(x)
553
+ if not self.use_linear:
554
+ x = self.proj_in(x)
555
+ x = rearrange(x, 'b c h w -> b (h w) c').contiguous()
556
+ if self.use_linear:
557
+ x = self.proj_in(x)
558
+ for i, block in enumerate(self.transformer_blocks):
559
+ transformer_options["block_index"] = i
560
+ x = block(x, context=context[i], transformer_options=transformer_options)
561
+ if self.use_linear:
562
+ x = self.proj_out(x)
563
+ x = rearrange(x, 'b (h w) c -> b c h w', h=h, w=w).contiguous()
564
+ if not self.use_linear:
565
+ x = self.proj_out(x)
566
+ return x + x_in
567
+
backend/headless/fcbh/ldm/modules/diffusionmodules/__init__.py ADDED
File without changes
backend/headless/fcbh/ldm/modules/diffusionmodules/model.py ADDED
@@ -0,0 +1,649 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 fcbh import model_management
10
+ import fcbh.ops
11
+
12
+ if model_management.xformers_enabled_vae():
13
+ import xformers
14
+ import xformers.ops
15
+
16
+ def get_timestep_embedding(timesteps, embedding_dim):
17
+ """
18
+ This matches the implementation in Denoising Diffusion Probabilistic Models:
19
+ From Fairseq.
20
+ Build sinusoidal embeddings.
21
+ This matches the implementation in tensor2tensor, but differs slightly
22
+ from the description in Section 3.5 of "Attention Is All You Need".
23
+ """
24
+ assert len(timesteps.shape) == 1
25
+
26
+ half_dim = embedding_dim // 2
27
+ emb = math.log(10000) / (half_dim - 1)
28
+ emb = torch.exp(torch.arange(half_dim, dtype=torch.float32) * -emb)
29
+ emb = emb.to(device=timesteps.device)
30
+ emb = timesteps.float()[:, None] * emb[None, :]
31
+ emb = torch.cat([torch.sin(emb), torch.cos(emb)], dim=1)
32
+ if embedding_dim % 2 == 1: # zero pad
33
+ emb = torch.nn.functional.pad(emb, (0,1,0,0))
34
+ return emb
35
+
36
+
37
+ def nonlinearity(x):
38
+ # swish
39
+ return x*torch.sigmoid(x)
40
+
41
+
42
+ def Normalize(in_channels, num_groups=32):
43
+ return torch.nn.GroupNorm(num_groups=num_groups, num_channels=in_channels, eps=1e-6, affine=True)
44
+
45
+
46
+ class Upsample(nn.Module):
47
+ def __init__(self, in_channels, with_conv):
48
+ super().__init__()
49
+ self.with_conv = with_conv
50
+ if self.with_conv:
51
+ self.conv = fcbh.ops.Conv2d(in_channels,
52
+ in_channels,
53
+ kernel_size=3,
54
+ stride=1,
55
+ padding=1)
56
+
57
+ def forward(self, x):
58
+ try:
59
+ x = torch.nn.functional.interpolate(x, scale_factor=2.0, mode="nearest")
60
+ except: #operation not implemented for bf16
61
+ b, c, h, w = x.shape
62
+ out = torch.empty((b, c, h*2, w*2), dtype=x.dtype, layout=x.layout, device=x.device)
63
+ split = 8
64
+ l = out.shape[1] // split
65
+ for i in range(0, out.shape[1], l):
66
+ out[:,i:i+l] = torch.nn.functional.interpolate(x[:,i:i+l].to(torch.float32), scale_factor=2.0, mode="nearest").to(x.dtype)
67
+ del x
68
+ x = out
69
+
70
+ if self.with_conv:
71
+ x = self.conv(x)
72
+ return x
73
+
74
+
75
+ class Downsample(nn.Module):
76
+ def __init__(self, in_channels, with_conv):
77
+ super().__init__()
78
+ self.with_conv = with_conv
79
+ if self.with_conv:
80
+ # no asymmetric padding in torch conv, must do it ourselves
81
+ self.conv = fcbh.ops.Conv2d(in_channels,
82
+ in_channels,
83
+ kernel_size=3,
84
+ stride=2,
85
+ padding=0)
86
+
87
+ def forward(self, x):
88
+ if self.with_conv:
89
+ pad = (0,1,0,1)
90
+ x = torch.nn.functional.pad(x, pad, mode="constant", value=0)
91
+ x = self.conv(x)
92
+ else:
93
+ x = torch.nn.functional.avg_pool2d(x, kernel_size=2, stride=2)
94
+ return x
95
+
96
+
97
+ class ResnetBlock(nn.Module):
98
+ def __init__(self, *, in_channels, out_channels=None, conv_shortcut=False,
99
+ dropout, temb_channels=512):
100
+ super().__init__()
101
+ self.in_channels = in_channels
102
+ out_channels = in_channels if out_channels is None else out_channels
103
+ self.out_channels = out_channels
104
+ self.use_conv_shortcut = conv_shortcut
105
+
106
+ self.swish = torch.nn.SiLU(inplace=True)
107
+ self.norm1 = Normalize(in_channels)
108
+ self.conv1 = fcbh.ops.Conv2d(in_channels,
109
+ out_channels,
110
+ kernel_size=3,
111
+ stride=1,
112
+ padding=1)
113
+ if temb_channels > 0:
114
+ self.temb_proj = fcbh.ops.Linear(temb_channels,
115
+ out_channels)
116
+ self.norm2 = Normalize(out_channels)
117
+ self.dropout = torch.nn.Dropout(dropout, inplace=True)
118
+ self.conv2 = fcbh.ops.Conv2d(out_channels,
119
+ out_channels,
120
+ kernel_size=3,
121
+ stride=1,
122
+ padding=1)
123
+ if self.in_channels != self.out_channels:
124
+ if self.use_conv_shortcut:
125
+ self.conv_shortcut = fcbh.ops.Conv2d(in_channels,
126
+ out_channels,
127
+ kernel_size=3,
128
+ stride=1,
129
+ padding=1)
130
+ else:
131
+ self.nin_shortcut = fcbh.ops.Conv2d(in_channels,
132
+ out_channels,
133
+ kernel_size=1,
134
+ stride=1,
135
+ padding=0)
136
+
137
+ def forward(self, x, temb):
138
+ h = x
139
+ h = self.norm1(h)
140
+ h = self.swish(h)
141
+ h = self.conv1(h)
142
+
143
+ if temb is not None:
144
+ h = h + self.temb_proj(self.swish(temb))[:,:,None,None]
145
+
146
+ h = self.norm2(h)
147
+ h = self.swish(h)
148
+ h = self.dropout(h)
149
+ h = self.conv2(h)
150
+
151
+ if self.in_channels != self.out_channels:
152
+ if self.use_conv_shortcut:
153
+ x = self.conv_shortcut(x)
154
+ else:
155
+ x = self.nin_shortcut(x)
156
+
157
+ return x+h
158
+
159
+ def slice_attention(q, k, v):
160
+ r1 = torch.zeros_like(k, device=q.device)
161
+ scale = (int(q.shape[-1])**(-0.5))
162
+
163
+ mem_free_total = model_management.get_free_memory(q.device)
164
+
165
+ gb = 1024 ** 3
166
+ tensor_size = q.shape[0] * q.shape[1] * k.shape[2] * q.element_size()
167
+ modifier = 3 if q.element_size() == 2 else 2.5
168
+ mem_required = tensor_size * modifier
169
+ steps = 1
170
+
171
+ if mem_required > mem_free_total:
172
+ steps = 2**(math.ceil(math.log(mem_required / mem_free_total, 2)))
173
+
174
+ while True:
175
+ try:
176
+ slice_size = q.shape[1] // steps if (q.shape[1] % steps) == 0 else q.shape[1]
177
+ for i in range(0, q.shape[1], slice_size):
178
+ end = i + slice_size
179
+ s1 = torch.bmm(q[:, i:end], k) * scale
180
+
181
+ s2 = torch.nn.functional.softmax(s1, dim=2).permute(0,2,1)
182
+ del s1
183
+
184
+ r1[:, :, i:end] = torch.bmm(v, s2)
185
+ del s2
186
+ break
187
+ except model_management.OOM_EXCEPTION as e:
188
+ model_management.soft_empty_cache(True)
189
+ steps *= 2
190
+ if steps > 128:
191
+ raise e
192
+ print("out of memory error, increasing steps and trying again", steps)
193
+
194
+ return r1
195
+
196
+ def normal_attention(q, k, v):
197
+ # compute attention
198
+ b,c,h,w = q.shape
199
+
200
+ q = q.reshape(b,c,h*w)
201
+ q = q.permute(0,2,1) # b,hw,c
202
+ k = k.reshape(b,c,h*w) # b,c,hw
203
+ v = v.reshape(b,c,h*w)
204
+
205
+ r1 = slice_attention(q, k, v)
206
+ h_ = r1.reshape(b,c,h,w)
207
+ del r1
208
+ return h_
209
+
210
+ def xformers_attention(q, k, v):
211
+ # compute attention
212
+ B, C, H, W = q.shape
213
+ q, k, v = map(
214
+ lambda t: t.view(B, C, -1).transpose(1, 2).contiguous(),
215
+ (q, k, v),
216
+ )
217
+
218
+ try:
219
+ out = xformers.ops.memory_efficient_attention(q, k, v, attn_bias=None)
220
+ out = out.transpose(1, 2).reshape(B, C, H, W)
221
+ except NotImplementedError as e:
222
+ 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)
223
+ return out
224
+
225
+ def pytorch_attention(q, k, v):
226
+ # compute attention
227
+ B, C, H, W = q.shape
228
+ q, k, v = map(
229
+ lambda t: t.view(B, 1, C, -1).transpose(2, 3).contiguous(),
230
+ (q, k, v),
231
+ )
232
+
233
+ try:
234
+ out = torch.nn.functional.scaled_dot_product_attention(q, k, v, attn_mask=None, dropout_p=0.0, is_causal=False)
235
+ out = out.transpose(2, 3).reshape(B, C, H, W)
236
+ except model_management.OOM_EXCEPTION as e:
237
+ print("scaled_dot_product_attention OOMed: switched to slice attention")
238
+ 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)
239
+ return out
240
+
241
+
242
+ class AttnBlock(nn.Module):
243
+ def __init__(self, in_channels):
244
+ super().__init__()
245
+ self.in_channels = in_channels
246
+
247
+ self.norm = Normalize(in_channels)
248
+ self.q = fcbh.ops.Conv2d(in_channels,
249
+ in_channels,
250
+ kernel_size=1,
251
+ stride=1,
252
+ padding=0)
253
+ self.k = fcbh.ops.Conv2d(in_channels,
254
+ in_channels,
255
+ kernel_size=1,
256
+ stride=1,
257
+ padding=0)
258
+ self.v = fcbh.ops.Conv2d(in_channels,
259
+ in_channels,
260
+ kernel_size=1,
261
+ stride=1,
262
+ padding=0)
263
+ self.proj_out = fcbh.ops.Conv2d(in_channels,
264
+ in_channels,
265
+ kernel_size=1,
266
+ stride=1,
267
+ padding=0)
268
+
269
+ if model_management.xformers_enabled_vae():
270
+ print("Using xformers attention in VAE")
271
+ self.optimized_attention = xformers_attention
272
+ elif model_management.pytorch_attention_enabled():
273
+ print("Using pytorch attention in VAE")
274
+ self.optimized_attention = pytorch_attention
275
+ else:
276
+ print("Using split attention in VAE")
277
+ self.optimized_attention = normal_attention
278
+
279
+ def forward(self, x):
280
+ h_ = x
281
+ h_ = self.norm(h_)
282
+ q = self.q(h_)
283
+ k = self.k(h_)
284
+ v = self.v(h_)
285
+
286
+ h_ = self.optimized_attention(q, k, v)
287
+
288
+ h_ = self.proj_out(h_)
289
+
290
+ return x+h_
291
+
292
+
293
+ def make_attn(in_channels, attn_type="vanilla", attn_kwargs=None):
294
+ return AttnBlock(in_channels)
295
+
296
+
297
+ class Model(nn.Module):
298
+ def __init__(self, *, ch, out_ch, ch_mult=(1,2,4,8), num_res_blocks,
299
+ attn_resolutions, dropout=0.0, resamp_with_conv=True, in_channels,
300
+ resolution, use_timestep=True, use_linear_attn=False, attn_type="vanilla"):
301
+ super().__init__()
302
+ if use_linear_attn: attn_type = "linear"
303
+ self.ch = ch
304
+ self.temb_ch = self.ch*4
305
+ self.num_resolutions = len(ch_mult)
306
+ self.num_res_blocks = num_res_blocks
307
+ self.resolution = resolution
308
+ self.in_channels = in_channels
309
+
310
+ self.use_timestep = use_timestep
311
+ if self.use_timestep:
312
+ # timestep embedding
313
+ self.temb = nn.Module()
314
+ self.temb.dense = nn.ModuleList([
315
+ fcbh.ops.Linear(self.ch,
316
+ self.temb_ch),
317
+ fcbh.ops.Linear(self.temb_ch,
318
+ self.temb_ch),
319
+ ])
320
+
321
+ # downsampling
322
+ self.conv_in = fcbh.ops.Conv2d(in_channels,
323
+ self.ch,
324
+ kernel_size=3,
325
+ stride=1,
326
+ padding=1)
327
+
328
+ curr_res = resolution
329
+ in_ch_mult = (1,)+tuple(ch_mult)
330
+ self.down = nn.ModuleList()
331
+ for i_level in range(self.num_resolutions):
332
+ block = nn.ModuleList()
333
+ attn = nn.ModuleList()
334
+ block_in = ch*in_ch_mult[i_level]
335
+ block_out = ch*ch_mult[i_level]
336
+ for i_block in range(self.num_res_blocks):
337
+ block.append(ResnetBlock(in_channels=block_in,
338
+ out_channels=block_out,
339
+ temb_channels=self.temb_ch,
340
+ dropout=dropout))
341
+ block_in = block_out
342
+ if curr_res in attn_resolutions:
343
+ attn.append(make_attn(block_in, attn_type=attn_type))
344
+ down = nn.Module()
345
+ down.block = block
346
+ down.attn = attn
347
+ if i_level != self.num_resolutions-1:
348
+ down.downsample = Downsample(block_in, resamp_with_conv)
349
+ curr_res = curr_res // 2
350
+ self.down.append(down)
351
+
352
+ # middle
353
+ self.mid = nn.Module()
354
+ self.mid.block_1 = ResnetBlock(in_channels=block_in,
355
+ out_channels=block_in,
356
+ temb_channels=self.temb_ch,
357
+ dropout=dropout)
358
+ self.mid.attn_1 = make_attn(block_in, attn_type=attn_type)
359
+ self.mid.block_2 = ResnetBlock(in_channels=block_in,
360
+ out_channels=block_in,
361
+ temb_channels=self.temb_ch,
362
+ dropout=dropout)
363
+
364
+ # upsampling
365
+ self.up = nn.ModuleList()
366
+ for i_level in reversed(range(self.num_resolutions)):
367
+ block = nn.ModuleList()
368
+ attn = nn.ModuleList()
369
+ block_out = ch*ch_mult[i_level]
370
+ skip_in = ch*ch_mult[i_level]
371
+ for i_block in range(self.num_res_blocks+1):
372
+ if i_block == self.num_res_blocks:
373
+ skip_in = ch*in_ch_mult[i_level]
374
+ block.append(ResnetBlock(in_channels=block_in+skip_in,
375
+ out_channels=block_out,
376
+ temb_channels=self.temb_ch,
377
+ dropout=dropout))
378
+ block_in = block_out
379
+ if curr_res in attn_resolutions:
380
+ attn.append(make_attn(block_in, attn_type=attn_type))
381
+ up = nn.Module()
382
+ up.block = block
383
+ up.attn = attn
384
+ if i_level != 0:
385
+ up.upsample = Upsample(block_in, resamp_with_conv)
386
+ curr_res = curr_res * 2
387
+ self.up.insert(0, up) # prepend to get consistent order
388
+
389
+ # end
390
+ self.norm_out = Normalize(block_in)
391
+ self.conv_out = fcbh.ops.Conv2d(block_in,
392
+ out_ch,
393
+ kernel_size=3,
394
+ stride=1,
395
+ padding=1)
396
+
397
+ def forward(self, x, t=None, context=None):
398
+ #assert x.shape[2] == x.shape[3] == self.resolution
399
+ if context is not None:
400
+ # assume aligned context, cat along channel axis
401
+ x = torch.cat((x, context), dim=1)
402
+ if self.use_timestep:
403
+ # timestep embedding
404
+ assert t is not None
405
+ temb = get_timestep_embedding(t, self.ch)
406
+ temb = self.temb.dense[0](temb)
407
+ temb = nonlinearity(temb)
408
+ temb = self.temb.dense[1](temb)
409
+ else:
410
+ temb = None
411
+
412
+ # downsampling
413
+ hs = [self.conv_in(x)]
414
+ for i_level in range(self.num_resolutions):
415
+ for i_block in range(self.num_res_blocks):
416
+ h = self.down[i_level].block[i_block](hs[-1], temb)
417
+ if len(self.down[i_level].attn) > 0:
418
+ h = self.down[i_level].attn[i_block](h)
419
+ hs.append(h)
420
+ if i_level != self.num_resolutions-1:
421
+ hs.append(self.down[i_level].downsample(hs[-1]))
422
+
423
+ # middle
424
+ h = hs[-1]
425
+ h = self.mid.block_1(h, temb)
426
+ h = self.mid.attn_1(h)
427
+ h = self.mid.block_2(h, temb)
428
+
429
+ # upsampling
430
+ for i_level in reversed(range(self.num_resolutions)):
431
+ for i_block in range(self.num_res_blocks+1):
432
+ h = self.up[i_level].block[i_block](
433
+ torch.cat([h, hs.pop()], dim=1), temb)
434
+ if len(self.up[i_level].attn) > 0:
435
+ h = self.up[i_level].attn[i_block](h)
436
+ if i_level != 0:
437
+ h = self.up[i_level].upsample(h)
438
+
439
+ # end
440
+ h = self.norm_out(h)
441
+ h = nonlinearity(h)
442
+ h = self.conv_out(h)
443
+ return h
444
+
445
+ def get_last_layer(self):
446
+ return self.conv_out.weight
447
+
448
+
449
+ class Encoder(nn.Module):
450
+ def __init__(self, *, ch, out_ch, ch_mult=(1,2,4,8), num_res_blocks,
451
+ attn_resolutions, dropout=0.0, resamp_with_conv=True, in_channels,
452
+ resolution, z_channels, double_z=True, use_linear_attn=False, attn_type="vanilla",
453
+ **ignore_kwargs):
454
+ super().__init__()
455
+ if use_linear_attn: attn_type = "linear"
456
+ self.ch = ch
457
+ self.temb_ch = 0
458
+ self.num_resolutions = len(ch_mult)
459
+ self.num_res_blocks = num_res_blocks
460
+ self.resolution = resolution
461
+ self.in_channels = in_channels
462
+
463
+ # downsampling
464
+ self.conv_in = fcbh.ops.Conv2d(in_channels,
465
+ self.ch,
466
+ kernel_size=3,
467
+ stride=1,
468
+ padding=1)
469
+
470
+ curr_res = resolution
471
+ in_ch_mult = (1,)+tuple(ch_mult)
472
+ self.in_ch_mult = in_ch_mult
473
+ self.down = nn.ModuleList()
474
+ for i_level in range(self.num_resolutions):
475
+ block = nn.ModuleList()
476
+ attn = nn.ModuleList()
477
+ block_in = ch*in_ch_mult[i_level]
478
+ block_out = ch*ch_mult[i_level]
479
+ for i_block in range(self.num_res_blocks):
480
+ block.append(ResnetBlock(in_channels=block_in,
481
+ out_channels=block_out,
482
+ temb_channels=self.temb_ch,
483
+ dropout=dropout))
484
+ block_in = block_out
485
+ if curr_res in attn_resolutions:
486
+ attn.append(make_attn(block_in, attn_type=attn_type))
487
+ down = nn.Module()
488
+ down.block = block
489
+ down.attn = attn
490
+ if i_level != self.num_resolutions-1:
491
+ down.downsample = Downsample(block_in, resamp_with_conv)
492
+ curr_res = curr_res // 2
493
+ self.down.append(down)
494
+
495
+ # middle
496
+ self.mid = nn.Module()
497
+ self.mid.block_1 = ResnetBlock(in_channels=block_in,
498
+ out_channels=block_in,
499
+ temb_channels=self.temb_ch,
500
+ dropout=dropout)
501
+ self.mid.attn_1 = make_attn(block_in, attn_type=attn_type)
502
+ self.mid.block_2 = ResnetBlock(in_channels=block_in,
503
+ out_channels=block_in,
504
+ temb_channels=self.temb_ch,
505
+ dropout=dropout)
506
+
507
+ # end
508
+ self.norm_out = Normalize(block_in)
509
+ self.conv_out = fcbh.ops.Conv2d(block_in,
510
+ 2*z_channels if double_z else z_channels,
511
+ kernel_size=3,
512
+ stride=1,
513
+ padding=1)
514
+
515
+ def forward(self, x):
516
+ # timestep embedding
517
+ temb = None
518
+ # downsampling
519
+ h = self.conv_in(x)
520
+ for i_level in range(self.num_resolutions):
521
+ for i_block in range(self.num_res_blocks):
522
+ h = self.down[i_level].block[i_block](h, temb)
523
+ if len(self.down[i_level].attn) > 0:
524
+ h = self.down[i_level].attn[i_block](h)
525
+ if i_level != self.num_resolutions-1:
526
+ h = self.down[i_level].downsample(h)
527
+
528
+ # middle
529
+ h = self.mid.block_1(h, temb)
530
+ h = self.mid.attn_1(h)
531
+ h = self.mid.block_2(h, temb)
532
+
533
+ # end
534
+ h = self.norm_out(h)
535
+ h = nonlinearity(h)
536
+ h = self.conv_out(h)
537
+ return h
538
+
539
+
540
+ class Decoder(nn.Module):
541
+ def __init__(self, *, ch, out_ch, ch_mult=(1,2,4,8), num_res_blocks,
542
+ attn_resolutions, dropout=0.0, resamp_with_conv=True, in_channels,
543
+ resolution, z_channels, give_pre_end=False, tanh_out=False, use_linear_attn=False,
544
+ conv_out_op=fcbh.ops.Conv2d,
545
+ resnet_op=ResnetBlock,
546
+ attn_op=AttnBlock,
547
+ **ignorekwargs):
548
+ super().__init__()
549
+ if use_linear_attn: attn_type = "linear"
550
+ self.ch = ch
551
+ self.temb_ch = 0
552
+ self.num_resolutions = len(ch_mult)
553
+ self.num_res_blocks = num_res_blocks
554
+ self.resolution = resolution
555
+ self.in_channels = in_channels
556
+ self.give_pre_end = give_pre_end
557
+ self.tanh_out = tanh_out
558
+
559
+ # compute in_ch_mult, block_in and curr_res at lowest res
560
+ in_ch_mult = (1,)+tuple(ch_mult)
561
+ block_in = ch*ch_mult[self.num_resolutions-1]
562
+ curr_res = resolution // 2**(self.num_resolutions-1)
563
+ self.z_shape = (1,z_channels,curr_res,curr_res)
564
+ print("Working with z of shape {} = {} dimensions.".format(
565
+ self.z_shape, np.prod(self.z_shape)))
566
+
567
+ # z to block_in
568
+ self.conv_in = fcbh.ops.Conv2d(z_channels,
569
+ block_in,
570
+ kernel_size=3,
571
+ stride=1,
572
+ padding=1)
573
+
574
+ # middle
575
+ self.mid = nn.Module()
576
+ self.mid.block_1 = resnet_op(in_channels=block_in,
577
+ out_channels=block_in,
578
+ temb_channels=self.temb_ch,
579
+ dropout=dropout)
580
+ self.mid.attn_1 = attn_op(block_in)
581
+ self.mid.block_2 = resnet_op(in_channels=block_in,
582
+ out_channels=block_in,
583
+ temb_channels=self.temb_ch,
584
+ dropout=dropout)
585
+
586
+ # upsampling
587
+ self.up = nn.ModuleList()
588
+ for i_level in reversed(range(self.num_resolutions)):
589
+ block = nn.ModuleList()
590
+ attn = nn.ModuleList()
591
+ block_out = ch*ch_mult[i_level]
592
+ for i_block in range(self.num_res_blocks+1):
593
+ block.append(resnet_op(in_channels=block_in,
594
+ out_channels=block_out,
595
+ temb_channels=self.temb_ch,
596
+ dropout=dropout))
597
+ block_in = block_out
598
+ if curr_res in attn_resolutions:
599
+ attn.append(attn_op(block_in))
600
+ up = nn.Module()
601
+ up.block = block
602
+ up.attn = attn
603
+ if i_level != 0:
604
+ up.upsample = Upsample(block_in, resamp_with_conv)
605
+ curr_res = curr_res * 2
606
+ self.up.insert(0, up) # prepend to get consistent order
607
+
608
+ # end
609
+ self.norm_out = Normalize(block_in)
610
+ self.conv_out = conv_out_op(block_in,
611
+ out_ch,
612
+ kernel_size=3,
613
+ stride=1,
614
+ padding=1)
615
+
616
+ def forward(self, z, **kwargs):
617
+ #assert z.shape[1:] == self.z_shape[1:]
618
+ self.last_z_shape = z.shape
619
+
620
+ # timestep embedding
621
+ temb = None
622
+
623
+ # z to block_in
624
+ h = self.conv_in(z)
625
+
626
+ # middle
627
+ h = self.mid.block_1(h, temb, **kwargs)
628
+ h = self.mid.attn_1(h, **kwargs)
629
+ h = self.mid.block_2(h, temb, **kwargs)
630
+
631
+ # upsampling
632
+ for i_level in reversed(range(self.num_resolutions)):
633
+ for i_block in range(self.num_res_blocks+1):
634
+ h = self.up[i_level].block[i_block](h, temb, **kwargs)
635
+ if len(self.up[i_level].attn) > 0:
636
+ h = self.up[i_level].attn[i_block](h, **kwargs)
637
+ if i_level != 0:
638
+ h = self.up[i_level].upsample(h)
639
+
640
+ # end
641
+ if self.give_pre_end:
642
+ return h
643
+
644
+ h = self.norm_out(h)
645
+ h = nonlinearity(h)
646
+ h = self.conv_out(h, **kwargs)
647
+ if self.tanh_out:
648
+ h = torch.tanh(h)
649
+ return h
backend/headless/fcbh/ldm/modules/diffusionmodules/openaimodel.py ADDED
@@ -0,0 +1,666 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from abc import abstractmethod
2
+ import math
3
+
4
+ import numpy as np
5
+ import torch as th
6
+ import torch.nn as nn
7
+ import torch.nn.functional as F
8
+
9
+ from .util import (
10
+ checkpoint,
11
+ avg_pool_nd,
12
+ zero_module,
13
+ normalization,
14
+ timestep_embedding,
15
+ )
16
+ from ..attention import SpatialTransformer
17
+ from fcbh.ldm.util import exists
18
+ import fcbh.ops
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
+
32
+ class TimestepEmbedSequential(nn.Sequential, TimestepBlock):
33
+ """
34
+ A sequential module that passes timestep embeddings to the children that
35
+ support it as an extra input.
36
+ """
37
+
38
+ def forward(self, x, emb, context=None, transformer_options={}, output_shape=None):
39
+ for layer in self:
40
+ if isinstance(layer, TimestepBlock):
41
+ x = layer(x, emb)
42
+ elif isinstance(layer, SpatialTransformer):
43
+ x = layer(x, context, transformer_options)
44
+ elif isinstance(layer, Upsample):
45
+ x = layer(x, output_shape=output_shape)
46
+ else:
47
+ x = layer(x)
48
+ return x
49
+
50
+ #This is needed because accelerate makes a copy of transformer_options which breaks "current_index"
51
+ def forward_timestep_embed(ts, x, emb, context=None, transformer_options={}, output_shape=None):
52
+ for layer in ts:
53
+ if isinstance(layer, TimestepBlock):
54
+ x = layer(x, emb)
55
+ elif isinstance(layer, SpatialTransformer):
56
+ x = layer(x, context, transformer_options)
57
+ transformer_options["current_index"] += 1
58
+ elif isinstance(layer, Upsample):
59
+ x = layer(x, output_shape=output_shape)
60
+ else:
61
+ x = layer(x)
62
+ return x
63
+
64
+ class Upsample(nn.Module):
65
+ """
66
+ An upsampling layer with an optional convolution.
67
+ :param channels: channels in the inputs and outputs.
68
+ :param use_conv: a bool determining if a convolution is applied.
69
+ :param dims: determines if the signal is 1D, 2D, or 3D. If 3D, then
70
+ upsampling occurs in the inner-two dimensions.
71
+ """
72
+
73
+ def __init__(self, channels, use_conv, dims=2, out_channels=None, padding=1, dtype=None, device=None, operations=fcbh.ops):
74
+ super().__init__()
75
+ self.channels = channels
76
+ self.out_channels = out_channels or channels
77
+ self.use_conv = use_conv
78
+ self.dims = dims
79
+ if use_conv:
80
+ self.conv = operations.conv_nd(dims, self.channels, self.out_channels, 3, padding=padding, dtype=dtype, device=device)
81
+
82
+ def forward(self, x, output_shape=None):
83
+ assert x.shape[1] == self.channels
84
+ if self.dims == 3:
85
+ shape = [x.shape[2], x.shape[3] * 2, x.shape[4] * 2]
86
+ if output_shape is not None:
87
+ shape[1] = output_shape[3]
88
+ shape[2] = output_shape[4]
89
+ else:
90
+ shape = [x.shape[2] * 2, x.shape[3] * 2]
91
+ if output_shape is not None:
92
+ shape[0] = output_shape[2]
93
+ shape[1] = output_shape[3]
94
+
95
+ x = F.interpolate(x, size=shape, mode="nearest")
96
+ if self.use_conv:
97
+ x = self.conv(x)
98
+ return x
99
+
100
+ class Downsample(nn.Module):
101
+ """
102
+ A downsampling layer with an optional convolution.
103
+ :param channels: channels in the inputs and outputs.
104
+ :param use_conv: a bool determining if a convolution is applied.
105
+ :param dims: determines if the signal is 1D, 2D, or 3D. If 3D, then
106
+ downsampling occurs in the inner-two dimensions.
107
+ """
108
+
109
+ def __init__(self, channels, use_conv, dims=2, out_channels=None, padding=1, dtype=None, device=None, operations=fcbh.ops):
110
+ super().__init__()
111
+ self.channels = channels
112
+ self.out_channels = out_channels or channels
113
+ self.use_conv = use_conv
114
+ self.dims = dims
115
+ stride = 2 if dims != 3 else (1, 2, 2)
116
+ if use_conv:
117
+ self.op = operations.conv_nd(
118
+ dims, self.channels, self.out_channels, 3, stride=stride, padding=padding, dtype=dtype, device=device
119
+ )
120
+ else:
121
+ assert self.channels == self.out_channels
122
+ self.op = avg_pool_nd(dims, kernel_size=stride, stride=stride)
123
+
124
+ def forward(self, x):
125
+ assert x.shape[1] == self.channels
126
+ return self.op(x)
127
+
128
+
129
+ class ResBlock(TimestepBlock):
130
+ """
131
+ A residual block that can optionally change the number of channels.
132
+ :param channels: the number of input channels.
133
+ :param emb_channels: the number of timestep embedding channels.
134
+ :param dropout: the rate of dropout.
135
+ :param out_channels: if specified, the number of out channels.
136
+ :param use_conv: if True and out_channels is specified, use a spatial
137
+ convolution instead of a smaller 1x1 convolution to change the
138
+ channels in the skip connection.
139
+ :param dims: determines if the signal is 1D, 2D, or 3D.
140
+ :param use_checkpoint: if True, use gradient checkpointing on this module.
141
+ :param up: if True, use this block for upsampling.
142
+ :param down: if True, use this block for downsampling.
143
+ """
144
+
145
+ def __init__(
146
+ self,
147
+ channels,
148
+ emb_channels,
149
+ dropout,
150
+ out_channels=None,
151
+ use_conv=False,
152
+ use_scale_shift_norm=False,
153
+ dims=2,
154
+ use_checkpoint=False,
155
+ up=False,
156
+ down=False,
157
+ dtype=None,
158
+ device=None,
159
+ operations=fcbh.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
+
170
+ self.in_layers = nn.Sequential(
171
+ nn.GroupNorm(32, channels, dtype=dtype, device=device),
172
+ nn.SiLU(),
173
+ operations.conv_nd(dims, channels, self.out_channels, 3, padding=1, dtype=dtype, device=device),
174
+ )
175
+
176
+ self.updown = up or down
177
+
178
+ if up:
179
+ self.h_upd = Upsample(channels, False, dims, dtype=dtype, device=device)
180
+ self.x_upd = Upsample(channels, False, dims, dtype=dtype, device=device)
181
+ elif down:
182
+ self.h_upd = Downsample(channels, False, dims, dtype=dtype, device=device)
183
+ self.x_upd = Downsample(channels, False, dims, dtype=dtype, device=device)
184
+ else:
185
+ self.h_upd = self.x_upd = nn.Identity()
186
+
187
+ self.emb_layers = nn.Sequential(
188
+ nn.SiLU(),
189
+ operations.Linear(
190
+ emb_channels,
191
+ 2 * self.out_channels if use_scale_shift_norm else self.out_channels, dtype=dtype, device=device
192
+ ),
193
+ )
194
+ self.out_layers = nn.Sequential(
195
+ nn.GroupNorm(32, self.out_channels, dtype=dtype, device=device),
196
+ nn.SiLU(),
197
+ nn.Dropout(p=dropout),
198
+ zero_module(
199
+ operations.conv_nd(dims, self.out_channels, self.out_channels, 3, padding=1, dtype=dtype, device=device)
200
+ ),
201
+ )
202
+
203
+ if self.out_channels == channels:
204
+ self.skip_connection = nn.Identity()
205
+ elif use_conv:
206
+ self.skip_connection = operations.conv_nd(
207
+ dims, channels, self.out_channels, 3, padding=1, dtype=dtype, device=device
208
+ )
209
+ else:
210
+ self.skip_connection = operations.conv_nd(dims, channels, self.out_channels, 1, dtype=dtype, device=device)
211
+
212
+ def forward(self, x, emb):
213
+ """
214
+ Apply the block to a Tensor, conditioned on a timestep embedding.
215
+ :param x: an [N x C x ...] Tensor of features.
216
+ :param emb: an [N x emb_channels] Tensor of timestep embeddings.
217
+ :return: an [N x C x ...] Tensor of outputs.
218
+ """
219
+ return checkpoint(
220
+ self._forward, (x, emb), self.parameters(), self.use_checkpoint
221
+ )
222
+
223
+
224
+ def _forward(self, x, emb):
225
+ if self.updown:
226
+ in_rest, in_conv = self.in_layers[:-1], self.in_layers[-1]
227
+ h = in_rest(x)
228
+ h = self.h_upd(h)
229
+ x = self.x_upd(x)
230
+ h = in_conv(h)
231
+ else:
232
+ h = self.in_layers(x)
233
+ emb_out = self.emb_layers(emb).type(h.dtype)
234
+ while len(emb_out.shape) < len(h.shape):
235
+ emb_out = emb_out[..., None]
236
+ if self.use_scale_shift_norm:
237
+ out_norm, out_rest = self.out_layers[0], self.out_layers[1:]
238
+ scale, shift = th.chunk(emb_out, 2, dim=1)
239
+ h = out_norm(h) * (1 + scale) + shift
240
+ h = out_rest(h)
241
+ else:
242
+ h = h + emb_out
243
+ h = self.out_layers(h)
244
+ return self.skip_connection(x) + h
245
+
246
+ class Timestep(nn.Module):
247
+ def __init__(self, dim):
248
+ super().__init__()
249
+ self.dim = dim
250
+
251
+ def forward(self, t):
252
+ return timestep_embedding(t, self.dim)
253
+
254
+ def apply_control(h, control, name):
255
+ if control is not None and name in control and len(control[name]) > 0:
256
+ ctrl = control[name].pop()
257
+ if ctrl is not None:
258
+ try:
259
+ h += ctrl
260
+ except:
261
+ print("warning control could not be applied", h.shape, ctrl.shape)
262
+ return h
263
+
264
+ class UNetModel(nn.Module):
265
+ """
266
+ The full UNet model with attention and timestep embedding.
267
+ :param in_channels: channels in the input Tensor.
268
+ :param model_channels: base channel count for the model.
269
+ :param out_channels: channels in the output Tensor.
270
+ :param num_res_blocks: number of residual blocks per downsample.
271
+ :param dropout: the dropout probability.
272
+ :param channel_mult: channel multiplier for each level of the UNet.
273
+ :param conv_resample: if True, use learned convolutions for upsampling and
274
+ downsampling.
275
+ :param dims: determines if the signal is 1D, 2D, or 3D.
276
+ :param num_classes: if specified (as an int), then this model will be
277
+ class-conditional with `num_classes` classes.
278
+ :param use_checkpoint: use gradient checkpointing to reduce memory usage.
279
+ :param num_heads: the number of attention heads in each attention layer.
280
+ :param num_heads_channels: if specified, ignore num_heads and instead use
281
+ a fixed channel width per attention head.
282
+ :param num_heads_upsample: works with num_heads to set a different number
283
+ of heads for upsampling. Deprecated.
284
+ :param use_scale_shift_norm: use a FiLM-like conditioning mechanism.
285
+ :param resblock_updown: use residual blocks for up/downsampling.
286
+ :param use_new_attention_order: use a different attention pattern for potentially
287
+ increased efficiency.
288
+ """
289
+
290
+ def __init__(
291
+ self,
292
+ image_size,
293
+ in_channels,
294
+ model_channels,
295
+ out_channels,
296
+ num_res_blocks,
297
+ dropout=0,
298
+ channel_mult=(1, 2, 4, 8),
299
+ conv_resample=True,
300
+ dims=2,
301
+ num_classes=None,
302
+ use_checkpoint=False,
303
+ dtype=th.float32,
304
+ num_heads=-1,
305
+ num_head_channels=-1,
306
+ num_heads_upsample=-1,
307
+ use_scale_shift_norm=False,
308
+ resblock_updown=False,
309
+ use_new_attention_order=False,
310
+ use_spatial_transformer=False, # custom transformer support
311
+ transformer_depth=1, # custom transformer support
312
+ context_dim=None, # custom transformer support
313
+ n_embed=None, # custom support for prediction of discrete ids into codebook of first stage vq model
314
+ legacy=True,
315
+ disable_self_attentions=None,
316
+ num_attention_blocks=None,
317
+ disable_middle_self_attn=False,
318
+ use_linear_in_transformer=False,
319
+ adm_in_channels=None,
320
+ transformer_depth_middle=None,
321
+ transformer_depth_output=None,
322
+ device=None,
323
+ operations=fcbh.ops,
324
+ ):
325
+ super().__init__()
326
+ assert use_spatial_transformer == True, "use_spatial_transformer has to be true"
327
+ if use_spatial_transformer:
328
+ assert context_dim is not None, 'Fool!! You forgot to include the dimension of your cross-attention conditioning...'
329
+
330
+ if context_dim is not None:
331
+ assert use_spatial_transformer, 'Fool!! You forgot to use the spatial transformer for your cross-attention conditioning...'
332
+ # from omegaconf.listconfig import ListConfig
333
+ # if type(context_dim) == ListConfig:
334
+ # context_dim = list(context_dim)
335
+
336
+ if num_heads_upsample == -1:
337
+ num_heads_upsample = num_heads
338
+
339
+ if num_heads == -1:
340
+ assert num_head_channels != -1, 'Either num_heads or num_head_channels has to be set'
341
+
342
+ if num_head_channels == -1:
343
+ assert num_heads != -1, 'Either num_heads or num_head_channels has to be set'
344
+
345
+ self.image_size = image_size
346
+ self.in_channels = in_channels
347
+ self.model_channels = model_channels
348
+ self.out_channels = out_channels
349
+
350
+ if isinstance(num_res_blocks, int):
351
+ self.num_res_blocks = len(channel_mult) * [num_res_blocks]
352
+ else:
353
+ if len(num_res_blocks) != len(channel_mult):
354
+ raise ValueError("provide num_res_blocks either as an int (globally constant) or "
355
+ "as a list/tuple (per-level) with the same length as channel_mult")
356
+ self.num_res_blocks = num_res_blocks
357
+
358
+ if disable_self_attentions is not None:
359
+ # should be a list of booleans, indicating whether to disable self-attention in TransformerBlocks or not
360
+ assert len(disable_self_attentions) == len(channel_mult)
361
+ if num_attention_blocks is not None:
362
+ assert len(num_attention_blocks) == len(self.num_res_blocks)
363
+
364
+ transformer_depth = transformer_depth[:]
365
+ transformer_depth_output = transformer_depth_output[:]
366
+
367
+ self.dropout = dropout
368
+ self.channel_mult = channel_mult
369
+ self.conv_resample = conv_resample
370
+ self.num_classes = num_classes
371
+ self.use_checkpoint = use_checkpoint
372
+ self.dtype = dtype
373
+ self.num_heads = num_heads
374
+ self.num_head_channels = num_head_channels
375
+ self.num_heads_upsample = num_heads_upsample
376
+ self.predict_codebook_ids = n_embed is not None
377
+
378
+ time_embed_dim = model_channels * 4
379
+ self.time_embed = nn.Sequential(
380
+ operations.Linear(model_channels, time_embed_dim, dtype=self.dtype, device=device),
381
+ nn.SiLU(),
382
+ operations.Linear(time_embed_dim, time_embed_dim, dtype=self.dtype, device=device),
383
+ )
384
+
385
+ if self.num_classes is not None:
386
+ if isinstance(self.num_classes, int):
387
+ self.label_emb = nn.Embedding(num_classes, time_embed_dim)
388
+ elif self.num_classes == "continuous":
389
+ print("setting up linear c_adm embedding layer")
390
+ self.label_emb = nn.Linear(1, time_embed_dim)
391
+ elif self.num_classes == "sequential":
392
+ assert adm_in_channels is not None
393
+ self.label_emb = nn.Sequential(
394
+ nn.Sequential(
395
+ operations.Linear(adm_in_channels, time_embed_dim, dtype=self.dtype, device=device),
396
+ nn.SiLU(),
397
+ operations.Linear(time_embed_dim, time_embed_dim, dtype=self.dtype, device=device),
398
+ )
399
+ )
400
+ else:
401
+ raise ValueError()
402
+
403
+ self.input_blocks = nn.ModuleList(
404
+ [
405
+ TimestepEmbedSequential(
406
+ operations.conv_nd(dims, in_channels, model_channels, 3, padding=1, dtype=self.dtype, device=device)
407
+ )
408
+ ]
409
+ )
410
+ self._feature_size = model_channels
411
+ input_block_chans = [model_channels]
412
+ ch = model_channels
413
+ ds = 1
414
+ for level, mult in enumerate(channel_mult):
415
+ for nr in range(self.num_res_blocks[level]):
416
+ layers = [
417
+ ResBlock(
418
+ ch,
419
+ time_embed_dim,
420
+ dropout,
421
+ out_channels=mult * model_channels,
422
+ dims=dims,
423
+ use_checkpoint=use_checkpoint,
424
+ use_scale_shift_norm=use_scale_shift_norm,
425
+ dtype=self.dtype,
426
+ device=device,
427
+ operations=operations,
428
+ )
429
+ ]
430
+ ch = mult * model_channels
431
+ num_transformers = transformer_depth.pop(0)
432
+ if num_transformers > 0:
433
+ if num_head_channels == -1:
434
+ dim_head = ch // num_heads
435
+ else:
436
+ num_heads = ch // num_head_channels
437
+ dim_head = num_head_channels
438
+ if legacy:
439
+ #num_heads = 1
440
+ dim_head = ch // num_heads if use_spatial_transformer else num_head_channels
441
+ if exists(disable_self_attentions):
442
+ disabled_sa = disable_self_attentions[level]
443
+ else:
444
+ disabled_sa = False
445
+
446
+ if not exists(num_attention_blocks) or nr < num_attention_blocks[level]:
447
+ layers.append(SpatialTransformer(
448
+ ch, num_heads, dim_head, depth=num_transformers, context_dim=context_dim,
449
+ disable_self_attn=disabled_sa, use_linear=use_linear_in_transformer,
450
+ use_checkpoint=use_checkpoint, dtype=self.dtype, device=device, operations=operations
451
+ )
452
+ )
453
+ self.input_blocks.append(TimestepEmbedSequential(*layers))
454
+ self._feature_size += ch
455
+ input_block_chans.append(ch)
456
+ if level != len(channel_mult) - 1:
457
+ out_ch = ch
458
+ self.input_blocks.append(
459
+ TimestepEmbedSequential(
460
+ ResBlock(
461
+ ch,
462
+ time_embed_dim,
463
+ dropout,
464
+ out_channels=out_ch,
465
+ dims=dims,
466
+ use_checkpoint=use_checkpoint,
467
+ use_scale_shift_norm=use_scale_shift_norm,
468
+ down=True,
469
+ dtype=self.dtype,
470
+ device=device,
471
+ operations=operations
472
+ )
473
+ if resblock_updown
474
+ else Downsample(
475
+ ch, conv_resample, dims=dims, out_channels=out_ch, dtype=self.dtype, device=device, operations=operations
476
+ )
477
+ )
478
+ )
479
+ ch = out_ch
480
+ input_block_chans.append(ch)
481
+ ds *= 2
482
+ self._feature_size += ch
483
+
484
+ if num_head_channels == -1:
485
+ dim_head = ch // num_heads
486
+ else:
487
+ num_heads = ch // num_head_channels
488
+ dim_head = num_head_channels
489
+ if legacy:
490
+ #num_heads = 1
491
+ dim_head = ch // num_heads if use_spatial_transformer else num_head_channels
492
+ mid_block = [
493
+ ResBlock(
494
+ ch,
495
+ time_embed_dim,
496
+ dropout,
497
+ dims=dims,
498
+ use_checkpoint=use_checkpoint,
499
+ use_scale_shift_norm=use_scale_shift_norm,
500
+ dtype=self.dtype,
501
+ device=device,
502
+ operations=operations
503
+ )]
504
+ if transformer_depth_middle >= 0:
505
+ mid_block += [SpatialTransformer( # always uses a self-attn
506
+ ch, num_heads, dim_head, depth=transformer_depth_middle, context_dim=context_dim,
507
+ disable_self_attn=disable_middle_self_attn, use_linear=use_linear_in_transformer,
508
+ use_checkpoint=use_checkpoint, dtype=self.dtype, device=device, operations=operations
509
+ ),
510
+ ResBlock(
511
+ ch,
512
+ time_embed_dim,
513
+ dropout,
514
+ dims=dims,
515
+ use_checkpoint=use_checkpoint,
516
+ use_scale_shift_norm=use_scale_shift_norm,
517
+ dtype=self.dtype,
518
+ device=device,
519
+ operations=operations
520
+ )]
521
+ self.middle_block = TimestepEmbedSequential(*mid_block)
522
+ self._feature_size += ch
523
+
524
+ self.output_blocks = nn.ModuleList([])
525
+ for level, mult in list(enumerate(channel_mult))[::-1]:
526
+ for i in range(self.num_res_blocks[level] + 1):
527
+ ich = input_block_chans.pop()
528
+ layers = [
529
+ ResBlock(
530
+ ch + ich,
531
+ time_embed_dim,
532
+ dropout,
533
+ out_channels=model_channels * mult,
534
+ dims=dims,
535
+ use_checkpoint=use_checkpoint,
536
+ use_scale_shift_norm=use_scale_shift_norm,
537
+ dtype=self.dtype,
538
+ device=device,
539
+ operations=operations
540
+ )
541
+ ]
542
+ ch = model_channels * mult
543
+ num_transformers = transformer_depth_output.pop()
544
+ if num_transformers > 0:
545
+ if num_head_channels == -1:
546
+ dim_head = ch // num_heads
547
+ else:
548
+ num_heads = ch // num_head_channels
549
+ dim_head = num_head_channels
550
+ if legacy:
551
+ #num_heads = 1
552
+ dim_head = ch // num_heads if use_spatial_transformer else num_head_channels
553
+ if exists(disable_self_attentions):
554
+ disabled_sa = disable_self_attentions[level]
555
+ else:
556
+ disabled_sa = False
557
+
558
+ if not exists(num_attention_blocks) or i < num_attention_blocks[level]:
559
+ layers.append(
560
+ SpatialTransformer(
561
+ ch, num_heads, dim_head, depth=num_transformers, context_dim=context_dim,
562
+ disable_self_attn=disabled_sa, use_linear=use_linear_in_transformer,
563
+ use_checkpoint=use_checkpoint, dtype=self.dtype, device=device, operations=operations
564
+ )
565
+ )
566
+ if level and i == self.num_res_blocks[level]:
567
+ out_ch = ch
568
+ layers.append(
569
+ ResBlock(
570
+ ch,
571
+ time_embed_dim,
572
+ dropout,
573
+ out_channels=out_ch,
574
+ dims=dims,
575
+ use_checkpoint=use_checkpoint,
576
+ use_scale_shift_norm=use_scale_shift_norm,
577
+ up=True,
578
+ dtype=self.dtype,
579
+ device=device,
580
+ operations=operations
581
+ )
582
+ if resblock_updown
583
+ else Upsample(ch, conv_resample, dims=dims, out_channels=out_ch, dtype=self.dtype, device=device, operations=operations)
584
+ )
585
+ ds //= 2
586
+ self.output_blocks.append(TimestepEmbedSequential(*layers))
587
+ self._feature_size += ch
588
+
589
+ self.out = nn.Sequential(
590
+ nn.GroupNorm(32, ch, dtype=self.dtype, device=device),
591
+ nn.SiLU(),
592
+ zero_module(operations.conv_nd(dims, model_channels, out_channels, 3, padding=1, dtype=self.dtype, device=device)),
593
+ )
594
+ if self.predict_codebook_ids:
595
+ self.id_predictor = nn.Sequential(
596
+ nn.GroupNorm(32, ch, dtype=self.dtype, device=device),
597
+ operations.conv_nd(dims, model_channels, n_embed, 1, dtype=self.dtype, device=device),
598
+ #nn.LogSoftmax(dim=1) # change to cross_entropy and produce non-normalized logits
599
+ )
600
+
601
+ def forward(self, x, timesteps=None, context=None, y=None, control=None, transformer_options={}, **kwargs):
602
+ """
603
+ Apply the model to an input batch.
604
+ :param x: an [N x C x ...] Tensor of inputs.
605
+ :param timesteps: a 1-D batch of timesteps.
606
+ :param context: conditioning plugged in via crossattn
607
+ :param y: an [N] Tensor of labels, if class-conditional.
608
+ :return: an [N x C x ...] Tensor of outputs.
609
+ """
610
+ transformer_options["original_shape"] = list(x.shape)
611
+ transformer_options["current_index"] = 0
612
+ transformer_patches = transformer_options.get("patches", {})
613
+
614
+ assert (y is not None) == (
615
+ self.num_classes is not None
616
+ ), "must specify y if and only if the model is class-conditional"
617
+ hs = []
618
+ t_emb = timestep_embedding(timesteps, self.model_channels, repeat_only=False).to(self.dtype)
619
+ emb = self.time_embed(t_emb)
620
+
621
+ if self.num_classes is not None:
622
+ assert y.shape[0] == x.shape[0]
623
+ emb = emb + self.label_emb(y)
624
+
625
+ h = x.type(self.dtype)
626
+ for id, module in enumerate(self.input_blocks):
627
+ transformer_options["block"] = ("input", id)
628
+ h = forward_timestep_embed(module, h, emb, context, transformer_options)
629
+ h = apply_control(h, control, 'input')
630
+ if "input_block_patch" in transformer_patches:
631
+ patch = transformer_patches["input_block_patch"]
632
+ for p in patch:
633
+ h = p(h, transformer_options)
634
+
635
+ hs.append(h)
636
+ if "input_block_patch_after_skip" in transformer_patches:
637
+ patch = transformer_patches["input_block_patch_after_skip"]
638
+ for p in patch:
639
+ h = p(h, transformer_options)
640
+
641
+ transformer_options["block"] = ("middle", 0)
642
+ h = forward_timestep_embed(self.middle_block, h, emb, context, transformer_options)
643
+ h = apply_control(h, control, 'middle')
644
+
645
+ for id, module in enumerate(self.output_blocks):
646
+ transformer_options["block"] = ("output", id)
647
+ hsp = hs.pop()
648
+ hsp = apply_control(hsp, control, 'output')
649
+
650
+ if "output_block_patch" in transformer_patches:
651
+ patch = transformer_patches["output_block_patch"]
652
+ for p in patch:
653
+ h, hsp = p(h, hsp, transformer_options)
654
+
655
+ h = th.cat([h, hsp], dim=1)
656
+ del hsp
657
+ if len(hs) > 0:
658
+ output_shape = hs[-1].shape
659
+ else:
660
+ output_shape = None
661
+ h = forward_timestep_embed(module, h, emb, context, transformer_options, output_shape)
662
+ h = h.type(x.dtype)
663
+ if self.predict_codebook_ids:
664
+ return self.id_predictor(h)
665
+ else:
666
+ return self.out(h)
backend/headless/fcbh/ldm/modules/diffusionmodules/upscaling.py ADDED
@@ -0,0 +1,81 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 fcbh.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):
45
+ noise = default(noise, lambda: torch.randn_like(x_start))
46
+ return (extract_into_tensor(self.sqrt_alphas_cumprod, t, x_start.shape) * x_start +
47
+ extract_into_tensor(self.sqrt_one_minus_alphas_cumprod, t, x_start.shape) * noise)
48
+
49
+ def forward(self, x):
50
+ return x, None
51
+
52
+ def decode(self, x):
53
+ return x
54
+
55
+
56
+ class SimpleImageConcat(AbstractLowScaleModel):
57
+ # no noise level conditioning
58
+ def __init__(self):
59
+ super(SimpleImageConcat, self).__init__(noise_schedule_config=None)
60
+ self.max_noise_level = 0
61
+
62
+ def forward(self, x):
63
+ # fix to constant noise level
64
+ return x, torch.zeros(x.shape[0], device=x.device).long()
65
+
66
+
67
+ class ImageConcatWithNoiseAugmentation(AbstractLowScaleModel):
68
+ def __init__(self, noise_schedule_config, max_noise_level=1000, to_cuda=False):
69
+ super().__init__(noise_schedule_config=noise_schedule_config)
70
+ self.max_noise_level = max_noise_level
71
+
72
+ def forward(self, x, noise_level=None):
73
+ if noise_level is None:
74
+ noise_level = torch.randint(0, self.max_noise_level, (x.shape[0],), device=x.device).long()
75
+ else:
76
+ assert isinstance(noise_level, torch.Tensor)
77
+ z = self.q_sample(x, noise_level)
78
+ return z, noise_level
79
+
80
+
81
+
backend/headless/fcbh/ldm/modules/diffusionmodules/util.py ADDED
@@ -0,0 +1,278 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
17
+
18
+ from fcbh.ldm.util import instantiate_from_config
19
+ import fcbh.ops
20
+
21
+ def make_beta_schedule(schedule, n_timestep, linear_start=1e-4, linear_end=2e-2, cosine_s=8e-3):
22
+ if schedule == "linear":
23
+ betas = (
24
+ torch.linspace(linear_start ** 0.5, linear_end ** 0.5, n_timestep, dtype=torch.float64) ** 2
25
+ )
26
+
27
+ elif schedule == "cosine":
28
+ timesteps = (
29
+ torch.arange(n_timestep + 1, dtype=torch.float64) / n_timestep + cosine_s
30
+ )
31
+ alphas = timesteps / (1 + cosine_s) * np.pi / 2
32
+ alphas = torch.cos(alphas).pow(2)
33
+ alphas = alphas / alphas[0]
34
+ betas = 1 - alphas[1:] / alphas[:-1]
35
+ betas = np.clip(betas, a_min=0, a_max=0.999)
36
+
37
+ elif schedule == "squaredcos_cap_v2": # used for karlo prior
38
+ # return early
39
+ return betas_for_alpha_bar(
40
+ n_timestep,
41
+ lambda t: math.cos((t + 0.008) / 1.008 * math.pi / 2) ** 2,
42
+ )
43
+
44
+ elif schedule == "sqrt_linear":
45
+ betas = torch.linspace(linear_start, linear_end, n_timestep, dtype=torch.float64)
46
+ elif schedule == "sqrt":
47
+ betas = torch.linspace(linear_start, linear_end, n_timestep, dtype=torch.float64) ** 0.5
48
+ else:
49
+ raise ValueError(f"schedule '{schedule}' unknown.")
50
+ return betas.numpy()
51
+
52
+
53
+ def make_ddim_timesteps(ddim_discr_method, num_ddim_timesteps, num_ddpm_timesteps, verbose=True):
54
+ if ddim_discr_method == 'uniform':
55
+ c = num_ddpm_timesteps // num_ddim_timesteps
56
+ ddim_timesteps = np.asarray(list(range(0, num_ddpm_timesteps, c)))
57
+ elif ddim_discr_method == 'quad':
58
+ ddim_timesteps = ((np.linspace(0, np.sqrt(num_ddpm_timesteps * .8), num_ddim_timesteps)) ** 2).astype(int)
59
+ else:
60
+ raise NotImplementedError(f'There is no ddim discretization method called "{ddim_discr_method}"')
61
+
62
+ # assert ddim_timesteps.shape[0] == num_ddim_timesteps
63
+ # add one to get the final alpha values right (the ones from first scale to data during sampling)
64
+ steps_out = ddim_timesteps + 1
65
+ if verbose:
66
+ print(f'Selected timesteps for ddim sampler: {steps_out}')
67
+ return steps_out
68
+
69
+
70
+ def make_ddim_sampling_parameters(alphacums, ddim_timesteps, eta, verbose=True):
71
+ # select alphas for computing the variance schedule
72
+ alphas = alphacums[ddim_timesteps]
73
+ alphas_prev = np.asarray([alphacums[0]] + alphacums[ddim_timesteps[:-1]].tolist())
74
+
75
+ # according the the formula provided in https://arxiv.org/abs/2010.02502
76
+ sigmas = eta * np.sqrt((1 - alphas_prev) / (1 - alphas) * (1 - alphas / alphas_prev))
77
+ if verbose:
78
+ print(f'Selected alphas for ddim sampler: a_t: {alphas}; a_(t-1): {alphas_prev}')
79
+ print(f'For the chosen value of eta, which is {eta}, '
80
+ f'this results in the following sigma_t schedule for ddim sampler {sigmas}')
81
+ return sigmas, alphas, alphas_prev
82
+
83
+
84
+ def betas_for_alpha_bar(num_diffusion_timesteps, alpha_bar, max_beta=0.999):
85
+ """
86
+ Create a beta schedule that discretizes the given alpha_t_bar function,
87
+ which defines the cumulative product of (1-beta) over time from t = [0,1].
88
+ :param num_diffusion_timesteps: the number of betas to produce.
89
+ :param alpha_bar: a lambda that takes an argument t from 0 to 1 and
90
+ produces the cumulative product of (1-beta) up to that
91
+ part of the diffusion process.
92
+ :param max_beta: the maximum beta to use; use values lower than 1 to
93
+ prevent singularities.
94
+ """
95
+ betas = []
96
+ for i in range(num_diffusion_timesteps):
97
+ t1 = i / num_diffusion_timesteps
98
+ t2 = (i + 1) / num_diffusion_timesteps
99
+ betas.append(min(1 - alpha_bar(t2) / alpha_bar(t1), max_beta))
100
+ return np.array(betas)
101
+
102
+
103
+ def extract_into_tensor(a, t, x_shape):
104
+ b, *_ = t.shape
105
+ out = a.gather(-1, t)
106
+ return out.reshape(b, *((1,) * (len(x_shape) - 1)))
107
+
108
+
109
+ def checkpoint(func, inputs, params, flag):
110
+ """
111
+ Evaluate a function without caching intermediate activations, allowing for
112
+ reduced memory at the expense of extra compute in the backward pass.
113
+ :param func: the function to evaluate.
114
+ :param inputs: the argument sequence to pass to `func`.
115
+ :param params: a sequence of parameters `func` depends on but does not
116
+ explicitly take as arguments.
117
+ :param flag: if False, disable gradient checkpointing.
118
+ """
119
+ if flag:
120
+ args = tuple(inputs) + tuple(params)
121
+ return CheckpointFunction.apply(func, len(inputs), *args)
122
+ else:
123
+ return func(*inputs)
124
+
125
+
126
+ class CheckpointFunction(torch.autograd.Function):
127
+ @staticmethod
128
+ def forward(ctx, run_function, length, *args):
129
+ ctx.run_function = run_function
130
+ ctx.input_tensors = list(args[:length])
131
+ ctx.input_params = list(args[length:])
132
+ ctx.gpu_autocast_kwargs = {"enabled": torch.is_autocast_enabled(),
133
+ "dtype": torch.get_autocast_gpu_dtype(),
134
+ "cache_enabled": torch.is_autocast_cache_enabled()}
135
+ with torch.no_grad():
136
+ output_tensors = ctx.run_function(*ctx.input_tensors)
137
+ return output_tensors
138
+
139
+ @staticmethod
140
+ def backward(ctx, *output_grads):
141
+ ctx.input_tensors = [x.detach().requires_grad_(True) for x in ctx.input_tensors]
142
+ with torch.enable_grad(), \
143
+ torch.cuda.amp.autocast(**ctx.gpu_autocast_kwargs):
144
+ # Fixes a bug where the first op in run_function modifies the
145
+ # Tensor storage in place, which is not allowed for detach()'d
146
+ # Tensors.
147
+ shallow_copies = [x.view_as(x) for x in ctx.input_tensors]
148
+ output_tensors = ctx.run_function(*shallow_copies)
149
+ input_grads = torch.autograd.grad(
150
+ output_tensors,
151
+ ctx.input_tensors + ctx.input_params,
152
+ output_grads,
153
+ allow_unused=True,
154
+ )
155
+ del ctx.input_tensors
156
+ del ctx.input_params
157
+ del output_tensors
158
+ return (None, None) + input_grads
159
+
160
+
161
+ def timestep_embedding(timesteps, dim, max_period=10000, repeat_only=False):
162
+ """
163
+ Create sinusoidal timestep embeddings.
164
+ :param timesteps: a 1-D Tensor of N indices, one per batch element.
165
+ These may be fractional.
166
+ :param dim: the dimension of the output.
167
+ :param max_period: controls the minimum frequency of the embeddings.
168
+ :return: an [N x dim] Tensor of positional embeddings.
169
+ """
170
+ if not repeat_only:
171
+ half = dim // 2
172
+ freqs = torch.exp(
173
+ -math.log(max_period) * torch.arange(start=0, end=half, dtype=torch.float32, device=timesteps.device) / half
174
+ )
175
+ args = timesteps[:, None].float() * freqs[None]
176
+ embedding = torch.cat([torch.cos(args), torch.sin(args)], dim=-1)
177
+ if dim % 2:
178
+ embedding = torch.cat([embedding, torch.zeros_like(embedding[:, :1])], dim=-1)
179
+ else:
180
+ embedding = repeat(timesteps, 'b -> b d', d=dim)
181
+ return embedding
182
+
183
+
184
+ def zero_module(module):
185
+ """
186
+ Zero out the parameters of a module and return it.
187
+ """
188
+ for p in module.parameters():
189
+ p.detach().zero_()
190
+ return module
191
+
192
+
193
+ def scale_module(module, scale):
194
+ """
195
+ Scale the parameters of a module and return it.
196
+ """
197
+ for p in module.parameters():
198
+ p.detach().mul_(scale)
199
+ return module
200
+
201
+
202
+ def mean_flat(tensor):
203
+ """
204
+ Take the mean over all non-batch dimensions.
205
+ """
206
+ return tensor.mean(dim=list(range(1, len(tensor.shape))))
207
+
208
+
209
+ def normalization(channels, dtype=None):
210
+ """
211
+ Make a standard normalization layer.
212
+ :param channels: number of input channels.
213
+ :return: an nn.Module for normalization.
214
+ """
215
+ return GroupNorm32(32, channels, dtype=dtype)
216
+
217
+
218
+ # PyTorch 1.7 has SiLU, but we support PyTorch 1.5.
219
+ class SiLU(nn.Module):
220
+ def forward(self, x):
221
+ return x * torch.sigmoid(x)
222
+
223
+
224
+ class GroupNorm32(nn.GroupNorm):
225
+ def forward(self, x):
226
+ return super().forward(x.float()).type(x.dtype)
227
+
228
+
229
+ def conv_nd(dims, *args, **kwargs):
230
+ """
231
+ Create a 1D, 2D, or 3D convolution module.
232
+ """
233
+ if dims == 1:
234
+ return nn.Conv1d(*args, **kwargs)
235
+ elif dims == 2:
236
+ return fcbh.ops.Conv2d(*args, **kwargs)
237
+ elif dims == 3:
238
+ return nn.Conv3d(*args, **kwargs)
239
+ raise ValueError(f"unsupported dimensions: {dims}")
240
+
241
+
242
+ def linear(*args, **kwargs):
243
+ """
244
+ Create a linear module.
245
+ """
246
+ return fcbh.ops.Linear(*args, **kwargs)
247
+
248
+
249
+ def avg_pool_nd(dims, *args, **kwargs):
250
+ """
251
+ Create a 1D, 2D, or 3D average pooling module.
252
+ """
253
+ if dims == 1:
254
+ return nn.AvgPool1d(*args, **kwargs)
255
+ elif dims == 2:
256
+ return nn.AvgPool2d(*args, **kwargs)
257
+ elif dims == 3:
258
+ return nn.AvgPool3d(*args, **kwargs)
259
+ raise ValueError(f"unsupported dimensions: {dims}")
260
+
261
+
262
+ class HybridConditioner(nn.Module):
263
+
264
+ def __init__(self, c_concat_config, c_crossattn_config):
265
+ super().__init__()
266
+ self.concat_conditioner = instantiate_from_config(c_concat_config)
267
+ self.crossattn_conditioner = instantiate_from_config(c_crossattn_config)
268
+
269
+ def forward(self, c_concat, c_crossattn):
270
+ c_concat = self.concat_conditioner(c_concat)
271
+ c_crossattn = self.crossattn_conditioner(c_crossattn)
272
+ return {'c_concat': [c_concat], 'c_crossattn': [c_crossattn]}
273
+
274
+
275
+ def noise_like(shape, device, repeat=False):
276
+ repeat_noise = lambda: torch.randn((1, *shape[1:]), device=device).repeat(shape[0], *((1,) * (len(shape) - 1)))
277
+ noise = lambda: torch.randn(shape, device=device)
278
+ return repeat_noise() if repeat else noise()
backend/headless/fcbh/ldm/modules/distributions/__init__.py ADDED
File without changes
backend/headless/fcbh/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
+ )
backend/headless/fcbh/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)
backend/headless/fcbh/ldm/modules/encoders/__init__.py ADDED
File without changes
backend/headless/fcbh/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) * 1. / self.data_std
19
+ return x
20
+
21
+ def unscale(self, x):
22
+ # back to original data stats
23
+ x = (x * self.data_std) + self.data_mean
24
+ return x
25
+
26
+ def forward(self, x, noise_level=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)
33
+ z = self.unscale(z)
34
+ noise_level = self.time_embed(noise_level)
35
+ return z, noise_level
backend/headless/fcbh/ldm/modules/sub_quadratic_attention.py ADDED
@@ -0,0 +1,251 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 fcbh 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
+ ) -> AttnChunk:
65
+ if upcast_attention:
66
+ with torch.autocast(enabled=False, device_type = 'cuda'):
67
+ query = query.float()
68
+ key_t = key_t.float()
69
+ attn_weights = torch.baddbmm(
70
+ torch.empty(1, 1, 1, device=query.device, dtype=query.dtype),
71
+ query,
72
+ key_t,
73
+ alpha=scale,
74
+ beta=0,
75
+ )
76
+ else:
77
+ attn_weights = torch.baddbmm(
78
+ torch.empty(1, 1, 1, device=query.device, dtype=query.dtype),
79
+ query,
80
+ key_t,
81
+ alpha=scale,
82
+ beta=0,
83
+ )
84
+ max_score, _ = torch.max(attn_weights, -1, keepdim=True)
85
+ max_score = max_score.detach()
86
+ attn_weights -= max_score
87
+ torch.exp(attn_weights, out=attn_weights)
88
+ exp_weights = attn_weights.to(value.dtype)
89
+ exp_values = torch.bmm(exp_weights, value)
90
+ max_score = max_score.squeeze(-1)
91
+ return AttnChunk(exp_values, exp_weights.sum(dim=-1), max_score)
92
+
93
+ def _query_chunk_attention(
94
+ query: Tensor,
95
+ key_t: Tensor,
96
+ value: Tensor,
97
+ summarize_chunk: SummarizeChunk,
98
+ kv_chunk_size: int,
99
+ ) -> Tensor:
100
+ batch_x_heads, k_channels_per_head, k_tokens = key_t.shape
101
+ _, _, v_channels_per_head = value.shape
102
+
103
+ def chunk_scanner(chunk_idx: int) -> AttnChunk:
104
+ key_chunk = dynamic_slice(
105
+ key_t,
106
+ (0, 0, chunk_idx),
107
+ (batch_x_heads, k_channels_per_head, kv_chunk_size)
108
+ )
109
+ value_chunk = dynamic_slice(
110
+ value,
111
+ (0, chunk_idx, 0),
112
+ (batch_x_heads, kv_chunk_size, v_channels_per_head)
113
+ )
114
+ return summarize_chunk(query, key_chunk, value_chunk)
115
+
116
+ chunks: List[AttnChunk] = [
117
+ chunk_scanner(chunk) for chunk in torch.arange(0, k_tokens, kv_chunk_size)
118
+ ]
119
+ acc_chunk = AttnChunk(*map(torch.stack, zip(*chunks)))
120
+ chunk_values, chunk_weights, chunk_max = acc_chunk
121
+
122
+ global_max, _ = torch.max(chunk_max, 0, keepdim=True)
123
+ max_diffs = torch.exp(chunk_max - global_max)
124
+ chunk_values *= torch.unsqueeze(max_diffs, -1)
125
+ chunk_weights *= max_diffs
126
+
127
+ all_values = chunk_values.sum(dim=0)
128
+ all_weights = torch.unsqueeze(chunk_weights, -1).sum(dim=0)
129
+ return all_values / all_weights
130
+
131
+ # TODO: refactor CrossAttention#get_attention_scores to share code with this
132
+ def _get_attention_scores_no_kv_chunking(
133
+ query: Tensor,
134
+ key_t: Tensor,
135
+ value: Tensor,
136
+ scale: float,
137
+ upcast_attention: bool,
138
+ ) -> Tensor:
139
+ if upcast_attention:
140
+ with torch.autocast(enabled=False, device_type = 'cuda'):
141
+ query = query.float()
142
+ key_t = key_t.float()
143
+ attn_scores = torch.baddbmm(
144
+ torch.empty(1, 1, 1, device=query.device, dtype=query.dtype),
145
+ query,
146
+ key_t,
147
+ alpha=scale,
148
+ beta=0,
149
+ )
150
+ else:
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
+
159
+ try:
160
+ attn_probs = attn_scores.softmax(dim=-1)
161
+ del attn_scores
162
+ except model_management.OOM_EXCEPTION:
163
+ print("ran out of memory while running softmax in _get_attention_scores_no_kv_chunking, trying slower in place softmax instead")
164
+ attn_scores -= attn_scores.max(dim=-1, keepdim=True).values
165
+ torch.exp(attn_scores, out=attn_scores)
166
+ summed = torch.sum(attn_scores, dim=-1, keepdim=True)
167
+ attn_scores /= summed
168
+ attn_probs = attn_scores
169
+
170
+ hidden_states_slice = torch.bmm(attn_probs.to(value.dtype), value)
171
+ return hidden_states_slice
172
+
173
+ class ScannedChunk(NamedTuple):
174
+ chunk_idx: int
175
+ attn_chunk: AttnChunk
176
+
177
+ def efficient_dot_product_attention(
178
+ query: Tensor,
179
+ key_t: Tensor,
180
+ value: Tensor,
181
+ query_chunk_size=1024,
182
+ kv_chunk_size: Optional[int] = None,
183
+ kv_chunk_size_min: Optional[int] = None,
184
+ use_checkpoint=True,
185
+ upcast_attention=False,
186
+ ):
187
+ """Computes efficient dot-product attention given query, transposed key, and value.
188
+ This is efficient version of attention presented in
189
+ https://arxiv.org/abs/2112.05682v2 which comes with O(sqrt(n)) memory requirements.
190
+ Args:
191
+ query: queries for calculating attention with shape of
192
+ `[batch * num_heads, tokens, channels_per_head]`.
193
+ key_t: keys for calculating attention with shape of
194
+ `[batch * num_heads, channels_per_head, tokens]`.
195
+ value: values to be used in attention with shape of
196
+ `[batch * num_heads, tokens, channels_per_head]`.
197
+ query_chunk_size: int: query chunks size
198
+ kv_chunk_size: Optional[int]: key/value chunks size. if None: defaults to sqrt(key_tokens)
199
+ 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).
200
+ use_checkpoint: bool: whether to use checkpointing (recommended True for training, False for inference)
201
+ Returns:
202
+ Output of shape `[batch * num_heads, query_tokens, channels_per_head]`.
203
+ """
204
+ batch_x_heads, q_tokens, q_channels_per_head = query.shape
205
+ _, _, k_tokens = key_t.shape
206
+ scale = q_channels_per_head ** -0.5
207
+
208
+ kv_chunk_size = min(kv_chunk_size or int(math.sqrt(k_tokens)), k_tokens)
209
+ if kv_chunk_size_min is not None:
210
+ kv_chunk_size = max(kv_chunk_size, kv_chunk_size_min)
211
+
212
+ def get_query_chunk(chunk_idx: int) -> Tensor:
213
+ return dynamic_slice(
214
+ query,
215
+ (0, chunk_idx, 0),
216
+ (batch_x_heads, min(query_chunk_size, q_tokens), q_channels_per_head)
217
+ )
218
+
219
+ summarize_chunk: SummarizeChunk = partial(_summarize_chunk, scale=scale, upcast_attention=upcast_attention)
220
+ summarize_chunk: SummarizeChunk = partial(checkpoint, summarize_chunk) if use_checkpoint else summarize_chunk
221
+ compute_query_chunk_attn: ComputeQueryChunkAttn = partial(
222
+ _get_attention_scores_no_kv_chunking,
223
+ scale=scale,
224
+ upcast_attention=upcast_attention
225
+ ) if k_tokens <= kv_chunk_size else (
226
+ # fast-path for when there's just 1 key-value chunk per query chunk (this is just sliced attention btw)
227
+ partial(
228
+ _query_chunk_attention,
229
+ kv_chunk_size=kv_chunk_size,
230
+ summarize_chunk=summarize_chunk,
231
+ )
232
+ )
233
+
234
+ if q_tokens <= query_chunk_size:
235
+ # fast-path for when there's just 1 query chunk
236
+ return compute_query_chunk_attn(
237
+ query=query,
238
+ key_t=key_t,
239
+ value=value,
240
+ )
241
+
242
+ # TODO: maybe we should use torch.empty_like(query) to allocate storage in-advance,
243
+ # and pass slices to be mutated, instead of torch.cat()ing the returned slices
244
+ res = torch.cat([
245
+ compute_query_chunk_attn(
246
+ query=get_query_chunk(i * query_chunk_size),
247
+ key_t=key_t,
248
+ value=value,
249
+ ) for i in range(math.ceil(q_tokens / query_chunk_size))
250
+ ], dim=1)
251
+ return res
backend/headless/fcbh/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
backend/headless/fcbh/lora.py ADDED
@@ -0,0 +1,213 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import fcbh.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[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]] = (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_w1, lokr_w2, alpha, lokr_w1_a, lokr_w1_b, lokr_w2_a, lokr_w2_b, lokr_t2)
120
+
121
+
122
+ w_norm_name = "{}.w_norm".format(x)
123
+ b_norm_name = "{}.b_norm".format(x)
124
+ w_norm = lora.get(w_norm_name, None)
125
+ b_norm = lora.get(b_norm_name, None)
126
+
127
+ if w_norm is not None:
128
+ loaded_keys.add(w_norm_name)
129
+ patch_dict[to_load[x]] = (w_norm,)
130
+ if b_norm is not None:
131
+ loaded_keys.add(b_norm_name)
132
+ patch_dict["{}.bias".format(to_load[x][:-len(".weight")])] = (b_norm,)
133
+
134
+ diff_name = "{}.diff".format(x)
135
+ diff_weight = lora.get(diff_name, None)
136
+ if diff_weight is not None:
137
+ patch_dict[to_load[x]] = (diff_weight,)
138
+ loaded_keys.add(diff_name)
139
+
140
+ diff_bias_name = "{}.diff_b".format(x)
141
+ diff_bias = lora.get(diff_bias_name, None)
142
+ if diff_bias is not None:
143
+ patch_dict["{}.bias".format(to_load[x][:-len(".weight")])] = (diff_bias,)
144
+ loaded_keys.add(diff_bias_name)
145
+
146
+ for x in lora.keys():
147
+ if x not in loaded_keys:
148
+ print("lora key not loaded", x)
149
+ return patch_dict
150
+
151
+ def model_lora_keys_clip(model, key_map={}):
152
+ sdk = model.state_dict().keys()
153
+
154
+ text_model_lora_key = "lora_te_text_model_encoder_layers_{}_{}"
155
+ clip_l_present = False
156
+ for b in range(32): #TODO: clean up
157
+ for c in LORA_CLIP_MAP:
158
+ k = "clip_h.transformer.text_model.encoder.layers.{}.{}.weight".format(b, c)
159
+ if k in sdk:
160
+ lora_key = text_model_lora_key.format(b, LORA_CLIP_MAP[c])
161
+ key_map[lora_key] = k
162
+ lora_key = "lora_te1_text_model_encoder_layers_{}_{}".format(b, LORA_CLIP_MAP[c])
163
+ key_map[lora_key] = k
164
+ lora_key = "text_encoder.text_model.encoder.layers.{}.{}".format(b, c) #diffusers lora
165
+ key_map[lora_key] = k
166
+
167
+ k = "clip_l.transformer.text_model.encoder.layers.{}.{}.weight".format(b, c)
168
+ if k in sdk:
169
+ lora_key = text_model_lora_key.format(b, LORA_CLIP_MAP[c])
170
+ key_map[lora_key] = k
171
+ lora_key = "lora_te1_text_model_encoder_layers_{}_{}".format(b, LORA_CLIP_MAP[c]) #SDXL base
172
+ key_map[lora_key] = k
173
+ clip_l_present = True
174
+ lora_key = "text_encoder.text_model.encoder.layers.{}.{}".format(b, c) #diffusers lora
175
+ key_map[lora_key] = k
176
+
177
+ k = "clip_g.transformer.text_model.encoder.layers.{}.{}.weight".format(b, c)
178
+ if k in sdk:
179
+ if clip_l_present:
180
+ lora_key = "lora_te2_text_model_encoder_layers_{}_{}".format(b, LORA_CLIP_MAP[c]) #SDXL base
181
+ key_map[lora_key] = k
182
+ lora_key = "text_encoder_2.text_model.encoder.layers.{}.{}".format(b, c) #diffusers lora
183
+ key_map[lora_key] = k
184
+ else:
185
+ lora_key = "lora_te_text_model_encoder_layers_{}_{}".format(b, LORA_CLIP_MAP[c]) #TODO: test if this is correct for SDXL-Refiner
186
+ key_map[lora_key] = k
187
+ lora_key = "text_encoder.text_model.encoder.layers.{}.{}".format(b, c) #diffusers lora
188
+ key_map[lora_key] = k
189
+
190
+ return key_map
191
+
192
+ def model_lora_keys_unet(model, key_map={}):
193
+ sdk = model.state_dict().keys()
194
+
195
+ for k in sdk:
196
+ if k.startswith("diffusion_model.") and k.endswith(".weight"):
197
+ key_lora = k[len("diffusion_model."):-len(".weight")].replace(".", "_")
198
+ key_map["lora_unet_{}".format(key_lora)] = k
199
+
200
+ diffusers_keys = fcbh.utils.unet_to_diffusers(model.model_config.unet_config)
201
+ for k in diffusers_keys:
202
+ if k.endswith(".weight"):
203
+ unet_key = "diffusion_model.{}".format(diffusers_keys[k])
204
+ key_lora = k[:-len(".weight")].replace(".", "_")
205
+ key_map["lora_unet_{}".format(key_lora)] = unet_key
206
+
207
+ diffusers_lora_prefix = ["", "unet."]
208
+ for p in diffusers_lora_prefix:
209
+ diffusers_lora_key = "{}{}".format(p, k[:-len(".weight")].replace(".to_", ".processor.to_"))
210
+ if diffusers_lora_key.endswith(".to_out.0"):
211
+ diffusers_lora_key = diffusers_lora_key[:-2]
212
+ key_map[diffusers_lora_key] = unet_key
213
+ return key_map
backend/headless/fcbh/model_base.py ADDED
@@ -0,0 +1,264 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from fcbh.ldm.modules.diffusionmodules.openaimodel import UNetModel
3
+ from fcbh.ldm.modules.encoders.noise_aug_modules import CLIPEmbeddingNoiseAugmentation
4
+ from fcbh.ldm.modules.diffusionmodules.openaimodel import Timestep
5
+ import fcbh.model_management
6
+ import fcbh.conds
7
+ from enum import Enum
8
+ from . import utils
9
+
10
+ class ModelType(Enum):
11
+ EPS = 1
12
+ V_PREDICTION = 2
13
+
14
+
15
+ from fcbh.model_sampling import EPS, V_PREDICTION, ModelSamplingDiscrete
16
+
17
+ def model_sampling(model_config, model_type):
18
+ if model_type == ModelType.EPS:
19
+ c = EPS
20
+ elif model_type == ModelType.V_PREDICTION:
21
+ c = V_PREDICTION
22
+
23
+ s = ModelSamplingDiscrete
24
+
25
+ class ModelSampling(s, c):
26
+ pass
27
+
28
+ return ModelSampling(model_config)
29
+
30
+
31
+ class BaseModel(torch.nn.Module):
32
+ def __init__(self, model_config, model_type=ModelType.EPS, device=None):
33
+ super().__init__()
34
+
35
+ unet_config = model_config.unet_config
36
+ self.latent_format = model_config.latent_format
37
+ self.model_config = model_config
38
+
39
+ if not unet_config.get("disable_unet_model_creation", False):
40
+ self.diffusion_model = UNetModel(**unet_config, device=device)
41
+ self.model_type = model_type
42
+ self.model_sampling = model_sampling(model_config, model_type)
43
+
44
+ self.adm_channels = unet_config.get("adm_in_channels", None)
45
+ if self.adm_channels is None:
46
+ self.adm_channels = 0
47
+ self.inpaint_model = False
48
+ print("model_type", model_type.name)
49
+ print("adm", self.adm_channels)
50
+
51
+ def apply_model(self, x, t, c_concat=None, c_crossattn=None, control=None, transformer_options={}, **kwargs):
52
+ sigma = t
53
+ xc = self.model_sampling.calculate_input(sigma, x)
54
+ if c_concat is not None:
55
+ xc = torch.cat([xc] + [c_concat], dim=1)
56
+
57
+ context = c_crossattn
58
+ dtype = self.get_dtype()
59
+ xc = xc.to(dtype)
60
+ t = self.model_sampling.timestep(t).float()
61
+ context = context.to(dtype)
62
+ extra_conds = {}
63
+ for o in kwargs:
64
+ extra = kwargs[o]
65
+ if hasattr(extra, "to"):
66
+ extra = extra.to(dtype)
67
+ extra_conds[o] = extra
68
+ model_output = self.diffusion_model(xc, t, context=context, control=control, transformer_options=transformer_options, **extra_conds).float()
69
+ return self.model_sampling.calculate_denoised(sigma, model_output, x)
70
+
71
+ def get_dtype(self):
72
+ return self.diffusion_model.dtype
73
+
74
+ def is_adm(self):
75
+ return self.adm_channels > 0
76
+
77
+ def encode_adm(self, **kwargs):
78
+ return None
79
+
80
+ def extra_conds(self, **kwargs):
81
+ out = {}
82
+ if self.inpaint_model:
83
+ concat_keys = ("mask", "masked_image")
84
+ cond_concat = []
85
+ denoise_mask = kwargs.get("denoise_mask", None)
86
+ latent_image = kwargs.get("latent_image", None)
87
+ noise = kwargs.get("noise", None)
88
+ device = kwargs["device"]
89
+
90
+ def blank_inpaint_image_like(latent_image):
91
+ blank_image = torch.ones_like(latent_image)
92
+ # these are the values for "zero" in pixel space translated to latent space
93
+ blank_image[:,0] *= 0.8223
94
+ blank_image[:,1] *= -0.6876
95
+ blank_image[:,2] *= 0.6364
96
+ blank_image[:,3] *= 0.1380
97
+ return blank_image
98
+
99
+ for ck in concat_keys:
100
+ if denoise_mask is not None:
101
+ if ck == "mask":
102
+ cond_concat.append(denoise_mask[:,:1].to(device))
103
+ elif ck == "masked_image":
104
+ cond_concat.append(latent_image.to(device)) #NOTE: the latent_image should be masked by the mask in pixel space
105
+ else:
106
+ if ck == "mask":
107
+ cond_concat.append(torch.ones_like(noise)[:,:1])
108
+ elif ck == "masked_image":
109
+ cond_concat.append(blank_inpaint_image_like(noise))
110
+ data = torch.cat(cond_concat, dim=1)
111
+ out['c_concat'] = fcbh.conds.CONDNoiseShape(data)
112
+ adm = self.encode_adm(**kwargs)
113
+ if adm is not None:
114
+ out['y'] = fcbh.conds.CONDRegular(adm)
115
+ return out
116
+
117
+ def load_model_weights(self, sd, unet_prefix=""):
118
+ to_load = {}
119
+ keys = list(sd.keys())
120
+ for k in keys:
121
+ if k.startswith(unet_prefix):
122
+ to_load[k[len(unet_prefix):]] = sd.pop(k)
123
+
124
+ to_load = self.model_config.process_unet_state_dict(to_load)
125
+ m, u = self.diffusion_model.load_state_dict(to_load, strict=False)
126
+ if len(m) > 0:
127
+ print("unet missing:", m)
128
+
129
+ if len(u) > 0:
130
+ print("unet unexpected:", u)
131
+ del to_load
132
+ return self
133
+
134
+ def process_latent_in(self, latent):
135
+ return self.latent_format.process_in(latent)
136
+
137
+ def process_latent_out(self, latent):
138
+ return self.latent_format.process_out(latent)
139
+
140
+ def state_dict_for_saving(self, clip_state_dict, vae_state_dict):
141
+ clip_state_dict = self.model_config.process_clip_state_dict_for_saving(clip_state_dict)
142
+ unet_sd = self.diffusion_model.state_dict()
143
+ unet_state_dict = {}
144
+ for k in unet_sd:
145
+ unet_state_dict[k] = fcbh.model_management.resolve_lowvram_weight(unet_sd[k], self.diffusion_model, k)
146
+
147
+ unet_state_dict = self.model_config.process_unet_state_dict_for_saving(unet_state_dict)
148
+ vae_state_dict = self.model_config.process_vae_state_dict_for_saving(vae_state_dict)
149
+ if self.get_dtype() == torch.float16:
150
+ clip_state_dict = utils.convert_sd_to(clip_state_dict, torch.float16)
151
+ vae_state_dict = utils.convert_sd_to(vae_state_dict, torch.float16)
152
+
153
+ if self.model_type == ModelType.V_PREDICTION:
154
+ unet_state_dict["v_pred"] = torch.tensor([])
155
+
156
+ return {**unet_state_dict, **vae_state_dict, **clip_state_dict}
157
+
158
+ def set_inpaint(self):
159
+ self.inpaint_model = True
160
+
161
+ def memory_required(self, input_shape):
162
+ area = input_shape[0] * input_shape[2] * input_shape[3]
163
+ if fcbh.model_management.xformers_enabled() or fcbh.model_management.pytorch_attention_flash_attention():
164
+ #TODO: this needs to be tweaked
165
+ return (area / (fcbh.model_management.dtype_size(self.get_dtype()) * 10)) * (1024 * 1024)
166
+ else:
167
+ #TODO: this formula might be too aggressive since I tweaked the sub-quad and split algorithms to use less memory.
168
+ return (((area * 0.6) / 0.9) + 1024) * (1024 * 1024)
169
+
170
+
171
+ def unclip_adm(unclip_conditioning, device, noise_augmentor, noise_augment_merge=0.0):
172
+ adm_inputs = []
173
+ weights = []
174
+ noise_aug = []
175
+ for unclip_cond in unclip_conditioning:
176
+ for adm_cond in unclip_cond["clip_vision_output"].image_embeds:
177
+ weight = unclip_cond["strength"]
178
+ noise_augment = unclip_cond["noise_augmentation"]
179
+ noise_level = round((noise_augmentor.max_noise_level - 1) * noise_augment)
180
+ c_adm, noise_level_emb = noise_augmentor(adm_cond.to(device), noise_level=torch.tensor([noise_level], device=device))
181
+ adm_out = torch.cat((c_adm, noise_level_emb), 1) * weight
182
+ weights.append(weight)
183
+ noise_aug.append(noise_augment)
184
+ adm_inputs.append(adm_out)
185
+
186
+ if len(noise_aug) > 1:
187
+ adm_out = torch.stack(adm_inputs).sum(0)
188
+ noise_augment = noise_augment_merge
189
+ noise_level = round((noise_augmentor.max_noise_level - 1) * noise_augment)
190
+ c_adm, noise_level_emb = noise_augmentor(adm_out[:, :noise_augmentor.time_embed.dim], noise_level=torch.tensor([noise_level], device=device))
191
+ adm_out = torch.cat((c_adm, noise_level_emb), 1)
192
+
193
+ return adm_out
194
+
195
+ class SD21UNCLIP(BaseModel):
196
+ def __init__(self, model_config, noise_aug_config, model_type=ModelType.V_PREDICTION, device=None):
197
+ super().__init__(model_config, model_type, device=device)
198
+ self.noise_augmentor = CLIPEmbeddingNoiseAugmentation(**noise_aug_config)
199
+
200
+ def encode_adm(self, **kwargs):
201
+ unclip_conditioning = kwargs.get("unclip_conditioning", None)
202
+ device = kwargs["device"]
203
+ if unclip_conditioning is None:
204
+ return torch.zeros((1, self.adm_channels))
205
+ else:
206
+ return unclip_adm(unclip_conditioning, device, self.noise_augmentor, kwargs.get("unclip_noise_augment_merge", 0.05))
207
+
208
+ def sdxl_pooled(args, noise_augmentor):
209
+ if "unclip_conditioning" in args:
210
+ return unclip_adm(args.get("unclip_conditioning", None), args["device"], noise_augmentor)[:,:1280]
211
+ else:
212
+ return args["pooled_output"]
213
+
214
+ class SDXLRefiner(BaseModel):
215
+ def __init__(self, model_config, model_type=ModelType.EPS, device=None):
216
+ super().__init__(model_config, model_type, device=device)
217
+ self.embedder = Timestep(256)
218
+ self.noise_augmentor = CLIPEmbeddingNoiseAugmentation(**{"noise_schedule_config": {"timesteps": 1000, "beta_schedule": "squaredcos_cap_v2"}, "timestep_dim": 1280})
219
+
220
+ def encode_adm(self, **kwargs):
221
+ clip_pooled = sdxl_pooled(kwargs, self.noise_augmentor)
222
+ width = kwargs.get("width", 768)
223
+ height = kwargs.get("height", 768)
224
+ crop_w = kwargs.get("crop_w", 0)
225
+ crop_h = kwargs.get("crop_h", 0)
226
+
227
+ if kwargs.get("prompt_type", "") == "negative":
228
+ aesthetic_score = kwargs.get("aesthetic_score", 2.5)
229
+ else:
230
+ aesthetic_score = kwargs.get("aesthetic_score", 6)
231
+
232
+ out = []
233
+ out.append(self.embedder(torch.Tensor([height])))
234
+ out.append(self.embedder(torch.Tensor([width])))
235
+ out.append(self.embedder(torch.Tensor([crop_h])))
236
+ out.append(self.embedder(torch.Tensor([crop_w])))
237
+ out.append(self.embedder(torch.Tensor([aesthetic_score])))
238
+ flat = torch.flatten(torch.cat(out)).unsqueeze(dim=0).repeat(clip_pooled.shape[0], 1)
239
+ return torch.cat((clip_pooled.to(flat.device), flat), dim=1)
240
+
241
+ class SDXL(BaseModel):
242
+ def __init__(self, model_config, model_type=ModelType.EPS, device=None):
243
+ super().__init__(model_config, model_type, device=device)
244
+ self.embedder = Timestep(256)
245
+ self.noise_augmentor = CLIPEmbeddingNoiseAugmentation(**{"noise_schedule_config": {"timesteps": 1000, "beta_schedule": "squaredcos_cap_v2"}, "timestep_dim": 1280})
246
+
247
+ def encode_adm(self, **kwargs):
248
+ clip_pooled = sdxl_pooled(kwargs, self.noise_augmentor)
249
+ width = kwargs.get("width", 768)
250
+ height = kwargs.get("height", 768)
251
+ crop_w = kwargs.get("crop_w", 0)
252
+ crop_h = kwargs.get("crop_h", 0)
253
+ target_width = kwargs.get("target_width", width)
254
+ target_height = kwargs.get("target_height", height)
255
+
256
+ out = []
257
+ out.append(self.embedder(torch.Tensor([height])))
258
+ out.append(self.embedder(torch.Tensor([width])))
259
+ out.append(self.embedder(torch.Tensor([crop_h])))
260
+ out.append(self.embedder(torch.Tensor([crop_w])))
261
+ out.append(self.embedder(torch.Tensor([target_height])))
262
+ out.append(self.embedder(torch.Tensor([target_width])))
263
+ flat = torch.flatten(torch.cat(out)).unsqueeze(dim=0).repeat(clip_pooled.shape[0], 1)
264
+ return torch.cat((clip_pooled.to(flat.device), flat), dim=1)
backend/headless/fcbh/model_detection.py ADDED
@@ -0,0 +1,282 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import fcbh.supported_models
2
+ import fcbh.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
+ return last_transformer_depth, context_dim, use_linear_in_transformer
28
+ return None
29
+
30
+ def detect_unet_config(state_dict, key_prefix, dtype):
31
+ state_dict_keys = list(state_dict.keys())
32
+
33
+ unet_config = {
34
+ "use_checkpoint": False,
35
+ "image_size": 32,
36
+ "out_channels": 4,
37
+ "use_spatial_transformer": True,
38
+ "legacy": False
39
+ }
40
+
41
+ y_input = '{}label_emb.0.0.weight'.format(key_prefix)
42
+ if y_input in state_dict_keys:
43
+ unet_config["num_classes"] = "sequential"
44
+ unet_config["adm_in_channels"] = state_dict[y_input].shape[1]
45
+ else:
46
+ unet_config["adm_in_channels"] = None
47
+
48
+ unet_config["dtype"] = dtype
49
+ model_channels = state_dict['{}input_blocks.0.0.weight'.format(key_prefix)].shape[0]
50
+ in_channels = state_dict['{}input_blocks.0.0.weight'.format(key_prefix)].shape[1]
51
+
52
+ num_res_blocks = []
53
+ channel_mult = []
54
+ attention_resolutions = []
55
+ transformer_depth = []
56
+ transformer_depth_output = []
57
+ context_dim = None
58
+ use_linear_in_transformer = False
59
+
60
+
61
+ current_res = 1
62
+ count = 0
63
+
64
+ last_res_blocks = 0
65
+ last_channel_mult = 0
66
+
67
+ input_block_count = count_blocks(state_dict_keys, '{}input_blocks'.format(key_prefix) + '.{}.')
68
+ for count in range(input_block_count):
69
+ prefix = '{}input_blocks.{}.'.format(key_prefix, count)
70
+ prefix_output = '{}output_blocks.{}.'.format(key_prefix, input_block_count - count - 1)
71
+
72
+ block_keys = sorted(list(filter(lambda a: a.startswith(prefix), state_dict_keys)))
73
+ if len(block_keys) == 0:
74
+ break
75
+
76
+ block_keys_output = sorted(list(filter(lambda a: a.startswith(prefix_output), state_dict_keys)))
77
+
78
+ if "{}0.op.weight".format(prefix) in block_keys: #new layer
79
+ num_res_blocks.append(last_res_blocks)
80
+ channel_mult.append(last_channel_mult)
81
+
82
+ current_res *= 2
83
+ last_res_blocks = 0
84
+ last_channel_mult = 0
85
+ out = calculate_transformer_depth(prefix_output, state_dict_keys, state_dict)
86
+ if out is not None:
87
+ transformer_depth_output.append(out[0])
88
+ else:
89
+ transformer_depth_output.append(0)
90
+ else:
91
+ res_block_prefix = "{}0.in_layers.0.weight".format(prefix)
92
+ if res_block_prefix in block_keys:
93
+ last_res_blocks += 1
94
+ last_channel_mult = state_dict["{}0.out_layers.3.weight".format(prefix)].shape[0] // model_channels
95
+
96
+ out = calculate_transformer_depth(prefix, state_dict_keys, state_dict)
97
+ if out is not None:
98
+ transformer_depth.append(out[0])
99
+ if context_dim is None:
100
+ context_dim = out[1]
101
+ use_linear_in_transformer = out[2]
102
+ else:
103
+ transformer_depth.append(0)
104
+
105
+ res_block_prefix = "{}0.in_layers.0.weight".format(prefix_output)
106
+ if res_block_prefix in block_keys_output:
107
+ out = calculate_transformer_depth(prefix_output, state_dict_keys, state_dict)
108
+ if out is not None:
109
+ transformer_depth_output.append(out[0])
110
+ else:
111
+ transformer_depth_output.append(0)
112
+
113
+
114
+ num_res_blocks.append(last_res_blocks)
115
+ channel_mult.append(last_channel_mult)
116
+ if "{}middle_block.1.proj_in.weight".format(key_prefix) in state_dict_keys:
117
+ transformer_depth_middle = count_blocks(state_dict_keys, '{}middle_block.1.transformer_blocks.'.format(key_prefix) + '{}')
118
+ else:
119
+ transformer_depth_middle = -1
120
+
121
+ unet_config["in_channels"] = in_channels
122
+ unet_config["model_channels"] = model_channels
123
+ unet_config["num_res_blocks"] = num_res_blocks
124
+ unet_config["transformer_depth"] = transformer_depth
125
+ unet_config["transformer_depth_output"] = transformer_depth_output
126
+ unet_config["channel_mult"] = channel_mult
127
+ unet_config["transformer_depth_middle"] = transformer_depth_middle
128
+ unet_config['use_linear_in_transformer'] = use_linear_in_transformer
129
+ unet_config["context_dim"] = context_dim
130
+ return unet_config
131
+
132
+ def model_config_from_unet_config(unet_config):
133
+ for model_config in fcbh.supported_models.models:
134
+ if model_config.matches(unet_config):
135
+ return model_config(unet_config)
136
+
137
+ print("no match", unet_config)
138
+ return None
139
+
140
+ def model_config_from_unet(state_dict, unet_key_prefix, dtype, use_base_if_no_match=False):
141
+ unet_config = detect_unet_config(state_dict, unet_key_prefix, dtype)
142
+ model_config = model_config_from_unet_config(unet_config)
143
+ if model_config is None and use_base_if_no_match:
144
+ return fcbh.supported_models_base.BASE(unet_config)
145
+ else:
146
+ return model_config
147
+
148
+ def convert_config(unet_config):
149
+ new_config = unet_config.copy()
150
+ num_res_blocks = new_config.get("num_res_blocks", None)
151
+ channel_mult = new_config.get("channel_mult", None)
152
+
153
+ if isinstance(num_res_blocks, int):
154
+ num_res_blocks = len(channel_mult) * [num_res_blocks]
155
+
156
+ if "attention_resolutions" in new_config:
157
+ attention_resolutions = new_config.pop("attention_resolutions")
158
+ transformer_depth = new_config.get("transformer_depth", None)
159
+ transformer_depth_middle = new_config.get("transformer_depth_middle", None)
160
+
161
+ if isinstance(transformer_depth, int):
162
+ transformer_depth = len(channel_mult) * [transformer_depth]
163
+ if transformer_depth_middle is None:
164
+ transformer_depth_middle = transformer_depth[-1]
165
+ t_in = []
166
+ t_out = []
167
+ s = 1
168
+ for i in range(len(num_res_blocks)):
169
+ res = num_res_blocks[i]
170
+ d = 0
171
+ if s in attention_resolutions:
172
+ d = transformer_depth[i]
173
+
174
+ t_in += [d] * res
175
+ t_out += [d] * (res + 1)
176
+ s *= 2
177
+ transformer_depth = t_in
178
+ transformer_depth_output = t_out
179
+ new_config["transformer_depth"] = t_in
180
+ new_config["transformer_depth_output"] = t_out
181
+ new_config["transformer_depth_middle"] = transformer_depth_middle
182
+
183
+ new_config["num_res_blocks"] = num_res_blocks
184
+ return new_config
185
+
186
+
187
+ def unet_config_from_diffusers_unet(state_dict, dtype):
188
+ match = {}
189
+ transformer_depth = []
190
+
191
+ attn_res = 1
192
+ down_blocks = count_blocks(state_dict, "down_blocks.{}")
193
+ for i in range(down_blocks):
194
+ attn_blocks = count_blocks(state_dict, "down_blocks.{}.attentions.".format(i) + '{}')
195
+ for ab in range(attn_blocks):
196
+ transformer_count = count_blocks(state_dict, "down_blocks.{}.attentions.{}.transformer_blocks.".format(i, ab) + '{}')
197
+ transformer_depth.append(transformer_count)
198
+ if transformer_count > 0:
199
+ match["context_dim"] = state_dict["down_blocks.{}.attentions.{}.transformer_blocks.0.attn2.to_k.weight".format(i, ab)].shape[1]
200
+
201
+ attn_res *= 2
202
+ if attn_blocks == 0:
203
+ transformer_depth.append(0)
204
+ transformer_depth.append(0)
205
+
206
+ match["transformer_depth"] = transformer_depth
207
+
208
+ match["model_channels"] = state_dict["conv_in.weight"].shape[0]
209
+ match["in_channels"] = state_dict["conv_in.weight"].shape[1]
210
+ match["adm_in_channels"] = None
211
+ if "class_embedding.linear_1.weight" in state_dict:
212
+ match["adm_in_channels"] = state_dict["class_embedding.linear_1.weight"].shape[1]
213
+ elif "add_embedding.linear_1.weight" in state_dict:
214
+ match["adm_in_channels"] = state_dict["add_embedding.linear_1.weight"].shape[1]
215
+
216
+ SDXL = {'use_checkpoint': False, 'image_size': 32, 'out_channels': 4, 'use_spatial_transformer': True, 'legacy': False,
217
+ 'num_classes': 'sequential', 'adm_in_channels': 2816, 'dtype': dtype, 'in_channels': 4, 'model_channels': 320,
218
+ 'num_res_blocks': [2, 2, 2], 'transformer_depth': [0, 0, 2, 2, 10, 10], 'channel_mult': [1, 2, 4], 'transformer_depth_middle': 10,
219
+ 'use_linear_in_transformer': True, 'context_dim': 2048, 'num_head_channels': 64, 'transformer_depth_output': [0, 0, 0, 2, 2, 2, 10, 10, 10]}
220
+
221
+ SDXL_refiner = {'use_checkpoint': False, 'image_size': 32, 'out_channels': 4, 'use_spatial_transformer': True, 'legacy': False,
222
+ 'num_classes': 'sequential', 'adm_in_channels': 2560, 'dtype': dtype, 'in_channels': 4, 'model_channels': 384,
223
+ '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,
224
+ '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]}
225
+
226
+ SD21 = {'use_checkpoint': False, 'image_size': 32, 'out_channels': 4, 'use_spatial_transformer': True, 'legacy': False,
227
+ 'adm_in_channels': None, 'dtype': dtype, 'in_channels': 4, 'model_channels': 320, 'num_res_blocks': [2, 2, 2, 2],
228
+ '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,
229
+ 'context_dim': 1024, 'num_head_channels': 64, 'transformer_depth_output': [1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0]}
230
+
231
+ SD21_uncliph = {'use_checkpoint': False, 'image_size': 32, 'out_channels': 4, 'use_spatial_transformer': True, 'legacy': False,
232
+ 'num_classes': 'sequential', 'adm_in_channels': 2048, 'dtype': dtype, 'in_channels': 4, 'model_channels': 320,
233
+ '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,
234
+ '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]}
235
+
236
+ SD21_unclipl = {'use_checkpoint': False, 'image_size': 32, 'out_channels': 4, 'use_spatial_transformer': True, 'legacy': False,
237
+ 'num_classes': 'sequential', 'adm_in_channels': 1536, 'dtype': dtype, 'in_channels': 4, 'model_channels': 320,
238
+ '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,
239
+ '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]}
240
+
241
+ SD15 = {'use_checkpoint': False, 'image_size': 32, 'out_channels': 4, 'use_spatial_transformer': True, 'legacy': False, 'adm_in_channels': None,
242
+ '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],
243
+ 'channel_mult': [1, 2, 4, 4], 'transformer_depth_middle': 1, 'use_linear_in_transformer': False, 'context_dim': 768, 'num_heads': 8,
244
+ 'transformer_depth_output': [1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0]}
245
+
246
+ SDXL_mid_cnet = {'use_checkpoint': False, 'image_size': 32, 'out_channels': 4, 'use_spatial_transformer': True, 'legacy': False,
247
+ 'num_classes': 'sequential', 'adm_in_channels': 2816, 'dtype': dtype, 'in_channels': 4, 'model_channels': 320,
248
+ 'num_res_blocks': [2, 2, 2], 'transformer_depth': [0, 0, 0, 0, 1, 1], 'channel_mult': [1, 2, 4], 'transformer_depth_middle': 1,
249
+ 'use_linear_in_transformer': True, 'context_dim': 2048, 'num_head_channels': 64, 'transformer_depth_output': [0, 0, 0, 0, 0, 0, 1, 1, 1]}
250
+
251
+ SDXL_small_cnet = {'use_checkpoint': False, 'image_size': 32, 'out_channels': 4, 'use_spatial_transformer': True, 'legacy': False,
252
+ 'num_classes': 'sequential', 'adm_in_channels': 2816, 'dtype': dtype, 'in_channels': 4, 'model_channels': 320,
253
+ 'num_res_blocks': [2, 2, 2], 'transformer_depth': [0, 0, 0, 0, 0, 0], 'channel_mult': [1, 2, 4], 'transformer_depth_middle': 0,
254
+ 'use_linear_in_transformer': True, 'num_head_channels': 64, 'context_dim': 1, 'transformer_depth_output': [0, 0, 0, 0, 0, 0, 0, 0, 0]}
255
+
256
+ SDXL_diffusers_inpaint = {'use_checkpoint': False, 'image_size': 32, 'out_channels': 4, 'use_spatial_transformer': True, 'legacy': False,
257
+ 'num_classes': 'sequential', 'adm_in_channels': 2816, 'dtype': dtype, 'in_channels': 9, 'model_channels': 320,
258
+ 'num_res_blocks': [2, 2, 2], 'transformer_depth': [0, 0, 2, 2, 10, 10], 'channel_mult': [1, 2, 4], 'transformer_depth_middle': 10,
259
+ 'use_linear_in_transformer': True, 'context_dim': 2048, 'num_head_channels': 64, 'transformer_depth_output': [0, 0, 0, 2, 2, 2, 10, 10, 10]}
260
+
261
+ SSD_1B = {'use_checkpoint': False, 'image_size': 32, 'out_channels': 4, 'use_spatial_transformer': True, 'legacy': False,
262
+ 'num_classes': 'sequential', 'adm_in_channels': 2816, 'dtype': dtype, 'in_channels': 4, 'model_channels': 320,
263
+ '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],
264
+ 'channel_mult': [1, 2, 4], 'transformer_depth_middle': -1, 'use_linear_in_transformer': True, 'context_dim': 2048, 'num_head_channels': 64}
265
+
266
+ supported_models = [SDXL, SDXL_refiner, SD21, SD15, SD21_uncliph, SD21_unclipl, SDXL_mid_cnet, SDXL_small_cnet, SDXL_diffusers_inpaint, SSD_1B]
267
+
268
+ for unet_config in supported_models:
269
+ matches = True
270
+ for k in match:
271
+ if match[k] != unet_config[k]:
272
+ matches = False
273
+ break
274
+ if matches:
275
+ return convert_config(unet_config)
276
+ return None
277
+
278
+ def model_config_from_diffusers_unet(state_dict, dtype):
279
+ unet_config = unet_config_from_diffusers_unet(state_dict, dtype)
280
+ if unet_config is not None:
281
+ return model_config_from_unet_config(unet_config)
282
+ return None
backend/headless/fcbh/model_management.py ADDED
@@ -0,0 +1,724 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import psutil
2
+ from enum import Enum
3
+ from fcbh.cli_args import args
4
+ import fcbh.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
+ directml_enabled = False
32
+ if args.directml is not None:
33
+ import torch_directml
34
+ directml_enabled = True
35
+ device_index = args.directml
36
+ if device_index < 0:
37
+ directml_device = torch_directml.device()
38
+ else:
39
+ directml_device = torch_directml.device(device_index)
40
+ print("Using directml with device:", torch_directml.device_name(device_index))
41
+ # torch_directml.disable_tiled_resources(True)
42
+ lowvram_available = False #TODO: need to find a way to get free memory in directml before this can be enabled by default.
43
+
44
+ try:
45
+ import intel_extension_for_pytorch as ipex
46
+ if torch.xpu.is_available():
47
+ xpu_available = True
48
+ except:
49
+ pass
50
+
51
+ try:
52
+ if torch.backends.mps.is_available():
53
+ cpu_state = CPUState.MPS
54
+ import torch.mps
55
+ except:
56
+ pass
57
+
58
+ if args.cpu:
59
+ cpu_state = CPUState.CPU
60
+
61
+ def is_intel_xpu():
62
+ global cpu_state
63
+ global xpu_available
64
+ if cpu_state == CPUState.GPU:
65
+ if xpu_available:
66
+ return True
67
+ return False
68
+
69
+ def get_torch_device():
70
+ global directml_enabled
71
+ global cpu_state
72
+ if directml_enabled:
73
+ global directml_device
74
+ return directml_device
75
+ if cpu_state == CPUState.MPS:
76
+ return torch.device("mps")
77
+ if cpu_state == CPUState.CPU:
78
+ return torch.device("cpu")
79
+ else:
80
+ if is_intel_xpu():
81
+ return torch.device("xpu")
82
+ else:
83
+ return torch.device(torch.cuda.current_device())
84
+
85
+ def get_total_memory(dev=None, torch_total_too=False):
86
+ global directml_enabled
87
+ if dev is None:
88
+ dev = get_torch_device()
89
+
90
+ if hasattr(dev, 'type') and (dev.type == 'cpu' or dev.type == 'mps'):
91
+ mem_total = psutil.virtual_memory().total
92
+ mem_total_torch = mem_total
93
+ else:
94
+ if directml_enabled:
95
+ mem_total = 1024 * 1024 * 1024 #TODO
96
+ mem_total_torch = mem_total
97
+ elif is_intel_xpu():
98
+ stats = torch.xpu.memory_stats(dev)
99
+ mem_reserved = stats['reserved_bytes.all.current']
100
+ mem_total = torch.xpu.get_device_properties(dev).total_memory
101
+ mem_total_torch = mem_reserved
102
+ else:
103
+ stats = torch.cuda.memory_stats(dev)
104
+ mem_reserved = stats['reserved_bytes.all.current']
105
+ _, mem_total_cuda = torch.cuda.mem_get_info(dev)
106
+ mem_total_torch = mem_reserved
107
+ mem_total = mem_total_cuda
108
+
109
+ if torch_total_too:
110
+ return (mem_total, mem_total_torch)
111
+ else:
112
+ return mem_total
113
+
114
+ total_vram = get_total_memory(get_torch_device()) / (1024 * 1024)
115
+ total_ram = psutil.virtual_memory().total / (1024 * 1024)
116
+ print("Total VRAM {:0.0f} MB, total RAM {:0.0f} MB".format(total_vram, total_ram))
117
+ if not args.normalvram and not args.cpu:
118
+ if lowvram_available and total_vram <= 4096:
119
+ print("Trying to enable lowvram mode because your GPU seems to have 4GB or less. If you don't want this use: --normalvram")
120
+ set_vram_to = VRAMState.LOW_VRAM
121
+
122
+ try:
123
+ OOM_EXCEPTION = torch.cuda.OutOfMemoryError
124
+ except:
125
+ OOM_EXCEPTION = Exception
126
+
127
+ XFORMERS_VERSION = ""
128
+ XFORMERS_ENABLED_VAE = True
129
+ if args.disable_xformers:
130
+ XFORMERS_IS_AVAILABLE = False
131
+ else:
132
+ try:
133
+ import xformers
134
+ import xformers.ops
135
+ XFORMERS_IS_AVAILABLE = True
136
+ try:
137
+ XFORMERS_IS_AVAILABLE = xformers._has_cpp_library
138
+ except:
139
+ pass
140
+ try:
141
+ XFORMERS_VERSION = xformers.version.__version__
142
+ print("xformers version:", XFORMERS_VERSION)
143
+ if XFORMERS_VERSION.startswith("0.0.18"):
144
+ print()
145
+ print("WARNING: This version of xformers has a major bug where you will get black images when generating high resolution images.")
146
+ print("Please downgrade or upgrade xformers to a different version.")
147
+ print()
148
+ XFORMERS_ENABLED_VAE = False
149
+ except:
150
+ pass
151
+ except:
152
+ XFORMERS_IS_AVAILABLE = False
153
+
154
+ def is_nvidia():
155
+ global cpu_state
156
+ if cpu_state == CPUState.GPU:
157
+ if torch.version.cuda:
158
+ return True
159
+ return False
160
+
161
+ ENABLE_PYTORCH_ATTENTION = False
162
+ if args.use_pytorch_cross_attention:
163
+ ENABLE_PYTORCH_ATTENTION = True
164
+ XFORMERS_IS_AVAILABLE = False
165
+
166
+ VAE_DTYPE = torch.float32
167
+
168
+ try:
169
+ if is_nvidia():
170
+ torch_version = torch.version.__version__
171
+ if int(torch_version[0]) >= 2:
172
+ if ENABLE_PYTORCH_ATTENTION == False and args.use_split_cross_attention == False and args.use_quad_cross_attention == False:
173
+ ENABLE_PYTORCH_ATTENTION = True
174
+ if torch.cuda.is_bf16_supported():
175
+ VAE_DTYPE = torch.bfloat16
176
+ if is_intel_xpu():
177
+ if args.use_split_cross_attention == False and args.use_quad_cross_attention == False:
178
+ ENABLE_PYTORCH_ATTENTION = True
179
+ except:
180
+ pass
181
+
182
+ if is_intel_xpu():
183
+ VAE_DTYPE = torch.bfloat16
184
+
185
+ if args.fp16_vae:
186
+ VAE_DTYPE = torch.float16
187
+ elif args.bf16_vae:
188
+ VAE_DTYPE = torch.bfloat16
189
+ elif args.fp32_vae:
190
+ VAE_DTYPE = torch.float32
191
+
192
+
193
+ if ENABLE_PYTORCH_ATTENTION:
194
+ torch.backends.cuda.enable_math_sdp(True)
195
+ torch.backends.cuda.enable_flash_sdp(True)
196
+ torch.backends.cuda.enable_mem_efficient_sdp(True)
197
+
198
+ if args.lowvram:
199
+ set_vram_to = VRAMState.LOW_VRAM
200
+ lowvram_available = True
201
+ elif args.novram:
202
+ set_vram_to = VRAMState.NO_VRAM
203
+ elif args.highvram or args.gpu_only:
204
+ vram_state = VRAMState.HIGH_VRAM
205
+
206
+ FORCE_FP32 = False
207
+ FORCE_FP16 = False
208
+ if args.force_fp32:
209
+ print("Forcing FP32, if this improves things please report it.")
210
+ FORCE_FP32 = True
211
+
212
+ if args.force_fp16:
213
+ print("Forcing FP16.")
214
+ FORCE_FP16 = True
215
+
216
+ if lowvram_available:
217
+ try:
218
+ import accelerate
219
+ if set_vram_to in (VRAMState.LOW_VRAM, VRAMState.NO_VRAM):
220
+ vram_state = set_vram_to
221
+ except Exception as e:
222
+ import traceback
223
+ print(traceback.format_exc())
224
+ print("ERROR: LOW VRAM MODE NEEDS accelerate.")
225
+ lowvram_available = False
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
+ class LoadedModel:
266
+ def __init__(self, model):
267
+ self.model = model
268
+ self.model_accelerated = False
269
+ self.device = model.load_device
270
+
271
+ def model_memory(self):
272
+ return self.model.model_size()
273
+
274
+ def model_memory_required(self, device):
275
+ if device == self.model.current_device:
276
+ return 0
277
+ else:
278
+ return self.model_memory()
279
+
280
+ def model_load(self, lowvram_model_memory=0):
281
+ patch_model_to = None
282
+ if lowvram_model_memory == 0:
283
+ patch_model_to = self.device
284
+
285
+ self.model.model_patches_to(self.device)
286
+ self.model.model_patches_to(self.model.model_dtype())
287
+
288
+ try:
289
+ self.real_model = self.model.patch_model(device_to=patch_model_to) #TODO: do something with loras and offloading to CPU
290
+ except Exception as e:
291
+ self.model.unpatch_model(self.model.offload_device)
292
+ self.model_unload()
293
+ raise e
294
+
295
+ if lowvram_model_memory > 0:
296
+ print("loading in lowvram mode", lowvram_model_memory/(1024 * 1024))
297
+ device_map = accelerate.infer_auto_device_map(self.real_model, max_memory={0: "{}MiB".format(lowvram_model_memory // (1024 * 1024)), "cpu": "16GiB"})
298
+ accelerate.dispatch_model(self.real_model, device_map=device_map, main_device=self.device)
299
+ self.model_accelerated = True
300
+
301
+ if is_intel_xpu() and not args.disable_ipex_optimize:
302
+ self.real_model = torch.xpu.optimize(self.real_model.eval(), inplace=True, auto_kernel_selection=True, graph_mode=True)
303
+
304
+ return self.real_model
305
+
306
+ def model_unload(self):
307
+ if self.model_accelerated:
308
+ accelerate.hooks.remove_hook_from_submodules(self.real_model)
309
+ self.model_accelerated = False
310
+
311
+ self.model.unpatch_model(self.model.offload_device)
312
+ self.model.model_patches_to(self.model.offload_device)
313
+
314
+ def __eq__(self, other):
315
+ return self.model is other.model
316
+
317
+ def minimum_inference_memory():
318
+ return (1024 * 1024 * 1024)
319
+
320
+ def unload_model_clones(model):
321
+ to_unload = []
322
+ for i in range(len(current_loaded_models)):
323
+ if model.is_clone(current_loaded_models[i].model):
324
+ to_unload = [i] + to_unload
325
+
326
+ for i in to_unload:
327
+ print("unload clone", i)
328
+ current_loaded_models.pop(i).model_unload()
329
+
330
+ def free_memory(memory_required, device, keep_loaded=[]):
331
+ unloaded_model = False
332
+ for i in range(len(current_loaded_models) -1, -1, -1):
333
+ if not DISABLE_SMART_MEMORY:
334
+ if get_free_memory(device) > memory_required:
335
+ break
336
+ shift_model = current_loaded_models[i]
337
+ if shift_model.device == device:
338
+ if shift_model not in keep_loaded:
339
+ m = current_loaded_models.pop(i)
340
+ m.model_unload()
341
+ del m
342
+ unloaded_model = True
343
+
344
+ if unloaded_model:
345
+ soft_empty_cache()
346
+ else:
347
+ if vram_state != VRAMState.HIGH_VRAM:
348
+ mem_free_total, mem_free_torch = get_free_memory(device, torch_free_too=True)
349
+ if mem_free_torch > mem_free_total * 0.25:
350
+ soft_empty_cache()
351
+
352
+ def load_models_gpu(models, memory_required=0):
353
+ global vram_state
354
+
355
+ inference_memory = minimum_inference_memory()
356
+ extra_mem = max(inference_memory, memory_required)
357
+
358
+ models_to_load = []
359
+ models_already_loaded = []
360
+ for x in models:
361
+ loaded_model = LoadedModel(x)
362
+
363
+ if loaded_model in current_loaded_models:
364
+ index = current_loaded_models.index(loaded_model)
365
+ current_loaded_models.insert(0, current_loaded_models.pop(index))
366
+ models_already_loaded.append(loaded_model)
367
+ else:
368
+ if hasattr(x, "model"):
369
+ print(f"Requested to load {x.model.__class__.__name__}")
370
+ models_to_load.append(loaded_model)
371
+
372
+ if len(models_to_load) == 0:
373
+ devs = set(map(lambda a: a.device, models_already_loaded))
374
+ for d in devs:
375
+ if d != torch.device("cpu"):
376
+ free_memory(extra_mem, d, models_already_loaded)
377
+ return
378
+
379
+ print(f"Loading {len(models_to_load)} new model{'s' if len(models_to_load) > 1 else ''}")
380
+
381
+ total_memory_required = {}
382
+ for loaded_model in models_to_load:
383
+ unload_model_clones(loaded_model.model)
384
+ total_memory_required[loaded_model.device] = total_memory_required.get(loaded_model.device, 0) + loaded_model.model_memory_required(loaded_model.device)
385
+
386
+ for device in total_memory_required:
387
+ if device != torch.device("cpu"):
388
+ free_memory(total_memory_required[device] * 1.3 + extra_mem, device, models_already_loaded)
389
+
390
+ for loaded_model in models_to_load:
391
+ model = loaded_model.model
392
+ torch_dev = model.load_device
393
+ if is_device_cpu(torch_dev):
394
+ vram_set_state = VRAMState.DISABLED
395
+ else:
396
+ vram_set_state = vram_state
397
+ lowvram_model_memory = 0
398
+ if lowvram_available and (vram_set_state == VRAMState.LOW_VRAM or vram_set_state == VRAMState.NORMAL_VRAM):
399
+ model_size = loaded_model.model_memory_required(torch_dev)
400
+ current_free_mem = get_free_memory(torch_dev)
401
+ lowvram_model_memory = int(max(256 * (1024 * 1024), (current_free_mem - 1024 * (1024 * 1024)) / 1.3 ))
402
+ if model_size > (current_free_mem - inference_memory): #only switch to lowvram if really necessary
403
+ vram_set_state = VRAMState.LOW_VRAM
404
+ else:
405
+ lowvram_model_memory = 0
406
+
407
+ if vram_set_state == VRAMState.NO_VRAM:
408
+ lowvram_model_memory = 256 * 1024 * 1024
409
+
410
+ cur_loaded_model = loaded_model.model_load(lowvram_model_memory)
411
+ current_loaded_models.insert(0, loaded_model)
412
+ return
413
+
414
+
415
+ def load_model_gpu(model):
416
+ return load_models_gpu([model])
417
+
418
+ def cleanup_models():
419
+ to_delete = []
420
+ for i in range(len(current_loaded_models)):
421
+ if sys.getrefcount(current_loaded_models[i].model) <= 2:
422
+ to_delete = [i] + to_delete
423
+
424
+ for i in to_delete:
425
+ x = current_loaded_models.pop(i)
426
+ x.model_unload()
427
+ del x
428
+
429
+ def dtype_size(dtype):
430
+ dtype_size = 4
431
+ if dtype == torch.float16 or dtype == torch.bfloat16:
432
+ dtype_size = 2
433
+ return dtype_size
434
+
435
+ def unet_offload_device():
436
+ if vram_state == VRAMState.HIGH_VRAM:
437
+ return get_torch_device()
438
+ else:
439
+ return torch.device("cpu")
440
+
441
+ def unet_inital_load_device(parameters, dtype):
442
+ torch_dev = get_torch_device()
443
+ if vram_state == VRAMState.HIGH_VRAM:
444
+ return torch_dev
445
+
446
+ cpu_dev = torch.device("cpu")
447
+ if DISABLE_SMART_MEMORY:
448
+ return cpu_dev
449
+
450
+ model_size = dtype_size(dtype) * parameters
451
+
452
+ mem_dev = get_free_memory(torch_dev)
453
+ mem_cpu = get_free_memory(cpu_dev)
454
+ if mem_dev > mem_cpu and model_size < mem_dev:
455
+ return torch_dev
456
+ else:
457
+ return cpu_dev
458
+
459
+ def unet_dtype(device=None, model_params=0):
460
+ if args.bf16_unet:
461
+ return torch.bfloat16
462
+ if should_use_fp16(device=device, model_params=model_params):
463
+ return torch.float16
464
+ return torch.float32
465
+
466
+ def text_encoder_offload_device():
467
+ if args.gpu_only:
468
+ return get_torch_device()
469
+ else:
470
+ return torch.device("cpu")
471
+
472
+ def text_encoder_device():
473
+ if args.gpu_only:
474
+ return get_torch_device()
475
+ elif vram_state == VRAMState.HIGH_VRAM or vram_state == VRAMState.NORMAL_VRAM:
476
+ if is_intel_xpu():
477
+ return torch.device("cpu")
478
+ if should_use_fp16(prioritize_performance=False):
479
+ return get_torch_device()
480
+ else:
481
+ return torch.device("cpu")
482
+ else:
483
+ return torch.device("cpu")
484
+
485
+ def text_encoder_dtype(device=None):
486
+ if args.fp8_e4m3fn_text_enc:
487
+ return torch.float8_e4m3fn
488
+ elif args.fp8_e5m2_text_enc:
489
+ return torch.float8_e5m2
490
+ elif args.fp16_text_enc:
491
+ return torch.float16
492
+ elif args.fp32_text_enc:
493
+ return torch.float32
494
+
495
+ if should_use_fp16(device, prioritize_performance=False):
496
+ return torch.float16
497
+ else:
498
+ return torch.float32
499
+
500
+ def vae_device():
501
+ return get_torch_device()
502
+
503
+ def vae_offload_device():
504
+ if args.gpu_only:
505
+ return get_torch_device()
506
+ else:
507
+ return torch.device("cpu")
508
+
509
+ def vae_dtype():
510
+ global VAE_DTYPE
511
+ return VAE_DTYPE
512
+
513
+ def get_autocast_device(dev):
514
+ if hasattr(dev, 'type'):
515
+ return dev.type
516
+ return "cuda"
517
+
518
+ def cast_to_device(tensor, device, dtype, copy=False):
519
+ device_supports_cast = False
520
+ if tensor.dtype == torch.float32 or tensor.dtype == torch.float16:
521
+ device_supports_cast = True
522
+ elif tensor.dtype == torch.bfloat16:
523
+ if hasattr(device, 'type') and device.type.startswith("cuda"):
524
+ device_supports_cast = True
525
+ elif is_intel_xpu():
526
+ device_supports_cast = True
527
+
528
+ if device_supports_cast:
529
+ if copy:
530
+ if tensor.device == device:
531
+ return tensor.to(dtype, copy=copy)
532
+ return tensor.to(device, copy=copy).to(dtype)
533
+ else:
534
+ return tensor.to(device).to(dtype)
535
+ else:
536
+ return tensor.to(dtype).to(device, copy=copy)
537
+
538
+ def xformers_enabled():
539
+ global directml_enabled
540
+ global cpu_state
541
+ if cpu_state != CPUState.GPU:
542
+ return False
543
+ if is_intel_xpu():
544
+ return False
545
+ if directml_enabled:
546
+ return False
547
+ return XFORMERS_IS_AVAILABLE
548
+
549
+
550
+ def xformers_enabled_vae():
551
+ enabled = xformers_enabled()
552
+ if not enabled:
553
+ return False
554
+
555
+ return XFORMERS_ENABLED_VAE
556
+
557
+ def pytorch_attention_enabled():
558
+ global ENABLE_PYTORCH_ATTENTION
559
+ return ENABLE_PYTORCH_ATTENTION
560
+
561
+ def pytorch_attention_flash_attention():
562
+ global ENABLE_PYTORCH_ATTENTION
563
+ if ENABLE_PYTORCH_ATTENTION:
564
+ #TODO: more reliable way of checking for flash attention?
565
+ if is_nvidia(): #pytorch flash attention only works on Nvidia
566
+ return True
567
+ return False
568
+
569
+ def get_free_memory(dev=None, torch_free_too=False):
570
+ global directml_enabled
571
+ if dev is None:
572
+ dev = get_torch_device()
573
+
574
+ if hasattr(dev, 'type') and (dev.type == 'cpu' or dev.type == 'mps'):
575
+ mem_free_total = psutil.virtual_memory().available
576
+ mem_free_torch = mem_free_total
577
+ else:
578
+ if directml_enabled:
579
+ mem_free_total = 1024 * 1024 * 1024 #TODO
580
+ mem_free_torch = mem_free_total
581
+ elif is_intel_xpu():
582
+ stats = torch.xpu.memory_stats(dev)
583
+ mem_active = stats['active_bytes.all.current']
584
+ mem_allocated = stats['allocated_bytes.all.current']
585
+ mem_reserved = stats['reserved_bytes.all.current']
586
+ mem_free_torch = mem_reserved - mem_active
587
+ mem_free_total = torch.xpu.get_device_properties(dev).total_memory - mem_allocated
588
+ else:
589
+ stats = torch.cuda.memory_stats(dev)
590
+ mem_active = stats['active_bytes.all.current']
591
+ mem_reserved = stats['reserved_bytes.all.current']
592
+ mem_free_cuda, _ = torch.cuda.mem_get_info(dev)
593
+ mem_free_torch = mem_reserved - mem_active
594
+ mem_free_total = mem_free_cuda + mem_free_torch
595
+
596
+ if torch_free_too:
597
+ return (mem_free_total, mem_free_torch)
598
+ else:
599
+ return mem_free_total
600
+
601
+ def cpu_mode():
602
+ global cpu_state
603
+ return cpu_state == CPUState.CPU
604
+
605
+ def mps_mode():
606
+ global cpu_state
607
+ return cpu_state == CPUState.MPS
608
+
609
+ def is_device_cpu(device):
610
+ if hasattr(device, 'type'):
611
+ if (device.type == 'cpu'):
612
+ return True
613
+ return False
614
+
615
+ def is_device_mps(device):
616
+ if hasattr(device, 'type'):
617
+ if (device.type == 'mps'):
618
+ return True
619
+ return False
620
+
621
+ def should_use_fp16(device=None, model_params=0, prioritize_performance=True):
622
+ global directml_enabled
623
+
624
+ if device is not None:
625
+ if is_device_cpu(device):
626
+ return False
627
+
628
+ if FORCE_FP16:
629
+ return True
630
+
631
+ if device is not None: #TODO
632
+ if is_device_mps(device):
633
+ return False
634
+
635
+ if FORCE_FP32:
636
+ return False
637
+
638
+ if directml_enabled:
639
+ return False
640
+
641
+ if cpu_mode() or mps_mode():
642
+ return False #TODO ?
643
+
644
+ if is_intel_xpu():
645
+ return True
646
+
647
+ if torch.cuda.is_bf16_supported():
648
+ return True
649
+
650
+ props = torch.cuda.get_device_properties("cuda")
651
+ if props.major < 6:
652
+ return False
653
+
654
+ fp16_works = False
655
+ #FP16 is confirmed working on a 1080 (GP104) but it's a bit slower than FP32 so it should only be enabled
656
+ #when the model doesn't actually fit on the card
657
+ #TODO: actually test if GP106 and others have the same type of behavior
658
+ nvidia_10_series = ["1080", "1070", "titan x", "p3000", "p3200", "p4000", "p4200", "p5000", "p5200", "p6000", "1060", "1050"]
659
+ for x in nvidia_10_series:
660
+ if x in props.name.lower():
661
+ fp16_works = True
662
+
663
+ if fp16_works:
664
+ free_model_memory = (get_free_memory() * 0.9 - minimum_inference_memory())
665
+ if (not prioritize_performance) or model_params * 4 > free_model_memory:
666
+ return True
667
+
668
+ if props.major < 7:
669
+ return False
670
+
671
+ #FP16 is just broken on these cards
672
+ nvidia_16_series = ["1660", "1650", "1630", "T500", "T550", "T600", "MX550", "MX450", "CMP 30HX", "T2000", "T1000", "T1200"]
673
+ for x in nvidia_16_series:
674
+ if x in props.name:
675
+ return False
676
+
677
+ return True
678
+
679
+ def soft_empty_cache(force=False):
680
+ global cpu_state
681
+ if cpu_state == CPUState.MPS:
682
+ torch.mps.empty_cache()
683
+ elif is_intel_xpu():
684
+ torch.xpu.empty_cache()
685
+ elif torch.cuda.is_available():
686
+ if force or is_nvidia(): #This seems to make things worse on ROCm so I only do it for cuda
687
+ torch.cuda.empty_cache()
688
+ torch.cuda.ipc_collect()
689
+
690
+ def resolve_lowvram_weight(weight, model, key):
691
+ if weight.device == torch.device("meta"): #lowvram NOTE: this depends on the inner working of the accelerate library so it might break.
692
+ key_split = key.split('.') # I have no idea why they don't just leave the weight there instead of using the meta device.
693
+ op = fcbh.utils.get_attr(model, '.'.join(key_split[:-1]))
694
+ weight = op._hf_hook.weights_map[key_split[-1]]
695
+ return weight
696
+
697
+ #TODO: might be cleaner to put this somewhere else
698
+ import threading
699
+
700
+ class InterruptProcessingException(Exception):
701
+ pass
702
+
703
+ interrupt_processing_mutex = threading.RLock()
704
+
705
+ interrupt_processing = False
706
+ def interrupt_current_processing(value=True):
707
+ global interrupt_processing
708
+ global interrupt_processing_mutex
709
+ with interrupt_processing_mutex:
710
+ interrupt_processing = value
711
+
712
+ def processing_interrupted():
713
+ global interrupt_processing
714
+ global interrupt_processing_mutex
715
+ with interrupt_processing_mutex:
716
+ return interrupt_processing
717
+
718
+ def throw_exception_if_processing_interrupted():
719
+ global interrupt_processing
720
+ global interrupt_processing_mutex
721
+ with interrupt_processing_mutex:
722
+ if interrupt_processing:
723
+ interrupt_processing = False
724
+ raise InterruptProcessingException()
backend/headless/fcbh/model_patcher.py ADDED
@@ -0,0 +1,331 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import copy
3
+ import inspect
4
+
5
+ import fcbh.utils
6
+ import fcbh.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
+ size = 0
32
+ for k in model_sd:
33
+ t = model_sd[k]
34
+ size += t.nelement() * t.element_size()
35
+ self.size = size
36
+ self.model_keys = set(model_sd.keys())
37
+ return size
38
+
39
+ def clone(self):
40
+ n = ModelPatcher(self.model, self.load_device, self.offload_device, self.size, self.current_device, weight_inplace_update=self.weight_inplace_update)
41
+ n.patches = {}
42
+ for k in self.patches:
43
+ n.patches[k] = self.patches[k][:]
44
+
45
+ n.object_patches = self.object_patches.copy()
46
+ n.model_options = copy.deepcopy(self.model_options)
47
+ n.model_keys = self.model_keys
48
+ return n
49
+
50
+ def is_clone(self, other):
51
+ if hasattr(other, 'model') and self.model is other.model:
52
+ return True
53
+ return False
54
+
55
+ def memory_required(self, input_shape):
56
+ return self.model.memory_required(input_shape=input_shape)
57
+
58
+ def set_model_sampler_cfg_function(self, sampler_cfg_function):
59
+ if len(inspect.signature(sampler_cfg_function).parameters) == 3:
60
+ self.model_options["sampler_cfg_function"] = lambda args: sampler_cfg_function(args["cond"], args["uncond"], args["cond_scale"]) #Old way
61
+ else:
62
+ self.model_options["sampler_cfg_function"] = sampler_cfg_function
63
+
64
+ def set_model_unet_function_wrapper(self, unet_wrapper_function):
65
+ self.model_options["model_function_wrapper"] = unet_wrapper_function
66
+
67
+ def set_model_patch(self, patch, name):
68
+ to = self.model_options["transformer_options"]
69
+ if "patches" not in to:
70
+ to["patches"] = {}
71
+ to["patches"][name] = to["patches"].get(name, []) + [patch]
72
+
73
+ def set_model_patch_replace(self, patch, name, block_name, number):
74
+ to = self.model_options["transformer_options"]
75
+ if "patches_replace" not in to:
76
+ to["patches_replace"] = {}
77
+ if name not in to["patches_replace"]:
78
+ to["patches_replace"][name] = {}
79
+ to["patches_replace"][name][(block_name, number)] = patch
80
+
81
+ def set_model_attn1_patch(self, patch):
82
+ self.set_model_patch(patch, "attn1_patch")
83
+
84
+ def set_model_attn2_patch(self, patch):
85
+ self.set_model_patch(patch, "attn2_patch")
86
+
87
+ def set_model_attn1_replace(self, patch, block_name, number):
88
+ self.set_model_patch_replace(patch, "attn1", block_name, number)
89
+
90
+ def set_model_attn2_replace(self, patch, block_name, number):
91
+ self.set_model_patch_replace(patch, "attn2", block_name, number)
92
+
93
+ def set_model_attn1_output_patch(self, patch):
94
+ self.set_model_patch(patch, "attn1_output_patch")
95
+
96
+ def set_model_attn2_output_patch(self, patch):
97
+ self.set_model_patch(patch, "attn2_output_patch")
98
+
99
+ def set_model_input_block_patch(self, patch):
100
+ self.set_model_patch(patch, "input_block_patch")
101
+
102
+ def set_model_input_block_patch_after_skip(self, patch):
103
+ self.set_model_patch(patch, "input_block_patch_after_skip")
104
+
105
+ def set_model_output_block_patch(self, patch):
106
+ self.set_model_patch(patch, "output_block_patch")
107
+
108
+ def add_object_patch(self, name, obj):
109
+ self.object_patches[name] = obj
110
+
111
+ def model_patches_to(self, device):
112
+ to = self.model_options["transformer_options"]
113
+ if "patches" in to:
114
+ patches = to["patches"]
115
+ for name in patches:
116
+ patch_list = patches[name]
117
+ for i in range(len(patch_list)):
118
+ if hasattr(patch_list[i], "to"):
119
+ patch_list[i] = patch_list[i].to(device)
120
+ if "patches_replace" in to:
121
+ patches = to["patches_replace"]
122
+ for name in patches:
123
+ patch_list = patches[name]
124
+ for k in patch_list:
125
+ if hasattr(patch_list[k], "to"):
126
+ patch_list[k] = patch_list[k].to(device)
127
+ if "model_function_wrapper" in self.model_options:
128
+ wrap_func = self.model_options["model_function_wrapper"]
129
+ if hasattr(wrap_func, "to"):
130
+ self.model_options["model_function_wrapper"] = wrap_func.to(device)
131
+
132
+ def model_dtype(self):
133
+ if hasattr(self.model, "get_dtype"):
134
+ return self.model.get_dtype()
135
+
136
+ def add_patches(self, patches, strength_patch=1.0, strength_model=1.0):
137
+ p = set()
138
+ for k in patches:
139
+ if k in self.model_keys:
140
+ p.add(k)
141
+ current_patches = self.patches.get(k, [])
142
+ current_patches.append((strength_patch, patches[k], strength_model))
143
+ self.patches[k] = current_patches
144
+
145
+ return list(p)
146
+
147
+ def get_key_patches(self, filter_prefix=None):
148
+ fcbh.model_management.unload_model_clones(self)
149
+ model_sd = self.model_state_dict()
150
+ p = {}
151
+ for k in model_sd:
152
+ if filter_prefix is not None:
153
+ if not k.startswith(filter_prefix):
154
+ continue
155
+ if k in self.patches:
156
+ p[k] = [model_sd[k]] + self.patches[k]
157
+ else:
158
+ p[k] = (model_sd[k],)
159
+ return p
160
+
161
+ def model_state_dict(self, filter_prefix=None):
162
+ sd = self.model.state_dict()
163
+ keys = list(sd.keys())
164
+ if filter_prefix is not None:
165
+ for k in keys:
166
+ if not k.startswith(filter_prefix):
167
+ sd.pop(k)
168
+ return sd
169
+
170
+ def patch_model(self, device_to=None):
171
+ for k in self.object_patches:
172
+ old = getattr(self.model, k)
173
+ if k not in self.object_patches_backup:
174
+ self.object_patches_backup[k] = old
175
+ setattr(self.model, k, self.object_patches[k])
176
+
177
+ model_sd = self.model_state_dict()
178
+ for key in self.patches:
179
+ if key not in model_sd:
180
+ print("could not patch. key doesn't exist in model:", key)
181
+ continue
182
+
183
+ weight = model_sd[key]
184
+
185
+ inplace_update = self.weight_inplace_update
186
+
187
+ if key not in self.backup:
188
+ self.backup[key] = weight.to(device=self.offload_device, copy=inplace_update)
189
+
190
+ if device_to is not None:
191
+ temp_weight = fcbh.model_management.cast_to_device(weight, device_to, torch.float32, copy=True)
192
+ else:
193
+ temp_weight = weight.to(torch.float32, copy=True)
194
+ out_weight = self.calculate_weight(self.patches[key], temp_weight, key).to(weight.dtype)
195
+ if inplace_update:
196
+ fcbh.utils.copy_to_param(self.model, key, out_weight)
197
+ else:
198
+ fcbh.utils.set_attr(self.model, key, out_weight)
199
+ del temp_weight
200
+
201
+ if device_to is not None:
202
+ self.model.to(device_to)
203
+ self.current_device = device_to
204
+
205
+ return self.model
206
+
207
+ def calculate_weight(self, patches, weight, key):
208
+ for p in patches:
209
+ alpha = p[0]
210
+ v = p[1]
211
+ strength_model = p[2]
212
+
213
+ if strength_model != 1.0:
214
+ weight *= strength_model
215
+
216
+ if isinstance(v, list):
217
+ v = (self.calculate_weight(v[1:], v[0].clone(), key), )
218
+
219
+ if len(v) == 1:
220
+ w1 = v[0]
221
+ if alpha != 0.0:
222
+ if w1.shape != weight.shape:
223
+ print("WARNING SHAPE MISMATCH {} WEIGHT NOT MERGED {} != {}".format(key, w1.shape, weight.shape))
224
+ else:
225
+ weight += alpha * fcbh.model_management.cast_to_device(w1, weight.device, weight.dtype)
226
+ elif len(v) == 4: #lora/locon
227
+ mat1 = fcbh.model_management.cast_to_device(v[0], weight.device, torch.float32)
228
+ mat2 = fcbh.model_management.cast_to_device(v[1], weight.device, torch.float32)
229
+ if v[2] is not None:
230
+ alpha *= v[2] / mat2.shape[0]
231
+ if v[3] is not None:
232
+ #locon mid weights, hopefully the math is fine because I didn't properly test it
233
+ mat3 = fcbh.model_management.cast_to_device(v[3], weight.device, torch.float32)
234
+ final_shape = [mat2.shape[1], mat2.shape[0], mat3.shape[2], mat3.shape[3]]
235
+ 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)
236
+ try:
237
+ weight += (alpha * torch.mm(mat1.flatten(start_dim=1), mat2.flatten(start_dim=1))).reshape(weight.shape).type(weight.dtype)
238
+ except Exception as e:
239
+ print("ERROR", key, e)
240
+ elif len(v) == 8: #lokr
241
+ w1 = v[0]
242
+ w2 = v[1]
243
+ w1_a = v[3]
244
+ w1_b = v[4]
245
+ w2_a = v[5]
246
+ w2_b = v[6]
247
+ t2 = v[7]
248
+ dim = None
249
+
250
+ if w1 is None:
251
+ dim = w1_b.shape[0]
252
+ w1 = torch.mm(fcbh.model_management.cast_to_device(w1_a, weight.device, torch.float32),
253
+ fcbh.model_management.cast_to_device(w1_b, weight.device, torch.float32))
254
+ else:
255
+ w1 = fcbh.model_management.cast_to_device(w1, weight.device, torch.float32)
256
+
257
+ if w2 is None:
258
+ dim = w2_b.shape[0]
259
+ if t2 is None:
260
+ w2 = torch.mm(fcbh.model_management.cast_to_device(w2_a, weight.device, torch.float32),
261
+ fcbh.model_management.cast_to_device(w2_b, weight.device, torch.float32))
262
+ else:
263
+ w2 = torch.einsum('i j k l, j r, i p -> p r k l',
264
+ fcbh.model_management.cast_to_device(t2, weight.device, torch.float32),
265
+ fcbh.model_management.cast_to_device(w2_b, weight.device, torch.float32),
266
+ fcbh.model_management.cast_to_device(w2_a, weight.device, torch.float32))
267
+ else:
268
+ w2 = fcbh.model_management.cast_to_device(w2, weight.device, torch.float32)
269
+
270
+ if len(w2.shape) == 4:
271
+ w1 = w1.unsqueeze(2).unsqueeze(2)
272
+ if v[2] is not None and dim is not None:
273
+ alpha *= v[2] / dim
274
+
275
+ try:
276
+ weight += alpha * torch.kron(w1, w2).reshape(weight.shape).type(weight.dtype)
277
+ except Exception as e:
278
+ print("ERROR", key, e)
279
+ else: #loha
280
+ w1a = v[0]
281
+ w1b = v[1]
282
+ if v[2] is not None:
283
+ alpha *= v[2] / w1b.shape[0]
284
+ w2a = v[3]
285
+ w2b = v[4]
286
+ if v[5] is not None: #cp decomposition
287
+ t1 = v[5]
288
+ t2 = v[6]
289
+ m1 = torch.einsum('i j k l, j r, i p -> p r k l',
290
+ fcbh.model_management.cast_to_device(t1, weight.device, torch.float32),
291
+ fcbh.model_management.cast_to_device(w1b, weight.device, torch.float32),
292
+ fcbh.model_management.cast_to_device(w1a, weight.device, torch.float32))
293
+
294
+ m2 = torch.einsum('i j k l, j r, i p -> p r k l',
295
+ fcbh.model_management.cast_to_device(t2, weight.device, torch.float32),
296
+ fcbh.model_management.cast_to_device(w2b, weight.device, torch.float32),
297
+ fcbh.model_management.cast_to_device(w2a, weight.device, torch.float32))
298
+ else:
299
+ m1 = torch.mm(fcbh.model_management.cast_to_device(w1a, weight.device, torch.float32),
300
+ fcbh.model_management.cast_to_device(w1b, weight.device, torch.float32))
301
+ m2 = torch.mm(fcbh.model_management.cast_to_device(w2a, weight.device, torch.float32),
302
+ fcbh.model_management.cast_to_device(w2b, weight.device, torch.float32))
303
+
304
+ try:
305
+ weight += (alpha * m1 * m2).reshape(weight.shape).type(weight.dtype)
306
+ except Exception as e:
307
+ print("ERROR", key, e)
308
+
309
+ return weight
310
+
311
+ def unpatch_model(self, device_to=None):
312
+ keys = list(self.backup.keys())
313
+
314
+ if self.weight_inplace_update:
315
+ for k in keys:
316
+ fcbh.utils.copy_to_param(self.model, k, self.backup[k])
317
+ else:
318
+ for k in keys:
319
+ fcbh.utils.set_attr(self.model, k, self.backup[k])
320
+
321
+ self.backup = {}
322
+
323
+ if device_to is not None:
324
+ self.model.to(device_to)
325
+ self.current_device = device_to
326
+
327
+ keys = list(self.object_patches_backup.keys())
328
+ for k in keys:
329
+ setattr(self.model, k, self.object_patches_backup[k])
330
+
331
+ self.object_patches_backup = {}
backend/headless/fcbh/model_sampling.py ADDED
@@ -0,0 +1,85 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import numpy as np
3
+ from fcbh.ldm.modules.diffusionmodules.util import make_beta_schedule
4
+
5
+
6
+ class EPS:
7
+ def calculate_input(self, sigma, noise):
8
+ sigma = sigma.view(sigma.shape[:1] + (1,) * (noise.ndim - 1))
9
+ return noise / (sigma ** 2 + self.sigma_data ** 2) ** 0.5
10
+
11
+ def calculate_denoised(self, sigma, model_output, model_input):
12
+ sigma = sigma.view(sigma.shape[:1] + (1,) * (model_output.ndim - 1))
13
+ return model_input - model_output * sigma
14
+
15
+
16
+ class V_PREDICTION(EPS):
17
+ def calculate_denoised(self, sigma, model_output, model_input):
18
+ sigma = sigma.view(sigma.shape[:1] + (1,) * (model_output.ndim - 1))
19
+ 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
20
+
21
+
22
+ class ModelSamplingDiscrete(torch.nn.Module):
23
+ def __init__(self, model_config=None):
24
+ super().__init__()
25
+ beta_schedule = "linear"
26
+ if model_config is not None:
27
+ beta_schedule = model_config.beta_schedule
28
+ self._register_schedule(given_betas=None, beta_schedule=beta_schedule, timesteps=1000, linear_start=0.00085, linear_end=0.012, cosine_s=8e-3)
29
+ self.sigma_data = 1.0
30
+
31
+ def _register_schedule(self, given_betas=None, beta_schedule="linear", timesteps=1000,
32
+ linear_start=1e-4, linear_end=2e-2, cosine_s=8e-3):
33
+ if given_betas is not None:
34
+ betas = given_betas
35
+ else:
36
+ betas = make_beta_schedule(beta_schedule, timesteps, linear_start=linear_start, linear_end=linear_end, cosine_s=cosine_s)
37
+ alphas = 1. - betas
38
+ alphas_cumprod = torch.tensor(np.cumprod(alphas, axis=0), dtype=torch.float32)
39
+ # alphas_cumprod_prev = np.append(1., alphas_cumprod[:-1])
40
+
41
+ timesteps, = betas.shape
42
+ self.num_timesteps = int(timesteps)
43
+ self.linear_start = linear_start
44
+ self.linear_end = linear_end
45
+
46
+ # self.register_buffer('betas', torch.tensor(betas, dtype=torch.float32))
47
+ # self.register_buffer('alphas_cumprod', torch.tensor(alphas_cumprod, dtype=torch.float32))
48
+ # self.register_buffer('alphas_cumprod_prev', torch.tensor(alphas_cumprod_prev, dtype=torch.float32))
49
+
50
+ sigmas = ((1 - alphas_cumprod) / alphas_cumprod) ** 0.5
51
+ self.set_sigmas(sigmas)
52
+
53
+ def set_sigmas(self, sigmas):
54
+ self.register_buffer('sigmas', sigmas)
55
+ self.register_buffer('log_sigmas', sigmas.log())
56
+
57
+ @property
58
+ def sigma_min(self):
59
+ return self.sigmas[0]
60
+
61
+ @property
62
+ def sigma_max(self):
63
+ return self.sigmas[-1]
64
+
65
+ def timestep(self, sigma):
66
+ log_sigma = sigma.log()
67
+ dists = log_sigma.to(self.log_sigmas.device) - self.log_sigmas[:, None]
68
+ return dists.abs().argmin(dim=0).view(sigma.shape)
69
+
70
+ def sigma(self, timestep):
71
+ t = torch.clamp(timestep.float(), min=0, max=(len(self.sigmas) - 1))
72
+ low_idx = t.floor().long()
73
+ high_idx = t.ceil().long()
74
+ w = t.frac()
75
+ log_sigma = (1 - w) * self.log_sigmas[low_idx] + w * self.log_sigmas[high_idx]
76
+ return log_sigma.exp()
77
+
78
+ def percent_to_sigma(self, percent):
79
+ if percent <= 0.0:
80
+ return 999999999.9
81
+ if percent >= 1.0:
82
+ return 0.0
83
+ percent = 1.0 - percent
84
+ return self.sigma(torch.tensor(percent * 999.0)).item()
85
+
backend/headless/fcbh/ops.py ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from contextlib import contextmanager
3
+
4
+ class Linear(torch.nn.Linear):
5
+ def reset_parameters(self):
6
+ return None
7
+
8
+ class Conv2d(torch.nn.Conv2d):
9
+ def reset_parameters(self):
10
+ return None
11
+
12
+ class Conv3d(torch.nn.Conv3d):
13
+ def reset_parameters(self):
14
+ return None
15
+
16
+ def conv_nd(dims, *args, **kwargs):
17
+ if dims == 2:
18
+ return Conv2d(*args, **kwargs)
19
+ elif dims == 3:
20
+ return Conv3d(*args, **kwargs)
21
+ else:
22
+ raise ValueError(f"unsupported dimensions: {dims}")
23
+
24
+ @contextmanager
25
+ def use_fcbh_ops(device=None, dtype=None): # Kind of an ugly hack but I can't think of a better way
26
+ old_torch_nn_linear = torch.nn.Linear
27
+ force_device = device
28
+ force_dtype = dtype
29
+ def linear_with_dtype(in_features: int, out_features: int, bias: bool = True, device=None, dtype=None):
30
+ if force_device is not None:
31
+ device = force_device
32
+ if force_dtype is not None:
33
+ dtype = force_dtype
34
+ return Linear(in_features, out_features, bias=bias, device=device, dtype=dtype)
35
+
36
+ torch.nn.Linear = linear_with_dtype
37
+ try:
38
+ yield
39
+ finally:
40
+ torch.nn.Linear = old_torch_nn_linear
backend/headless/fcbh/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
backend/headless/fcbh/sample.py ADDED
@@ -0,0 +1,118 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import fcbh.model_management
3
+ import fcbh.samplers
4
+ import fcbh.conds
5
+ import fcbh.utils
6
+ import math
7
+ import numpy as np
8
+
9
+ def prepare_noise(latent_image, seed, noise_inds=None):
10
+ """
11
+ creates random noise given a latent image and a seed.
12
+ optional arg skip can be used to skip and discard x number of noise generations for a given seed
13
+ """
14
+ generator = torch.manual_seed(seed)
15
+ if noise_inds is None:
16
+ return torch.randn(latent_image.size(), dtype=latent_image.dtype, layout=latent_image.layout, generator=generator, device="cpu")
17
+
18
+ unique_inds, inverse = np.unique(noise_inds, return_inverse=True)
19
+ noises = []
20
+ for i in range(unique_inds[-1]+1):
21
+ noise = torch.randn([1] + list(latent_image.size())[1:], dtype=latent_image.dtype, layout=latent_image.layout, generator=generator, device="cpu")
22
+ if i in unique_inds:
23
+ noises.append(noise)
24
+ noises = [noises[i] for i in inverse]
25
+ noises = torch.cat(noises, axis=0)
26
+ return noises
27
+
28
+ def prepare_mask(noise_mask, shape, device):
29
+ """ensures noise mask is of proper dimensions"""
30
+ noise_mask = torch.nn.functional.interpolate(noise_mask.reshape((-1, 1, noise_mask.shape[-2], noise_mask.shape[-1])), size=(shape[2], shape[3]), mode="bilinear")
31
+ noise_mask = noise_mask.round()
32
+ noise_mask = torch.cat([noise_mask] * shape[1], dim=1)
33
+ noise_mask = fcbh.utils.repeat_to_batch_size(noise_mask, shape[0])
34
+ noise_mask = noise_mask.to(device)
35
+ return noise_mask
36
+
37
+ def get_models_from_cond(cond, model_type):
38
+ models = []
39
+ for c in cond:
40
+ if model_type in c:
41
+ models += [c[model_type]]
42
+ return models
43
+
44
+ def convert_cond(cond):
45
+ out = []
46
+ for c in cond:
47
+ temp = c[1].copy()
48
+ model_conds = temp.get("model_conds", {})
49
+ if c[0] is not None:
50
+ model_conds["c_crossattn"] = fcbh.conds.CONDCrossAttn(c[0])
51
+ temp["model_conds"] = model_conds
52
+ out.append(temp)
53
+ return out
54
+
55
+ def get_additional_models(positive, negative, dtype):
56
+ """loads additional models in positive and negative conditioning"""
57
+ control_nets = set(get_models_from_cond(positive, "control") + get_models_from_cond(negative, "control"))
58
+
59
+ inference_memory = 0
60
+ control_models = []
61
+ for m in control_nets:
62
+ control_models += m.get_models()
63
+ inference_memory += m.inference_memory_requirements(dtype)
64
+
65
+ gligen = get_models_from_cond(positive, "gligen") + get_models_from_cond(negative, "gligen")
66
+ gligen = [x[1] for x in gligen]
67
+ models = control_models + gligen
68
+ return models, inference_memory
69
+
70
+ def cleanup_additional_models(models):
71
+ """cleanup additional models that were loaded"""
72
+ for m in models:
73
+ if hasattr(m, 'cleanup'):
74
+ m.cleanup()
75
+
76
+ def prepare_sampling(model, noise_shape, positive, negative, noise_mask):
77
+ device = model.load_device
78
+ positive = convert_cond(positive)
79
+ negative = convert_cond(negative)
80
+
81
+ if noise_mask is not None:
82
+ noise_mask = prepare_mask(noise_mask, noise_shape, device)
83
+
84
+ real_model = None
85
+ models, inference_memory = get_additional_models(positive, negative, model.model_dtype())
86
+ fcbh.model_management.load_models_gpu([model] + models, model.memory_required(noise_shape) + inference_memory)
87
+ real_model = model.model
88
+
89
+ return real_model, positive, negative, noise_mask, models
90
+
91
+
92
+ def sample(model, noise, steps, cfg, sampler_name, scheduler, positive, negative, latent_image, denoise=1.0, disable_noise=False, start_step=None, last_step=None, force_full_denoise=False, noise_mask=None, sigmas=None, callback=None, disable_pbar=False, seed=None):
93
+ real_model, positive_copy, negative_copy, noise_mask, models = prepare_sampling(model, noise.shape, positive, negative, noise_mask)
94
+
95
+ noise = noise.to(model.load_device)
96
+ latent_image = latent_image.to(model.load_device)
97
+
98
+ sampler = fcbh.samplers.KSampler(real_model, steps=steps, device=model.load_device, sampler=sampler_name, scheduler=scheduler, denoise=denoise, model_options=model.model_options)
99
+
100
+ samples = sampler.sample(noise, positive_copy, negative_copy, cfg=cfg, latent_image=latent_image, start_step=start_step, last_step=last_step, force_full_denoise=force_full_denoise, denoise_mask=noise_mask, sigmas=sigmas, callback=callback, disable_pbar=disable_pbar, seed=seed)
101
+ samples = samples.cpu()
102
+
103
+ cleanup_additional_models(models)
104
+ cleanup_additional_models(set(get_models_from_cond(positive, "control") + get_models_from_cond(negative, "control")))
105
+ return samples
106
+
107
+ def sample_custom(model, noise, cfg, sampler, sigmas, positive, negative, latent_image, noise_mask=None, callback=None, disable_pbar=False, seed=None):
108
+ real_model, positive_copy, negative_copy, noise_mask, models = prepare_sampling(model, noise.shape, positive, negative, noise_mask)
109
+ noise = noise.to(model.load_device)
110
+ latent_image = latent_image.to(model.load_device)
111
+ sigmas = sigmas.to(model.load_device)
112
+
113
+ samples = fcbh.samplers.sample(real_model, noise, positive_copy, negative_copy, cfg, model.load_device, sampler, sigmas, model_options=model.model_options, latent_image=latent_image, denoise_mask=noise_mask, callback=callback, disable_pbar=disable_pbar, seed=seed)
114
+ samples = samples.cpu()
115
+ cleanup_additional_models(models)
116
+ cleanup_additional_models(set(get_models_from_cond(positive, "control") + get_models_from_cond(negative, "control")))
117
+ return samples
118
+
backend/headless/fcbh/samplers.py ADDED
@@ -0,0 +1,711 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from .k_diffusion import sampling as k_diffusion_sampling
2
+ from .extra_samplers import uni_pc
3
+ import torch
4
+ import enum
5
+ from fcbh import model_management
6
+ import math
7
+ from fcbh import model_base
8
+ import fcbh.utils
9
+ import fcbh.conds
10
+
11
+
12
+ #The main sampling function shared by all the samplers
13
+ #Returns denoised
14
+ def sampling_function(model, x, timestep, uncond, cond, cond_scale, model_options={}, seed=None):
15
+ def get_area_and_mult(conds, x_in, timestep_in):
16
+ area = (x_in.shape[2], x_in.shape[3], 0, 0)
17
+ strength = 1.0
18
+
19
+ if 'timestep_start' in conds:
20
+ timestep_start = conds['timestep_start']
21
+ if timestep_in[0] > timestep_start:
22
+ return None
23
+ if 'timestep_end' in conds:
24
+ timestep_end = conds['timestep_end']
25
+ if timestep_in[0] < timestep_end:
26
+ return None
27
+ if 'area' in conds:
28
+ area = conds['area']
29
+ if 'strength' in conds:
30
+ strength = conds['strength']
31
+
32
+ input_x = x_in[:,:,area[2]:area[0] + area[2],area[3]:area[1] + area[3]]
33
+ if 'mask' in conds:
34
+ # Scale the mask to the size of the input
35
+ # The mask should have been resized as we began the sampling process
36
+ mask_strength = 1.0
37
+ if "mask_strength" in conds:
38
+ mask_strength = conds["mask_strength"]
39
+ mask = conds['mask']
40
+ assert(mask.shape[1] == x_in.shape[2])
41
+ assert(mask.shape[2] == x_in.shape[3])
42
+ mask = mask[:,area[2]:area[0] + area[2],area[3]:area[1] + area[3]] * mask_strength
43
+ mask = mask.unsqueeze(1).repeat(input_x.shape[0] // mask.shape[0], input_x.shape[1], 1, 1)
44
+ else:
45
+ mask = torch.ones_like(input_x)
46
+ mult = mask * strength
47
+
48
+ if 'mask' not in conds:
49
+ rr = 8
50
+ if area[2] != 0:
51
+ for t in range(rr):
52
+ mult[:,:,t:1+t,:] *= ((1.0/rr) * (t + 1))
53
+ if (area[0] + area[2]) < x_in.shape[2]:
54
+ for t in range(rr):
55
+ mult[:,:,area[0] - 1 - t:area[0] - t,:] *= ((1.0/rr) * (t + 1))
56
+ if area[3] != 0:
57
+ for t in range(rr):
58
+ mult[:,:,:,t:1+t] *= ((1.0/rr) * (t + 1))
59
+ if (area[1] + area[3]) < x_in.shape[3]:
60
+ for t in range(rr):
61
+ mult[:,:,:,area[1] - 1 - t:area[1] - t] *= ((1.0/rr) * (t + 1))
62
+
63
+ conditionning = {}
64
+ model_conds = conds["model_conds"]
65
+ for c in model_conds:
66
+ conditionning[c] = model_conds[c].process_cond(batch_size=x_in.shape[0], device=x_in.device, area=area)
67
+
68
+ control = None
69
+ if 'control' in conds:
70
+ control = conds['control']
71
+
72
+ patches = None
73
+ if 'gligen' in conds:
74
+ gligen = conds['gligen']
75
+ patches = {}
76
+ gligen_type = gligen[0]
77
+ gligen_model = gligen[1]
78
+ if gligen_type == "position":
79
+ gligen_patch = gligen_model.model.set_position(input_x.shape, gligen[2], input_x.device)
80
+ else:
81
+ gligen_patch = gligen_model.model.set_empty(input_x.shape, input_x.device)
82
+
83
+ patches['middle_patch'] = [gligen_patch]
84
+
85
+ return (input_x, mult, conditionning, area, control, patches)
86
+
87
+ def cond_equal_size(c1, c2):
88
+ if c1 is c2:
89
+ return True
90
+ if c1.keys() != c2.keys():
91
+ return False
92
+ for k in c1:
93
+ if not c1[k].can_concat(c2[k]):
94
+ return False
95
+ return True
96
+
97
+ def can_concat_cond(c1, c2):
98
+ if c1[0].shape != c2[0].shape:
99
+ return False
100
+
101
+ #control
102
+ if (c1[4] is None) != (c2[4] is None):
103
+ return False
104
+ if c1[4] is not None:
105
+ if c1[4] is not c2[4]:
106
+ return False
107
+
108
+ #patches
109
+ if (c1[5] is None) != (c2[5] is None):
110
+ return False
111
+ if (c1[5] is not None):
112
+ if c1[5] is not c2[5]:
113
+ return False
114
+
115
+ return cond_equal_size(c1[2], c2[2])
116
+
117
+ def cond_cat(c_list):
118
+ c_crossattn = []
119
+ c_concat = []
120
+ c_adm = []
121
+ crossattn_max_len = 0
122
+
123
+ temp = {}
124
+ for x in c_list:
125
+ for k in x:
126
+ cur = temp.get(k, [])
127
+ cur.append(x[k])
128
+ temp[k] = cur
129
+
130
+ out = {}
131
+ for k in temp:
132
+ conds = temp[k]
133
+ out[k] = conds[0].concat(conds[1:])
134
+
135
+ return out
136
+
137
+ def calc_cond_uncond_batch(model, cond, uncond, x_in, timestep, model_options):
138
+ out_cond = torch.zeros_like(x_in)
139
+ out_count = torch.ones_like(x_in) * 1e-37
140
+
141
+ out_uncond = torch.zeros_like(x_in)
142
+ out_uncond_count = torch.ones_like(x_in) * 1e-37
143
+
144
+ COND = 0
145
+ UNCOND = 1
146
+
147
+ to_run = []
148
+ for x in cond:
149
+ p = get_area_and_mult(x, x_in, timestep)
150
+ if p is None:
151
+ continue
152
+
153
+ to_run += [(p, COND)]
154
+ if uncond is not None:
155
+ for x in uncond:
156
+ p = get_area_and_mult(x, x_in, timestep)
157
+ if p is None:
158
+ continue
159
+
160
+ to_run += [(p, UNCOND)]
161
+
162
+ while len(to_run) > 0:
163
+ first = to_run[0]
164
+ first_shape = first[0][0].shape
165
+ to_batch_temp = []
166
+ for x in range(len(to_run)):
167
+ if can_concat_cond(to_run[x][0], first[0]):
168
+ to_batch_temp += [x]
169
+
170
+ to_batch_temp.reverse()
171
+ to_batch = to_batch_temp[:1]
172
+
173
+ free_memory = model_management.get_free_memory(x_in.device)
174
+ for i in range(1, len(to_batch_temp) + 1):
175
+ batch_amount = to_batch_temp[:len(to_batch_temp)//i]
176
+ input_shape = [len(batch_amount) * first_shape[0]] + list(first_shape)[1:]
177
+ if model.memory_required(input_shape) < free_memory:
178
+ to_batch = batch_amount
179
+ break
180
+
181
+ input_x = []
182
+ mult = []
183
+ c = []
184
+ cond_or_uncond = []
185
+ area = []
186
+ control = None
187
+ patches = None
188
+ for x in to_batch:
189
+ o = to_run.pop(x)
190
+ p = o[0]
191
+ input_x += [p[0]]
192
+ mult += [p[1]]
193
+ c += [p[2]]
194
+ area += [p[3]]
195
+ cond_or_uncond += [o[1]]
196
+ control = p[4]
197
+ patches = p[5]
198
+
199
+ batch_chunks = len(cond_or_uncond)
200
+ input_x = torch.cat(input_x)
201
+ c = cond_cat(c)
202
+ timestep_ = torch.cat([timestep] * batch_chunks)
203
+
204
+ if control is not None:
205
+ c['control'] = control.get_control(input_x, timestep_, c, len(cond_or_uncond))
206
+
207
+ transformer_options = {}
208
+ if 'transformer_options' in model_options:
209
+ transformer_options = model_options['transformer_options'].copy()
210
+
211
+ if patches is not None:
212
+ if "patches" in transformer_options:
213
+ cur_patches = transformer_options["patches"].copy()
214
+ for p in patches:
215
+ if p in cur_patches:
216
+ cur_patches[p] = cur_patches[p] + patches[p]
217
+ else:
218
+ cur_patches[p] = patches[p]
219
+ else:
220
+ transformer_options["patches"] = patches
221
+
222
+ transformer_options["cond_or_uncond"] = cond_or_uncond[:]
223
+ transformer_options["sigmas"] = timestep
224
+
225
+ c['transformer_options'] = transformer_options
226
+
227
+ if 'model_function_wrapper' in model_options:
228
+ output = model_options['model_function_wrapper'](model.apply_model, {"input": input_x, "timestep": timestep_, "c": c, "cond_or_uncond": cond_or_uncond}).chunk(batch_chunks)
229
+ else:
230
+ output = model.apply_model(input_x, timestep_, **c).chunk(batch_chunks)
231
+ del input_x
232
+
233
+ for o in range(batch_chunks):
234
+ if cond_or_uncond[o] == COND:
235
+ out_cond[:,:,area[o][2]:area[o][0] + area[o][2],area[o][3]:area[o][1] + area[o][3]] += output[o] * mult[o]
236
+ out_count[:,:,area[o][2]:area[o][0] + area[o][2],area[o][3]:area[o][1] + area[o][3]] += mult[o]
237
+ else:
238
+ out_uncond[:,:,area[o][2]:area[o][0] + area[o][2],area[o][3]:area[o][1] + area[o][3]] += output[o] * mult[o]
239
+ out_uncond_count[:,:,area[o][2]:area[o][0] + area[o][2],area[o][3]:area[o][1] + area[o][3]] += mult[o]
240
+ del mult
241
+
242
+ out_cond /= out_count
243
+ del out_count
244
+ out_uncond /= out_uncond_count
245
+ del out_uncond_count
246
+ return out_cond, out_uncond
247
+
248
+
249
+ if math.isclose(cond_scale, 1.0):
250
+ uncond = None
251
+
252
+ cond, uncond = calc_cond_uncond_batch(model, cond, uncond, x, timestep, model_options)
253
+ if "sampler_cfg_function" in model_options:
254
+ args = {"cond": x - cond, "uncond": x - uncond, "cond_scale": cond_scale, "timestep": timestep, "input": x, "sigma": timestep}
255
+ return x - model_options["sampler_cfg_function"](args)
256
+ else:
257
+ return uncond + (cond - uncond) * cond_scale
258
+
259
+ class CFGNoisePredictor(torch.nn.Module):
260
+ def __init__(self, model):
261
+ super().__init__()
262
+ self.inner_model = model
263
+ def apply_model(self, x, timestep, cond, uncond, cond_scale, model_options={}, seed=None):
264
+ out = sampling_function(self.inner_model, x, timestep, uncond, cond, cond_scale, model_options=model_options, seed=seed)
265
+ return out
266
+ def forward(self, *args, **kwargs):
267
+ return self.apply_model(*args, **kwargs)
268
+
269
+ class KSamplerX0Inpaint(torch.nn.Module):
270
+ def __init__(self, model):
271
+ super().__init__()
272
+ self.inner_model = model
273
+ def forward(self, x, sigma, uncond, cond, cond_scale, denoise_mask, model_options={}, seed=None):
274
+ if denoise_mask is not None:
275
+ latent_mask = 1. - denoise_mask
276
+ x = x * denoise_mask + (self.latent_image + self.noise * sigma.reshape([sigma.shape[0]] + [1] * (len(self.noise.shape) - 1))) * latent_mask
277
+ out = self.inner_model(x, sigma, cond=cond, uncond=uncond, cond_scale=cond_scale, model_options=model_options, seed=seed)
278
+ if denoise_mask is not None:
279
+ out *= denoise_mask
280
+
281
+ if denoise_mask is not None:
282
+ out += self.latent_image * latent_mask
283
+ return out
284
+
285
+ def simple_scheduler(model, steps):
286
+ s = model.model_sampling
287
+ sigs = []
288
+ ss = len(s.sigmas) / steps
289
+ for x in range(steps):
290
+ sigs += [float(s.sigmas[-(1 + int(x * ss))])]
291
+ sigs += [0.0]
292
+ return torch.FloatTensor(sigs)
293
+
294
+ def ddim_scheduler(model, steps):
295
+ s = model.model_sampling
296
+ sigs = []
297
+ ss = len(s.sigmas) // steps
298
+ x = 1
299
+ while x < len(s.sigmas):
300
+ sigs += [float(s.sigmas[x])]
301
+ x += ss
302
+ sigs = sigs[::-1]
303
+ sigs += [0.0]
304
+ return torch.FloatTensor(sigs)
305
+
306
+ def normal_scheduler(model, steps, sgm=False, floor=False):
307
+ s = model.model_sampling
308
+ start = s.timestep(s.sigma_max)
309
+ end = s.timestep(s.sigma_min)
310
+
311
+ if sgm:
312
+ timesteps = torch.linspace(start, end, steps + 1)[:-1]
313
+ else:
314
+ timesteps = torch.linspace(start, end, steps)
315
+
316
+ sigs = []
317
+ for x in range(len(timesteps)):
318
+ ts = timesteps[x]
319
+ sigs.append(s.sigma(ts))
320
+ sigs += [0.0]
321
+ return torch.FloatTensor(sigs)
322
+
323
+ def get_mask_aabb(masks):
324
+ if masks.numel() == 0:
325
+ return torch.zeros((0, 4), device=masks.device, dtype=torch.int)
326
+
327
+ b = masks.shape[0]
328
+
329
+ bounding_boxes = torch.zeros((b, 4), device=masks.device, dtype=torch.int)
330
+ is_empty = torch.zeros((b), device=masks.device, dtype=torch.bool)
331
+ for i in range(b):
332
+ mask = masks[i]
333
+ if mask.numel() == 0:
334
+ continue
335
+ if torch.max(mask != 0) == False:
336
+ is_empty[i] = True
337
+ continue
338
+ y, x = torch.where(mask)
339
+ bounding_boxes[i, 0] = torch.min(x)
340
+ bounding_boxes[i, 1] = torch.min(y)
341
+ bounding_boxes[i, 2] = torch.max(x)
342
+ bounding_boxes[i, 3] = torch.max(y)
343
+
344
+ return bounding_boxes, is_empty
345
+
346
+ def resolve_areas_and_cond_masks(conditions, h, w, device):
347
+ # We need to decide on an area outside the sampling loop in order to properly generate opposite areas of equal sizes.
348
+ # While we're doing this, we can also resolve the mask device and scaling for performance reasons
349
+ for i in range(len(conditions)):
350
+ c = conditions[i]
351
+ if 'area' in c:
352
+ area = c['area']
353
+ if area[0] == "percentage":
354
+ modified = c.copy()
355
+ area = (max(1, round(area[1] * h)), max(1, round(area[2] * w)), round(area[3] * h), round(area[4] * w))
356
+ modified['area'] = area
357
+ c = modified
358
+ conditions[i] = c
359
+
360
+ if 'mask' in c:
361
+ mask = c['mask']
362
+ mask = mask.to(device=device)
363
+ modified = c.copy()
364
+ if len(mask.shape) == 2:
365
+ mask = mask.unsqueeze(0)
366
+ if mask.shape[1] != h or mask.shape[2] != w:
367
+ mask = torch.nn.functional.interpolate(mask.unsqueeze(1), size=(h, w), mode='bilinear', align_corners=False).squeeze(1)
368
+
369
+ if modified.get("set_area_to_bounds", False):
370
+ bounds = torch.max(torch.abs(mask),dim=0).values.unsqueeze(0)
371
+ boxes, is_empty = get_mask_aabb(bounds)
372
+ if is_empty[0]:
373
+ # Use the minimum possible size for efficiency reasons. (Since the mask is all-0, this becomes a noop anyway)
374
+ modified['area'] = (8, 8, 0, 0)
375
+ else:
376
+ box = boxes[0]
377
+ H, W, Y, X = (box[3] - box[1] + 1, box[2] - box[0] + 1, box[1], box[0])
378
+ H = max(8, H)
379
+ W = max(8, W)
380
+ area = (int(H), int(W), int(Y), int(X))
381
+ modified['area'] = area
382
+
383
+ modified['mask'] = mask
384
+ conditions[i] = modified
385
+
386
+ def create_cond_with_same_area_if_none(conds, c):
387
+ if 'area' not in c:
388
+ return
389
+
390
+ c_area = c['area']
391
+ smallest = None
392
+ for x in conds:
393
+ if 'area' in x:
394
+ a = x['area']
395
+ if c_area[2] >= a[2] and c_area[3] >= a[3]:
396
+ if a[0] + a[2] >= c_area[0] + c_area[2]:
397
+ if a[1] + a[3] >= c_area[1] + c_area[3]:
398
+ if smallest is None:
399
+ smallest = x
400
+ elif 'area' not in smallest:
401
+ smallest = x
402
+ else:
403
+ if smallest['area'][0] * smallest['area'][1] > a[0] * a[1]:
404
+ smallest = x
405
+ else:
406
+ if smallest is None:
407
+ smallest = x
408
+ if smallest is None:
409
+ return
410
+ if 'area' in smallest:
411
+ if smallest['area'] == c_area:
412
+ return
413
+
414
+ out = c.copy()
415
+ out['model_conds'] = smallest['model_conds'].copy() #TODO: which fields should be copied?
416
+ conds += [out]
417
+
418
+ def calculate_start_end_timesteps(model, conds):
419
+ s = model.model_sampling
420
+ for t in range(len(conds)):
421
+ x = conds[t]
422
+
423
+ timestep_start = None
424
+ timestep_end = None
425
+ if 'start_percent' in x:
426
+ timestep_start = s.percent_to_sigma(x['start_percent'])
427
+ if 'end_percent' in x:
428
+ timestep_end = s.percent_to_sigma(x['end_percent'])
429
+
430
+ if (timestep_start is not None) or (timestep_end is not None):
431
+ n = x.copy()
432
+ if (timestep_start is not None):
433
+ n['timestep_start'] = timestep_start
434
+ if (timestep_end is not None):
435
+ n['timestep_end'] = timestep_end
436
+ conds[t] = n
437
+
438
+ def pre_run_control(model, conds):
439
+ s = model.model_sampling
440
+ for t in range(len(conds)):
441
+ x = conds[t]
442
+
443
+ timestep_start = None
444
+ timestep_end = None
445
+ percent_to_timestep_function = lambda a: s.percent_to_sigma(a)
446
+ if 'control' in x:
447
+ x['control'].pre_run(model, percent_to_timestep_function)
448
+
449
+ def apply_empty_x_to_equal_area(conds, uncond, name, uncond_fill_func):
450
+ cond_cnets = []
451
+ cond_other = []
452
+ uncond_cnets = []
453
+ uncond_other = []
454
+ for t in range(len(conds)):
455
+ x = conds[t]
456
+ if 'area' not in x:
457
+ if name in x and x[name] is not None:
458
+ cond_cnets.append(x[name])
459
+ else:
460
+ cond_other.append((x, t))
461
+ for t in range(len(uncond)):
462
+ x = uncond[t]
463
+ if 'area' not in x:
464
+ if name in x and x[name] is not None:
465
+ uncond_cnets.append(x[name])
466
+ else:
467
+ uncond_other.append((x, t))
468
+
469
+ if len(uncond_cnets) > 0:
470
+ return
471
+
472
+ for x in range(len(cond_cnets)):
473
+ temp = uncond_other[x % len(uncond_other)]
474
+ o = temp[0]
475
+ if name in o and o[name] is not None:
476
+ n = o.copy()
477
+ n[name] = uncond_fill_func(cond_cnets, x)
478
+ uncond += [n]
479
+ else:
480
+ n = o.copy()
481
+ n[name] = uncond_fill_func(cond_cnets, x)
482
+ uncond[temp[1]] = n
483
+
484
+ def encode_model_conds(model_function, conds, noise, device, prompt_type, **kwargs):
485
+ for t in range(len(conds)):
486
+ x = conds[t]
487
+ params = x.copy()
488
+ params["device"] = device
489
+ params["noise"] = noise
490
+ params["width"] = params.get("width", noise.shape[3] * 8)
491
+ params["height"] = params.get("height", noise.shape[2] * 8)
492
+ params["prompt_type"] = params.get("prompt_type", prompt_type)
493
+ for k in kwargs:
494
+ if k not in params:
495
+ params[k] = kwargs[k]
496
+
497
+ out = model_function(**params)
498
+ x = x.copy()
499
+ model_conds = x['model_conds'].copy()
500
+ for k in out:
501
+ model_conds[k] = out[k]
502
+ x['model_conds'] = model_conds
503
+ conds[t] = x
504
+ return conds
505
+
506
+ class Sampler:
507
+ def sample(self):
508
+ pass
509
+
510
+ def max_denoise(self, model_wrap, sigmas):
511
+ max_sigma = float(model_wrap.inner_model.model_sampling.sigma_max)
512
+ sigma = float(sigmas[0])
513
+ return math.isclose(max_sigma, sigma, rel_tol=1e-05) or sigma > max_sigma
514
+
515
+ class UNIPC(Sampler):
516
+ def sample(self, model_wrap, sigmas, extra_args, callback, noise, latent_image=None, denoise_mask=None, disable_pbar=False):
517
+ return uni_pc.sample_unipc(model_wrap, noise, latent_image, sigmas, max_denoise=self.max_denoise(model_wrap, sigmas), extra_args=extra_args, noise_mask=denoise_mask, callback=callback, disable=disable_pbar)
518
+
519
+ class UNIPCBH2(Sampler):
520
+ def sample(self, model_wrap, sigmas, extra_args, callback, noise, latent_image=None, denoise_mask=None, disable_pbar=False):
521
+ return uni_pc.sample_unipc(model_wrap, noise, latent_image, sigmas, max_denoise=self.max_denoise(model_wrap, sigmas), extra_args=extra_args, noise_mask=denoise_mask, callback=callback, variant='bh2', disable=disable_pbar)
522
+
523
+ KSAMPLER_NAMES = ["euler", "euler_ancestral", "heun", "heunpp2","dpm_2", "dpm_2_ancestral",
524
+ "lms", "dpm_fast", "dpm_adaptive", "dpmpp_2s_ancestral", "dpmpp_sde", "dpmpp_sde_gpu",
525
+ "dpmpp_2m", "dpmpp_2m_sde", "dpmpp_2m_sde_gpu", "dpmpp_3m_sde", "dpmpp_3m_sde_gpu", "ddpm", "lcm"]
526
+
527
+ class KSAMPLER(Sampler):
528
+ def __init__(self, sampler_function, extra_options={}, inpaint_options={}):
529
+ self.sampler_function = sampler_function
530
+ self.extra_options = extra_options
531
+ self.inpaint_options = inpaint_options
532
+
533
+ def sample(self, model_wrap, sigmas, extra_args, callback, noise, latent_image=None, denoise_mask=None, disable_pbar=False):
534
+ extra_args["denoise_mask"] = denoise_mask
535
+ model_k = KSamplerX0Inpaint(model_wrap)
536
+ model_k.latent_image = latent_image
537
+ if self.inpaint_options.get("random", False): #TODO: Should this be the default?
538
+ generator = torch.manual_seed(extra_args.get("seed", 41) + 1)
539
+ model_k.noise = torch.randn(noise.shape, generator=generator, device="cpu").to(noise.dtype).to(noise.device)
540
+ else:
541
+ model_k.noise = noise
542
+
543
+ if self.max_denoise(model_wrap, sigmas):
544
+ noise = noise * torch.sqrt(1.0 + sigmas[0] ** 2.0)
545
+ else:
546
+ noise = noise * sigmas[0]
547
+
548
+ k_callback = None
549
+ total_steps = len(sigmas) - 1
550
+ if callback is not None:
551
+ k_callback = lambda x: callback(x["i"], x["denoised"], x["x"], total_steps)
552
+
553
+ if latent_image is not None:
554
+ noise += latent_image
555
+
556
+ samples = self.sampler_function(model_k, noise, sigmas, extra_args=extra_args, callback=k_callback, disable=disable_pbar, **self.extra_options)
557
+ return samples
558
+
559
+
560
+ def ksampler(sampler_name, extra_options={}, inpaint_options={}):
561
+ if sampler_name == "dpm_fast":
562
+ def dpm_fast_function(model, noise, sigmas, extra_args, callback, disable):
563
+ sigma_min = sigmas[-1]
564
+ if sigma_min == 0:
565
+ sigma_min = sigmas[-2]
566
+ total_steps = len(sigmas) - 1
567
+ return k_diffusion_sampling.sample_dpm_fast(model, noise, sigma_min, sigmas[0], total_steps, extra_args=extra_args, callback=callback, disable=disable)
568
+ sampler_function = dpm_fast_function
569
+ elif sampler_name == "dpm_adaptive":
570
+ def dpm_adaptive_function(model, noise, sigmas, extra_args, callback, disable):
571
+ sigma_min = sigmas[-1]
572
+ if sigma_min == 0:
573
+ sigma_min = sigmas[-2]
574
+ return k_diffusion_sampling.sample_dpm_adaptive(model, noise, sigma_min, sigmas[0], extra_args=extra_args, callback=callback, disable=disable)
575
+ sampler_function = dpm_adaptive_function
576
+ else:
577
+ sampler_function = getattr(k_diffusion_sampling, "sample_{}".format(sampler_name))
578
+
579
+ return KSAMPLER(sampler_function, extra_options, inpaint_options)
580
+
581
+ def wrap_model(model):
582
+ model_denoise = CFGNoisePredictor(model)
583
+ return model_denoise
584
+
585
+ def sample(model, noise, positive, negative, cfg, device, sampler, sigmas, model_options={}, latent_image=None, denoise_mask=None, callback=None, disable_pbar=False, seed=None):
586
+ positive = positive[:]
587
+ negative = negative[:]
588
+
589
+ resolve_areas_and_cond_masks(positive, noise.shape[2], noise.shape[3], device)
590
+ resolve_areas_and_cond_masks(negative, noise.shape[2], noise.shape[3], device)
591
+
592
+ model_wrap = wrap_model(model)
593
+
594
+ calculate_start_end_timesteps(model, negative)
595
+ calculate_start_end_timesteps(model, positive)
596
+
597
+ #make sure each cond area has an opposite one with the same area
598
+ for c in positive:
599
+ create_cond_with_same_area_if_none(negative, c)
600
+ for c in negative:
601
+ create_cond_with_same_area_if_none(positive, c)
602
+
603
+ pre_run_control(model, negative + positive)
604
+
605
+ apply_empty_x_to_equal_area(list(filter(lambda c: c.get('control_apply_to_uncond', False) == True, positive)), negative, 'control', lambda cond_cnets, x: cond_cnets[x])
606
+ apply_empty_x_to_equal_area(positive, negative, 'gligen', lambda cond_cnets, x: cond_cnets[x])
607
+
608
+ if latent_image is not None:
609
+ latent_image = model.process_latent_in(latent_image)
610
+
611
+ if hasattr(model, 'extra_conds'):
612
+ positive = encode_model_conds(model.extra_conds, positive, noise, device, "positive", latent_image=latent_image, denoise_mask=denoise_mask)
613
+ negative = encode_model_conds(model.extra_conds, negative, noise, device, "negative", latent_image=latent_image, denoise_mask=denoise_mask)
614
+
615
+ extra_args = {"cond":positive, "uncond":negative, "cond_scale": cfg, "model_options": model_options, "seed":seed}
616
+
617
+ samples = sampler.sample(model_wrap, sigmas, extra_args, callback, noise, latent_image, denoise_mask, disable_pbar)
618
+ return model.process_latent_out(samples.to(torch.float32))
619
+
620
+ SCHEDULER_NAMES = ["normal", "karras", "exponential", "sgm_uniform", "simple", "ddim_uniform"]
621
+ SAMPLER_NAMES = KSAMPLER_NAMES + ["ddim", "uni_pc", "uni_pc_bh2"]
622
+
623
+ def calculate_sigmas_scheduler(model, scheduler_name, steps):
624
+ if scheduler_name == "karras":
625
+ sigmas = k_diffusion_sampling.get_sigmas_karras(n=steps, sigma_min=float(model.model_sampling.sigma_min), sigma_max=float(model.model_sampling.sigma_max))
626
+ elif scheduler_name == "exponential":
627
+ sigmas = k_diffusion_sampling.get_sigmas_exponential(n=steps, sigma_min=float(model.model_sampling.sigma_min), sigma_max=float(model.model_sampling.sigma_max))
628
+ elif scheduler_name == "normal":
629
+ sigmas = normal_scheduler(model, steps)
630
+ elif scheduler_name == "simple":
631
+ sigmas = simple_scheduler(model, steps)
632
+ elif scheduler_name == "ddim_uniform":
633
+ sigmas = ddim_scheduler(model, steps)
634
+ elif scheduler_name == "sgm_uniform":
635
+ sigmas = normal_scheduler(model, steps, sgm=True)
636
+ else:
637
+ print("error invalid scheduler", self.scheduler)
638
+ return sigmas
639
+
640
+ def sampler_object(name):
641
+ if name == "uni_pc":
642
+ sampler = UNIPC()
643
+ elif name == "uni_pc_bh2":
644
+ sampler = UNIPCBH2()
645
+ elif name == "ddim":
646
+ sampler = ksampler("euler", inpaint_options={"random": True})
647
+ else:
648
+ sampler = ksampler(name)
649
+ return sampler
650
+
651
+ class KSampler:
652
+ SCHEDULERS = SCHEDULER_NAMES
653
+ SAMPLERS = SAMPLER_NAMES
654
+
655
+ def __init__(self, model, steps, device, sampler=None, scheduler=None, denoise=None, model_options={}):
656
+ self.model = model
657
+ self.device = device
658
+ if scheduler not in self.SCHEDULERS:
659
+ scheduler = self.SCHEDULERS[0]
660
+ if sampler not in self.SAMPLERS:
661
+ sampler = self.SAMPLERS[0]
662
+ self.scheduler = scheduler
663
+ self.sampler = sampler
664
+ self.set_steps(steps, denoise)
665
+ self.denoise = denoise
666
+ self.model_options = model_options
667
+
668
+ def calculate_sigmas(self, steps):
669
+ sigmas = None
670
+
671
+ discard_penultimate_sigma = False
672
+ if self.sampler in ['dpm_2', 'dpm_2_ancestral', 'uni_pc', 'uni_pc_bh2']:
673
+ steps += 1
674
+ discard_penultimate_sigma = True
675
+
676
+ sigmas = calculate_sigmas_scheduler(self.model, self.scheduler, steps)
677
+
678
+ if discard_penultimate_sigma:
679
+ sigmas = torch.cat([sigmas[:-2], sigmas[-1:]])
680
+ return sigmas
681
+
682
+ def set_steps(self, steps, denoise=None):
683
+ self.steps = steps
684
+ if denoise is None or denoise > 0.9999:
685
+ self.sigmas = self.calculate_sigmas(steps).to(self.device)
686
+ else:
687
+ new_steps = int(steps/denoise)
688
+ sigmas = self.calculate_sigmas(new_steps).to(self.device)
689
+ self.sigmas = sigmas[-(steps + 1):]
690
+
691
+ def sample(self, noise, positive, negative, cfg, latent_image=None, start_step=None, last_step=None, force_full_denoise=False, denoise_mask=None, sigmas=None, callback=None, disable_pbar=False, seed=None):
692
+ if sigmas is None:
693
+ sigmas = self.sigmas
694
+
695
+ if last_step is not None and last_step < (len(sigmas) - 1):
696
+ sigmas = sigmas[:last_step + 1]
697
+ if force_full_denoise:
698
+ sigmas[-1] = 0
699
+
700
+ if start_step is not None:
701
+ if start_step < (len(sigmas) - 1):
702
+ sigmas = sigmas[start_step:]
703
+ else:
704
+ if latent_image is not None:
705
+ return latent_image
706
+ else:
707
+ return torch.zeros_like(noise)
708
+
709
+ sampler = sampler_object(self.sampler)
710
+
711
+ return sample(self.model, noise, positive, negative, cfg, self.device, sampler, sigmas, self.model_options, latent_image=latent_image, denoise_mask=denoise_mask, callback=callback, disable_pbar=disable_pbar, seed=seed)