Spaces:
Sleeping
Sleeping
mrfakename
commited on
Commit
•
4ee33aa
1
Parent(s):
716d8d8
Add source code
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- LICENSE +373 -0
- arch.png +0 -0
- demo.ipynb +0 -0
- setup.py +3 -0
- ttts-src/.gitignore +15 -0
- ttts.egg-info/PKG-INFO +3 -0
- ttts.egg-info/SOURCES.txt +5 -0
- ttts.egg-info/dependency_links.txt +1 -0
- ttts.egg-info/top_level.txt +1 -0
- ttts/0.wav +0 -0
- ttts/3.wav +0 -0
- ttts/AA_diffusion_deprecated/cldm/cldm.py +875 -0
- ttts/AA_diffusion_deprecated/cldm/cond_emb.py +339 -0
- ttts/AA_diffusion_deprecated/cldm/ddim_hacked.py +317 -0
- ttts/AA_diffusion_deprecated/cldm/hack.py +111 -0
- ttts/AA_diffusion_deprecated/cldm/hf_model.py +193 -0
- ttts/AA_diffusion_deprecated/cldm/logger.py +76 -0
- ttts/AA_diffusion_deprecated/cldm/model.py +28 -0
- ttts/AA_diffusion_deprecated/cldm/modified_resnet.py +181 -0
- ttts/AA_diffusion_deprecated/cldm/pos_embed.py +96 -0
- ttts/AA_diffusion_deprecated/cldm/timm_model.py +152 -0
- ttts/AA_diffusion_deprecated/cldm/transformer.py +806 -0
- ttts/AA_diffusion_deprecated/cldm/utils.py +89 -0
- ttts/AA_diffusion_deprecated/config.yaml +134 -0
- ttts/AA_diffusion_deprecated/dataset.py +152 -0
- ttts/AA_diffusion_deprecated/ldm/data/__init__.py +0 -0
- ttts/AA_diffusion_deprecated/ldm/data/util.py +24 -0
- ttts/AA_diffusion_deprecated/ldm/models/autoencoder.py +219 -0
- ttts/AA_diffusion_deprecated/ldm/models/diffusion/__init__.py +0 -0
- ttts/AA_diffusion_deprecated/ldm/models/diffusion/ddim.py +336 -0
- ttts/AA_diffusion_deprecated/ldm/models/diffusion/ddpm.py +1827 -0
- ttts/AA_diffusion_deprecated/ldm/models/diffusion/dpm_solver/__init__.py +1 -0
- ttts/AA_diffusion_deprecated/ldm/models/diffusion/dpm_solver/dpm_solver.py +1154 -0
- ttts/AA_diffusion_deprecated/ldm/models/diffusion/dpm_solver/sampler.py +87 -0
- ttts/AA_diffusion_deprecated/ldm/models/diffusion/plms.py +244 -0
- ttts/AA_diffusion_deprecated/ldm/models/diffusion/sampling_util.py +22 -0
- ttts/AA_diffusion_deprecated/ldm/modules/attention.py +365 -0
- ttts/AA_diffusion_deprecated/ldm/modules/diffusionmodules/__init__.py +0 -0
- ttts/AA_diffusion_deprecated/ldm/modules/diffusionmodules/model.py +852 -0
- ttts/AA_diffusion_deprecated/ldm/modules/diffusionmodules/openaimodel.py +796 -0
- ttts/AA_diffusion_deprecated/ldm/modules/diffusionmodules/upscaling.py +81 -0
- ttts/AA_diffusion_deprecated/ldm/modules/diffusionmodules/util.py +275 -0
- ttts/AA_diffusion_deprecated/ldm/modules/distributions/__init__.py +0 -0
- ttts/AA_diffusion_deprecated/ldm/modules/distributions/distributions.py +92 -0
- ttts/AA_diffusion_deprecated/ldm/modules/ema.py +80 -0
- ttts/AA_diffusion_deprecated/ldm/modules/encoders/__init__.py +0 -0
- ttts/AA_diffusion_deprecated/ldm/modules/encoders/modules.py +213 -0
- ttts/AA_diffusion_deprecated/ldm/modules/image_degradation/__init__.py +2 -0
- ttts/AA_diffusion_deprecated/ldm/modules/image_degradation/bsrgan.py +730 -0
- ttts/AA_diffusion_deprecated/ldm/modules/image_degradation/bsrgan_light.py +651 -0
LICENSE
ADDED
@@ -0,0 +1,373 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
Mozilla Public License Version 2.0
|
2 |
+
==================================
|
3 |
+
|
4 |
+
1. Definitions
|
5 |
+
--------------
|
6 |
+
|
7 |
+
1.1. "Contributor"
|
8 |
+
means each individual or legal entity that creates, contributes to
|
9 |
+
the creation of, or owns Covered Software.
|
10 |
+
|
11 |
+
1.2. "Contributor Version"
|
12 |
+
means the combination of the Contributions of others (if any) used
|
13 |
+
by a Contributor and that particular Contributor's Contribution.
|
14 |
+
|
15 |
+
1.3. "Contribution"
|
16 |
+
means Covered Software of a particular Contributor.
|
17 |
+
|
18 |
+
1.4. "Covered Software"
|
19 |
+
means Source Code Form to which the initial Contributor has attached
|
20 |
+
the notice in Exhibit A, the Executable Form of such Source Code
|
21 |
+
Form, and Modifications of such Source Code Form, in each case
|
22 |
+
including portions thereof.
|
23 |
+
|
24 |
+
1.5. "Incompatible With Secondary Licenses"
|
25 |
+
means
|
26 |
+
|
27 |
+
(a) that the initial Contributor has attached the notice described
|
28 |
+
in Exhibit B to the Covered Software; or
|
29 |
+
|
30 |
+
(b) that the Covered Software was made available under the terms of
|
31 |
+
version 1.1 or earlier of the License, but not also under the
|
32 |
+
terms of a Secondary License.
|
33 |
+
|
34 |
+
1.6. "Executable Form"
|
35 |
+
means any form of the work other than Source Code Form.
|
36 |
+
|
37 |
+
1.7. "Larger Work"
|
38 |
+
means a work that combines Covered Software with other material, in
|
39 |
+
a separate file or files, that is not Covered Software.
|
40 |
+
|
41 |
+
1.8. "License"
|
42 |
+
means this document.
|
43 |
+
|
44 |
+
1.9. "Licensable"
|
45 |
+
means having the right to grant, to the maximum extent possible,
|
46 |
+
whether at the time of the initial grant or subsequently, any and
|
47 |
+
all of the rights conveyed by this License.
|
48 |
+
|
49 |
+
1.10. "Modifications"
|
50 |
+
means any of the following:
|
51 |
+
|
52 |
+
(a) any file in Source Code Form that results from an addition to,
|
53 |
+
deletion from, or modification of the contents of Covered
|
54 |
+
Software; or
|
55 |
+
|
56 |
+
(b) any new file in Source Code Form that contains any Covered
|
57 |
+
Software.
|
58 |
+
|
59 |
+
1.11. "Patent Claims" of a Contributor
|
60 |
+
means any patent claim(s), including without limitation, method,
|
61 |
+
process, and apparatus claims, in any patent Licensable by such
|
62 |
+
Contributor that would be infringed, but for the grant of the
|
63 |
+
License, by the making, using, selling, offering for sale, having
|
64 |
+
made, import, or transfer of either its Contributions or its
|
65 |
+
Contributor Version.
|
66 |
+
|
67 |
+
1.12. "Secondary License"
|
68 |
+
means either the GNU General Public License, Version 2.0, the GNU
|
69 |
+
Lesser General Public License, Version 2.1, the GNU Affero General
|
70 |
+
Public License, Version 3.0, or any later versions of those
|
71 |
+
licenses.
|
72 |
+
|
73 |
+
1.13. "Source Code Form"
|
74 |
+
means the form of the work preferred for making modifications.
|
75 |
+
|
76 |
+
1.14. "You" (or "Your")
|
77 |
+
means an individual or a legal entity exercising rights under this
|
78 |
+
License. For legal entities, "You" includes any entity that
|
79 |
+
controls, is controlled by, or is under common control with You. For
|
80 |
+
purposes of this definition, "control" means (a) the power, direct
|
81 |
+
or indirect, to cause the direction or management of such entity,
|
82 |
+
whether by contract or otherwise, or (b) ownership of more than
|
83 |
+
fifty percent (50%) of the outstanding shares or beneficial
|
84 |
+
ownership of such entity.
|
85 |
+
|
86 |
+
2. License Grants and Conditions
|
87 |
+
--------------------------------
|
88 |
+
|
89 |
+
2.1. Grants
|
90 |
+
|
91 |
+
Each Contributor hereby grants You a world-wide, royalty-free,
|
92 |
+
non-exclusive license:
|
93 |
+
|
94 |
+
(a) under intellectual property rights (other than patent or trademark)
|
95 |
+
Licensable by such Contributor to use, reproduce, make available,
|
96 |
+
modify, display, perform, distribute, and otherwise exploit its
|
97 |
+
Contributions, either on an unmodified basis, with Modifications, or
|
98 |
+
as part of a Larger Work; and
|
99 |
+
|
100 |
+
(b) under Patent Claims of such Contributor to make, use, sell, offer
|
101 |
+
for sale, have made, import, and otherwise transfer either its
|
102 |
+
Contributions or its Contributor Version.
|
103 |
+
|
104 |
+
2.2. Effective Date
|
105 |
+
|
106 |
+
The licenses granted in Section 2.1 with respect to any Contribution
|
107 |
+
become effective for each Contribution on the date the Contributor first
|
108 |
+
distributes such Contribution.
|
109 |
+
|
110 |
+
2.3. Limitations on Grant Scope
|
111 |
+
|
112 |
+
The licenses granted in this Section 2 are the only rights granted under
|
113 |
+
this License. No additional rights or licenses will be implied from the
|
114 |
+
distribution or licensing of Covered Software under this License.
|
115 |
+
Notwithstanding Section 2.1(b) above, no patent license is granted by a
|
116 |
+
Contributor:
|
117 |
+
|
118 |
+
(a) for any code that a Contributor has removed from Covered Software;
|
119 |
+
or
|
120 |
+
|
121 |
+
(b) for infringements caused by: (i) Your and any other third party's
|
122 |
+
modifications of Covered Software, or (ii) the combination of its
|
123 |
+
Contributions with other software (except as part of its Contributor
|
124 |
+
Version); or
|
125 |
+
|
126 |
+
(c) under Patent Claims infringed by Covered Software in the absence of
|
127 |
+
its Contributions.
|
128 |
+
|
129 |
+
This License does not grant any rights in the trademarks, service marks,
|
130 |
+
or logos of any Contributor (except as may be necessary to comply with
|
131 |
+
the notice requirements in Section 3.4).
|
132 |
+
|
133 |
+
2.4. Subsequent Licenses
|
134 |
+
|
135 |
+
No Contributor makes additional grants as a result of Your choice to
|
136 |
+
distribute the Covered Software under a subsequent version of this
|
137 |
+
License (see Section 10.2) or under the terms of a Secondary License (if
|
138 |
+
permitted under the terms of Section 3.3).
|
139 |
+
|
140 |
+
2.5. Representation
|
141 |
+
|
142 |
+
Each Contributor represents that the Contributor believes its
|
143 |
+
Contributions are its original creation(s) or it has sufficient rights
|
144 |
+
to grant the rights to its Contributions conveyed by this License.
|
145 |
+
|
146 |
+
2.6. Fair Use
|
147 |
+
|
148 |
+
This License is not intended to limit any rights You have under
|
149 |
+
applicable copyright doctrines of fair use, fair dealing, or other
|
150 |
+
equivalents.
|
151 |
+
|
152 |
+
2.7. Conditions
|
153 |
+
|
154 |
+
Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted
|
155 |
+
in Section 2.1.
|
156 |
+
|
157 |
+
3. Responsibilities
|
158 |
+
-------------------
|
159 |
+
|
160 |
+
3.1. Distribution of Source Form
|
161 |
+
|
162 |
+
All distribution of Covered Software in Source Code Form, including any
|
163 |
+
Modifications that You create or to which You contribute, must be under
|
164 |
+
the terms of this License. You must inform recipients that the Source
|
165 |
+
Code Form of the Covered Software is governed by the terms of this
|
166 |
+
License, and how they can obtain a copy of this License. You may not
|
167 |
+
attempt to alter or restrict the recipients' rights in the Source Code
|
168 |
+
Form.
|
169 |
+
|
170 |
+
3.2. Distribution of Executable Form
|
171 |
+
|
172 |
+
If You distribute Covered Software in Executable Form then:
|
173 |
+
|
174 |
+
(a) such Covered Software must also be made available in Source Code
|
175 |
+
Form, as described in Section 3.1, and You must inform recipients of
|
176 |
+
the Executable Form how they can obtain a copy of such Source Code
|
177 |
+
Form by reasonable means in a timely manner, at a charge no more
|
178 |
+
than the cost of distribution to the recipient; and
|
179 |
+
|
180 |
+
(b) You may distribute such Executable Form under the terms of this
|
181 |
+
License, or sublicense it under different terms, provided that the
|
182 |
+
license for the Executable Form does not attempt to limit or alter
|
183 |
+
the recipients' rights in the Source Code Form under this License.
|
184 |
+
|
185 |
+
3.3. Distribution of a Larger Work
|
186 |
+
|
187 |
+
You may create and distribute a Larger Work under terms of Your choice,
|
188 |
+
provided that You also comply with the requirements of this License for
|
189 |
+
the Covered Software. If the Larger Work is a combination of Covered
|
190 |
+
Software with a work governed by one or more Secondary Licenses, and the
|
191 |
+
Covered Software is not Incompatible With Secondary Licenses, this
|
192 |
+
License permits You to additionally distribute such Covered Software
|
193 |
+
under the terms of such Secondary License(s), so that the recipient of
|
194 |
+
the Larger Work may, at their option, further distribute the Covered
|
195 |
+
Software under the terms of either this License or such Secondary
|
196 |
+
License(s).
|
197 |
+
|
198 |
+
3.4. Notices
|
199 |
+
|
200 |
+
You may not remove or alter the substance of any license notices
|
201 |
+
(including copyright notices, patent notices, disclaimers of warranty,
|
202 |
+
or limitations of liability) contained within the Source Code Form of
|
203 |
+
the Covered Software, except that You may alter any license notices to
|
204 |
+
the extent required to remedy known factual inaccuracies.
|
205 |
+
|
206 |
+
3.5. Application of Additional Terms
|
207 |
+
|
208 |
+
You may choose to offer, and to charge a fee for, warranty, support,
|
209 |
+
indemnity or liability obligations to one or more recipients of Covered
|
210 |
+
Software. However, You may do so only on Your own behalf, and not on
|
211 |
+
behalf of any Contributor. You must make it absolutely clear that any
|
212 |
+
such warranty, support, indemnity, or liability obligation is offered by
|
213 |
+
You alone, and You hereby agree to indemnify every Contributor for any
|
214 |
+
liability incurred by such Contributor as a result of warranty, support,
|
215 |
+
indemnity or liability terms You offer. You may include additional
|
216 |
+
disclaimers of warranty and limitations of liability specific to any
|
217 |
+
jurisdiction.
|
218 |
+
|
219 |
+
4. Inability to Comply Due to Statute or Regulation
|
220 |
+
---------------------------------------------------
|
221 |
+
|
222 |
+
If it is impossible for You to comply with any of the terms of this
|
223 |
+
License with respect to some or all of the Covered Software due to
|
224 |
+
statute, judicial order, or regulation then You must: (a) comply with
|
225 |
+
the terms of this License to the maximum extent possible; and (b)
|
226 |
+
describe the limitations and the code they affect. Such description must
|
227 |
+
be placed in a text file included with all distributions of the Covered
|
228 |
+
Software under this License. Except to the extent prohibited by statute
|
229 |
+
or regulation, such description must be sufficiently detailed for a
|
230 |
+
recipient of ordinary skill to be able to understand it.
|
231 |
+
|
232 |
+
5. Termination
|
233 |
+
--------------
|
234 |
+
|
235 |
+
5.1. The rights granted under this License will terminate automatically
|
236 |
+
if You fail to comply with any of its terms. However, if You become
|
237 |
+
compliant, then the rights granted under this License from a particular
|
238 |
+
Contributor are reinstated (a) provisionally, unless and until such
|
239 |
+
Contributor explicitly and finally terminates Your grants, and (b) on an
|
240 |
+
ongoing basis, if such Contributor fails to notify You of the
|
241 |
+
non-compliance by some reasonable means prior to 60 days after You have
|
242 |
+
come back into compliance. Moreover, Your grants from a particular
|
243 |
+
Contributor are reinstated on an ongoing basis if such Contributor
|
244 |
+
notifies You of the non-compliance by some reasonable means, this is the
|
245 |
+
first time You have received notice of non-compliance with this License
|
246 |
+
from such Contributor, and You become compliant prior to 30 days after
|
247 |
+
Your receipt of the notice.
|
248 |
+
|
249 |
+
5.2. If You initiate litigation against any entity by asserting a patent
|
250 |
+
infringement claim (excluding declaratory judgment actions,
|
251 |
+
counter-claims, and cross-claims) alleging that a Contributor Version
|
252 |
+
directly or indirectly infringes any patent, then the rights granted to
|
253 |
+
You by any and all Contributors for the Covered Software under Section
|
254 |
+
2.1 of this License shall terminate.
|
255 |
+
|
256 |
+
5.3. In the event of termination under Sections 5.1 or 5.2 above, all
|
257 |
+
end user license agreements (excluding distributors and resellers) which
|
258 |
+
have been validly granted by You or Your distributors under this License
|
259 |
+
prior to termination shall survive termination.
|
260 |
+
|
261 |
+
************************************************************************
|
262 |
+
* *
|
263 |
+
* 6. Disclaimer of Warranty *
|
264 |
+
* ------------------------- *
|
265 |
+
* *
|
266 |
+
* Covered Software is provided under this License on an "as is" *
|
267 |
+
* basis, without warranty of any kind, either expressed, implied, or *
|
268 |
+
* statutory, including, without limitation, warranties that the *
|
269 |
+
* Covered Software is free of defects, merchantable, fit for a *
|
270 |
+
* particular purpose or non-infringing. The entire risk as to the *
|
271 |
+
* quality and performance of the Covered Software is with You. *
|
272 |
+
* Should any Covered Software prove defective in any respect, You *
|
273 |
+
* (not any Contributor) assume the cost of any necessary servicing, *
|
274 |
+
* repair, or correction. This disclaimer of warranty constitutes an *
|
275 |
+
* essential part of this License. No use of any Covered Software is *
|
276 |
+
* authorized under this License except under this disclaimer. *
|
277 |
+
* *
|
278 |
+
************************************************************************
|
279 |
+
|
280 |
+
************************************************************************
|
281 |
+
* *
|
282 |
+
* 7. Limitation of Liability *
|
283 |
+
* -------------------------- *
|
284 |
+
* *
|
285 |
+
* Under no circumstances and under no legal theory, whether tort *
|
286 |
+
* (including negligence), contract, or otherwise, shall any *
|
287 |
+
* Contributor, or anyone who distributes Covered Software as *
|
288 |
+
* permitted above, be liable to You for any direct, indirect, *
|
289 |
+
* special, incidental, or consequential damages of any character *
|
290 |
+
* including, without limitation, damages for lost profits, loss of *
|
291 |
+
* goodwill, work stoppage, computer failure or malfunction, or any *
|
292 |
+
* and all other commercial damages or losses, even if such party *
|
293 |
+
* shall have been informed of the possibility of such damages. This *
|
294 |
+
* limitation of liability shall not apply to liability for death or *
|
295 |
+
* personal injury resulting from such party's negligence to the *
|
296 |
+
* extent applicable law prohibits such limitation. Some *
|
297 |
+
* jurisdictions do not allow the exclusion or limitation of *
|
298 |
+
* incidental or consequential damages, so this exclusion and *
|
299 |
+
* limitation may not apply to You. *
|
300 |
+
* *
|
301 |
+
************************************************************************
|
302 |
+
|
303 |
+
8. Litigation
|
304 |
+
-------------
|
305 |
+
|
306 |
+
Any litigation relating to this License may be brought only in the
|
307 |
+
courts of a jurisdiction where the defendant maintains its principal
|
308 |
+
place of business and such litigation shall be governed by laws of that
|
309 |
+
jurisdiction, without reference to its conflict-of-law provisions.
|
310 |
+
Nothing in this Section shall prevent a party's ability to bring
|
311 |
+
cross-claims or counter-claims.
|
312 |
+
|
313 |
+
9. Miscellaneous
|
314 |
+
----------------
|
315 |
+
|
316 |
+
This License represents the complete agreement concerning the subject
|
317 |
+
matter hereof. If any provision of this License is held to be
|
318 |
+
unenforceable, such provision shall be reformed only to the extent
|
319 |
+
necessary to make it enforceable. Any law or regulation which provides
|
320 |
+
that the language of a contract shall be construed against the drafter
|
321 |
+
shall not be used to construe this License against a Contributor.
|
322 |
+
|
323 |
+
10. Versions of the License
|
324 |
+
---------------------------
|
325 |
+
|
326 |
+
10.1. New Versions
|
327 |
+
|
328 |
+
Mozilla Foundation is the license steward. Except as provided in Section
|
329 |
+
10.3, no one other than the license steward has the right to modify or
|
330 |
+
publish new versions of this License. Each version will be given a
|
331 |
+
distinguishing version number.
|
332 |
+
|
333 |
+
10.2. Effect of New Versions
|
334 |
+
|
335 |
+
You may distribute the Covered Software under the terms of the version
|
336 |
+
of the License under which You originally received the Covered Software,
|
337 |
+
or under the terms of any subsequent version published by the license
|
338 |
+
steward.
|
339 |
+
|
340 |
+
10.3. Modified Versions
|
341 |
+
|
342 |
+
If you create software not governed by this License, and you want to
|
343 |
+
create a new license for such software, you may create and use a
|
344 |
+
modified version of this License if you rename the license and remove
|
345 |
+
any references to the name of the license steward (except to note that
|
346 |
+
such modified license differs from this License).
|
347 |
+
|
348 |
+
10.4. Distributing Source Code Form that is Incompatible With Secondary
|
349 |
+
Licenses
|
350 |
+
|
351 |
+
If You choose to distribute Source Code Form that is Incompatible With
|
352 |
+
Secondary Licenses under the terms of this version of the License, the
|
353 |
+
notice described in Exhibit B of this License must be attached.
|
354 |
+
|
355 |
+
Exhibit A - Source Code Form License Notice
|
356 |
+
-------------------------------------------
|
357 |
+
|
358 |
+
This Source Code Form is subject to the terms of the Mozilla Public
|
359 |
+
License, v. 2.0. If a copy of the MPL was not distributed with this
|
360 |
+
file, You can obtain one at http://mozilla.org/MPL/2.0/.
|
361 |
+
|
362 |
+
If it is not possible or desirable to put the notice in a particular
|
363 |
+
file, then You may include the notice in a location (such as a LICENSE
|
364 |
+
file in a relevant directory) where a recipient would be likely to look
|
365 |
+
for such a notice.
|
366 |
+
|
367 |
+
You may add additional accurate notices of copyright ownership.
|
368 |
+
|
369 |
+
Exhibit B - "Incompatible With Secondary Licenses" Notice
|
370 |
+
---------------------------------------------------------
|
371 |
+
|
372 |
+
This Source Code Form is "Incompatible With Secondary Licenses", as
|
373 |
+
defined by the Mozilla Public License, v. 2.0.
|
arch.png
ADDED
demo.ipynb
ADDED
The diff for this file is too large to render.
See raw diff
|
|
setup.py
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
from setuptools import setup, find_packages
|
2 |
+
|
3 |
+
setup(name='ttts', version='0.1', packages=find_packages())
|
ttts-src/.gitignore
ADDED
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
ttts/datasets/*
|
2 |
+
*/**/*.pt
|
3 |
+
*/**/*.pyc
|
4 |
+
*/**/logs/*
|
5 |
+
*/**/*.txt
|
6 |
+
*/**/*.jsonl
|
7 |
+
*/**/*.m4a
|
8 |
+
ttts.egg-info/*
|
9 |
+
.vscode/*
|
10 |
+
damo/*
|
11 |
+
.cache/*
|
12 |
+
*/**/*.wav
|
13 |
+
*/**/*.mp3
|
14 |
+
ast_indexer
|
15 |
+
!3.wav
|
ttts.egg-info/PKG-INFO
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
Metadata-Version: 2.1
|
2 |
+
Name: ttts
|
3 |
+
Version: 0.1
|
ttts.egg-info/SOURCES.txt
ADDED
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
setup.py
|
2 |
+
ttts.egg-info/PKG-INFO
|
3 |
+
ttts.egg-info/SOURCES.txt
|
4 |
+
ttts.egg-info/dependency_links.txt
|
5 |
+
ttts.egg-info/top_level.txt
|
ttts.egg-info/dependency_links.txt
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
|
ttts.egg-info/top_level.txt
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
|
ttts/0.wav
ADDED
Binary file (443 kB). View file
|
|
ttts/3.wav
ADDED
Binary file (204 kB). View file
|
|
ttts/AA_diffusion_deprecated/cldm/cldm.py
ADDED
@@ -0,0 +1,875 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import einops
|
2 |
+
import torch
|
3 |
+
import torch as th
|
4 |
+
import torch.nn as nn
|
5 |
+
|
6 |
+
from ldm.modules.diffusionmodules.util import (
|
7 |
+
conv_nd,
|
8 |
+
linear,
|
9 |
+
normalization,
|
10 |
+
zero_module,
|
11 |
+
timestep_embedding,
|
12 |
+
)
|
13 |
+
|
14 |
+
from einops import rearrange, repeat
|
15 |
+
from torchvision.utils import make_grid
|
16 |
+
from ldm.modules.attention import SpatialTransformer
|
17 |
+
from ldm.modules.diffusionmodules.openaimodel import UNetModel, TimestepEmbedSequential, ResBlock, Downsample, AttentionBlock, Upsample, convert_module_to_f16, convert_module_to_f32
|
18 |
+
from ldm.models.diffusion.ddpm import LatentDiffusion
|
19 |
+
from ldm.util import log_txt_as_img, exists, instantiate_from_config
|
20 |
+
from ldm.models.diffusion.ddim import DDIMSampler
|
21 |
+
|
22 |
+
|
23 |
+
class ControlledUnetModel(nn.Module):
|
24 |
+
"""
|
25 |
+
The full UNet model with attention and timestep embedding.
|
26 |
+
:param in_channels: channels in the input Tensor.
|
27 |
+
:param model_channels: base channel count for the model.
|
28 |
+
:param out_channels: channels in the output Tensor.
|
29 |
+
:param num_res_blocks: number of residual blocks per downsample.
|
30 |
+
:param attention_resolutions: a collection of downsample rates at which
|
31 |
+
attention will take place. May be a set, list, or tuple.
|
32 |
+
For example, if this contains 4, then at 4x downsampling, attention
|
33 |
+
will be used.
|
34 |
+
:param dropout: the dropout probability.
|
35 |
+
:param channel_mult: channel multiplier for each level of the UNet.
|
36 |
+
:param conv_resample: if True, use learned convolutions for upsampling and
|
37 |
+
downsampling.
|
38 |
+
:param dims: determines if the signal is 1D, 2D, or 3D.
|
39 |
+
:param num_classes: if specified (as an int), then this model will be
|
40 |
+
class-conditional with `num_classes` classes.
|
41 |
+
:param use_checkpoint: use gradient checkpointing to reduce memory usage.
|
42 |
+
:param num_heads: the number of attention heads in each attention layer.
|
43 |
+
:param num_heads_channels: if specified, ignore num_heads and instead use
|
44 |
+
a fixed channel width per attention head.
|
45 |
+
:param num_heads_upsample: works with num_heads to set a different number
|
46 |
+
of heads for upsampling. Deprecated.
|
47 |
+
:param use_scale_shift_norm: use a FiLM-like conditioning mechanism.
|
48 |
+
:param resblock_updown: use residual blocks for up/downsampling.
|
49 |
+
:param use_new_attention_order: use a different attention pattern for potentially
|
50 |
+
increased efficiency.
|
51 |
+
"""
|
52 |
+
|
53 |
+
def __init__(
|
54 |
+
self,
|
55 |
+
hint_in_channels,
|
56 |
+
hint_out_channels,
|
57 |
+
image_size,
|
58 |
+
in_channels,
|
59 |
+
model_channels,
|
60 |
+
out_channels,
|
61 |
+
num_res_blocks,
|
62 |
+
attention_resolutions,
|
63 |
+
dropout=0,
|
64 |
+
channel_mult=(1, 2, 4, 8),
|
65 |
+
conv_resample=True,
|
66 |
+
dims=1,
|
67 |
+
num_classes=None,
|
68 |
+
use_checkpoint=False,
|
69 |
+
use_fp16=False,
|
70 |
+
num_heads=-1,
|
71 |
+
num_head_channels=-1,
|
72 |
+
num_heads_upsample=-1,
|
73 |
+
use_scale_shift_norm=False,
|
74 |
+
resblock_updown=False,
|
75 |
+
use_new_attention_order=False,
|
76 |
+
use_spatial_transformer=False, # custom transformer support
|
77 |
+
transformer_depth=1, # custom transformer support
|
78 |
+
context_dim=None, # custom transformer support
|
79 |
+
n_embed=None, # custom support for prediction of discrete ids into codebook of first stage vq model
|
80 |
+
legacy=True,
|
81 |
+
disable_self_attentions=None,
|
82 |
+
num_attention_blocks=None,
|
83 |
+
disable_middle_self_attn=False,
|
84 |
+
use_linear_in_transformer=False,
|
85 |
+
):
|
86 |
+
super().__init__()
|
87 |
+
if use_spatial_transformer:
|
88 |
+
assert context_dim is not None, 'Fool!! You forgot to include the dimension of your cross-attention conditioning...'
|
89 |
+
|
90 |
+
if context_dim is not None:
|
91 |
+
assert use_spatial_transformer, 'Fool!! You forgot to use the spatial transformer for your cross-attention conditioning...'
|
92 |
+
from omegaconf.listconfig import ListConfig
|
93 |
+
if type(context_dim) == ListConfig:
|
94 |
+
context_dim = list(context_dim)
|
95 |
+
|
96 |
+
if num_heads_upsample == -1:
|
97 |
+
num_heads_upsample = num_heads
|
98 |
+
|
99 |
+
if num_heads == -1:
|
100 |
+
assert num_head_channels != -1, 'Either num_heads or num_head_channels has to be set'
|
101 |
+
|
102 |
+
if num_head_channels == -1:
|
103 |
+
assert num_heads != -1, 'Either num_heads or num_head_channels has to be set'
|
104 |
+
|
105 |
+
self.image_size = image_size
|
106 |
+
self.in_channels = in_channels
|
107 |
+
self.model_channels = model_channels
|
108 |
+
self.out_channels = out_channels
|
109 |
+
if isinstance(num_res_blocks, int):
|
110 |
+
self.num_res_blocks = len(channel_mult) * [num_res_blocks]
|
111 |
+
else:
|
112 |
+
if len(num_res_blocks) != len(channel_mult):
|
113 |
+
raise ValueError("provide num_res_blocks either as an int (globally constant) or "
|
114 |
+
"as a list/tuple (per-level) with the same length as channel_mult")
|
115 |
+
self.num_res_blocks = num_res_blocks
|
116 |
+
if disable_self_attentions is not None:
|
117 |
+
# should be a list of booleans, indicating whether to disable self-attention in TransformerBlocks or not
|
118 |
+
assert len(disable_self_attentions) == len(channel_mult)
|
119 |
+
if num_attention_blocks is not None:
|
120 |
+
assert len(num_attention_blocks) == len(self.num_res_blocks)
|
121 |
+
assert all(map(lambda i: self.num_res_blocks[i] >= num_attention_blocks[i], range(len(num_attention_blocks))))
|
122 |
+
print(f"Constructor of UNetModel received num_attention_blocks={num_attention_blocks}. "
|
123 |
+
f"This option has LESS priority than attention_resolutions {attention_resolutions}, "
|
124 |
+
f"i.e., in cases where num_attention_blocks[i] > 0 but 2**i not in attention_resolutions, "
|
125 |
+
f"attention will still not be set.")
|
126 |
+
|
127 |
+
self.attention_resolutions = attention_resolutions
|
128 |
+
self.dropout = dropout
|
129 |
+
self.channel_mult = channel_mult
|
130 |
+
self.conv_resample = conv_resample
|
131 |
+
self.num_classes = num_classes
|
132 |
+
self.use_checkpoint = use_checkpoint
|
133 |
+
self.dtype = th.float16 if use_fp16 else th.float32
|
134 |
+
self.num_heads = num_heads
|
135 |
+
self.num_head_channels = num_head_channels
|
136 |
+
self.num_heads_upsample = num_heads_upsample
|
137 |
+
self.predict_codebook_ids = n_embed is not None
|
138 |
+
|
139 |
+
time_embed_dim = model_channels * 4
|
140 |
+
self.time_embed = nn.Sequential(
|
141 |
+
linear(model_channels, time_embed_dim),
|
142 |
+
nn.SiLU(),
|
143 |
+
linear(time_embed_dim, time_embed_dim),
|
144 |
+
)
|
145 |
+
|
146 |
+
if self.num_classes is not None:
|
147 |
+
if isinstance(self.num_classes, int):
|
148 |
+
self.label_emb = nn.Embedding(num_classes, time_embed_dim)
|
149 |
+
elif self.num_classes == "continuous":
|
150 |
+
print("setting up linear c_adm embedding layer")
|
151 |
+
self.label_emb = nn.Linear(1, time_embed_dim)
|
152 |
+
else:
|
153 |
+
raise ValueError()
|
154 |
+
|
155 |
+
self.input_blocks = nn.ModuleList(
|
156 |
+
[
|
157 |
+
TimestepEmbedSequential(
|
158 |
+
conv_nd(dims, in_channels, model_channels, 3, padding=1)
|
159 |
+
)
|
160 |
+
]
|
161 |
+
)
|
162 |
+
self._feature_size = model_channels
|
163 |
+
input_block_chans = [model_channels]
|
164 |
+
ch = model_channels
|
165 |
+
ds = 1
|
166 |
+
for level, mult in enumerate(channel_mult):
|
167 |
+
for nr in range(self.num_res_blocks[level]):
|
168 |
+
layers = [
|
169 |
+
ResBlock(
|
170 |
+
ch,
|
171 |
+
time_embed_dim,
|
172 |
+
dropout,
|
173 |
+
out_channels=mult * model_channels,
|
174 |
+
dims=dims,
|
175 |
+
use_checkpoint=use_checkpoint,
|
176 |
+
use_scale_shift_norm=use_scale_shift_norm,
|
177 |
+
)
|
178 |
+
]
|
179 |
+
ch = mult * model_channels
|
180 |
+
if ds in attention_resolutions:
|
181 |
+
if num_head_channels == -1:
|
182 |
+
dim_head = ch // num_heads
|
183 |
+
else:
|
184 |
+
num_heads = ch // num_head_channels
|
185 |
+
dim_head = num_head_channels
|
186 |
+
if legacy:
|
187 |
+
#num_heads = 1
|
188 |
+
dim_head = ch // num_heads if use_spatial_transformer else num_head_channels
|
189 |
+
if exists(disable_self_attentions):
|
190 |
+
disabled_sa = disable_self_attentions[level]
|
191 |
+
else:
|
192 |
+
disabled_sa = False
|
193 |
+
|
194 |
+
if not exists(num_attention_blocks) or nr < num_attention_blocks[level]:
|
195 |
+
layers.append(
|
196 |
+
AttentionBlock(
|
197 |
+
ch,
|
198 |
+
use_checkpoint=use_checkpoint,
|
199 |
+
num_heads=num_heads,
|
200 |
+
num_head_channels=dim_head,
|
201 |
+
use_new_attention_order=use_new_attention_order,
|
202 |
+
) if not use_spatial_transformer else SpatialTransformer(
|
203 |
+
ch, num_heads, dim_head, depth=transformer_depth, context_dim=context_dim,
|
204 |
+
disable_self_attn=disabled_sa, use_linear=use_linear_in_transformer,
|
205 |
+
use_checkpoint=use_checkpoint
|
206 |
+
)
|
207 |
+
)
|
208 |
+
self.input_blocks.append(TimestepEmbedSequential(*layers))
|
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 |
+
)
|
225 |
+
if resblock_updown
|
226 |
+
else Downsample(
|
227 |
+
ch, conv_resample, dims=dims, out_channels=out_ch
|
228 |
+
)
|
229 |
+
)
|
230 |
+
)
|
231 |
+
ch = out_ch
|
232 |
+
input_block_chans.append(ch)
|
233 |
+
ds *= 2
|
234 |
+
self._feature_size += ch
|
235 |
+
|
236 |
+
if num_head_channels == -1:
|
237 |
+
dim_head = ch // num_heads
|
238 |
+
else:
|
239 |
+
num_heads = ch // num_head_channels
|
240 |
+
dim_head = num_head_channels
|
241 |
+
if legacy:
|
242 |
+
#num_heads = 1
|
243 |
+
dim_head = ch // num_heads if use_spatial_transformer else num_head_channels
|
244 |
+
self.middle_block = TimestepEmbedSequential(
|
245 |
+
ResBlock(
|
246 |
+
ch,
|
247 |
+
time_embed_dim,
|
248 |
+
dropout,
|
249 |
+
dims=dims,
|
250 |
+
use_checkpoint=use_checkpoint,
|
251 |
+
use_scale_shift_norm=use_scale_shift_norm,
|
252 |
+
),
|
253 |
+
AttentionBlock(
|
254 |
+
ch,
|
255 |
+
use_checkpoint=use_checkpoint,
|
256 |
+
num_heads=num_heads,
|
257 |
+
num_head_channels=dim_head,
|
258 |
+
use_new_attention_order=use_new_attention_order,
|
259 |
+
) if not use_spatial_transformer else SpatialTransformer( # always uses a self-attn
|
260 |
+
ch, num_heads, dim_head, depth=transformer_depth, context_dim=context_dim,
|
261 |
+
disable_self_attn=disable_middle_self_attn, use_linear=use_linear_in_transformer,
|
262 |
+
use_checkpoint=use_checkpoint
|
263 |
+
),
|
264 |
+
ResBlock(
|
265 |
+
ch,
|
266 |
+
time_embed_dim,
|
267 |
+
dropout,
|
268 |
+
dims=dims,
|
269 |
+
use_checkpoint=use_checkpoint,
|
270 |
+
use_scale_shift_norm=use_scale_shift_norm,
|
271 |
+
),
|
272 |
+
)
|
273 |
+
self._feature_size += ch
|
274 |
+
|
275 |
+
self.output_blocks = nn.ModuleList([])
|
276 |
+
for level, mult in list(enumerate(channel_mult))[::-1]:
|
277 |
+
for i in range(self.num_res_blocks[level] + 1):
|
278 |
+
ich = input_block_chans.pop()
|
279 |
+
layers = [
|
280 |
+
ResBlock(
|
281 |
+
# ch + ich,
|
282 |
+
ch,
|
283 |
+
time_embed_dim,
|
284 |
+
dropout,
|
285 |
+
out_channels=model_channels * mult,
|
286 |
+
dims=dims,
|
287 |
+
use_checkpoint=use_checkpoint,
|
288 |
+
use_scale_shift_norm=use_scale_shift_norm,
|
289 |
+
)
|
290 |
+
]
|
291 |
+
ch = model_channels * mult
|
292 |
+
if ds in attention_resolutions:
|
293 |
+
if num_head_channels == -1:
|
294 |
+
dim_head = ch // num_heads
|
295 |
+
else:
|
296 |
+
num_heads = ch // num_head_channels
|
297 |
+
dim_head = num_head_channels
|
298 |
+
if legacy:
|
299 |
+
#num_heads = 1
|
300 |
+
dim_head = ch // num_heads if use_spatial_transformer else num_head_channels
|
301 |
+
if exists(disable_self_attentions):
|
302 |
+
disabled_sa = disable_self_attentions[level]
|
303 |
+
else:
|
304 |
+
disabled_sa = False
|
305 |
+
|
306 |
+
if not exists(num_attention_blocks) or i < num_attention_blocks[level]:
|
307 |
+
layers.append(
|
308 |
+
AttentionBlock(
|
309 |
+
ch,
|
310 |
+
use_checkpoint=use_checkpoint,
|
311 |
+
num_heads=num_heads_upsample,
|
312 |
+
num_head_channels=dim_head,
|
313 |
+
use_new_attention_order=use_new_attention_order,
|
314 |
+
) if not use_spatial_transformer else SpatialTransformer(
|
315 |
+
ch, num_heads, dim_head, depth=transformer_depth, context_dim=context_dim,
|
316 |
+
disable_self_attn=disabled_sa, use_linear=use_linear_in_transformer,
|
317 |
+
use_checkpoint=use_checkpoint
|
318 |
+
)
|
319 |
+
)
|
320 |
+
if level and i == self.num_res_blocks[level]:
|
321 |
+
out_ch = ch
|
322 |
+
layers.append(
|
323 |
+
ResBlock(
|
324 |
+
ch,
|
325 |
+
time_embed_dim,
|
326 |
+
dropout,
|
327 |
+
out_channels=out_ch,
|
328 |
+
dims=dims,
|
329 |
+
use_checkpoint=use_checkpoint,
|
330 |
+
use_scale_shift_norm=use_scale_shift_norm,
|
331 |
+
# up=True,
|
332 |
+
)
|
333 |
+
if resblock_updown
|
334 |
+
else Upsample(ch, conv_resample, dims=dims, out_channels=out_ch)
|
335 |
+
)
|
336 |
+
ds //= 2
|
337 |
+
self.output_blocks.append(TimestepEmbedSequential(*layers))
|
338 |
+
self._feature_size += ch
|
339 |
+
|
340 |
+
self.out = nn.Sequential(
|
341 |
+
normalization(ch),
|
342 |
+
nn.SiLU(),
|
343 |
+
zero_module(conv_nd(dims, model_channels, out_channels, 3, padding=1)),
|
344 |
+
)
|
345 |
+
if self.predict_codebook_ids:
|
346 |
+
self.id_predictor = nn.Sequential(
|
347 |
+
normalization(ch),
|
348 |
+
conv_nd(dims, model_channels, n_embed, 1),
|
349 |
+
#nn.LogSoftmax(dim=1) # change to cross_entropy and produce non-normalized logits
|
350 |
+
)
|
351 |
+
# self.input_hint_block = TimestepEmbedSequential(
|
352 |
+
# conv_nd(dims, hint_in_channels, 128, 3, padding=1),
|
353 |
+
# nn.SiLU(),
|
354 |
+
# conv_nd(dims, 128, 128, 3, padding=1),
|
355 |
+
# nn.SiLU(),
|
356 |
+
# conv_nd(dims, 128, 256, 3, padding=1),
|
357 |
+
# nn.SiLU(),
|
358 |
+
# conv_nd(dims, 256, 256, 3, padding=1),
|
359 |
+
# nn.SiLU(),
|
360 |
+
# zero_module(conv_nd(dims, 256, hint_out_channels, 3, padding=1))
|
361 |
+
# )
|
362 |
+
self.context_proj = nn.Linear(context_dim, 2*model_channels)
|
363 |
+
self.hint_converter = TimestepEmbedSequential(
|
364 |
+
SpatialTransformer(
|
365 |
+
model_channels, num_heads, dim_head, depth=transformer_depth, context_dim=context_dim,
|
366 |
+
disable_self_attn=disabled_sa, use_linear=use_linear_in_transformer,
|
367 |
+
use_checkpoint=use_checkpoint
|
368 |
+
),
|
369 |
+
SpatialTransformer(
|
370 |
+
model_channels, num_heads, dim_head, depth=transformer_depth, context_dim=context_dim,
|
371 |
+
disable_self_attn=disabled_sa, use_linear=use_linear_in_transformer,
|
372 |
+
use_checkpoint=use_checkpoint
|
373 |
+
),
|
374 |
+
SpatialTransformer(
|
375 |
+
model_channels, num_heads, dim_head, depth=transformer_depth, context_dim=context_dim,
|
376 |
+
disable_self_attn=disabled_sa, use_linear=use_linear_in_transformer,
|
377 |
+
use_checkpoint=use_checkpoint
|
378 |
+
)
|
379 |
+
)
|
380 |
+
|
381 |
+
def convert_to_fp16(self):
|
382 |
+
"""
|
383 |
+
Convert the torso of the model to float16.
|
384 |
+
"""
|
385 |
+
self.input_blocks.apply(convert_module_to_f16)
|
386 |
+
self.middle_block.apply(convert_module_to_f16)
|
387 |
+
self.output_blocks.apply(convert_module_to_f16)
|
388 |
+
|
389 |
+
def convert_to_fp32(self):
|
390 |
+
"""
|
391 |
+
Convert the torso of the model to float32.
|
392 |
+
"""
|
393 |
+
self.input_blocks.apply(convert_module_to_f32)
|
394 |
+
self.middle_block.apply(convert_module_to_f32)
|
395 |
+
self.output_blocks.apply(convert_module_to_f32)
|
396 |
+
|
397 |
+
def forward(self, x, hint, timesteps=None, context=None, control=None, only_mid_control=False, **kwargs):
|
398 |
+
hs = []
|
399 |
+
t_emb = timestep_embedding(timesteps, self.model_channels, repeat_only=False)
|
400 |
+
emb = self.time_embed(t_emb)
|
401 |
+
# guided_hint = self.input_hint_block(hint, emb, context)
|
402 |
+
hint = self.hint_converter(hint)
|
403 |
+
context = self.context_proj(context).unsqueeze(-1)
|
404 |
+
scale, shift = torch.chunk(context, 2, dim = 1)
|
405 |
+
hint = hint*(1+scale)+shift
|
406 |
+
h = x.type(self.dtype)
|
407 |
+
flag=0
|
408 |
+
for module in self.input_blocks:
|
409 |
+
if flag==0:
|
410 |
+
# h = module(h, emb, context, control.pop(0))
|
411 |
+
# h = module(h, emb, context)
|
412 |
+
h = module(h, emb)
|
413 |
+
h += hint
|
414 |
+
flag=1
|
415 |
+
else:
|
416 |
+
# h = module(h, emb, context, control.pop(0))
|
417 |
+
# h = module(h, emb, context)
|
418 |
+
h = module(h, emb)
|
419 |
+
hs.append(h)
|
420 |
+
# h = self.middle_block(h, emb, context, control.pop(0))
|
421 |
+
# h = self.middle_block(h, emb, context)
|
422 |
+
h = self.middle_block(h, emb)
|
423 |
+
|
424 |
+
for i, module in enumerate(self.output_blocks):
|
425 |
+
# h = torch.cat([h, hs.pop()], dim=1)
|
426 |
+
# h = module(h, emb, context, control.pop(0))
|
427 |
+
# h = module(h, emb, context)
|
428 |
+
h = module(h, emb)
|
429 |
+
|
430 |
+
h = h.type(x.dtype)
|
431 |
+
return self.out(h)
|
432 |
+
|
433 |
+
class ReferenceNet(ControlledUnetModel):
|
434 |
+
def forward(self, x, timesteps=None, context=None, only_mid_control=False, **kwargs):
|
435 |
+
hs = []
|
436 |
+
control = []
|
437 |
+
t_emb = timestep_embedding(timesteps, self.model_channels, repeat_only=False)
|
438 |
+
emb = self.time_embed(t_emb)
|
439 |
+
h = x.type(self.dtype)
|
440 |
+
for module in self.input_blocks:
|
441 |
+
h,refer = module(h, emb, context,return_refer=True)
|
442 |
+
hs.append(h)
|
443 |
+
control.append(refer)
|
444 |
+
h,refer = self.middle_block(h, emb, context,return_refer=True)
|
445 |
+
control.append(refer)
|
446 |
+
|
447 |
+
for i, module in enumerate(self.output_blocks):
|
448 |
+
h = torch.cat([h, hs.pop()], dim=1)
|
449 |
+
h,refer = module(h, emb, context, return_refer=True)
|
450 |
+
control.append(refer)
|
451 |
+
h = h.type(x.dtype)
|
452 |
+
# h = self.out(h)
|
453 |
+
return control
|
454 |
+
|
455 |
+
class ControlNet(nn.Module):
|
456 |
+
def __init__(
|
457 |
+
self,
|
458 |
+
image_size,
|
459 |
+
in_channels,
|
460 |
+
model_channels,
|
461 |
+
hint_channels,
|
462 |
+
num_res_blocks,
|
463 |
+
attention_resolutions,
|
464 |
+
dropout=0,
|
465 |
+
channel_mult=(1, 2, 4, 8),
|
466 |
+
conv_resample=True,
|
467 |
+
dims=1,
|
468 |
+
use_checkpoint=False,
|
469 |
+
use_fp16=False,
|
470 |
+
num_heads=-1,
|
471 |
+
num_head_channels=-1,
|
472 |
+
num_heads_upsample=-1,
|
473 |
+
use_scale_shift_norm=False,
|
474 |
+
resblock_updown=False,
|
475 |
+
use_new_attention_order=False,
|
476 |
+
use_spatial_transformer=False, # custom transformer support
|
477 |
+
transformer_depth=1, # custom transformer support
|
478 |
+
context_dim=None, # custom transformer support
|
479 |
+
n_embed=None, # custom support for prediction of discrete ids into codebook of first stage vq model
|
480 |
+
legacy=True,
|
481 |
+
disable_self_attentions=None,
|
482 |
+
num_attention_blocks=None,
|
483 |
+
disable_middle_self_attn=False,
|
484 |
+
use_linear_in_transformer=False,
|
485 |
+
):
|
486 |
+
super().__init__()
|
487 |
+
if use_spatial_transformer:
|
488 |
+
assert context_dim is not None, 'Fool!! You forgot to include the dimension of your cross-attention conditioning...'
|
489 |
+
|
490 |
+
if context_dim is not None:
|
491 |
+
assert use_spatial_transformer, 'Fool!! You forgot to use the spatial transformer for your cross-attention conditioning...'
|
492 |
+
from omegaconf.listconfig import ListConfig
|
493 |
+
if type(context_dim) == ListConfig:
|
494 |
+
context_dim = list(context_dim)
|
495 |
+
|
496 |
+
if num_heads_upsample == -1:
|
497 |
+
num_heads_upsample = num_heads
|
498 |
+
|
499 |
+
if num_heads == -1:
|
500 |
+
assert num_head_channels != -1, 'Either num_heads or num_head_channels has to be set'
|
501 |
+
|
502 |
+
if num_head_channels == -1:
|
503 |
+
assert num_heads != -1, 'Either num_heads or num_head_channels has to be set'
|
504 |
+
|
505 |
+
self.dims = dims
|
506 |
+
self.image_size = image_size
|
507 |
+
self.in_channels = in_channels
|
508 |
+
self.model_channels = model_channels
|
509 |
+
if isinstance(num_res_blocks, int):
|
510 |
+
self.num_res_blocks = len(channel_mult) * [num_res_blocks]
|
511 |
+
else:
|
512 |
+
if len(num_res_blocks) != len(channel_mult):
|
513 |
+
raise ValueError("provide num_res_blocks either as an int (globally constant) or "
|
514 |
+
"as a list/tuple (per-level) with the same length as channel_mult")
|
515 |
+
self.num_res_blocks = num_res_blocks
|
516 |
+
if disable_self_attentions is not None:
|
517 |
+
# should be a list of booleans, indicating whether to disable self-attention in TransformerBlocks or not
|
518 |
+
assert len(disable_self_attentions) == len(channel_mult)
|
519 |
+
if num_attention_blocks is not None:
|
520 |
+
assert len(num_attention_blocks) == len(self.num_res_blocks)
|
521 |
+
assert all(map(lambda i: self.num_res_blocks[i] >= num_attention_blocks[i], range(len(num_attention_blocks))))
|
522 |
+
print(f"Constructor of UNetModel received num_attention_blocks={num_attention_blocks}. "
|
523 |
+
f"This option has LESS priority than attention_resolutions {attention_resolutions}, "
|
524 |
+
f"i.e., in cases where num_attention_blocks[i] > 0 but 2**i not in attention_resolutions, "
|
525 |
+
f"attention will still not be set.")
|
526 |
+
|
527 |
+
self.attention_resolutions = attention_resolutions
|
528 |
+
self.dropout = dropout
|
529 |
+
self.channel_mult = channel_mult
|
530 |
+
self.conv_resample = conv_resample
|
531 |
+
self.use_checkpoint = use_checkpoint
|
532 |
+
self.dtype = th.float16 if use_fp16 else th.float32
|
533 |
+
self.num_heads = num_heads
|
534 |
+
self.num_head_channels = num_head_channels
|
535 |
+
self.num_heads_upsample = num_heads_upsample
|
536 |
+
self.predict_codebook_ids = n_embed is not None
|
537 |
+
|
538 |
+
time_embed_dim = model_channels * 4
|
539 |
+
self.time_embed = nn.Sequential(
|
540 |
+
linear(model_channels, time_embed_dim),
|
541 |
+
nn.SiLU(),
|
542 |
+
linear(time_embed_dim, time_embed_dim),
|
543 |
+
)
|
544 |
+
|
545 |
+
self.input_blocks = nn.ModuleList(
|
546 |
+
[
|
547 |
+
TimestepEmbedSequential(
|
548 |
+
conv_nd(dims, in_channels, model_channels, 3, padding=1)
|
549 |
+
)
|
550 |
+
]
|
551 |
+
)
|
552 |
+
self.zero_convs = nn.ModuleList([self.make_zero_conv(model_channels)])
|
553 |
+
|
554 |
+
self.input_hint_block = TimestepEmbedSequential(
|
555 |
+
conv_nd(dims, hint_channels, 16, 3, padding=1),
|
556 |
+
nn.SiLU(),
|
557 |
+
conv_nd(dims, 16, 16, 3, padding=1),
|
558 |
+
nn.SiLU(),
|
559 |
+
conv_nd(dims, 16, 32, 3, padding=1),
|
560 |
+
nn.SiLU(),
|
561 |
+
conv_nd(dims, 32, 32, 3, padding=1),
|
562 |
+
nn.SiLU(),
|
563 |
+
conv_nd(dims, 32, 96, 3, padding=1),
|
564 |
+
nn.SiLU(),
|
565 |
+
conv_nd(dims, 96, 96, 3, padding=1),
|
566 |
+
nn.SiLU(),
|
567 |
+
conv_nd(dims, 96, 256, 3, padding=1),
|
568 |
+
nn.SiLU(),
|
569 |
+
zero_module(conv_nd(dims, 256, model_channels, 3, padding=1))
|
570 |
+
)
|
571 |
+
|
572 |
+
self._feature_size = model_channels
|
573 |
+
input_block_chans = [model_channels]
|
574 |
+
ch = model_channels
|
575 |
+
ds = 1
|
576 |
+
for level, mult in enumerate(channel_mult):
|
577 |
+
for nr in range(self.num_res_blocks[level]):
|
578 |
+
layers = [
|
579 |
+
ResBlock(
|
580 |
+
ch,
|
581 |
+
time_embed_dim,
|
582 |
+
dropout,
|
583 |
+
out_channels=mult * model_channels,
|
584 |
+
dims=dims,
|
585 |
+
use_checkpoint=use_checkpoint,
|
586 |
+
use_scale_shift_norm=use_scale_shift_norm,
|
587 |
+
)
|
588 |
+
]
|
589 |
+
ch = mult * model_channels
|
590 |
+
if ds in attention_resolutions:
|
591 |
+
if num_head_channels == -1:
|
592 |
+
dim_head = ch // num_heads
|
593 |
+
else:
|
594 |
+
num_heads = ch // num_head_channels
|
595 |
+
dim_head = num_head_channels
|
596 |
+
if legacy:
|
597 |
+
# num_heads = 1
|
598 |
+
dim_head = ch // num_heads if use_spatial_transformer else num_head_channels
|
599 |
+
if exists(disable_self_attentions):
|
600 |
+
disabled_sa = disable_self_attentions[level]
|
601 |
+
else:
|
602 |
+
disabled_sa = False
|
603 |
+
|
604 |
+
if not exists(num_attention_blocks) or nr < num_attention_blocks[level]:
|
605 |
+
layers.append(
|
606 |
+
AttentionBlock(
|
607 |
+
ch,
|
608 |
+
use_checkpoint=use_checkpoint,
|
609 |
+
num_heads=num_heads,
|
610 |
+
num_head_channels=dim_head,
|
611 |
+
use_new_attention_order=use_new_attention_order,
|
612 |
+
) if not use_spatial_transformer else SpatialTransformer(
|
613 |
+
ch, num_heads, dim_head, depth=transformer_depth, context_dim=context_dim,
|
614 |
+
disable_self_attn=disabled_sa, use_linear=use_linear_in_transformer,
|
615 |
+
use_checkpoint=use_checkpoint
|
616 |
+
)
|
617 |
+
)
|
618 |
+
self.input_blocks.append(TimestepEmbedSequential(*layers))
|
619 |
+
self.zero_convs.append(self.make_zero_conv(ch))
|
620 |
+
self._feature_size += ch
|
621 |
+
input_block_chans.append(ch)
|
622 |
+
if level != len(channel_mult) - 1:
|
623 |
+
out_ch = ch
|
624 |
+
self.input_blocks.append(
|
625 |
+
TimestepEmbedSequential(
|
626 |
+
ResBlock(
|
627 |
+
ch,
|
628 |
+
time_embed_dim,
|
629 |
+
dropout,
|
630 |
+
out_channels=out_ch,
|
631 |
+
dims=dims,
|
632 |
+
use_checkpoint=use_checkpoint,
|
633 |
+
use_scale_shift_norm=use_scale_shift_norm,
|
634 |
+
down=True,
|
635 |
+
)
|
636 |
+
if resblock_updown
|
637 |
+
else Downsample(
|
638 |
+
ch, conv_resample, dims=dims, out_channels=out_ch
|
639 |
+
)
|
640 |
+
)
|
641 |
+
)
|
642 |
+
ch = out_ch
|
643 |
+
input_block_chans.append(ch)
|
644 |
+
self.zero_convs.append(self.make_zero_conv(ch))
|
645 |
+
ds *= 2
|
646 |
+
self._feature_size += ch
|
647 |
+
|
648 |
+
if num_head_channels == -1:
|
649 |
+
dim_head = ch // num_heads
|
650 |
+
else:
|
651 |
+
num_heads = ch // num_head_channels
|
652 |
+
dim_head = num_head_channels
|
653 |
+
if legacy:
|
654 |
+
# num_heads = 1
|
655 |
+
dim_head = ch // num_heads if use_spatial_transformer else num_head_channels
|
656 |
+
self.middle_block = TimestepEmbedSequential(
|
657 |
+
ResBlock(
|
658 |
+
ch,
|
659 |
+
time_embed_dim,
|
660 |
+
dropout,
|
661 |
+
dims=dims,
|
662 |
+
use_checkpoint=use_checkpoint,
|
663 |
+
use_scale_shift_norm=use_scale_shift_norm,
|
664 |
+
),
|
665 |
+
AttentionBlock(
|
666 |
+
ch,
|
667 |
+
use_checkpoint=use_checkpoint,
|
668 |
+
num_heads=num_heads,
|
669 |
+
num_head_channels=dim_head,
|
670 |
+
use_new_attention_order=use_new_attention_order,
|
671 |
+
) if not use_spatial_transformer else SpatialTransformer( # always uses a self-attn
|
672 |
+
ch, num_heads, dim_head, depth=transformer_depth, context_dim=context_dim,
|
673 |
+
disable_self_attn=disable_middle_self_attn, use_linear=use_linear_in_transformer,
|
674 |
+
use_checkpoint=use_checkpoint
|
675 |
+
),
|
676 |
+
ResBlock(
|
677 |
+
ch,
|
678 |
+
time_embed_dim,
|
679 |
+
dropout,
|
680 |
+
dims=dims,
|
681 |
+
use_checkpoint=use_checkpoint,
|
682 |
+
use_scale_shift_norm=use_scale_shift_norm,
|
683 |
+
),
|
684 |
+
)
|
685 |
+
self.middle_block_out = self.make_zero_conv(ch)
|
686 |
+
self._feature_size += ch
|
687 |
+
|
688 |
+
def make_zero_conv(self, channels):
|
689 |
+
return TimestepEmbedSequential(zero_module(conv_nd(self.dims, channels, channels, 1, padding=0)))
|
690 |
+
|
691 |
+
def forward(self, x, hint, timesteps, context, **kwargs):
|
692 |
+
t_emb = timestep_embedding(timesteps, self.model_channels, repeat_only=False)
|
693 |
+
emb = self.time_embed(t_emb)
|
694 |
+
|
695 |
+
guided_hint = self.input_hint_block(hint, emb, context)
|
696 |
+
|
697 |
+
outs = []
|
698 |
+
|
699 |
+
h = x.type(self.dtype)
|
700 |
+
for module, zero_conv in zip(self.input_blocks, self.zero_convs):
|
701 |
+
if guided_hint is not None:
|
702 |
+
h = module(h, emb, context)
|
703 |
+
h += guided_hint
|
704 |
+
guided_hint = None
|
705 |
+
else:
|
706 |
+
h = module(h, emb, context)
|
707 |
+
outs.append(zero_conv(h, emb, context))
|
708 |
+
|
709 |
+
h = self.middle_block(h, emb, context)
|
710 |
+
outs.append(self.middle_block_out(h, emb, context))
|
711 |
+
|
712 |
+
return outs
|
713 |
+
TACOTRON_MEL_MAX = 5.5451774444795624753378569716654
|
714 |
+
TACOTRON_MEL_MIN = -16.118095650958319788125940182791
|
715 |
+
# TACOTRON_MEL_MIN = -11.512925464970228420089957273422
|
716 |
+
|
717 |
+
CVEC_MAX = 5.5451774444795624753378569716654
|
718 |
+
CVEC_MIN = -5.5451774444795624753378569716654
|
719 |
+
def denormalize_tacotron_mel(norm_mel):
|
720 |
+
return norm_mel/0.18215
|
721 |
+
def normalize_tacotron_mel(mel):
|
722 |
+
mel = torch.clamp(mel, min=-TACOTRON_MEL_MAX)
|
723 |
+
return mel*0.18215
|
724 |
+
|
725 |
+
def denormalize_cvec(norm_mel):
|
726 |
+
return norm_mel/0.11111
|
727 |
+
def normalize_cvec(mel):
|
728 |
+
return mel*0.11111
|
729 |
+
|
730 |
+
class ControlLDM(LatentDiffusion):
|
731 |
+
|
732 |
+
def __init__(self, refer_config, control_key, only_mid_control, *args, **kwargs):
|
733 |
+
super().__init__(*args, **kwargs)
|
734 |
+
# self.control_model = instantiate_from_config(control_stage_config)
|
735 |
+
# self.refer_model = instantiate_from_config(refer_config)
|
736 |
+
self.control_key = control_key
|
737 |
+
self.only_mid_control = only_mid_control
|
738 |
+
self.control_scales = [1.0] * 13
|
739 |
+
self.unconditioned_embedding = nn.Parameter(torch.randn(1,100,1))
|
740 |
+
self.unconditioned_cat_embedding = nn.Parameter(torch.randn(1,1024,1))
|
741 |
+
|
742 |
+
@torch.no_grad()
|
743 |
+
def get_input(self, batch, k, bs=None, *args, **kwargs):
|
744 |
+
x, c = super().get_input(batch, self.first_stage_key, *args, **kwargs)
|
745 |
+
control = batch[self.control_key]
|
746 |
+
if bs is not None:
|
747 |
+
control = control[:bs]
|
748 |
+
control = control.to(self.device)
|
749 |
+
# control = einops.rearrange(control, 'b h w c -> b c h w')
|
750 |
+
control = control.to(memory_format=torch.contiguous_format).float()
|
751 |
+
# control = normalize_cvec(control)
|
752 |
+
c = normalize_tacotron_mel(c)
|
753 |
+
x = normalize_tacotron_mel(x)
|
754 |
+
|
755 |
+
return x, dict(c_crossattn=[c], c_concat=[control])
|
756 |
+
|
757 |
+
def apply_model(self, x_noisy, t, cond, *args, **kwargs):
|
758 |
+
assert isinstance(cond, dict)
|
759 |
+
diffusion_model = self.model.diffusion_model
|
760 |
+
|
761 |
+
cond_txt = torch.cat(cond['c_crossattn'], 1)
|
762 |
+
|
763 |
+
if cond['c_concat'] is None:
|
764 |
+
eps = diffusion_model(x=x_noisy, timesteps=t, context=cond_txt, control=None, only_mid_control=self.only_mid_control)
|
765 |
+
else:
|
766 |
+
# control = self.control_model(x=x_noisy, hint=torch.cat(cond['c_concat'], 1), timesteps=t, context=cond_txt)
|
767 |
+
# control = [c * scale for c, scale in zip(control, self.control_scales)]
|
768 |
+
# control = self.refer_model(x=torch.cat(cond['c_refer'], 1), timesteps=t, context=cond_txt)
|
769 |
+
control=[]
|
770 |
+
eps = diffusion_model(x=x_noisy, hint=torch.cat(cond['c_concat'], 1), timesteps=t, context=cond_txt, control=control, only_mid_control=self.only_mid_control)
|
771 |
+
|
772 |
+
return eps
|
773 |
+
|
774 |
+
def get_unconditional_conditioning(self, cross, cat):
|
775 |
+
return cross,\
|
776 |
+
self.unconditioned_cat_embedding.repeat(cat.shape[0], 1, cat.shape[-1]).to(self.device)
|
777 |
+
# return self.unconditioned_embedding.repeat(cross.shape[0], 1, cross.shape[-1]).to(self.device), \
|
778 |
+
# self.unconditioned_cat_embedding.repeat(cat.shape[0], 1, cat.shape[-1]).to(self.device)
|
779 |
+
|
780 |
+
@torch.no_grad()
|
781 |
+
def log_images(self, batch, N=1, n_row=2, sample=True, ddim_steps=50, ddim_eta=0.0, return_keys=None,
|
782 |
+
quantize_denoised=True, inpaint=True, plot_denoise_rows=False, plot_progressive_rows=True,
|
783 |
+
plot_diffusion_rows=False, unconditional_guidance_scale=1.0, unconditional_guidance_label=None,
|
784 |
+
use_ema_scope=True,
|
785 |
+
**kwargs):
|
786 |
+
use_ddim = ddim_steps is not None
|
787 |
+
|
788 |
+
log = dict()
|
789 |
+
z, c = self.get_input(batch, self.first_stage_key, bs=N)
|
790 |
+
c_cat, c = c["c_concat"][0][:N], c["c_crossattn"][0][:N]
|
791 |
+
N = min(z.shape[0], N)
|
792 |
+
n_row = min(z.shape[0], n_row)
|
793 |
+
# log["reconstruction"] = self.decode_first_stage(z)
|
794 |
+
log["control"] = denormalize_cvec(c_cat)
|
795 |
+
log["conditioning"] = batch[self.cond_stage_key]
|
796 |
+
|
797 |
+
if plot_diffusion_rows:
|
798 |
+
# get diffusion row
|
799 |
+
diffusion_row = list()
|
800 |
+
z_start = z[:n_row]
|
801 |
+
for t in range(self.num_timesteps):
|
802 |
+
if t % self.log_every_t == 0 or t == self.num_timesteps - 1:
|
803 |
+
t = repeat(torch.tensor([t]), '1 -> b', b=n_row)
|
804 |
+
t = t.to(self.device).long()
|
805 |
+
noise = torch.randn_like(z_start)
|
806 |
+
z_noisy = self.q_sample(x_start=z_start, t=t, noise=noise)
|
807 |
+
diffusion_row.append(self.decode_first_stage(z_noisy))
|
808 |
+
|
809 |
+
diffusion_row = torch.stack(diffusion_row) # n_log_step, n_row, C, H, W
|
810 |
+
diffusion_grid = rearrange(diffusion_row, 'n b c h w -> b n c h w')
|
811 |
+
diffusion_grid = rearrange(diffusion_grid, 'b n c h w -> (b n) c h w')
|
812 |
+
diffusion_grid = make_grid(diffusion_grid, nrow=diffusion_row.shape[0])
|
813 |
+
log["diffusion_row"] = diffusion_grid
|
814 |
+
|
815 |
+
if sample:
|
816 |
+
# get denoise row
|
817 |
+
c_refer = c
|
818 |
+
# c = self.get_learned_conditioning(c)
|
819 |
+
samples, z_denoise_row = self.sample_log(cond={"c_concat": [c_cat], "c_crossattn": [c], 'c_refer':[c_refer]},
|
820 |
+
batch_size=N, ddim=use_ddim,
|
821 |
+
ddim_steps=ddim_steps, eta=ddim_eta)
|
822 |
+
# x_samples = self.decode_first_stage(samples)
|
823 |
+
log["samples"] = samples
|
824 |
+
if plot_denoise_rows:
|
825 |
+
denoise_grid = self._get_denoise_row_from_list(z_denoise_row)
|
826 |
+
log["denoise_row"] = denoise_grid
|
827 |
+
|
828 |
+
if unconditional_guidance_scale > 1.0:
|
829 |
+
uc_cross, uc_cat = self.get_unconditional_conditioning(c, c_cat)
|
830 |
+
c_refer = c
|
831 |
+
uc_refer = uc_cross
|
832 |
+
c = self.get_learned_conditioning(c)
|
833 |
+
uc_cross = self.get_learned_conditioning(uc_cross)
|
834 |
+
uc_full = {"c_concat": [uc_cat], "c_crossattn": [uc_cross], 'c_refer': [uc_refer]}
|
835 |
+
samples_cfg, _ = self.sample_log(cond={"c_concat": [c_cat], "c_crossattn": [c], 'c_refer':[c_refer]},
|
836 |
+
batch_size=N, ddim=use_ddim,
|
837 |
+
ddim_steps=ddim_steps, eta=ddim_eta,
|
838 |
+
unconditional_guidance_scale=unconditional_guidance_scale,
|
839 |
+
unconditional_conditioning=uc_full,
|
840 |
+
)
|
841 |
+
# x_samples_cfg = self.decode_first_stage(samples_cfg)
|
842 |
+
x_samples_cfg = samples_cfg
|
843 |
+
log['cfg_scale'] = unconditional_guidance_scale
|
844 |
+
log["samples_cfg"] = x_samples_cfg
|
845 |
+
|
846 |
+
return log
|
847 |
+
|
848 |
+
@torch.no_grad()
|
849 |
+
def sample_log(self, cond, batch_size, ddim, ddim_steps, **kwargs):
|
850 |
+
ddim_sampler = DDIMSampler(self)
|
851 |
+
b, c, t = cond["c_concat"][0].shape
|
852 |
+
shape = (self.channels, t)
|
853 |
+
samples, intermediates = ddim_sampler.sample(ddim_steps, batch_size, shape, cond, verbose=False, **kwargs)
|
854 |
+
return samples, intermediates
|
855 |
+
|
856 |
+
def configure_optimizers(self):
|
857 |
+
lr = self.learning_rate
|
858 |
+
params = list(self.control_model.parameters())
|
859 |
+
if not self.sd_locked:
|
860 |
+
params += list(self.model.diffusion_model.output_blocks.parameters())
|
861 |
+
params += list(self.model.diffusion_model.out.parameters())
|
862 |
+
opt = torch.optim.AdamW(params, lr=lr)
|
863 |
+
return opt
|
864 |
+
|
865 |
+
def low_vram_shift(self, is_diffusing):
|
866 |
+
if is_diffusing:
|
867 |
+
self.model = self.model.cuda()
|
868 |
+
self.control_model = self.control_model.cuda()
|
869 |
+
self.first_stage_model = self.first_stage_model.cpu()
|
870 |
+
self.cond_stage_model = self.cond_stage_model.cpu()
|
871 |
+
else:
|
872 |
+
self.model = self.model.cpu()
|
873 |
+
self.control_model = self.control_model.cpu()
|
874 |
+
self.first_stage_model = self.first_stage_model.cuda()
|
875 |
+
self.cond_stage_model = self.cond_stage_model.cuda()
|
ttts/AA_diffusion_deprecated/cldm/cond_emb.py
ADDED
@@ -0,0 +1,339 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
""" CLIP Model
|
2 |
+
|
3 |
+
Adapted from https://github.com/openai/CLIP. Originally MIT License, Copyright (c) 2021 OpenAI.
|
4 |
+
"""
|
5 |
+
import copy
|
6 |
+
import logging
|
7 |
+
import math
|
8 |
+
from dataclasses import dataclass
|
9 |
+
from typing import Any, Dict, Optional, Tuple, Union
|
10 |
+
|
11 |
+
import numpy as np
|
12 |
+
import torch
|
13 |
+
import torch.nn.functional as F
|
14 |
+
from torch import nn
|
15 |
+
from torch.utils.checkpoint import checkpoint
|
16 |
+
from functools import partial
|
17 |
+
|
18 |
+
# from .hf_model import HFTextEncoder
|
19 |
+
from .modified_resnet import ModifiedResNet
|
20 |
+
from .timm_model import TimmModel
|
21 |
+
from .transformer import LayerNormFp32, LayerNorm, QuickGELU, Attention, VisionTransformer, TextTransformer,\
|
22 |
+
text_global_pool
|
23 |
+
from .utils import to_2tuple
|
24 |
+
|
25 |
+
|
26 |
+
@dataclass
|
27 |
+
class CLIPVisionCfg:
|
28 |
+
layers: Union[Tuple[int, int, int, int], int] = 12
|
29 |
+
width: int = 768
|
30 |
+
head_width: int = 64
|
31 |
+
mlp_ratio: float = 4.0
|
32 |
+
patch_size: int = 16
|
33 |
+
image_size: Union[Tuple[int, int], int] = 224
|
34 |
+
in_channels: int = 100
|
35 |
+
|
36 |
+
ls_init_value: Optional[float] = None # layer scale initial value
|
37 |
+
patch_dropout: float = 0. # what fraction of patches to dropout during training (0 would mean disabled and no patches dropped) - 0.5 to 0.75 recommended in the paper for optimal results
|
38 |
+
attentional_pool: bool = False # whether to use attentional pooler in the last embedding layer (overrides pool_type)
|
39 |
+
attn_pooler_queries: int = 256 # n_queries for attentional pooler
|
40 |
+
attn_pooler_heads: int = 8 # n heads for attentional_pooling
|
41 |
+
no_ln_pre: bool = False # disable pre transformer LayerNorm
|
42 |
+
pos_embed_type: str = 'learnable'
|
43 |
+
final_ln_after_pool: bool = False # apply final LayerNorm after pooling
|
44 |
+
pool_type: str = 'tok'
|
45 |
+
output_tokens: bool = False
|
46 |
+
act_kwargs: Optional[dict] = None
|
47 |
+
norm_kwargs: Optional[dict] = None
|
48 |
+
|
49 |
+
timm_model_name: Optional[str] = None # a valid model name overrides layers, width, patch_size
|
50 |
+
timm_model_pretrained: bool = False # use (imagenet) pretrained weights for named model
|
51 |
+
timm_pool: str = 'avg' # feature pooling for timm model ('abs_attn', 'rot_attn', 'avg', '')
|
52 |
+
timm_proj: str = 'linear' # linear projection for timm model output ('linear', 'mlp', '')
|
53 |
+
timm_proj_bias: bool = False # enable bias final projection
|
54 |
+
timm_drop: float = 0. # head dropout
|
55 |
+
timm_drop_path: Optional[float] = None # backbone stochastic depth
|
56 |
+
|
57 |
+
def get_cast_dtype(precision: str):
|
58 |
+
cast_dtype = None
|
59 |
+
if precision == 'bf16':
|
60 |
+
cast_dtype = torch.bfloat16
|
61 |
+
elif precision == 'fp16':
|
62 |
+
cast_dtype = torch.float16
|
63 |
+
return cast_dtype
|
64 |
+
|
65 |
+
|
66 |
+
def get_input_dtype(precision: str):
|
67 |
+
input_dtype = None
|
68 |
+
if precision in ('bf16', 'pure_bf16'):
|
69 |
+
input_dtype = torch.bfloat16
|
70 |
+
elif precision in ('fp16', 'pure_fp16'):
|
71 |
+
input_dtype = torch.float16
|
72 |
+
return input_dtype
|
73 |
+
|
74 |
+
|
75 |
+
def _build_vision_tower(
|
76 |
+
embed_dim: int,
|
77 |
+
vision_cfg: CLIPVisionCfg,
|
78 |
+
quick_gelu: bool = False,
|
79 |
+
cast_dtype: Optional[torch.dtype] = None
|
80 |
+
):
|
81 |
+
if isinstance(vision_cfg, dict):
|
82 |
+
vision_cfg = CLIPVisionCfg(**vision_cfg)
|
83 |
+
|
84 |
+
# OpenAI models are pretrained w/ QuickGELU but native nn.GELU is both faster and more
|
85 |
+
# memory efficient in recent PyTorch releases (>= 1.10).
|
86 |
+
# NOTE: timm models always use native GELU regardless of quick_gelu flag.
|
87 |
+
act_layer = QuickGELU if quick_gelu else nn.GELU
|
88 |
+
|
89 |
+
if vision_cfg.timm_model_name:
|
90 |
+
visual = TimmModel(
|
91 |
+
vision_cfg.timm_model_name,
|
92 |
+
pretrained=vision_cfg.timm_model_pretrained,
|
93 |
+
pool=vision_cfg.timm_pool,
|
94 |
+
proj=vision_cfg.timm_proj,
|
95 |
+
proj_bias=vision_cfg.timm_proj_bias,
|
96 |
+
drop=vision_cfg.timm_drop,
|
97 |
+
drop_path=vision_cfg.timm_drop_path,
|
98 |
+
patch_drop=vision_cfg.patch_dropout if vision_cfg.patch_dropout > 0 else None,
|
99 |
+
embed_dim=embed_dim,
|
100 |
+
image_size=vision_cfg.image_size,
|
101 |
+
)
|
102 |
+
elif isinstance(vision_cfg.layers, (tuple, list)):
|
103 |
+
vision_heads = vision_cfg.width * 32 // vision_cfg.head_width
|
104 |
+
visual = ModifiedResNet(
|
105 |
+
layers=vision_cfg.layers,
|
106 |
+
output_dim=embed_dim,
|
107 |
+
heads=vision_heads,
|
108 |
+
image_size=vision_cfg.image_size,
|
109 |
+
width=vision_cfg.width,
|
110 |
+
)
|
111 |
+
else:
|
112 |
+
vision_heads = vision_cfg.width // vision_cfg.head_width
|
113 |
+
norm_layer = LayerNormFp32 if cast_dtype in (torch.float16, torch.bfloat16) else LayerNorm
|
114 |
+
if vision_cfg.norm_kwargs:
|
115 |
+
norm_layer = partial(norm_layer, **vision_cfg.norm_kwargs)
|
116 |
+
if vision_cfg.act_kwargs is not None:
|
117 |
+
act_layer = partial(act_layer, **vision_cfg.act_kwargs)
|
118 |
+
|
119 |
+
visual = VisionTransformer(
|
120 |
+
image_size=vision_cfg.image_size,
|
121 |
+
patch_size=vision_cfg.patch_size,
|
122 |
+
width=vision_cfg.width,
|
123 |
+
layers=vision_cfg.layers,
|
124 |
+
heads=vision_heads,
|
125 |
+
in_channels=vision_cfg.in_channels,
|
126 |
+
mlp_ratio=vision_cfg.mlp_ratio,
|
127 |
+
ls_init_value=vision_cfg.ls_init_value,
|
128 |
+
patch_dropout=vision_cfg.patch_dropout,
|
129 |
+
attentional_pool=vision_cfg.attentional_pool,
|
130 |
+
attn_pooler_queries=vision_cfg.attn_pooler_queries,
|
131 |
+
attn_pooler_heads=vision_cfg.attn_pooler_heads,
|
132 |
+
pos_embed_type=vision_cfg.pos_embed_type,
|
133 |
+
no_ln_pre=vision_cfg.no_ln_pre,
|
134 |
+
final_ln_after_pool=vision_cfg.final_ln_after_pool,
|
135 |
+
pool_type=vision_cfg.pool_type,
|
136 |
+
output_tokens=vision_cfg.output_tokens,
|
137 |
+
output_dim=embed_dim,
|
138 |
+
act_layer=act_layer,
|
139 |
+
norm_layer=norm_layer,
|
140 |
+
)
|
141 |
+
|
142 |
+
return visual
|
143 |
+
|
144 |
+
class CLIP(nn.Module):
|
145 |
+
output_dict: torch.jit.Final[bool]
|
146 |
+
|
147 |
+
def __init__(
|
148 |
+
self,
|
149 |
+
embed_dim: int,
|
150 |
+
vision_cfg: CLIPVisionCfg,
|
151 |
+
quick_gelu: bool = False,
|
152 |
+
init_logit_scale: float = np.log(1 / 0.07),
|
153 |
+
init_logit_bias: Optional[float] = None,
|
154 |
+
cast_dtype: Optional[torch.dtype] = None,
|
155 |
+
output_dict: bool = False,
|
156 |
+
):
|
157 |
+
super().__init__()
|
158 |
+
self.output_dict = output_dict
|
159 |
+
|
160 |
+
self.visual = _build_vision_tower(embed_dim, vision_cfg, quick_gelu, cast_dtype)
|
161 |
+
|
162 |
+
# self.logit_scale = nn.Parameter(torch.ones([]) * init_logit_scale)
|
163 |
+
if init_logit_bias is not None:
|
164 |
+
self.logit_bias = nn.Parameter(torch.ones([]) * init_logit_bias)
|
165 |
+
else:
|
166 |
+
self.logit_bias = None
|
167 |
+
|
168 |
+
def lock_image_tower(self, unlocked_groups=0, freeze_bn_stats=False):
|
169 |
+
# lock image tower as per LiT - https://arxiv.org/abs/2111.07991
|
170 |
+
self.visual.lock(unlocked_groups=unlocked_groups, freeze_bn_stats=freeze_bn_stats)
|
171 |
+
|
172 |
+
@torch.jit.ignore
|
173 |
+
def set_grad_checkpointing(self, enable=True):
|
174 |
+
self.visual.set_grad_checkpointing(enable)
|
175 |
+
self.transformer.grad_checkpointing = enable
|
176 |
+
|
177 |
+
def encode_image(self, image, normalize: bool = False):
|
178 |
+
features = self.visual(image)
|
179 |
+
return F.normalize(features, dim=-1) if normalize else features
|
180 |
+
|
181 |
+
def forward(
|
182 |
+
self,
|
183 |
+
image: Optional[torch.Tensor] = None,
|
184 |
+
):
|
185 |
+
image_features = self.encode_image(image, normalize=True) if image is not None else None
|
186 |
+
return image_features
|
187 |
+
|
188 |
+
|
189 |
+
def convert_weights_to_lp(model: nn.Module, dtype=torch.float16):
|
190 |
+
"""Convert applicable model parameters to low-precision (bf16 or fp16)"""
|
191 |
+
|
192 |
+
def _convert_weights(l):
|
193 |
+
if isinstance(l, (nn.Conv1d, nn.Conv2d, nn.Linear)):
|
194 |
+
l.weight.data = l.weight.data.to(dtype)
|
195 |
+
if l.bias is not None:
|
196 |
+
l.bias.data = l.bias.data.to(dtype)
|
197 |
+
|
198 |
+
if isinstance(l, (nn.MultiheadAttention, Attention)):
|
199 |
+
for attr in [*[f"{s}_proj_weight" for s in ["in", "q", "k", "v"]], "in_proj_bias", "bias_k", "bias_v"]:
|
200 |
+
tensor = getattr(l, attr)
|
201 |
+
if tensor is not None:
|
202 |
+
tensor.data = tensor.data.to(dtype)
|
203 |
+
|
204 |
+
if isinstance(l, (CLIP, TextTransformer)):
|
205 |
+
# convert text nn.Parameter projections
|
206 |
+
attr = getattr(l, "text_projection", None)
|
207 |
+
if attr is not None:
|
208 |
+
attr.data = attr.data.to(dtype)
|
209 |
+
|
210 |
+
if isinstance(l, VisionTransformer):
|
211 |
+
# convert vision nn.Parameter projections
|
212 |
+
attr = getattr(l, "proj", None)
|
213 |
+
if attr is not None:
|
214 |
+
attr.data = attr.data.to(dtype)
|
215 |
+
|
216 |
+
model.apply(_convert_weights)
|
217 |
+
|
218 |
+
|
219 |
+
convert_weights_to_fp16 = convert_weights_to_lp # backwards compat
|
220 |
+
|
221 |
+
|
222 |
+
# used to maintain checkpoint compatibility
|
223 |
+
def convert_to_custom_text_state_dict(state_dict: dict):
|
224 |
+
if 'text_projection' in state_dict:
|
225 |
+
# old format state_dict, move text tower -> .text
|
226 |
+
new_state_dict = {}
|
227 |
+
for k, v in state_dict.items():
|
228 |
+
if any(k.startswith(p) for p in (
|
229 |
+
'text_projection',
|
230 |
+
'positional_embedding',
|
231 |
+
'token_embedding',
|
232 |
+
'transformer',
|
233 |
+
'ln_final',
|
234 |
+
)):
|
235 |
+
k = 'text.' + k
|
236 |
+
new_state_dict[k] = v
|
237 |
+
return new_state_dict
|
238 |
+
return state_dict
|
239 |
+
|
240 |
+
|
241 |
+
def build_model_from_openai_state_dict(
|
242 |
+
state_dict: dict,
|
243 |
+
quick_gelu=True,
|
244 |
+
cast_dtype=torch.float16,
|
245 |
+
):
|
246 |
+
vit = "visual.proj" in state_dict
|
247 |
+
|
248 |
+
if vit:
|
249 |
+
vision_width = state_dict["visual.conv1.weight"].shape[0]
|
250 |
+
vision_layers = len(
|
251 |
+
[k for k in state_dict.keys() if k.startswith("visual.") and k.endswith(".attn.in_proj_weight")])
|
252 |
+
vision_patch_size = state_dict["visual.conv1.weight"].shape[-1]
|
253 |
+
grid_size = round((state_dict["visual.positional_embedding"].shape[0] - 1) ** 0.5)
|
254 |
+
image_size = vision_patch_size * grid_size
|
255 |
+
else:
|
256 |
+
counts: list = [
|
257 |
+
len(set(k.split(".")[2] for k in state_dict if k.startswith(f"visual.layer{b}"))) for b in [1, 2, 3, 4]]
|
258 |
+
vision_layers = tuple(counts)
|
259 |
+
vision_width = state_dict["visual.layer1.0.conv1.weight"].shape[0]
|
260 |
+
output_width = round((state_dict["visual.attnpool.positional_embedding"].shape[0] - 1) ** 0.5)
|
261 |
+
vision_patch_size = None
|
262 |
+
assert output_width ** 2 + 1 == state_dict["visual.attnpool.positional_embedding"].shape[0]
|
263 |
+
image_size = output_width * 32
|
264 |
+
|
265 |
+
embed_dim = state_dict["text_projection"].shape[1]
|
266 |
+
context_length = state_dict["positional_embedding"].shape[0]
|
267 |
+
vocab_size = state_dict["token_embedding.weight"].shape[0]
|
268 |
+
transformer_width = state_dict["ln_final.weight"].shape[0]
|
269 |
+
transformer_heads = transformer_width // 64
|
270 |
+
transformer_layers = len(set(k.split(".")[2] for k in state_dict if k.startswith(f"transformer.resblocks")))
|
271 |
+
|
272 |
+
vision_cfg = CLIPVisionCfg(
|
273 |
+
layers=vision_layers,
|
274 |
+
width=vision_width,
|
275 |
+
patch_size=vision_patch_size,
|
276 |
+
image_size=image_size,
|
277 |
+
)
|
278 |
+
model = CLIP(
|
279 |
+
embed_dim,
|
280 |
+
vision_cfg=vision_cfg,
|
281 |
+
quick_gelu=quick_gelu, # OpenAI models were trained with QuickGELU
|
282 |
+
cast_dtype=cast_dtype,
|
283 |
+
)
|
284 |
+
|
285 |
+
for key in ["input_resolution", "context_length", "vocab_size"]:
|
286 |
+
state_dict.pop(key, None)
|
287 |
+
convert_weights_to_fp16(model) # OpenAI state dicts are partially converted to float16
|
288 |
+
model.load_state_dict(state_dict)
|
289 |
+
return model.eval()
|
290 |
+
|
291 |
+
|
292 |
+
def trace_model(model, batch_size=256, device=torch.device('cpu')):
|
293 |
+
model.eval()
|
294 |
+
image_size = model.visual.image_size
|
295 |
+
example_images = torch.ones((batch_size, 3, image_size, image_size), device=device)
|
296 |
+
example_text = torch.zeros((batch_size, model.context_length), dtype=torch.int, device=device)
|
297 |
+
model = torch.jit.trace_module(
|
298 |
+
model,
|
299 |
+
inputs=dict(
|
300 |
+
forward=(example_images, example_text),
|
301 |
+
encode_text=(example_text,),
|
302 |
+
encode_image=(example_images,)
|
303 |
+
))
|
304 |
+
model.visual.image_size = image_size
|
305 |
+
return model
|
306 |
+
|
307 |
+
|
308 |
+
def resize_pos_embed(state_dict, model, interpolation: str = 'bicubic', antialias: bool = True):
|
309 |
+
# Rescale the grid of position embeddings when loading from state_dict
|
310 |
+
old_pos_embed = state_dict.get('visual.positional_embedding', None)
|
311 |
+
if old_pos_embed is None or not hasattr(model.visual, 'grid_size'):
|
312 |
+
return
|
313 |
+
grid_size = to_2tuple(model.visual.grid_size)
|
314 |
+
extra_tokens = 1 # FIXME detect different token configs (ie no class token, or more)
|
315 |
+
new_seq_len = grid_size[0] * grid_size[1] + extra_tokens
|
316 |
+
if new_seq_len == old_pos_embed.shape[0]:
|
317 |
+
return
|
318 |
+
|
319 |
+
if extra_tokens:
|
320 |
+
pos_emb_tok, pos_emb_img = old_pos_embed[:extra_tokens], old_pos_embed[extra_tokens:]
|
321 |
+
else:
|
322 |
+
pos_emb_tok, pos_emb_img = None, old_pos_embed
|
323 |
+
old_grid_size = to_2tuple(int(math.sqrt(len(pos_emb_img))))
|
324 |
+
|
325 |
+
logging.info('Resizing position embedding grid-size from %s to %s', old_grid_size, grid_size)
|
326 |
+
pos_emb_img = pos_emb_img.reshape(1, old_grid_size[0], old_grid_size[1], -1).permute(0, 3, 1, 2)
|
327 |
+
pos_emb_img = F.interpolate(
|
328 |
+
pos_emb_img,
|
329 |
+
size=grid_size,
|
330 |
+
mode=interpolation,
|
331 |
+
antialias=antialias,
|
332 |
+
align_corners=False,
|
333 |
+
)
|
334 |
+
pos_emb_img = pos_emb_img.permute(0, 2, 3, 1).reshape(1, grid_size[0] * grid_size[1], -1)[0]
|
335 |
+
if pos_emb_tok is not None:
|
336 |
+
new_pos_embed = torch.cat([pos_emb_tok, pos_emb_img], dim=0)
|
337 |
+
else:
|
338 |
+
new_pos_embed = pos_emb_img
|
339 |
+
state_dict['visual.positional_embedding'] = new_pos_embed
|
ttts/AA_diffusion_deprecated/cldm/ddim_hacked.py
ADDED
@@ -0,0 +1,317 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""SAMPLING ONLY."""
|
2 |
+
|
3 |
+
import torch
|
4 |
+
import numpy as np
|
5 |
+
from tqdm import tqdm
|
6 |
+
|
7 |
+
from ldm.modules.diffusionmodules.util import make_ddim_sampling_parameters, make_ddim_timesteps, noise_like, extract_into_tensor
|
8 |
+
|
9 |
+
|
10 |
+
class DDIMSampler(object):
|
11 |
+
def __init__(self, model, schedule="linear", **kwargs):
|
12 |
+
super().__init__()
|
13 |
+
self.model = model
|
14 |
+
self.ddpm_num_timesteps = model.num_timesteps
|
15 |
+
self.schedule = schedule
|
16 |
+
|
17 |
+
def register_buffer(self, name, attr):
|
18 |
+
if type(attr) == torch.Tensor:
|
19 |
+
if attr.device != torch.device("cuda"):
|
20 |
+
attr = attr.to(torch.device("cuda"))
|
21 |
+
setattr(self, name, attr)
|
22 |
+
|
23 |
+
def make_schedule(self, ddim_num_steps, ddim_discretize="uniform", ddim_eta=0., verbose=True):
|
24 |
+
self.ddim_timesteps = make_ddim_timesteps(ddim_discr_method=ddim_discretize, num_ddim_timesteps=ddim_num_steps,
|
25 |
+
num_ddpm_timesteps=self.ddpm_num_timesteps,verbose=verbose)
|
26 |
+
alphas_cumprod = self.model.alphas_cumprod
|
27 |
+
assert alphas_cumprod.shape[0] == self.ddpm_num_timesteps, 'alphas have to be defined for each timestep'
|
28 |
+
to_torch = lambda x: x.clone().detach().to(torch.float32).to(self.model.device)
|
29 |
+
|
30 |
+
self.register_buffer('betas', to_torch(self.model.betas))
|
31 |
+
self.register_buffer('alphas_cumprod', to_torch(alphas_cumprod))
|
32 |
+
self.register_buffer('alphas_cumprod_prev', to_torch(self.model.alphas_cumprod_prev))
|
33 |
+
|
34 |
+
# calculations for diffusion q(x_t | x_{t-1}) and others
|
35 |
+
self.register_buffer('sqrt_alphas_cumprod', to_torch(np.sqrt(alphas_cumprod.cpu())))
|
36 |
+
self.register_buffer('sqrt_one_minus_alphas_cumprod', to_torch(np.sqrt(1. - alphas_cumprod.cpu())))
|
37 |
+
self.register_buffer('log_one_minus_alphas_cumprod', to_torch(np.log(1. - alphas_cumprod.cpu())))
|
38 |
+
self.register_buffer('sqrt_recip_alphas_cumprod', to_torch(np.sqrt(1. / alphas_cumprod.cpu())))
|
39 |
+
self.register_buffer('sqrt_recipm1_alphas_cumprod', to_torch(np.sqrt(1. / alphas_cumprod.cpu() - 1)))
|
40 |
+
|
41 |
+
# ddim sampling parameters
|
42 |
+
ddim_sigmas, ddim_alphas, ddim_alphas_prev = make_ddim_sampling_parameters(alphacums=alphas_cumprod.cpu(),
|
43 |
+
ddim_timesteps=self.ddim_timesteps,
|
44 |
+
eta=ddim_eta,verbose=verbose)
|
45 |
+
self.register_buffer('ddim_sigmas', ddim_sigmas)
|
46 |
+
self.register_buffer('ddim_alphas', ddim_alphas)
|
47 |
+
self.register_buffer('ddim_alphas_prev', ddim_alphas_prev)
|
48 |
+
self.register_buffer('ddim_sqrt_one_minus_alphas', np.sqrt(1. - ddim_alphas))
|
49 |
+
sigmas_for_original_sampling_steps = ddim_eta * torch.sqrt(
|
50 |
+
(1 - self.alphas_cumprod_prev) / (1 - self.alphas_cumprod) * (
|
51 |
+
1 - self.alphas_cumprod / self.alphas_cumprod_prev))
|
52 |
+
self.register_buffer('ddim_sigmas_for_original_num_steps', sigmas_for_original_sampling_steps)
|
53 |
+
|
54 |
+
@torch.no_grad()
|
55 |
+
def sample(self,
|
56 |
+
S,
|
57 |
+
batch_size,
|
58 |
+
shape,
|
59 |
+
conditioning=None,
|
60 |
+
callback=None,
|
61 |
+
normals_sequence=None,
|
62 |
+
img_callback=None,
|
63 |
+
quantize_x0=False,
|
64 |
+
eta=0.,
|
65 |
+
mask=None,
|
66 |
+
x0=None,
|
67 |
+
temperature=1.,
|
68 |
+
noise_dropout=0.,
|
69 |
+
score_corrector=None,
|
70 |
+
corrector_kwargs=None,
|
71 |
+
verbose=True,
|
72 |
+
x_T=None,
|
73 |
+
log_every_t=100,
|
74 |
+
unconditional_guidance_scale=1.,
|
75 |
+
unconditional_conditioning=None, # this has to come in the same format as the conditioning, # e.g. as encoded tokens, ...
|
76 |
+
dynamic_threshold=None,
|
77 |
+
ucg_schedule=None,
|
78 |
+
**kwargs
|
79 |
+
):
|
80 |
+
if conditioning is not None:
|
81 |
+
if isinstance(conditioning, dict):
|
82 |
+
ctmp = conditioning[list(conditioning.keys())[0]]
|
83 |
+
while isinstance(ctmp, list): ctmp = ctmp[0]
|
84 |
+
cbs = ctmp.shape[0]
|
85 |
+
if cbs != batch_size:
|
86 |
+
print(f"Warning: Got {cbs} conditionings but batch-size is {batch_size}")
|
87 |
+
|
88 |
+
elif isinstance(conditioning, list):
|
89 |
+
for ctmp in conditioning:
|
90 |
+
if ctmp.shape[0] != batch_size:
|
91 |
+
print(f"Warning: Got {cbs} conditionings but batch-size is {batch_size}")
|
92 |
+
|
93 |
+
else:
|
94 |
+
if conditioning.shape[0] != batch_size:
|
95 |
+
print(f"Warning: Got {conditioning.shape[0]} conditionings but batch-size is {batch_size}")
|
96 |
+
|
97 |
+
self.make_schedule(ddim_num_steps=S, ddim_eta=eta, verbose=verbose)
|
98 |
+
# sampling
|
99 |
+
C, H, W = shape
|
100 |
+
size = (batch_size, C, H, W)
|
101 |
+
print(f'Data shape for DDIM sampling is {size}, eta {eta}')
|
102 |
+
|
103 |
+
samples, intermediates = self.ddim_sampling(conditioning, size,
|
104 |
+
callback=callback,
|
105 |
+
img_callback=img_callback,
|
106 |
+
quantize_denoised=quantize_x0,
|
107 |
+
mask=mask, x0=x0,
|
108 |
+
ddim_use_original_steps=False,
|
109 |
+
noise_dropout=noise_dropout,
|
110 |
+
temperature=temperature,
|
111 |
+
score_corrector=score_corrector,
|
112 |
+
corrector_kwargs=corrector_kwargs,
|
113 |
+
x_T=x_T,
|
114 |
+
log_every_t=log_every_t,
|
115 |
+
unconditional_guidance_scale=unconditional_guidance_scale,
|
116 |
+
unconditional_conditioning=unconditional_conditioning,
|
117 |
+
dynamic_threshold=dynamic_threshold,
|
118 |
+
ucg_schedule=ucg_schedule
|
119 |
+
)
|
120 |
+
return samples, intermediates
|
121 |
+
|
122 |
+
@torch.no_grad()
|
123 |
+
def ddim_sampling(self, cond, shape,
|
124 |
+
x_T=None, ddim_use_original_steps=False,
|
125 |
+
callback=None, timesteps=None, quantize_denoised=False,
|
126 |
+
mask=None, x0=None, img_callback=None, log_every_t=100,
|
127 |
+
temperature=1., noise_dropout=0., score_corrector=None, corrector_kwargs=None,
|
128 |
+
unconditional_guidance_scale=1., unconditional_conditioning=None, dynamic_threshold=None,
|
129 |
+
ucg_schedule=None):
|
130 |
+
device = self.model.betas.device
|
131 |
+
b = shape[0]
|
132 |
+
if x_T is None:
|
133 |
+
img = torch.randn(shape, device=device)
|
134 |
+
else:
|
135 |
+
img = x_T
|
136 |
+
|
137 |
+
if timesteps is None:
|
138 |
+
timesteps = self.ddpm_num_timesteps if ddim_use_original_steps else self.ddim_timesteps
|
139 |
+
elif timesteps is not None and not ddim_use_original_steps:
|
140 |
+
subset_end = int(min(timesteps / self.ddim_timesteps.shape[0], 1) * self.ddim_timesteps.shape[0]) - 1
|
141 |
+
timesteps = self.ddim_timesteps[:subset_end]
|
142 |
+
|
143 |
+
intermediates = {'x_inter': [img], 'pred_x0': [img]}
|
144 |
+
time_range = reversed(range(0,timesteps)) if ddim_use_original_steps else np.flip(timesteps)
|
145 |
+
total_steps = timesteps if ddim_use_original_steps else timesteps.shape[0]
|
146 |
+
print(f"Running DDIM Sampling with {total_steps} timesteps")
|
147 |
+
|
148 |
+
iterator = tqdm(time_range, desc='DDIM Sampler', total=total_steps)
|
149 |
+
|
150 |
+
for i, step in enumerate(iterator):
|
151 |
+
index = total_steps - i - 1
|
152 |
+
ts = torch.full((b,), step, device=device, dtype=torch.long)
|
153 |
+
|
154 |
+
if mask is not None:
|
155 |
+
assert x0 is not None
|
156 |
+
img_orig = self.model.q_sample(x0, ts) # TODO: deterministic forward pass?
|
157 |
+
img = img_orig * mask + (1. - mask) * img
|
158 |
+
|
159 |
+
if ucg_schedule is not None:
|
160 |
+
assert len(ucg_schedule) == len(time_range)
|
161 |
+
unconditional_guidance_scale = ucg_schedule[i]
|
162 |
+
|
163 |
+
outs = self.p_sample_ddim(img, cond, ts, index=index, use_original_steps=ddim_use_original_steps,
|
164 |
+
quantize_denoised=quantize_denoised, temperature=temperature,
|
165 |
+
noise_dropout=noise_dropout, score_corrector=score_corrector,
|
166 |
+
corrector_kwargs=corrector_kwargs,
|
167 |
+
unconditional_guidance_scale=unconditional_guidance_scale,
|
168 |
+
unconditional_conditioning=unconditional_conditioning,
|
169 |
+
dynamic_threshold=dynamic_threshold)
|
170 |
+
img, pred_x0 = outs
|
171 |
+
if callback: callback(i)
|
172 |
+
if img_callback: img_callback(pred_x0, i)
|
173 |
+
|
174 |
+
if index % log_every_t == 0 or index == total_steps - 1:
|
175 |
+
intermediates['x_inter'].append(img)
|
176 |
+
intermediates['pred_x0'].append(pred_x0)
|
177 |
+
|
178 |
+
return img, intermediates
|
179 |
+
|
180 |
+
@torch.no_grad()
|
181 |
+
def p_sample_ddim(self, x, c, t, index, repeat_noise=False, use_original_steps=False, quantize_denoised=False,
|
182 |
+
temperature=1., noise_dropout=0., score_corrector=None, corrector_kwargs=None,
|
183 |
+
unconditional_guidance_scale=1., unconditional_conditioning=None,
|
184 |
+
dynamic_threshold=None):
|
185 |
+
b, *_, device = *x.shape, x.device
|
186 |
+
|
187 |
+
if unconditional_conditioning is None or unconditional_guidance_scale == 1.:
|
188 |
+
model_output = self.model.apply_model(x, t, c)
|
189 |
+
else:
|
190 |
+
model_t = self.model.apply_model(x, t, c)
|
191 |
+
model_uncond = self.model.apply_model(x, t, unconditional_conditioning)
|
192 |
+
model_output = model_uncond + unconditional_guidance_scale * (model_t - model_uncond)
|
193 |
+
|
194 |
+
if self.model.parameterization == "v":
|
195 |
+
e_t = self.model.predict_eps_from_z_and_v(x, t, model_output)
|
196 |
+
else:
|
197 |
+
e_t = model_output
|
198 |
+
|
199 |
+
if score_corrector is not None:
|
200 |
+
assert self.model.parameterization == "eps", 'not implemented'
|
201 |
+
e_t = score_corrector.modify_score(self.model, e_t, x, t, c, **corrector_kwargs)
|
202 |
+
|
203 |
+
alphas = self.model.alphas_cumprod if use_original_steps else self.ddim_alphas
|
204 |
+
alphas_prev = self.model.alphas_cumprod_prev if use_original_steps else self.ddim_alphas_prev
|
205 |
+
sqrt_one_minus_alphas = self.model.sqrt_one_minus_alphas_cumprod if use_original_steps else self.ddim_sqrt_one_minus_alphas
|
206 |
+
sigmas = self.model.ddim_sigmas_for_original_num_steps if use_original_steps else self.ddim_sigmas
|
207 |
+
# select parameters corresponding to the currently considered timestep
|
208 |
+
a_t = torch.full((b, 1, 1, 1), alphas[index], device=device)
|
209 |
+
a_prev = torch.full((b, 1, 1, 1), alphas_prev[index], device=device)
|
210 |
+
sigma_t = torch.full((b, 1, 1, 1), sigmas[index], device=device)
|
211 |
+
sqrt_one_minus_at = torch.full((b, 1, 1, 1), sqrt_one_minus_alphas[index],device=device)
|
212 |
+
|
213 |
+
# current prediction for x_0
|
214 |
+
if self.model.parameterization != "v":
|
215 |
+
pred_x0 = (x - sqrt_one_minus_at * e_t) / a_t.sqrt()
|
216 |
+
else:
|
217 |
+
pred_x0 = self.model.predict_start_from_z_and_v(x, t, model_output)
|
218 |
+
|
219 |
+
if quantize_denoised:
|
220 |
+
pred_x0, _, *_ = self.model.first_stage_model.quantize(pred_x0)
|
221 |
+
|
222 |
+
if dynamic_threshold is not None:
|
223 |
+
raise NotImplementedError()
|
224 |
+
|
225 |
+
# direction pointing to x_t
|
226 |
+
dir_xt = (1. - a_prev - sigma_t**2).sqrt() * e_t
|
227 |
+
noise = sigma_t * noise_like(x.shape, device, repeat_noise) * temperature
|
228 |
+
if noise_dropout > 0.:
|
229 |
+
noise = torch.nn.functional.dropout(noise, p=noise_dropout)
|
230 |
+
x_prev = a_prev.sqrt() * pred_x0 + dir_xt + noise
|
231 |
+
return x_prev, pred_x0
|
232 |
+
|
233 |
+
@torch.no_grad()
|
234 |
+
def encode(self, x0, c, t_enc, use_original_steps=False, return_intermediates=None,
|
235 |
+
unconditional_guidance_scale=1.0, unconditional_conditioning=None, callback=None):
|
236 |
+
timesteps = np.arange(self.ddpm_num_timesteps) if use_original_steps else self.ddim_timesteps
|
237 |
+
num_reference_steps = timesteps.shape[0]
|
238 |
+
|
239 |
+
assert t_enc <= num_reference_steps
|
240 |
+
num_steps = t_enc
|
241 |
+
|
242 |
+
if use_original_steps:
|
243 |
+
alphas_next = self.alphas_cumprod[:num_steps]
|
244 |
+
alphas = self.alphas_cumprod_prev[:num_steps]
|
245 |
+
else:
|
246 |
+
alphas_next = self.ddim_alphas[:num_steps]
|
247 |
+
alphas = torch.tensor(self.ddim_alphas_prev[:num_steps])
|
248 |
+
|
249 |
+
x_next = x0
|
250 |
+
intermediates = []
|
251 |
+
inter_steps = []
|
252 |
+
for i in tqdm(range(num_steps), desc='Encoding Image'):
|
253 |
+
t = torch.full((x0.shape[0],), timesteps[i], device=self.model.device, dtype=torch.long)
|
254 |
+
if unconditional_guidance_scale == 1.:
|
255 |
+
noise_pred = self.model.apply_model(x_next, t, c)
|
256 |
+
else:
|
257 |
+
assert unconditional_conditioning is not None
|
258 |
+
e_t_uncond, noise_pred = torch.chunk(
|
259 |
+
self.model.apply_model(torch.cat((x_next, x_next)), torch.cat((t, t)),
|
260 |
+
torch.cat((unconditional_conditioning, c))), 2)
|
261 |
+
noise_pred = e_t_uncond + unconditional_guidance_scale * (noise_pred - e_t_uncond)
|
262 |
+
|
263 |
+
xt_weighted = (alphas_next[i] / alphas[i]).sqrt() * x_next
|
264 |
+
weighted_noise_pred = alphas_next[i].sqrt() * (
|
265 |
+
(1 / alphas_next[i] - 1).sqrt() - (1 / alphas[i] - 1).sqrt()) * noise_pred
|
266 |
+
x_next = xt_weighted + weighted_noise_pred
|
267 |
+
if return_intermediates and i % (
|
268 |
+
num_steps // return_intermediates) == 0 and i < num_steps - 1:
|
269 |
+
intermediates.append(x_next)
|
270 |
+
inter_steps.append(i)
|
271 |
+
elif return_intermediates and i >= num_steps - 2:
|
272 |
+
intermediates.append(x_next)
|
273 |
+
inter_steps.append(i)
|
274 |
+
if callback: callback(i)
|
275 |
+
|
276 |
+
out = {'x_encoded': x_next, 'intermediate_steps': inter_steps}
|
277 |
+
if return_intermediates:
|
278 |
+
out.update({'intermediates': intermediates})
|
279 |
+
return x_next, out
|
280 |
+
|
281 |
+
@torch.no_grad()
|
282 |
+
def stochastic_encode(self, x0, t, use_original_steps=False, noise=None):
|
283 |
+
# fast, but does not allow for exact reconstruction
|
284 |
+
# t serves as an index to gather the correct alphas
|
285 |
+
if use_original_steps:
|
286 |
+
sqrt_alphas_cumprod = self.sqrt_alphas_cumprod
|
287 |
+
sqrt_one_minus_alphas_cumprod = self.sqrt_one_minus_alphas_cumprod
|
288 |
+
else:
|
289 |
+
sqrt_alphas_cumprod = torch.sqrt(self.ddim_alphas)
|
290 |
+
sqrt_one_minus_alphas_cumprod = self.ddim_sqrt_one_minus_alphas
|
291 |
+
|
292 |
+
if noise is None:
|
293 |
+
noise = torch.randn_like(x0)
|
294 |
+
return (extract_into_tensor(sqrt_alphas_cumprod, t, x0.shape) * x0 +
|
295 |
+
extract_into_tensor(sqrt_one_minus_alphas_cumprod, t, x0.shape) * noise)
|
296 |
+
|
297 |
+
@torch.no_grad()
|
298 |
+
def decode(self, x_latent, cond, t_start, unconditional_guidance_scale=1.0, unconditional_conditioning=None,
|
299 |
+
use_original_steps=False, callback=None):
|
300 |
+
|
301 |
+
timesteps = np.arange(self.ddpm_num_timesteps) if use_original_steps else self.ddim_timesteps
|
302 |
+
timesteps = timesteps[:t_start]
|
303 |
+
|
304 |
+
time_range = np.flip(timesteps)
|
305 |
+
total_steps = timesteps.shape[0]
|
306 |
+
print(f"Running DDIM Sampling with {total_steps} timesteps")
|
307 |
+
|
308 |
+
iterator = tqdm(time_range, desc='Decoding image', total=total_steps)
|
309 |
+
x_dec = x_latent
|
310 |
+
for i, step in enumerate(iterator):
|
311 |
+
index = total_steps - i - 1
|
312 |
+
ts = torch.full((x_latent.shape[0],), step, device=x_latent.device, dtype=torch.long)
|
313 |
+
x_dec, _ = self.p_sample_ddim(x_dec, cond, ts, index=index, use_original_steps=use_original_steps,
|
314 |
+
unconditional_guidance_scale=unconditional_guidance_scale,
|
315 |
+
unconditional_conditioning=unconditional_conditioning)
|
316 |
+
if callback: callback(i)
|
317 |
+
return x_dec
|
ttts/AA_diffusion_deprecated/cldm/hack.py
ADDED
@@ -0,0 +1,111 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
import einops
|
3 |
+
|
4 |
+
import ldm.modules.encoders.modules
|
5 |
+
import ldm.modules.attention
|
6 |
+
|
7 |
+
from transformers import logging
|
8 |
+
from ldm.modules.attention import default
|
9 |
+
|
10 |
+
|
11 |
+
def disable_verbosity():
|
12 |
+
logging.set_verbosity_error()
|
13 |
+
print('logging improved.')
|
14 |
+
return
|
15 |
+
|
16 |
+
|
17 |
+
def enable_sliced_attention():
|
18 |
+
ldm.modules.attention.CrossAttention.forward = _hacked_sliced_attentin_forward
|
19 |
+
print('Enabled sliced_attention.')
|
20 |
+
return
|
21 |
+
|
22 |
+
|
23 |
+
def hack_everything(clip_skip=0):
|
24 |
+
disable_verbosity()
|
25 |
+
ldm.modules.encoders.modules.FrozenCLIPEmbedder.forward = _hacked_clip_forward
|
26 |
+
ldm.modules.encoders.modules.FrozenCLIPEmbedder.clip_skip = clip_skip
|
27 |
+
print('Enabled clip hacks.')
|
28 |
+
return
|
29 |
+
|
30 |
+
|
31 |
+
# Written by Lvmin
|
32 |
+
def _hacked_clip_forward(self, text):
|
33 |
+
PAD = self.tokenizer.pad_token_id
|
34 |
+
EOS = self.tokenizer.eos_token_id
|
35 |
+
BOS = self.tokenizer.bos_token_id
|
36 |
+
|
37 |
+
def tokenize(t):
|
38 |
+
return self.tokenizer(t, truncation=False, add_special_tokens=False)["input_ids"]
|
39 |
+
|
40 |
+
def transformer_encode(t):
|
41 |
+
if self.clip_skip > 1:
|
42 |
+
rt = self.transformer(input_ids=t, output_hidden_states=True)
|
43 |
+
return self.transformer.text_model.final_layer_norm(rt.hidden_states[-self.clip_skip])
|
44 |
+
else:
|
45 |
+
return self.transformer(input_ids=t, output_hidden_states=False).last_hidden_state
|
46 |
+
|
47 |
+
def split(x):
|
48 |
+
return x[75 * 0: 75 * 1], x[75 * 1: 75 * 2], x[75 * 2: 75 * 3]
|
49 |
+
|
50 |
+
def pad(x, p, i):
|
51 |
+
return x[:i] if len(x) >= i else x + [p] * (i - len(x))
|
52 |
+
|
53 |
+
raw_tokens_list = tokenize(text)
|
54 |
+
tokens_list = []
|
55 |
+
|
56 |
+
for raw_tokens in raw_tokens_list:
|
57 |
+
raw_tokens_123 = split(raw_tokens)
|
58 |
+
raw_tokens_123 = [[BOS] + raw_tokens_i + [EOS] for raw_tokens_i in raw_tokens_123]
|
59 |
+
raw_tokens_123 = [pad(raw_tokens_i, PAD, 77) for raw_tokens_i in raw_tokens_123]
|
60 |
+
tokens_list.append(raw_tokens_123)
|
61 |
+
|
62 |
+
tokens_list = torch.IntTensor(tokens_list).to(self.device)
|
63 |
+
|
64 |
+
feed = einops.rearrange(tokens_list, 'b f i -> (b f) i')
|
65 |
+
y = transformer_encode(feed)
|
66 |
+
z = einops.rearrange(y, '(b f) i c -> b (f i) c', f=3)
|
67 |
+
|
68 |
+
return z
|
69 |
+
|
70 |
+
|
71 |
+
# Stolen from https://github.com/basujindal/stable-diffusion/blob/main/optimizedSD/splitAttention.py
|
72 |
+
def _hacked_sliced_attentin_forward(self, x, context=None, mask=None):
|
73 |
+
h = self.heads
|
74 |
+
|
75 |
+
q = self.to_q(x)
|
76 |
+
context = default(context, x)
|
77 |
+
k = self.to_k(context)
|
78 |
+
v = self.to_v(context)
|
79 |
+
del context, x
|
80 |
+
|
81 |
+
q, k, v = map(lambda t: einops.rearrange(t, 'b n (h d) -> (b h) n d', h=h), (q, k, v))
|
82 |
+
|
83 |
+
limit = k.shape[0]
|
84 |
+
att_step = 1
|
85 |
+
q_chunks = list(torch.tensor_split(q, limit // att_step, dim=0))
|
86 |
+
k_chunks = list(torch.tensor_split(k, limit // att_step, dim=0))
|
87 |
+
v_chunks = list(torch.tensor_split(v, limit // att_step, dim=0))
|
88 |
+
|
89 |
+
q_chunks.reverse()
|
90 |
+
k_chunks.reverse()
|
91 |
+
v_chunks.reverse()
|
92 |
+
sim = torch.zeros(q.shape[0], q.shape[1], v.shape[2], device=q.device)
|
93 |
+
del k, q, v
|
94 |
+
for i in range(0, limit, att_step):
|
95 |
+
q_buffer = q_chunks.pop()
|
96 |
+
k_buffer = k_chunks.pop()
|
97 |
+
v_buffer = v_chunks.pop()
|
98 |
+
sim_buffer = torch.einsum('b i d, b j d -> b i j', q_buffer, k_buffer) * self.scale
|
99 |
+
|
100 |
+
del k_buffer, q_buffer
|
101 |
+
# attention, what we cannot get enough of, by chunks
|
102 |
+
|
103 |
+
sim_buffer = sim_buffer.softmax(dim=-1)
|
104 |
+
|
105 |
+
sim_buffer = torch.einsum('b i j, b j d -> b i d', sim_buffer, v_buffer)
|
106 |
+
del v_buffer
|
107 |
+
sim[i:i + att_step, :, :] = sim_buffer
|
108 |
+
|
109 |
+
del sim_buffer
|
110 |
+
sim = einops.rearrange(sim, '(b h) n d -> b n (h d)', h=h)
|
111 |
+
return self.to_out(sim)
|
ttts/AA_diffusion_deprecated/cldm/hf_model.py
ADDED
@@ -0,0 +1,193 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
""" huggingface model adapter
|
2 |
+
|
3 |
+
Wraps HuggingFace transformers (https://github.com/huggingface/transformers) models for use as a text tower in CLIP model.
|
4 |
+
"""
|
5 |
+
import re
|
6 |
+
|
7 |
+
import torch
|
8 |
+
import torch.nn as nn
|
9 |
+
from torch import TensorType
|
10 |
+
|
11 |
+
try:
|
12 |
+
import transformers
|
13 |
+
from transformers import AutoModel, AutoTokenizer, AutoConfig, PretrainedConfig
|
14 |
+
from transformers.modeling_outputs import BaseModelOutput, BaseModelOutputWithPooling, \
|
15 |
+
BaseModelOutputWithPoolingAndCrossAttentions
|
16 |
+
except ImportError as e:
|
17 |
+
transformers = None
|
18 |
+
|
19 |
+
|
20 |
+
class BaseModelOutput:
|
21 |
+
pass
|
22 |
+
|
23 |
+
|
24 |
+
class PretrainedConfig:
|
25 |
+
pass
|
26 |
+
|
27 |
+
from .hf_configs import arch_dict
|
28 |
+
|
29 |
+
|
30 |
+
# utils
|
31 |
+
def _camel2snake(s):
|
32 |
+
return re.sub(r'(?<!^)(?=[A-Z])', '_', s).lower()
|
33 |
+
|
34 |
+
|
35 |
+
# TODO: ?last - for gpt-like models
|
36 |
+
_POOLERS = {}
|
37 |
+
|
38 |
+
|
39 |
+
def register_pooler(cls):
|
40 |
+
"""Decorator registering pooler class"""
|
41 |
+
_POOLERS[_camel2snake(cls.__name__)] = cls
|
42 |
+
return cls
|
43 |
+
|
44 |
+
|
45 |
+
@register_pooler
|
46 |
+
class MeanPooler(nn.Module):
|
47 |
+
"""Mean pooling"""
|
48 |
+
|
49 |
+
def forward(self, x: BaseModelOutput, attention_mask: TensorType):
|
50 |
+
masked_output = x.last_hidden_state * attention_mask.unsqueeze(-1)
|
51 |
+
return masked_output.sum(dim=1) / attention_mask.sum(-1, keepdim=True)
|
52 |
+
|
53 |
+
|
54 |
+
@register_pooler
|
55 |
+
class MaxPooler(nn.Module):
|
56 |
+
"""Max pooling"""
|
57 |
+
|
58 |
+
def forward(self, x: BaseModelOutput, attention_mask: TensorType):
|
59 |
+
masked_output = x.last_hidden_state.masked_fill(attention_mask.unsqueeze(-1), -torch.inf)
|
60 |
+
return masked_output.max(1).values
|
61 |
+
|
62 |
+
|
63 |
+
@register_pooler
|
64 |
+
class ClsPooler(nn.Module):
|
65 |
+
"""CLS token pooling"""
|
66 |
+
|
67 |
+
def __init__(self, use_pooler_output=True):
|
68 |
+
super().__init__()
|
69 |
+
self.cls_token_position = 0
|
70 |
+
self.use_pooler_output = use_pooler_output
|
71 |
+
|
72 |
+
def forward(self, x: BaseModelOutput, attention_mask: TensorType):
|
73 |
+
if (self.use_pooler_output and
|
74 |
+
isinstance(x, (BaseModelOutputWithPooling, BaseModelOutputWithPoolingAndCrossAttentions)) and
|
75 |
+
(x.pooler_output is not None)
|
76 |
+
):
|
77 |
+
return x.pooler_output
|
78 |
+
|
79 |
+
return x.last_hidden_state[:, self.cls_token_position, :]
|
80 |
+
|
81 |
+
|
82 |
+
@register_pooler
|
83 |
+
class ClsLastHiddenStatePooler(nn.Module):
|
84 |
+
"""CLS token pooling
|
85 |
+
NOTE: this is equivalent to ClsPooler above with use_pooler_output=False
|
86 |
+
"""
|
87 |
+
|
88 |
+
def __init__(self):
|
89 |
+
super().__init__()
|
90 |
+
self.cls_token_position = 0
|
91 |
+
|
92 |
+
def forward(self, x: BaseModelOutput, attention_mask: TensorType):
|
93 |
+
return x.last_hidden_state[:, self.cls_token_position, :]
|
94 |
+
|
95 |
+
|
96 |
+
class HFTextEncoder(nn.Module):
|
97 |
+
"""HuggingFace model adapter"""
|
98 |
+
output_tokens: torch.jit.Final[bool]
|
99 |
+
|
100 |
+
def __init__(
|
101 |
+
self,
|
102 |
+
model_name_or_path: str,
|
103 |
+
output_dim: int,
|
104 |
+
config: PretrainedConfig = None,
|
105 |
+
pooler_type: str = None,
|
106 |
+
proj_type: str = None,
|
107 |
+
pretrained: bool = True,
|
108 |
+
output_tokens: bool = False,
|
109 |
+
):
|
110 |
+
super().__init__()
|
111 |
+
self.output_tokens = output_tokens
|
112 |
+
self.output_dim = output_dim
|
113 |
+
|
114 |
+
# TODO: find better way to get this information
|
115 |
+
uses_transformer_pooler = (pooler_type == "cls_pooler")
|
116 |
+
|
117 |
+
if transformers is None:
|
118 |
+
raise RuntimeError("Please `pip install transformers` to use pre-trained HuggingFace models")
|
119 |
+
if config is None:
|
120 |
+
self.config = AutoConfig.from_pretrained(model_name_or_path)
|
121 |
+
create_func, model_args = (AutoModel.from_pretrained, model_name_or_path) if pretrained else (
|
122 |
+
AutoModel.from_config, self.config)
|
123 |
+
# TODO: do all model configs have this attribute? PretrainedConfig does so yes??
|
124 |
+
if hasattr(self.config, "is_encoder_decoder") and self.config.is_encoder_decoder:
|
125 |
+
self.transformer = create_func(model_args)
|
126 |
+
self.transformer = self.transformer.encoder
|
127 |
+
else:
|
128 |
+
self.transformer = create_func(model_args, add_pooling_layer=uses_transformer_pooler)
|
129 |
+
else:
|
130 |
+
self.config = config
|
131 |
+
self.transformer = AutoModel.from_config(config)
|
132 |
+
if pooler_type is None: # get default arch pooler
|
133 |
+
pooler_type = (arch_dict[self.config.model_type]["pooler"])
|
134 |
+
|
135 |
+
# FIXME downstream users of OpenCLIP models use these attr, need to verify valid across all models
|
136 |
+
self.vocab_size = getattr(self.config, 'vocab_size', 0)
|
137 |
+
self.context_length = getattr(self.config, 'max_position_embeddings', 0)
|
138 |
+
|
139 |
+
self.pooler = _POOLERS[pooler_type]()
|
140 |
+
|
141 |
+
d_model = getattr(self.config, arch_dict[self.config.model_type]["config_names"]["width"])
|
142 |
+
if (d_model == output_dim) and (proj_type is None): # do we always need a proj?
|
143 |
+
self.proj = nn.Identity()
|
144 |
+
elif proj_type == 'linear':
|
145 |
+
self.proj = nn.Linear(d_model, output_dim, bias=False)
|
146 |
+
elif proj_type == 'mlp':
|
147 |
+
hidden_size = (d_model + output_dim) // 2
|
148 |
+
self.proj = nn.Sequential(
|
149 |
+
nn.Linear(d_model, hidden_size, bias=False),
|
150 |
+
nn.GELU(),
|
151 |
+
nn.Linear(hidden_size, output_dim, bias=False),
|
152 |
+
)
|
153 |
+
|
154 |
+
def forward(self, x: TensorType):
|
155 |
+
attn_mask = (x != self.config.pad_token_id).long()
|
156 |
+
out = self.transformer(input_ids=x, attention_mask=attn_mask)
|
157 |
+
pooled_out = self.pooler(out, attn_mask)
|
158 |
+
projected = self.proj(pooled_out)
|
159 |
+
|
160 |
+
seq_len = out.last_hidden_state.shape[1]
|
161 |
+
tokens = (
|
162 |
+
out.last_hidden_state[:, torch.arange(seq_len) != self.pooler.cls_token_position, :]
|
163 |
+
if type(self.pooler) == ClsPooler
|
164 |
+
else out.last_hidden_state
|
165 |
+
)
|
166 |
+
|
167 |
+
if self.output_tokens:
|
168 |
+
return projected, tokens
|
169 |
+
return projected
|
170 |
+
|
171 |
+
def lock(self, unlocked_layers: int = 0, freeze_layer_norm: bool = True):
|
172 |
+
if not unlocked_layers: # full freezing
|
173 |
+
for n, p in self.transformer.named_parameters():
|
174 |
+
p.requires_grad = (not freeze_layer_norm) if "LayerNorm" in n.split(".") else False
|
175 |
+
return
|
176 |
+
|
177 |
+
encoder = self.transformer.encoder if hasattr(self.transformer, 'encoder') else self.transformer
|
178 |
+
layer_list = getattr(encoder, arch_dict[self.config.model_type]["config_names"]["layer_attr"])
|
179 |
+
print(f"Unlocking {unlocked_layers}/{len(layer_list) + 1} layers of hf model")
|
180 |
+
embeddings = getattr(
|
181 |
+
self.transformer, arch_dict[self.config.model_type]["config_names"]["token_embeddings_attr"])
|
182 |
+
modules = [embeddings, *layer_list][:-unlocked_layers]
|
183 |
+
# freeze layers
|
184 |
+
for module in modules:
|
185 |
+
for n, p in module.named_parameters():
|
186 |
+
p.requires_grad = (not freeze_layer_norm) if "LayerNorm" in n.split(".") else False
|
187 |
+
|
188 |
+
@torch.jit.ignore
|
189 |
+
def set_grad_checkpointing(self, enable=True):
|
190 |
+
self.transformer.gradient_checkpointing_enable()
|
191 |
+
|
192 |
+
def init_parameters(self):
|
193 |
+
pass
|
ttts/AA_diffusion_deprecated/cldm/logger.py
ADDED
@@ -0,0 +1,76 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
|
3 |
+
import numpy as np
|
4 |
+
import torch
|
5 |
+
import torchvision
|
6 |
+
from PIL import Image
|
7 |
+
from pytorch_lightning.callbacks import Callback
|
8 |
+
from pytorch_lightning.utilities.distributed import rank_zero_only
|
9 |
+
|
10 |
+
|
11 |
+
class ImageLogger(Callback):
|
12 |
+
def __init__(self, batch_frequency=2000, max_images=4, clamp=True, increase_log_steps=True,
|
13 |
+
rescale=True, disabled=False, log_on_batch_idx=False, log_first_step=False,
|
14 |
+
log_images_kwargs=None):
|
15 |
+
super().__init__()
|
16 |
+
self.rescale = rescale
|
17 |
+
self.batch_freq = batch_frequency
|
18 |
+
self.max_images = max_images
|
19 |
+
if not increase_log_steps:
|
20 |
+
self.log_steps = [self.batch_freq]
|
21 |
+
self.clamp = clamp
|
22 |
+
self.disabled = disabled
|
23 |
+
self.log_on_batch_idx = log_on_batch_idx
|
24 |
+
self.log_images_kwargs = log_images_kwargs if log_images_kwargs else {}
|
25 |
+
self.log_first_step = log_first_step
|
26 |
+
|
27 |
+
@rank_zero_only
|
28 |
+
def log_local(self, save_dir, split, images, global_step, current_epoch, batch_idx):
|
29 |
+
root = os.path.join(save_dir, "image_log", split)
|
30 |
+
for k in images:
|
31 |
+
grid = torchvision.utils.make_grid(images[k], nrow=4)
|
32 |
+
if self.rescale:
|
33 |
+
grid = (grid + 1.0) / 2.0 # -1,1 -> 0,1; c,h,w
|
34 |
+
grid = grid.transpose(0, 1).transpose(1, 2).squeeze(-1)
|
35 |
+
grid = grid.numpy()
|
36 |
+
grid = (grid * 255).astype(np.uint8)
|
37 |
+
filename = "{}_gs-{:06}_e-{:06}_b-{:06}.png".format(k, global_step, current_epoch, batch_idx)
|
38 |
+
path = os.path.join(root, filename)
|
39 |
+
os.makedirs(os.path.split(path)[0], exist_ok=True)
|
40 |
+
Image.fromarray(grid).save(path)
|
41 |
+
|
42 |
+
def log_img(self, pl_module, batch, batch_idx, split="train"):
|
43 |
+
check_idx = batch_idx # if self.log_on_batch_idx else pl_module.global_step
|
44 |
+
if (self.check_frequency(check_idx) and # batch_idx % self.batch_freq == 0
|
45 |
+
hasattr(pl_module, "log_images") and
|
46 |
+
callable(pl_module.log_images) and
|
47 |
+
self.max_images > 0):
|
48 |
+
logger = type(pl_module.logger)
|
49 |
+
|
50 |
+
is_train = pl_module.training
|
51 |
+
if is_train:
|
52 |
+
pl_module.eval()
|
53 |
+
|
54 |
+
with torch.no_grad():
|
55 |
+
images = pl_module.log_images(batch, split=split, **self.log_images_kwargs)
|
56 |
+
|
57 |
+
for k in images:
|
58 |
+
N = min(images[k].shape[0], self.max_images)
|
59 |
+
images[k] = images[k][:N]
|
60 |
+
if isinstance(images[k], torch.Tensor):
|
61 |
+
images[k] = images[k].detach().cpu()
|
62 |
+
if self.clamp:
|
63 |
+
images[k] = torch.clamp(images[k], -1., 1.)
|
64 |
+
|
65 |
+
self.log_local(pl_module.logger.save_dir, split, images,
|
66 |
+
pl_module.global_step, pl_module.current_epoch, batch_idx)
|
67 |
+
|
68 |
+
if is_train:
|
69 |
+
pl_module.train()
|
70 |
+
|
71 |
+
def check_frequency(self, check_idx):
|
72 |
+
return check_idx % self.batch_freq == 0
|
73 |
+
|
74 |
+
def on_train_batch_end(self, trainer, pl_module, outputs, batch, batch_idx, dataloader_idx):
|
75 |
+
if not self.disabled:
|
76 |
+
self.log_img(pl_module, batch, batch_idx, split="train")
|
ttts/AA_diffusion_deprecated/cldm/model.py
ADDED
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import torch
|
3 |
+
|
4 |
+
from omegaconf import OmegaConf
|
5 |
+
from ldm.util import instantiate_from_config
|
6 |
+
|
7 |
+
|
8 |
+
def get_state_dict(d):
|
9 |
+
return d.get('state_dict', d)
|
10 |
+
|
11 |
+
|
12 |
+
def load_state_dict(ckpt_path, location='cpu'):
|
13 |
+
_, extension = os.path.splitext(ckpt_path)
|
14 |
+
if extension.lower() == ".safetensors":
|
15 |
+
import safetensors.torch
|
16 |
+
state_dict = safetensors.torch.load_file(ckpt_path, device=location)
|
17 |
+
else:
|
18 |
+
state_dict = get_state_dict(torch.load(ckpt_path, map_location=torch.device(location)))
|
19 |
+
state_dict = get_state_dict(state_dict)
|
20 |
+
print(f'Loaded state_dict from [{ckpt_path}]')
|
21 |
+
return state_dict
|
22 |
+
|
23 |
+
|
24 |
+
def create_model(config_path):
|
25 |
+
config = OmegaConf.load(config_path)
|
26 |
+
model = instantiate_from_config(config.model).cpu()
|
27 |
+
print(f'Loaded model config from [{config_path}]')
|
28 |
+
return model
|
ttts/AA_diffusion_deprecated/cldm/modified_resnet.py
ADDED
@@ -0,0 +1,181 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from collections import OrderedDict
|
2 |
+
|
3 |
+
import torch
|
4 |
+
from torch import nn
|
5 |
+
from torch.nn import functional as F
|
6 |
+
|
7 |
+
from .utils import freeze_batch_norm_2d
|
8 |
+
|
9 |
+
|
10 |
+
class Bottleneck(nn.Module):
|
11 |
+
expansion = 4
|
12 |
+
|
13 |
+
def __init__(self, inplanes, planes, stride=1):
|
14 |
+
super().__init__()
|
15 |
+
|
16 |
+
# all conv layers have stride 1. an avgpool is performed after the second convolution when stride > 1
|
17 |
+
self.conv1 = nn.Conv2d(inplanes, planes, 1, bias=False)
|
18 |
+
self.bn1 = nn.BatchNorm2d(planes)
|
19 |
+
self.act1 = nn.ReLU(inplace=True)
|
20 |
+
|
21 |
+
self.conv2 = nn.Conv2d(planes, planes, 3, padding=1, bias=False)
|
22 |
+
self.bn2 = nn.BatchNorm2d(planes)
|
23 |
+
self.act2 = nn.ReLU(inplace=True)
|
24 |
+
|
25 |
+
self.avgpool = nn.AvgPool2d(stride) if stride > 1 else nn.Identity()
|
26 |
+
|
27 |
+
self.conv3 = nn.Conv2d(planes, planes * self.expansion, 1, bias=False)
|
28 |
+
self.bn3 = nn.BatchNorm2d(planes * self.expansion)
|
29 |
+
self.act3 = nn.ReLU(inplace=True)
|
30 |
+
|
31 |
+
self.downsample = None
|
32 |
+
self.stride = stride
|
33 |
+
|
34 |
+
if stride > 1 or inplanes != planes * Bottleneck.expansion:
|
35 |
+
# downsampling layer is prepended with an avgpool, and the subsequent convolution has stride 1
|
36 |
+
self.downsample = nn.Sequential(OrderedDict([
|
37 |
+
("-1", nn.AvgPool2d(stride)),
|
38 |
+
("0", nn.Conv2d(inplanes, planes * self.expansion, 1, stride=1, bias=False)),
|
39 |
+
("1", nn.BatchNorm2d(planes * self.expansion))
|
40 |
+
]))
|
41 |
+
|
42 |
+
def forward(self, x: torch.Tensor):
|
43 |
+
identity = x
|
44 |
+
|
45 |
+
out = self.act1(self.bn1(self.conv1(x)))
|
46 |
+
out = self.act2(self.bn2(self.conv2(out)))
|
47 |
+
out = self.avgpool(out)
|
48 |
+
out = self.bn3(self.conv3(out))
|
49 |
+
|
50 |
+
if self.downsample is not None:
|
51 |
+
identity = self.downsample(x)
|
52 |
+
|
53 |
+
out += identity
|
54 |
+
out = self.act3(out)
|
55 |
+
return out
|
56 |
+
|
57 |
+
|
58 |
+
class AttentionPool2d(nn.Module):
|
59 |
+
def __init__(self, spacial_dim: int, embed_dim: int, num_heads: int, output_dim: int = None):
|
60 |
+
super().__init__()
|
61 |
+
self.positional_embedding = nn.Parameter(torch.randn(spacial_dim ** 2 + 1, embed_dim) / embed_dim ** 0.5)
|
62 |
+
self.k_proj = nn.Linear(embed_dim, embed_dim)
|
63 |
+
self.q_proj = nn.Linear(embed_dim, embed_dim)
|
64 |
+
self.v_proj = nn.Linear(embed_dim, embed_dim)
|
65 |
+
self.c_proj = nn.Linear(embed_dim, output_dim or embed_dim)
|
66 |
+
self.num_heads = num_heads
|
67 |
+
|
68 |
+
def forward(self, x):
|
69 |
+
x = x.reshape(x.shape[0], x.shape[1], x.shape[2] * x.shape[3]).permute(2, 0, 1) # NCHW -> (HW)NC
|
70 |
+
x = torch.cat([x.mean(dim=0, keepdim=True), x], dim=0) # (HW+1)NC
|
71 |
+
x = x + self.positional_embedding[:, None, :].to(x.dtype) # (HW+1)NC
|
72 |
+
x, _ = F.multi_head_attention_forward(
|
73 |
+
query=x, key=x, value=x,
|
74 |
+
embed_dim_to_check=x.shape[-1],
|
75 |
+
num_heads=self.num_heads,
|
76 |
+
q_proj_weight=self.q_proj.weight,
|
77 |
+
k_proj_weight=self.k_proj.weight,
|
78 |
+
v_proj_weight=self.v_proj.weight,
|
79 |
+
in_proj_weight=None,
|
80 |
+
in_proj_bias=torch.cat([self.q_proj.bias, self.k_proj.bias, self.v_proj.bias]),
|
81 |
+
bias_k=None,
|
82 |
+
bias_v=None,
|
83 |
+
add_zero_attn=False,
|
84 |
+
dropout_p=0.,
|
85 |
+
out_proj_weight=self.c_proj.weight,
|
86 |
+
out_proj_bias=self.c_proj.bias,
|
87 |
+
use_separate_proj_weight=True,
|
88 |
+
training=self.training,
|
89 |
+
need_weights=False
|
90 |
+
)
|
91 |
+
|
92 |
+
return x[0]
|
93 |
+
|
94 |
+
|
95 |
+
class ModifiedResNet(nn.Module):
|
96 |
+
"""
|
97 |
+
A ResNet class that is similar to torchvision's but contains the following changes:
|
98 |
+
- There are now 3 "stem" convolutions as opposed to 1, with an average pool instead of a max pool.
|
99 |
+
- Performs anti-aliasing strided convolutions, where an avgpool is prepended to convolutions with stride > 1
|
100 |
+
- The final pooling layer is a QKV attention instead of an average pool
|
101 |
+
"""
|
102 |
+
|
103 |
+
def __init__(self, layers, output_dim, heads, image_size=224, width=64):
|
104 |
+
super().__init__()
|
105 |
+
self.output_dim = output_dim
|
106 |
+
self.image_size = image_size
|
107 |
+
|
108 |
+
# the 3-layer stem
|
109 |
+
self.conv1 = nn.Conv2d(3, width // 2, kernel_size=3, stride=2, padding=1, bias=False)
|
110 |
+
self.bn1 = nn.BatchNorm2d(width // 2)
|
111 |
+
self.act1 = nn.ReLU(inplace=True)
|
112 |
+
self.conv2 = nn.Conv2d(width // 2, width // 2, kernel_size=3, padding=1, bias=False)
|
113 |
+
self.bn2 = nn.BatchNorm2d(width // 2)
|
114 |
+
self.act2 = nn.ReLU(inplace=True)
|
115 |
+
self.conv3 = nn.Conv2d(width // 2, width, kernel_size=3, padding=1, bias=False)
|
116 |
+
self.bn3 = nn.BatchNorm2d(width)
|
117 |
+
self.act3 = nn.ReLU(inplace=True)
|
118 |
+
self.avgpool = nn.AvgPool2d(2)
|
119 |
+
|
120 |
+
# residual layers
|
121 |
+
self._inplanes = width # this is a *mutable* variable used during construction
|
122 |
+
self.layer1 = self._make_layer(width, layers[0])
|
123 |
+
self.layer2 = self._make_layer(width * 2, layers[1], stride=2)
|
124 |
+
self.layer3 = self._make_layer(width * 4, layers[2], stride=2)
|
125 |
+
self.layer4 = self._make_layer(width * 8, layers[3], stride=2)
|
126 |
+
|
127 |
+
embed_dim = width * 32 # the ResNet feature dimension
|
128 |
+
self.attnpool = AttentionPool2d(image_size // 32, embed_dim, heads, output_dim)
|
129 |
+
|
130 |
+
self.init_parameters()
|
131 |
+
|
132 |
+
def _make_layer(self, planes, blocks, stride=1):
|
133 |
+
layers = [Bottleneck(self._inplanes, planes, stride)]
|
134 |
+
|
135 |
+
self._inplanes = planes * Bottleneck.expansion
|
136 |
+
for _ in range(1, blocks):
|
137 |
+
layers.append(Bottleneck(self._inplanes, planes))
|
138 |
+
|
139 |
+
return nn.Sequential(*layers)
|
140 |
+
|
141 |
+
def init_parameters(self):
|
142 |
+
if self.attnpool is not None:
|
143 |
+
std = self.attnpool.c_proj.in_features ** -0.5
|
144 |
+
nn.init.normal_(self.attnpool.q_proj.weight, std=std)
|
145 |
+
nn.init.normal_(self.attnpool.k_proj.weight, std=std)
|
146 |
+
nn.init.normal_(self.attnpool.v_proj.weight, std=std)
|
147 |
+
nn.init.normal_(self.attnpool.c_proj.weight, std=std)
|
148 |
+
|
149 |
+
for resnet_block in [self.layer1, self.layer2, self.layer3, self.layer4]:
|
150 |
+
for name, param in resnet_block.named_parameters():
|
151 |
+
if name.endswith("bn3.weight"):
|
152 |
+
nn.init.zeros_(param)
|
153 |
+
|
154 |
+
def lock(self, unlocked_groups=0, freeze_bn_stats=False):
|
155 |
+
assert unlocked_groups == 0, 'partial locking not currently supported for this model'
|
156 |
+
for param in self.parameters():
|
157 |
+
param.requires_grad = False
|
158 |
+
if freeze_bn_stats:
|
159 |
+
freeze_batch_norm_2d(self)
|
160 |
+
|
161 |
+
@torch.jit.ignore
|
162 |
+
def set_grad_checkpointing(self, enable=True):
|
163 |
+
# FIXME support for non-transformer
|
164 |
+
pass
|
165 |
+
|
166 |
+
def stem(self, x):
|
167 |
+
x = self.act1(self.bn1(self.conv1(x)))
|
168 |
+
x = self.act2(self.bn2(self.conv2(x)))
|
169 |
+
x = self.act3(self.bn3(self.conv3(x)))
|
170 |
+
x = self.avgpool(x)
|
171 |
+
return x
|
172 |
+
|
173 |
+
def forward(self, x):
|
174 |
+
x = self.stem(x)
|
175 |
+
x = self.layer1(x)
|
176 |
+
x = self.layer2(x)
|
177 |
+
x = self.layer3(x)
|
178 |
+
x = self.layer4(x)
|
179 |
+
x = self.attnpool(x)
|
180 |
+
|
181 |
+
return x
|
ttts/AA_diffusion_deprecated/cldm/pos_embed.py
ADDED
@@ -0,0 +1,96 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright (c) Meta Platforms, Inc. and affiliates.
|
2 |
+
# All rights reserved.
|
3 |
+
|
4 |
+
# This source code is licensed under the license found in the
|
5 |
+
# LICENSE file in the root directory of this source tree.
|
6 |
+
# --------------------------------------------------------
|
7 |
+
# Position embedding utils
|
8 |
+
# --------------------------------------------------------
|
9 |
+
|
10 |
+
import numpy as np
|
11 |
+
|
12 |
+
import torch
|
13 |
+
|
14 |
+
# --------------------------------------------------------
|
15 |
+
# 2D sine-cosine position embedding
|
16 |
+
# References:
|
17 |
+
# Transformer: https://github.com/tensorflow/models/blob/master/official/nlp/transformer/model_utils.py
|
18 |
+
# MoCo v3: https://github.com/facebookresearch/moco-v3
|
19 |
+
# --------------------------------------------------------
|
20 |
+
def get_2d_sincos_pos_embed(embed_dim, grid_size, cls_token=False):
|
21 |
+
"""
|
22 |
+
grid_size: int of the grid height and width
|
23 |
+
return:
|
24 |
+
pos_embed: [grid_size*grid_size, embed_dim] or [1+grid_size*grid_size, embed_dim] (w/ or w/o cls_token)
|
25 |
+
"""
|
26 |
+
grid_h = np.arange(grid_size, dtype=np.float32)
|
27 |
+
grid_w = np.arange(grid_size, dtype=np.float32)
|
28 |
+
grid = np.meshgrid(grid_w, grid_h) # here w goes first
|
29 |
+
grid = np.stack(grid, axis=0)
|
30 |
+
|
31 |
+
grid = grid.reshape([2, 1, grid_size, grid_size])
|
32 |
+
pos_embed = get_2d_sincos_pos_embed_from_grid(embed_dim, grid)
|
33 |
+
if cls_token:
|
34 |
+
pos_embed = np.concatenate([np.zeros([1, embed_dim]), pos_embed], axis=0)
|
35 |
+
return pos_embed
|
36 |
+
|
37 |
+
|
38 |
+
def get_2d_sincos_pos_embed_from_grid(embed_dim, grid):
|
39 |
+
assert embed_dim % 2 == 0
|
40 |
+
|
41 |
+
# use half of dimensions to encode grid_h
|
42 |
+
emb_h = get_1d_sincos_pos_embed_from_grid(embed_dim // 2, grid[0]) # (H*W, D/2)
|
43 |
+
emb_w = get_1d_sincos_pos_embed_from_grid(embed_dim // 2, grid[1]) # (H*W, D/2)
|
44 |
+
|
45 |
+
emb = np.concatenate([emb_h, emb_w], axis=1) # (H*W, D)
|
46 |
+
return emb
|
47 |
+
|
48 |
+
|
49 |
+
def get_1d_sincos_pos_embed_from_grid(embed_dim, pos):
|
50 |
+
"""
|
51 |
+
embed_dim: output dimension for each position
|
52 |
+
pos: a list of positions to be encoded: size (M,)
|
53 |
+
out: (M, D)
|
54 |
+
"""
|
55 |
+
assert embed_dim % 2 == 0
|
56 |
+
omega = np.arange(embed_dim // 2, dtype=float)
|
57 |
+
omega /= embed_dim / 2.
|
58 |
+
omega = 1. / 10000**omega # (D/2,)
|
59 |
+
|
60 |
+
pos = pos.reshape(-1) # (M,)
|
61 |
+
out = np.einsum('m,d->md', pos, omega) # (M, D/2), outer product
|
62 |
+
|
63 |
+
emb_sin = np.sin(out) # (M, D/2)
|
64 |
+
emb_cos = np.cos(out) # (M, D/2)
|
65 |
+
|
66 |
+
emb = np.concatenate([emb_sin, emb_cos], axis=1) # (M, D)
|
67 |
+
return emb
|
68 |
+
|
69 |
+
|
70 |
+
# --------------------------------------------------------
|
71 |
+
# Interpolate position embeddings for high-resolution
|
72 |
+
# References:
|
73 |
+
# DeiT: https://github.com/facebookresearch/deit
|
74 |
+
# --------------------------------------------------------
|
75 |
+
def interpolate_pos_embed(model, checkpoint_model):
|
76 |
+
if 'pos_embed' in checkpoint_model:
|
77 |
+
pos_embed_checkpoint = checkpoint_model['pos_embed']
|
78 |
+
embedding_size = pos_embed_checkpoint.shape[-1]
|
79 |
+
num_patches = model.patch_embed.num_patches
|
80 |
+
num_extra_tokens = model.pos_embed.shape[-2] - num_patches
|
81 |
+
# height (== width) for the checkpoint position embedding
|
82 |
+
orig_size = int((pos_embed_checkpoint.shape[-2] - num_extra_tokens) ** 0.5)
|
83 |
+
# height (== width) for the new position embedding
|
84 |
+
new_size = int(num_patches ** 0.5)
|
85 |
+
# class_token and dist_token are kept unchanged
|
86 |
+
if orig_size != new_size:
|
87 |
+
print("Position interpolate from %dx%d to %dx%d" % (orig_size, orig_size, new_size, new_size))
|
88 |
+
extra_tokens = pos_embed_checkpoint[:, :num_extra_tokens]
|
89 |
+
# only the position tokens are interpolated
|
90 |
+
pos_tokens = pos_embed_checkpoint[:, num_extra_tokens:]
|
91 |
+
pos_tokens = pos_tokens.reshape(-1, orig_size, orig_size, embedding_size).permute(0, 3, 1, 2)
|
92 |
+
pos_tokens = torch.nn.functional.interpolate(
|
93 |
+
pos_tokens, size=(new_size, new_size), mode='bicubic', align_corners=False)
|
94 |
+
pos_tokens = pos_tokens.permute(0, 2, 3, 1).flatten(1, 2)
|
95 |
+
new_pos_embed = torch.cat((extra_tokens, pos_tokens), dim=1)
|
96 |
+
checkpoint_model['pos_embed'] = new_pos_embed
|
ttts/AA_diffusion_deprecated/cldm/timm_model.py
ADDED
@@ -0,0 +1,152 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
""" timm model adapter
|
2 |
+
|
3 |
+
Wraps timm (https://github.com/rwightman/pytorch-image-models) models for use as a vision tower in CLIP model.
|
4 |
+
"""
|
5 |
+
import logging
|
6 |
+
from collections import OrderedDict
|
7 |
+
|
8 |
+
import torch
|
9 |
+
import torch.nn as nn
|
10 |
+
|
11 |
+
try:
|
12 |
+
import timm
|
13 |
+
from timm.models.layers import Mlp, to_2tuple
|
14 |
+
try:
|
15 |
+
# old timm imports < 0.8.1
|
16 |
+
from timm.models.layers.attention_pool2d import RotAttentionPool2d
|
17 |
+
from timm.models.layers.attention_pool2d import AttentionPool2d as AbsAttentionPool2d
|
18 |
+
except ImportError:
|
19 |
+
# new timm imports >= 0.8.1
|
20 |
+
from timm.layers import RotAttentionPool2d
|
21 |
+
from timm.layers import AttentionPool2d as AbsAttentionPool2d
|
22 |
+
except ImportError:
|
23 |
+
timm = None
|
24 |
+
|
25 |
+
from .utils import freeze_batch_norm_2d
|
26 |
+
|
27 |
+
|
28 |
+
class TimmModel(nn.Module):
|
29 |
+
""" timm model adapter
|
30 |
+
"""
|
31 |
+
|
32 |
+
def __init__(
|
33 |
+
self,
|
34 |
+
model_name,
|
35 |
+
embed_dim,
|
36 |
+
image_size=224,
|
37 |
+
pool='avg',
|
38 |
+
proj='linear',
|
39 |
+
proj_bias=False,
|
40 |
+
drop=0.,
|
41 |
+
drop_path=None,
|
42 |
+
patch_drop=None,
|
43 |
+
pretrained=False,
|
44 |
+
):
|
45 |
+
super().__init__()
|
46 |
+
if timm is None:
|
47 |
+
raise RuntimeError("Please `pip install timm` to use timm models.")
|
48 |
+
self.image_size = to_2tuple(image_size)
|
49 |
+
|
50 |
+
# setup kwargs that may not be common across all models
|
51 |
+
timm_kwargs = {}
|
52 |
+
if drop_path is not None:
|
53 |
+
timm_kwargs['drop_path_rate'] = drop_path
|
54 |
+
if patch_drop is not None:
|
55 |
+
timm_kwargs['patch_drop_rate'] = patch_drop
|
56 |
+
|
57 |
+
custom_pool = pool in ('abs_attn', 'rot_attn')
|
58 |
+
if proj:
|
59 |
+
assert proj in ("linear", "mlp", "none")
|
60 |
+
extra_proj = proj in ("linear", "mlp")
|
61 |
+
if not extra_proj and not custom_pool:
|
62 |
+
# use network classifier head as projection if no proj specified and no custom pooling used
|
63 |
+
# if projection is explicitly set to "none" will be pass through from network trunk
|
64 |
+
proj_dim = 0 if proj == 'none' else embed_dim
|
65 |
+
self.trunk = timm.create_model(
|
66 |
+
model_name,
|
67 |
+
num_classes=proj_dim,
|
68 |
+
global_pool=pool,
|
69 |
+
pretrained=pretrained,
|
70 |
+
**timm_kwargs,
|
71 |
+
)
|
72 |
+
prev_chs = embed_dim
|
73 |
+
else:
|
74 |
+
self.trunk = timm.create_model(
|
75 |
+
model_name,
|
76 |
+
pretrained=pretrained,
|
77 |
+
**timm_kwargs,
|
78 |
+
)
|
79 |
+
feat_size = self.trunk.default_cfg.get('pool_size', None)
|
80 |
+
feature_ndim = 1 if not feat_size else 2
|
81 |
+
if custom_pool:
|
82 |
+
assert feature_ndim == 2
|
83 |
+
# if attn pooling used, remove both classifier and default pool
|
84 |
+
self.trunk.reset_classifier(0, global_pool='')
|
85 |
+
else:
|
86 |
+
# reset global pool if pool config set, otherwise leave as network default
|
87 |
+
reset_kwargs = dict(global_pool=pool) if pool else {}
|
88 |
+
self.trunk.reset_classifier(0, **reset_kwargs)
|
89 |
+
prev_chs = self.trunk.num_features
|
90 |
+
|
91 |
+
head_layers = OrderedDict()
|
92 |
+
|
93 |
+
# Add custom pooling to head
|
94 |
+
if pool == 'abs_attn':
|
95 |
+
head_layers['pool'] = AbsAttentionPool2d(prev_chs, feat_size=feat_size, out_features=embed_dim)
|
96 |
+
prev_chs = embed_dim
|
97 |
+
elif pool == 'rot_attn':
|
98 |
+
head_layers['pool'] = RotAttentionPool2d(prev_chs, out_features=embed_dim)
|
99 |
+
prev_chs = embed_dim
|
100 |
+
|
101 |
+
# NOTE attention pool ends with a projection layer, so proj should usually be set to '' if such pooling is used
|
102 |
+
if proj == 'linear':
|
103 |
+
head_layers['drop'] = nn.Dropout(drop)
|
104 |
+
head_layers['proj'] = nn.Linear(prev_chs, embed_dim, bias=proj_bias)
|
105 |
+
elif proj == 'mlp':
|
106 |
+
head_layers['mlp'] = Mlp(prev_chs, 2 * embed_dim, embed_dim, drop=(drop, 0), bias=(True, proj_bias))
|
107 |
+
|
108 |
+
self.head = nn.Sequential(head_layers)
|
109 |
+
|
110 |
+
def lock(self, unlocked_groups=0, freeze_bn_stats=False):
|
111 |
+
""" lock modules
|
112 |
+
Args:
|
113 |
+
unlocked_groups (int): leave last n layer groups unlocked (default: 0)
|
114 |
+
"""
|
115 |
+
if not unlocked_groups:
|
116 |
+
# lock full model
|
117 |
+
for param in self.trunk.parameters():
|
118 |
+
param.requires_grad = False
|
119 |
+
if freeze_bn_stats:
|
120 |
+
freeze_batch_norm_2d(self.trunk)
|
121 |
+
else:
|
122 |
+
# NOTE: partial freeze requires latest timm (master) branch and is subject to change
|
123 |
+
try:
|
124 |
+
# FIXME import here until API stable and in an official release
|
125 |
+
from timm.models.helpers import group_parameters, group_modules
|
126 |
+
except ImportError:
|
127 |
+
raise RuntimeError(
|
128 |
+
'Please install latest timm `pip install git+https://github.com/rwightman/pytorch-image-models`')
|
129 |
+
matcher = self.trunk.group_matcher()
|
130 |
+
gparams = group_parameters(self.trunk, matcher)
|
131 |
+
max_layer_id = max(gparams.keys())
|
132 |
+
max_layer_id = max_layer_id - unlocked_groups
|
133 |
+
for group_idx in range(max_layer_id + 1):
|
134 |
+
group = gparams[group_idx]
|
135 |
+
for param in group:
|
136 |
+
self.trunk.get_parameter(param).requires_grad = False
|
137 |
+
if freeze_bn_stats:
|
138 |
+
gmodules = group_modules(self.trunk, matcher, reverse=True)
|
139 |
+
gmodules = {k for k, v in gmodules.items() if v <= max_layer_id}
|
140 |
+
freeze_batch_norm_2d(self.trunk, gmodules)
|
141 |
+
|
142 |
+
@torch.jit.ignore
|
143 |
+
def set_grad_checkpointing(self, enable=True):
|
144 |
+
try:
|
145 |
+
self.trunk.set_grad_checkpointing(enable)
|
146 |
+
except Exception as e:
|
147 |
+
logging.warning('grad checkpointing not supported for this timm image tower, continuing without...')
|
148 |
+
|
149 |
+
def forward(self, x):
|
150 |
+
x = self.trunk(x)
|
151 |
+
x = self.head(x)
|
152 |
+
return x
|
ttts/AA_diffusion_deprecated/cldm/transformer.py
ADDED
@@ -0,0 +1,806 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from collections import OrderedDict
|
2 |
+
import math
|
3 |
+
from typing import Callable, Optional, Sequence, Tuple
|
4 |
+
from functools import partial
|
5 |
+
|
6 |
+
import torch
|
7 |
+
from torch import nn
|
8 |
+
from torch.nn import functional as F
|
9 |
+
from torch.utils.checkpoint import checkpoint
|
10 |
+
|
11 |
+
from .utils import to_2tuple
|
12 |
+
from .pos_embed import get_2d_sincos_pos_embed
|
13 |
+
|
14 |
+
|
15 |
+
class LayerNormFp32(nn.LayerNorm):
|
16 |
+
"""Subclass torch's LayerNorm to handle fp16 (by casting to float32 and back)."""
|
17 |
+
|
18 |
+
def forward(self, x: torch.Tensor):
|
19 |
+
orig_type = x.dtype
|
20 |
+
x = F.layer_norm(x.to(torch.float32), self.normalized_shape, self.weight, self.bias, self.eps)
|
21 |
+
return x.to(orig_type)
|
22 |
+
|
23 |
+
|
24 |
+
class LayerNorm(nn.LayerNorm):
|
25 |
+
"""Subclass torch's LayerNorm (with cast back to input dtype)."""
|
26 |
+
|
27 |
+
def forward(self, x: torch.Tensor):
|
28 |
+
orig_type = x.dtype
|
29 |
+
x = F.layer_norm(x, self.normalized_shape, self.weight, self.bias, self.eps)
|
30 |
+
return x.to(orig_type)
|
31 |
+
|
32 |
+
|
33 |
+
class QuickGELU(nn.Module):
|
34 |
+
# NOTE This is slower than nn.GELU or nn.SiLU and uses more GPU memory
|
35 |
+
def forward(self, x: torch.Tensor):
|
36 |
+
return x * torch.sigmoid(1.702 * x)
|
37 |
+
|
38 |
+
|
39 |
+
class LayerScale(nn.Module):
|
40 |
+
def __init__(self, dim, init_values=1e-5, inplace=False):
|
41 |
+
super().__init__()
|
42 |
+
self.inplace = inplace
|
43 |
+
self.gamma = nn.Parameter(init_values * torch.ones(dim))
|
44 |
+
|
45 |
+
def forward(self, x):
|
46 |
+
return x.mul_(self.gamma) if self.inplace else x * self.gamma
|
47 |
+
|
48 |
+
|
49 |
+
class PatchDropout(nn.Module):
|
50 |
+
"""
|
51 |
+
https://arxiv.org/abs/2212.00794
|
52 |
+
"""
|
53 |
+
|
54 |
+
def __init__(self, prob, exclude_first_token=True):
|
55 |
+
super().__init__()
|
56 |
+
assert 0 <= prob < 1.
|
57 |
+
self.prob = prob
|
58 |
+
self.exclude_first_token = exclude_first_token # exclude CLS token
|
59 |
+
|
60 |
+
def forward(self, x):
|
61 |
+
if not self.training or self.prob == 0.:
|
62 |
+
return x
|
63 |
+
|
64 |
+
if self.exclude_first_token:
|
65 |
+
cls_tokens, x = x[:, :1], x[:, 1:]
|
66 |
+
else:
|
67 |
+
cls_tokens = torch.jit.annotate(torch.Tensor, x[:, :1])
|
68 |
+
|
69 |
+
batch = x.size()[0]
|
70 |
+
num_tokens = x.size()[1]
|
71 |
+
|
72 |
+
batch_indices = torch.arange(batch)
|
73 |
+
batch_indices = batch_indices[..., None]
|
74 |
+
|
75 |
+
keep_prob = 1 - self.prob
|
76 |
+
num_patches_keep = max(1, int(num_tokens * keep_prob))
|
77 |
+
|
78 |
+
rand = torch.randn(batch, num_tokens)
|
79 |
+
patch_indices_keep = rand.topk(num_patches_keep, dim=-1).indices
|
80 |
+
|
81 |
+
x = x[batch_indices, patch_indices_keep]
|
82 |
+
|
83 |
+
if self.exclude_first_token:
|
84 |
+
x = torch.cat((cls_tokens, x), dim=1)
|
85 |
+
|
86 |
+
return x
|
87 |
+
|
88 |
+
|
89 |
+
class Attention(nn.Module):
|
90 |
+
def __init__(
|
91 |
+
self,
|
92 |
+
dim,
|
93 |
+
num_heads=8,
|
94 |
+
qkv_bias=True,
|
95 |
+
scaled_cosine=False,
|
96 |
+
scale_heads=False,
|
97 |
+
logit_scale_max=math.log(1. / 0.01),
|
98 |
+
attn_drop=0.,
|
99 |
+
proj_drop=0.
|
100 |
+
):
|
101 |
+
super().__init__()
|
102 |
+
self.scaled_cosine = scaled_cosine
|
103 |
+
self.scale_heads = scale_heads
|
104 |
+
assert dim % num_heads == 0, 'dim should be divisible by num_heads'
|
105 |
+
self.num_heads = num_heads
|
106 |
+
self.head_dim = dim // num_heads
|
107 |
+
self.scale = self.head_dim ** -0.5
|
108 |
+
self.logit_scale_max = logit_scale_max
|
109 |
+
|
110 |
+
# keeping in_proj in this form (instead of nn.Linear) to match weight scheme of original
|
111 |
+
self.in_proj_weight = nn.Parameter(torch.randn((dim * 3, dim)) * self.scale)
|
112 |
+
if qkv_bias:
|
113 |
+
self.in_proj_bias = nn.Parameter(torch.zeros(dim * 3))
|
114 |
+
else:
|
115 |
+
self.in_proj_bias = None
|
116 |
+
|
117 |
+
if self.scaled_cosine:
|
118 |
+
self.logit_scale = nn.Parameter(torch.log(10 * torch.ones((num_heads, 1, 1))))
|
119 |
+
else:
|
120 |
+
self.logit_scale = None
|
121 |
+
self.attn_drop = nn.Dropout(attn_drop)
|
122 |
+
if self.scale_heads:
|
123 |
+
self.head_scale = nn.Parameter(torch.ones((num_heads, 1, 1)))
|
124 |
+
else:
|
125 |
+
self.head_scale = None
|
126 |
+
self.out_proj = nn.Linear(dim, dim)
|
127 |
+
self.out_drop = nn.Dropout(proj_drop)
|
128 |
+
|
129 |
+
def forward(self, x, attn_mask: Optional[torch.Tensor] = None):
|
130 |
+
L, N, C = x.shape
|
131 |
+
q, k, v = F.linear(x, self.in_proj_weight, self.in_proj_bias).chunk(3, dim=-1)
|
132 |
+
q = q.contiguous().view(L, N * self.num_heads, -1).transpose(0, 1)
|
133 |
+
k = k.contiguous().view(L, N * self.num_heads, -1).transpose(0, 1)
|
134 |
+
v = v.contiguous().view(L, N * self.num_heads, -1).transpose(0, 1)
|
135 |
+
|
136 |
+
if self.logit_scale is not None:
|
137 |
+
attn = torch.bmm(F.normalize(q, dim=-1), F.normalize(k, dim=-1).transpose(-1, -2))
|
138 |
+
logit_scale = torch.clamp(self.logit_scale, max=self.logit_scale_max).exp()
|
139 |
+
attn = attn.view(N, self.num_heads, L, L) * logit_scale
|
140 |
+
attn = attn.view(-1, L, L)
|
141 |
+
else:
|
142 |
+
q = q * self.scale
|
143 |
+
attn = torch.bmm(q, k.transpose(-1, -2))
|
144 |
+
|
145 |
+
if attn_mask is not None:
|
146 |
+
if attn_mask.dtype == torch.bool:
|
147 |
+
new_attn_mask = torch.zeros_like(attn_mask, dtype=q.dtype)
|
148 |
+
new_attn_mask.masked_fill_(attn_mask, float("-inf"))
|
149 |
+
attn_mask = new_attn_mask
|
150 |
+
attn += attn_mask
|
151 |
+
|
152 |
+
attn = attn.softmax(dim=-1)
|
153 |
+
attn = self.attn_drop(attn)
|
154 |
+
|
155 |
+
x = torch.bmm(attn, v)
|
156 |
+
if self.head_scale is not None:
|
157 |
+
x = x.view(N, self.num_heads, L, C) * self.head_scale
|
158 |
+
x = x.view(-1, L, C)
|
159 |
+
x = x.transpose(0, 1).reshape(L, N, C)
|
160 |
+
x = self.out_proj(x)
|
161 |
+
x = self.out_drop(x)
|
162 |
+
return x
|
163 |
+
|
164 |
+
|
165 |
+
class AttentionalPooler(nn.Module):
|
166 |
+
def __init__(
|
167 |
+
self,
|
168 |
+
d_model: int,
|
169 |
+
context_dim: int,
|
170 |
+
n_head: int = 8,
|
171 |
+
n_queries: int = 256,
|
172 |
+
norm_layer: Callable = LayerNorm
|
173 |
+
):
|
174 |
+
super().__init__()
|
175 |
+
self.query = nn.Parameter(torch.randn(n_queries, d_model))
|
176 |
+
self.attn = nn.MultiheadAttention(d_model, n_head, kdim=context_dim, vdim=context_dim)
|
177 |
+
self.ln_q = norm_layer(d_model)
|
178 |
+
self.ln_k = norm_layer(context_dim)
|
179 |
+
|
180 |
+
def forward(self, x: torch.Tensor):
|
181 |
+
x = self.ln_k(x).permute(1, 0, 2) # NLD -> LND
|
182 |
+
N = x.shape[1]
|
183 |
+
q = self.ln_q(self.query)
|
184 |
+
out = self.attn(q.unsqueeze(1).expand(-1, N, -1), x, x, need_weights=False)[0]
|
185 |
+
return out.permute(1, 0, 2) # LND -> NLD
|
186 |
+
|
187 |
+
|
188 |
+
class ResidualAttentionBlock(nn.Module):
|
189 |
+
def __init__(
|
190 |
+
self,
|
191 |
+
d_model: int,
|
192 |
+
n_head: int,
|
193 |
+
mlp_ratio: float = 4.0,
|
194 |
+
ls_init_value: float = None,
|
195 |
+
act_layer: Callable = nn.GELU,
|
196 |
+
norm_layer: Callable = LayerNorm,
|
197 |
+
is_cross_attention: bool = False,
|
198 |
+
):
|
199 |
+
super().__init__()
|
200 |
+
|
201 |
+
self.ln_1 = norm_layer(d_model)
|
202 |
+
self.attn = nn.MultiheadAttention(d_model, n_head)
|
203 |
+
self.ls_1 = LayerScale(d_model, ls_init_value) if ls_init_value is not None else nn.Identity()
|
204 |
+
if is_cross_attention:
|
205 |
+
self.ln_1_kv = norm_layer(d_model)
|
206 |
+
|
207 |
+
self.ln_2 = norm_layer(d_model)
|
208 |
+
mlp_width = int(d_model * mlp_ratio)
|
209 |
+
self.mlp = nn.Sequential(OrderedDict([
|
210 |
+
("c_fc", nn.Linear(d_model, mlp_width)),
|
211 |
+
("gelu", act_layer()),
|
212 |
+
("c_proj", nn.Linear(mlp_width, d_model))
|
213 |
+
]))
|
214 |
+
self.ls_2 = LayerScale(d_model, ls_init_value) if ls_init_value is not None else nn.Identity()
|
215 |
+
|
216 |
+
def attention(
|
217 |
+
self,
|
218 |
+
q_x: torch.Tensor,
|
219 |
+
k_x: Optional[torch.Tensor] = None,
|
220 |
+
v_x: Optional[torch.Tensor] = None,
|
221 |
+
attn_mask: Optional[torch.Tensor] = None,
|
222 |
+
):
|
223 |
+
k_x = k_x if k_x is not None else q_x
|
224 |
+
v_x = v_x if v_x is not None else q_x
|
225 |
+
|
226 |
+
attn_mask = attn_mask.to(q_x.dtype) if attn_mask is not None else None
|
227 |
+
return self.attn(
|
228 |
+
q_x, k_x, v_x, need_weights=False, attn_mask=attn_mask
|
229 |
+
)[0]
|
230 |
+
|
231 |
+
def forward(
|
232 |
+
self,
|
233 |
+
q_x: torch.Tensor,
|
234 |
+
k_x: Optional[torch.Tensor] = None,
|
235 |
+
v_x: Optional[torch.Tensor] = None,
|
236 |
+
attn_mask: Optional[torch.Tensor] = None,
|
237 |
+
):
|
238 |
+
k_x = self.ln_1_kv(k_x) if hasattr(self, "ln_1_kv") and k_x is not None else None
|
239 |
+
v_x = self.ln_1_kv(v_x) if hasattr(self, "ln_1_kv") and v_x is not None else None
|
240 |
+
|
241 |
+
x = q_x + self.ls_1(self.attention(q_x=self.ln_1(q_x), k_x=k_x, v_x=v_x, attn_mask=attn_mask))
|
242 |
+
x = x + self.ls_2(self.mlp(self.ln_2(x)))
|
243 |
+
return x
|
244 |
+
|
245 |
+
|
246 |
+
class CustomResidualAttentionBlock(nn.Module):
|
247 |
+
def __init__(
|
248 |
+
self,
|
249 |
+
d_model: int,
|
250 |
+
n_head: int,
|
251 |
+
mlp_ratio: float = 4.0,
|
252 |
+
ls_init_value: float = None,
|
253 |
+
act_layer: Callable = nn.GELU,
|
254 |
+
norm_layer: Callable = LayerNorm,
|
255 |
+
scale_cosine_attn: bool = False,
|
256 |
+
scale_heads: bool = False,
|
257 |
+
scale_attn: bool = False,
|
258 |
+
scale_fc: bool = False,
|
259 |
+
):
|
260 |
+
super().__init__()
|
261 |
+
|
262 |
+
self.ln_1 = norm_layer(d_model)
|
263 |
+
self.attn = Attention(
|
264 |
+
d_model, n_head,
|
265 |
+
scaled_cosine=scale_cosine_attn,
|
266 |
+
scale_heads=scale_heads,
|
267 |
+
)
|
268 |
+
self.ln_attn = norm_layer(d_model) if scale_attn else nn.Identity()
|
269 |
+
self.ls_1 = LayerScale(d_model, ls_init_value) if ls_init_value is not None else nn.Identity()
|
270 |
+
|
271 |
+
self.ln_2 = norm_layer(d_model)
|
272 |
+
mlp_width = int(d_model * mlp_ratio)
|
273 |
+
self.mlp = nn.Sequential(OrderedDict([
|
274 |
+
("c_fc", nn.Linear(d_model, mlp_width)),
|
275 |
+
("gelu", act_layer()),
|
276 |
+
('ln', norm_layer(mlp_width) if scale_fc else nn.Identity()),
|
277 |
+
("c_proj", nn.Linear(mlp_width, d_model))
|
278 |
+
]))
|
279 |
+
self.ls_2 = LayerScale(d_model, ls_init_value) if ls_init_value is not None else nn.Identity()
|
280 |
+
|
281 |
+
def forward(self, x: torch.Tensor, attn_mask: Optional[torch.Tensor] = None):
|
282 |
+
x = x + self.ls_1(self.ln_attn(self.attn(self.ln_1(x), attn_mask=attn_mask)))
|
283 |
+
x = x + self.ls_2(self.mlp(self.ln_2(x)))
|
284 |
+
return x
|
285 |
+
|
286 |
+
|
287 |
+
def _expand_token(token, batch_size: int):
|
288 |
+
return token.view(1, 1, -1).expand(batch_size, -1, -1)
|
289 |
+
|
290 |
+
|
291 |
+
class Transformer(nn.Module):
|
292 |
+
def __init__(
|
293 |
+
self,
|
294 |
+
width: int,
|
295 |
+
layers: int,
|
296 |
+
heads: int,
|
297 |
+
mlp_ratio: float = 4.0,
|
298 |
+
ls_init_value: float = None,
|
299 |
+
act_layer: Callable = nn.GELU,
|
300 |
+
norm_layer: Callable = LayerNorm,
|
301 |
+
):
|
302 |
+
super().__init__()
|
303 |
+
self.width = width
|
304 |
+
self.layers = layers
|
305 |
+
self.grad_checkpointing = False
|
306 |
+
|
307 |
+
self.resblocks = nn.ModuleList([
|
308 |
+
ResidualAttentionBlock(
|
309 |
+
width, heads, mlp_ratio, ls_init_value=ls_init_value, act_layer=act_layer, norm_layer=norm_layer)
|
310 |
+
for _ in range(layers)
|
311 |
+
])
|
312 |
+
|
313 |
+
def get_cast_dtype(self) -> torch.dtype:
|
314 |
+
if hasattr(self.resblocks[0].mlp.c_fc, 'int8_original_dtype'):
|
315 |
+
return self.resblocks[0].mlp.c_fc.int8_original_dtype
|
316 |
+
return self.resblocks[0].mlp.c_fc.weight.dtype
|
317 |
+
|
318 |
+
def forward(self, x: torch.Tensor, attn_mask: Optional[torch.Tensor] = None):
|
319 |
+
for r in self.resblocks:
|
320 |
+
if self.grad_checkpointing and not torch.jit.is_scripting():
|
321 |
+
# TODO: handle kwargs https://github.com/pytorch/pytorch/issues/79887#issuecomment-1161758372
|
322 |
+
x = checkpoint(r, x, None, None, attn_mask)
|
323 |
+
else:
|
324 |
+
x = r(x, attn_mask=attn_mask)
|
325 |
+
return x
|
326 |
+
|
327 |
+
|
328 |
+
class VisionTransformer(nn.Module):
|
329 |
+
output_tokens: torch.jit.Final[bool]
|
330 |
+
|
331 |
+
def __init__(
|
332 |
+
self,
|
333 |
+
image_size: int,
|
334 |
+
patch_size: int,
|
335 |
+
width: int,
|
336 |
+
layers: int,
|
337 |
+
heads: int,
|
338 |
+
mlp_ratio: float,
|
339 |
+
in_channels:int,
|
340 |
+
ls_init_value: float = None,
|
341 |
+
attentional_pool: bool = False,
|
342 |
+
attn_pooler_queries: int = 256,
|
343 |
+
attn_pooler_heads: int = 8,
|
344 |
+
output_dim: int = 512,
|
345 |
+
patch_dropout: float = 0.,
|
346 |
+
no_ln_pre: bool = False,
|
347 |
+
pos_embed_type: str = 'learnable',
|
348 |
+
pool_type: str = 'tok',
|
349 |
+
final_ln_after_pool: bool = False,
|
350 |
+
act_layer: Callable = nn.GELU,
|
351 |
+
norm_layer: Callable = LayerNorm,
|
352 |
+
output_tokens: bool = False,
|
353 |
+
):
|
354 |
+
super().__init__()
|
355 |
+
assert pool_type in ('tok', 'avg', 'none')
|
356 |
+
self.output_tokens = output_tokens
|
357 |
+
image_height, image_width = self.image_size = to_2tuple(image_size)
|
358 |
+
patch_height, patch_width = self.patch_size = to_2tuple(patch_size)
|
359 |
+
self.grid_size = (image_height // patch_height, image_width // patch_width)
|
360 |
+
self.final_ln_after_pool = final_ln_after_pool # currently ignored w/ attn pool enabled
|
361 |
+
self.output_dim = output_dim
|
362 |
+
|
363 |
+
self.conv1 = nn.Conv1d(in_channels=in_channels, out_channels=width, kernel_size=patch_size, stride=patch_size, bias=False)
|
364 |
+
|
365 |
+
# class embeddings and positional embeddings
|
366 |
+
scale = width ** -0.5
|
367 |
+
self.class_embedding = nn.Parameter(scale * torch.randn(width))
|
368 |
+
if pos_embed_type == 'learnable':
|
369 |
+
self.positional_embedding = nn.Parameter(
|
370 |
+
scale * torch.randn(self.grid_size[0] * self.grid_size[1] + 1, width))
|
371 |
+
elif pos_embed_type == 'sin_cos_2d':
|
372 |
+
# fixed sin-cos embedding
|
373 |
+
assert self.grid_size[0] == self.grid_size[1],\
|
374 |
+
'currently sin cos 2d pos embedding only supports square input'
|
375 |
+
self.positional_embedding = nn.Parameter(
|
376 |
+
torch.zeros(200 + 1, width), requires_grad=False)
|
377 |
+
pos_embed_type = get_2d_sincos_pos_embed(width, self.grid_size[0], cls_token=True)
|
378 |
+
self.positional_embedding.data.copy_(torch.from_numpy(pos_embed_type).float())
|
379 |
+
else:
|
380 |
+
raise ValueError
|
381 |
+
|
382 |
+
# setting a patch_dropout of 0. would mean it is disabled and this function would be the identity fn
|
383 |
+
self.patch_dropout = PatchDropout(patch_dropout) if patch_dropout > 0. else nn.Identity()
|
384 |
+
|
385 |
+
self.ln_pre = nn.Identity() if no_ln_pre else norm_layer(width)
|
386 |
+
self.transformer = Transformer(
|
387 |
+
width,
|
388 |
+
layers,
|
389 |
+
heads,
|
390 |
+
mlp_ratio,
|
391 |
+
ls_init_value=ls_init_value,
|
392 |
+
act_layer=act_layer,
|
393 |
+
norm_layer=norm_layer,
|
394 |
+
)
|
395 |
+
|
396 |
+
if attentional_pool:
|
397 |
+
if isinstance(attentional_pool, str):
|
398 |
+
self.attn_pool_type = attentional_pool
|
399 |
+
self.pool_type = 'none'
|
400 |
+
if attentional_pool in ('parallel', 'cascade'):
|
401 |
+
self.attn_pool = AttentionalPooler(
|
402 |
+
output_dim,
|
403 |
+
width,
|
404 |
+
n_head=attn_pooler_heads,
|
405 |
+
n_queries=attn_pooler_queries,
|
406 |
+
)
|
407 |
+
self.attn_pool_contrastive = AttentionalPooler(
|
408 |
+
output_dim,
|
409 |
+
width,
|
410 |
+
n_head=attn_pooler_heads,
|
411 |
+
n_queries=1,
|
412 |
+
)
|
413 |
+
else:
|
414 |
+
assert False
|
415 |
+
else:
|
416 |
+
self.attn_pool_type = ''
|
417 |
+
self.pool_type = pool_type
|
418 |
+
self.attn_pool = AttentionalPooler(
|
419 |
+
output_dim,
|
420 |
+
width,
|
421 |
+
n_head=attn_pooler_heads,
|
422 |
+
n_queries=attn_pooler_queries,
|
423 |
+
)
|
424 |
+
self.attn_pool_contrastive = None
|
425 |
+
pool_dim = output_dim
|
426 |
+
else:
|
427 |
+
self.attn_pool = None
|
428 |
+
pool_dim = width
|
429 |
+
self.pool_type = pool_type
|
430 |
+
|
431 |
+
self.ln_post = norm_layer(pool_dim)
|
432 |
+
self.proj = nn.Parameter(scale * torch.randn(pool_dim, output_dim))
|
433 |
+
|
434 |
+
self.init_parameters()
|
435 |
+
|
436 |
+
def lock(self, unlocked_groups=0, freeze_bn_stats=False):
|
437 |
+
for param in self.parameters():
|
438 |
+
param.requires_grad = False
|
439 |
+
|
440 |
+
if unlocked_groups != 0:
|
441 |
+
groups = [
|
442 |
+
[
|
443 |
+
self.conv1,
|
444 |
+
self.class_embedding,
|
445 |
+
self.positional_embedding,
|
446 |
+
self.ln_pre,
|
447 |
+
],
|
448 |
+
*self.transformer.resblocks[:-1],
|
449 |
+
[
|
450 |
+
self.transformer.resblocks[-1],
|
451 |
+
self.ln_post,
|
452 |
+
],
|
453 |
+
self.proj,
|
454 |
+
]
|
455 |
+
|
456 |
+
def _unlock(x):
|
457 |
+
if isinstance(x, Sequence):
|
458 |
+
for g in x:
|
459 |
+
_unlock(g)
|
460 |
+
else:
|
461 |
+
if isinstance(x, torch.nn.Parameter):
|
462 |
+
x.requires_grad = True
|
463 |
+
else:
|
464 |
+
for p in x.parameters():
|
465 |
+
p.requires_grad = True
|
466 |
+
|
467 |
+
_unlock(groups[-unlocked_groups:])
|
468 |
+
|
469 |
+
def init_parameters(self):
|
470 |
+
# FIXME OpenAI CLIP did not define an init for the VisualTransformer
|
471 |
+
# TODO experiment if default PyTorch init, below, or alternate init is best.
|
472 |
+
|
473 |
+
# nn.init.normal_(self.class_embedding, std=self.scale)
|
474 |
+
# nn.init.normal_(self.positional_embedding, std=self.scale)
|
475 |
+
#
|
476 |
+
# proj_std = (self.transformer.width ** -0.5) * ((2 * self.transformer.layers) ** -0.5)
|
477 |
+
# attn_std = self.transformer.width ** -0.5
|
478 |
+
# fc_std = (2 * self.transformer.width) ** -0.5
|
479 |
+
# for block in self.transformer.resblocks:
|
480 |
+
# nn.init.normal_(block.attn.in_proj_weight, std=attn_std)
|
481 |
+
# nn.init.normal_(block.attn.out_proj.weight, std=proj_std)
|
482 |
+
# nn.init.normal_(block.mlp.c_fc.weight, std=fc_std)
|
483 |
+
# nn.init.normal_(block.mlp.c_proj.weight, std=proj_std)
|
484 |
+
#
|
485 |
+
# if self.text_projection is not None:
|
486 |
+
# nn.init.normal_(self.text_projection, std=self.scale)
|
487 |
+
pass
|
488 |
+
|
489 |
+
@torch.jit.ignore
|
490 |
+
def set_grad_checkpointing(self, enable=True):
|
491 |
+
self.transformer.grad_checkpointing = enable
|
492 |
+
|
493 |
+
def _global_pool(self, x: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
|
494 |
+
if self.pool_type == 'avg':
|
495 |
+
pooled, tokens = x[:, 1:].mean(dim=1), x[:, 1:]
|
496 |
+
elif self.pool_type == 'tok':
|
497 |
+
pooled, tokens = x[:, 0], x[:, 1:]
|
498 |
+
else:
|
499 |
+
pooled = tokens = x
|
500 |
+
|
501 |
+
return pooled, tokens
|
502 |
+
|
503 |
+
def forward(self, x: torch.Tensor):
|
504 |
+
x = self.conv1(x) # shape = [*, width, grid, grid]
|
505 |
+
x = x.reshape(x.shape[0], x.shape[1], -1) # shape = [*, width, grid ** 2]
|
506 |
+
x = x.permute(0, 2, 1) # shape = [*, grid ** 2, width]
|
507 |
+
|
508 |
+
# class embeddings and positional embeddings
|
509 |
+
x = torch.cat([_expand_token(self.class_embedding, x.shape[0]).to(x.dtype), x], dim=1)
|
510 |
+
# shape = [*, grid ** 2 + 1, width]
|
511 |
+
x = x + self.positional_embedding[:x.shape[1],:].to(x.dtype)
|
512 |
+
|
513 |
+
x = self.patch_dropout(x)
|
514 |
+
x = self.ln_pre(x)
|
515 |
+
|
516 |
+
x = x.permute(1, 0, 2) # NLD -> LND
|
517 |
+
x = self.transformer(x)
|
518 |
+
x = x.permute(1, 0, 2) # LND -> NLD
|
519 |
+
x = self.ln_post(x)
|
520 |
+
return x
|
521 |
+
|
522 |
+
if self.attn_pool is not None:
|
523 |
+
if self.attn_pool_contrastive is not None:
|
524 |
+
# This is untested, WIP pooling that should match paper
|
525 |
+
x = self.ln_post(x) # TBD LN first or separate one after each pool?
|
526 |
+
tokens = self.attn_pool(x)
|
527 |
+
if self.attn_pool_type == 'parallel':
|
528 |
+
pooled = self.attn_pool_contrastive(x)
|
529 |
+
else:
|
530 |
+
assert self.attn_pool_type == 'cascade'
|
531 |
+
pooled = self.attn_pool_contrastive(tokens)
|
532 |
+
else:
|
533 |
+
# this is the original OpenCLIP CoCa setup, does not match paper
|
534 |
+
x = self.attn_pool(x)
|
535 |
+
x = self.ln_post(x)
|
536 |
+
pooled, tokens = self._global_pool(x)
|
537 |
+
elif self.final_ln_after_pool:
|
538 |
+
pooled, tokens = self._global_pool(x)
|
539 |
+
pooled = self.ln_post(pooled)
|
540 |
+
else:
|
541 |
+
x = self.ln_post(x)
|
542 |
+
pooled, tokens = self._global_pool(x)
|
543 |
+
|
544 |
+
if self.proj is not None:
|
545 |
+
pooled = pooled @ self.proj
|
546 |
+
|
547 |
+
if self.output_tokens:
|
548 |
+
return pooled, tokens
|
549 |
+
|
550 |
+
return pooled
|
551 |
+
|
552 |
+
|
553 |
+
def text_global_pool(x, text: Optional[torch.Tensor] = None, pool_type: str = 'argmax'):
|
554 |
+
if pool_type == 'first':
|
555 |
+
pooled, tokens = x[:, 0], x[:, 1:]
|
556 |
+
elif pool_type == 'last':
|
557 |
+
pooled, tokens = x[:, -1], x[:, :-1]
|
558 |
+
elif pool_type == 'argmax':
|
559 |
+
# take features from the eot embedding (eot_token is the highest number in each sequence)
|
560 |
+
assert text is not None
|
561 |
+
pooled, tokens = x[torch.arange(x.shape[0]), text.argmax(dim=-1)], x
|
562 |
+
else:
|
563 |
+
pooled = tokens = x
|
564 |
+
|
565 |
+
return pooled, tokens
|
566 |
+
|
567 |
+
|
568 |
+
class TextTransformer(nn.Module):
|
569 |
+
output_tokens: torch.jit.Final[bool]
|
570 |
+
|
571 |
+
def __init__(
|
572 |
+
self,
|
573 |
+
context_length: int = 77,
|
574 |
+
vocab_size: int = 49408,
|
575 |
+
width: int = 512,
|
576 |
+
heads: int = 8,
|
577 |
+
layers: int = 12,
|
578 |
+
mlp_ratio: float = 4.0,
|
579 |
+
ls_init_value: float = None,
|
580 |
+
output_dim: int = 512,
|
581 |
+
embed_cls: bool = False,
|
582 |
+
no_causal_mask: bool = False,
|
583 |
+
pad_id: int = 0,
|
584 |
+
pool_type: str = 'argmax',
|
585 |
+
proj_bias: bool = False,
|
586 |
+
act_layer: Callable = nn.GELU,
|
587 |
+
norm_layer: Callable = LayerNorm,
|
588 |
+
output_tokens: bool = False,
|
589 |
+
):
|
590 |
+
super().__init__()
|
591 |
+
assert pool_type in ('first', 'last', 'argmax', 'none')
|
592 |
+
self.output_tokens = output_tokens
|
593 |
+
self.num_pos = self.context_length = context_length
|
594 |
+
self.vocab_size = vocab_size
|
595 |
+
self.width = width
|
596 |
+
self.output_dim = output_dim
|
597 |
+
self.heads = heads
|
598 |
+
self.pad_id = pad_id
|
599 |
+
self.pool_type = pool_type
|
600 |
+
|
601 |
+
self.token_embedding = nn.Embedding(vocab_size, width)
|
602 |
+
if embed_cls:
|
603 |
+
self.cls_emb = nn.Parameter(torch.empty(width))
|
604 |
+
self.num_pos += 1
|
605 |
+
else:
|
606 |
+
self.cls_emb = None
|
607 |
+
self.positional_embedding = nn.Parameter(torch.empty(self.num_pos, width))
|
608 |
+
self.transformer = Transformer(
|
609 |
+
width=width,
|
610 |
+
layers=layers,
|
611 |
+
heads=heads,
|
612 |
+
mlp_ratio=mlp_ratio,
|
613 |
+
ls_init_value=ls_init_value,
|
614 |
+
act_layer=act_layer,
|
615 |
+
norm_layer=norm_layer,
|
616 |
+
)
|
617 |
+
self.ln_final = norm_layer(width)
|
618 |
+
|
619 |
+
if no_causal_mask:
|
620 |
+
self.attn_mask = None
|
621 |
+
else:
|
622 |
+
self.register_buffer('attn_mask', self.build_causal_mask(), persistent=False)
|
623 |
+
|
624 |
+
if proj_bias:
|
625 |
+
self.text_projection = nn.Linear(width, output_dim)
|
626 |
+
else:
|
627 |
+
self.text_projection = nn.Parameter(torch.empty(width, output_dim))
|
628 |
+
|
629 |
+
self.init_parameters()
|
630 |
+
|
631 |
+
def init_parameters(self):
|
632 |
+
nn.init.normal_(self.token_embedding.weight, std=0.02)
|
633 |
+
nn.init.normal_(self.positional_embedding, std=0.01)
|
634 |
+
if self.cls_emb is not None:
|
635 |
+
nn.init.normal_(self.cls_emb, std=0.01)
|
636 |
+
|
637 |
+
proj_std = (self.transformer.width ** -0.5) * ((2 * self.transformer.layers) ** -0.5)
|
638 |
+
attn_std = self.transformer.width ** -0.5
|
639 |
+
fc_std = (2 * self.transformer.width) ** -0.5
|
640 |
+
for block in self.transformer.resblocks:
|
641 |
+
nn.init.normal_(block.attn.in_proj_weight, std=attn_std)
|
642 |
+
nn.init.normal_(block.attn.out_proj.weight, std=proj_std)
|
643 |
+
nn.init.normal_(block.mlp.c_fc.weight, std=fc_std)
|
644 |
+
nn.init.normal_(block.mlp.c_proj.weight, std=proj_std)
|
645 |
+
|
646 |
+
if self.text_projection is not None:
|
647 |
+
if isinstance(self.text_projection, nn.Linear):
|
648 |
+
nn.init.normal_(self.text_projection.weight, std=self.transformer.width ** -0.5)
|
649 |
+
if self.text_projection.bias is not None:
|
650 |
+
nn.init.zeros_(self.text_projection.bias)
|
651 |
+
else:
|
652 |
+
nn.init.normal_(self.text_projection, std=self.transformer.width ** -0.5)
|
653 |
+
|
654 |
+
@torch.jit.ignore
|
655 |
+
def set_grad_checkpointing(self, enable=True):
|
656 |
+
self.transformer.grad_checkpointing = enable
|
657 |
+
|
658 |
+
def build_causal_mask(self):
|
659 |
+
# lazily create causal attention mask, with full attention between the tokens
|
660 |
+
# pytorch uses additive attention mask; fill with -inf
|
661 |
+
mask = torch.empty(self.num_pos, self.num_pos)
|
662 |
+
mask.fill_(float("-inf"))
|
663 |
+
mask.triu_(1) # zero out the lower diagonal
|
664 |
+
return mask
|
665 |
+
|
666 |
+
def build_cls_mask(self, text, cast_dtype: torch.dtype):
|
667 |
+
cls_mask = (text != self.pad_id).unsqueeze(1)
|
668 |
+
cls_mask = F.pad(cls_mask, (1, 0, cls_mask.shape[2], 0), value=True)
|
669 |
+
additive_mask = torch.empty(cls_mask.shape, dtype=cast_dtype, device=cls_mask.device)
|
670 |
+
additive_mask.fill_(0)
|
671 |
+
additive_mask.masked_fill_(~cls_mask, float("-inf"))
|
672 |
+
additive_mask = torch.repeat_interleave(additive_mask, self.heads, 0)
|
673 |
+
return additive_mask
|
674 |
+
|
675 |
+
def forward(self, text):
|
676 |
+
cast_dtype = self.transformer.get_cast_dtype()
|
677 |
+
seq_len = text.shape[1]
|
678 |
+
|
679 |
+
x = self.token_embedding(text).to(cast_dtype) # [batch_size, n_ctx, d_model]
|
680 |
+
attn_mask = self.attn_mask
|
681 |
+
if self.cls_emb is not None:
|
682 |
+
seq_len += 1
|
683 |
+
x = torch.cat([x, _expand_token(self.cls_emb, x.shape[0])], dim=1)
|
684 |
+
cls_mask = self.build_cls_mask(text, cast_dtype)
|
685 |
+
if attn_mask is not None:
|
686 |
+
attn_mask = attn_mask[None, :seq_len, :seq_len] + cls_mask[:, :seq_len, :seq_len]
|
687 |
+
|
688 |
+
x = x + self.positional_embedding[:seq_len].to(cast_dtype)
|
689 |
+
x = x.permute(1, 0, 2) # NLD -> LND
|
690 |
+
x = self.transformer(x, attn_mask=attn_mask)
|
691 |
+
x = x.permute(1, 0, 2) # LND -> NLD
|
692 |
+
|
693 |
+
# x.shape = [batch_size, n_ctx, transformer.width]
|
694 |
+
if self.cls_emb is not None:
|
695 |
+
# presence of appended cls embed (CoCa) overrides pool_type, always take last token
|
696 |
+
pooled, tokens = text_global_pool(x, pool_type='last')
|
697 |
+
pooled = self.ln_final(pooled) # final LN applied after pooling in this case
|
698 |
+
else:
|
699 |
+
x = self.ln_final(x)
|
700 |
+
pooled, tokens = text_global_pool(x, text, pool_type=self.pool_type)
|
701 |
+
|
702 |
+
if self.text_projection is not None:
|
703 |
+
if isinstance(self.text_projection, nn.Linear):
|
704 |
+
pooled = self.text_projection(pooled)
|
705 |
+
else:
|
706 |
+
pooled = pooled @ self.text_projection
|
707 |
+
|
708 |
+
if self.output_tokens:
|
709 |
+
return pooled, tokens
|
710 |
+
|
711 |
+
return pooled
|
712 |
+
|
713 |
+
|
714 |
+
class MultimodalTransformer(Transformer):
|
715 |
+
def __init__(
|
716 |
+
self,
|
717 |
+
width: int,
|
718 |
+
layers: int,
|
719 |
+
heads: int,
|
720 |
+
context_length: int = 77,
|
721 |
+
mlp_ratio: float = 4.0,
|
722 |
+
ls_init_value: float = None,
|
723 |
+
act_layer: Callable = nn.GELU,
|
724 |
+
norm_layer: Callable = LayerNorm,
|
725 |
+
output_dim: int = 512,
|
726 |
+
):
|
727 |
+
|
728 |
+
super().__init__(
|
729 |
+
width=width,
|
730 |
+
layers=layers,
|
731 |
+
heads=heads,
|
732 |
+
mlp_ratio=mlp_ratio,
|
733 |
+
ls_init_value=ls_init_value,
|
734 |
+
act_layer=act_layer,
|
735 |
+
norm_layer=norm_layer,
|
736 |
+
)
|
737 |
+
self.context_length = context_length
|
738 |
+
self.cross_attn = nn.ModuleList([
|
739 |
+
ResidualAttentionBlock(
|
740 |
+
width,
|
741 |
+
heads,
|
742 |
+
mlp_ratio,
|
743 |
+
ls_init_value=ls_init_value,
|
744 |
+
act_layer=act_layer,
|
745 |
+
norm_layer=norm_layer,
|
746 |
+
is_cross_attention=True,
|
747 |
+
)
|
748 |
+
for _ in range(layers)
|
749 |
+
])
|
750 |
+
|
751 |
+
self.register_buffer('attn_mask', self.build_attention_mask(), persistent=False)
|
752 |
+
|
753 |
+
self.ln_final = norm_layer(width)
|
754 |
+
self.text_projection = nn.Parameter(torch.empty(width, output_dim))
|
755 |
+
|
756 |
+
def init_parameters(self):
|
757 |
+
proj_std = (self.transformer.width ** -0.5) * ((2 * self.transformer.layers) ** -0.5)
|
758 |
+
attn_std = self.transformer.width ** -0.5
|
759 |
+
fc_std = (2 * self.transformer.width) ** -0.5
|
760 |
+
for block in self.transformer.resblocks:
|
761 |
+
nn.init.normal_(block.attn.in_proj_weight, std=attn_std)
|
762 |
+
nn.init.normal_(block.attn.out_proj.weight, std=proj_std)
|
763 |
+
nn.init.normal_(block.mlp.c_fc.weight, std=fc_std)
|
764 |
+
nn.init.normal_(block.mlp.c_proj.weight, std=proj_std)
|
765 |
+
for block in self.transformer.cross_attn:
|
766 |
+
nn.init.normal_(block.attn.in_proj_weight, std=attn_std)
|
767 |
+
nn.init.normal_(block.attn.out_proj.weight, std=proj_std)
|
768 |
+
nn.init.normal_(block.mlp.c_fc.weight, std=fc_std)
|
769 |
+
nn.init.normal_(block.mlp.c_proj.weight, std=proj_std)
|
770 |
+
|
771 |
+
if self.text_projection is not None:
|
772 |
+
nn.init.normal_(self.text_projection, std=self.transformer.width ** -0.5)
|
773 |
+
|
774 |
+
def build_attention_mask(self):
|
775 |
+
# lazily create causal attention mask, with full attention between the tokens
|
776 |
+
# pytorch uses additive attention mask; fill with -inf
|
777 |
+
mask = torch.empty(self.context_length, self.context_length)
|
778 |
+
mask.fill_(float("-inf"))
|
779 |
+
mask.triu_(1) # zero out the lower diagonal
|
780 |
+
return mask
|
781 |
+
|
782 |
+
def forward(self, image_embs, text_embs):
|
783 |
+
text_embs = text_embs.permute(1, 0, 2) # NLD -> LNDsq
|
784 |
+
image_embs = image_embs.permute(1, 0, 2) # NLD -> LND
|
785 |
+
seq_len = text_embs.shape[0]
|
786 |
+
|
787 |
+
for resblock, cross_attn in zip(self.resblocks, self.cross_attn):
|
788 |
+
if self.grad_checkpointing and not torch.jit.is_scripting():
|
789 |
+
# TODO: handle kwargs https://github.com/pytorch/pytorch/issues/79887#issuecomment-1161758372
|
790 |
+
text_embs = checkpoint(resblock, text_embs, None, None, self.attn_mask[:seq_len, :seq_len])
|
791 |
+
text_embs = checkpoint(cross_attn, text_embs, image_embs, image_embs, None)
|
792 |
+
else:
|
793 |
+
text_embs = resblock(text_embs, attn_mask=self.attn_mask[:seq_len, :seq_len])
|
794 |
+
text_embs = cross_attn(text_embs, k_x=image_embs, v_x=image_embs)
|
795 |
+
|
796 |
+
x = text_embs.permute(1, 0, 2) # LND -> NLD
|
797 |
+
x = self.ln_final(x)
|
798 |
+
|
799 |
+
if self.text_projection is not None:
|
800 |
+
x = x @ self.text_projection
|
801 |
+
|
802 |
+
return x
|
803 |
+
|
804 |
+
@torch.jit.ignore
|
805 |
+
def set_grad_checkpointing(self, enable=True):
|
806 |
+
self.grad_checkpointing = enable
|
ttts/AA_diffusion_deprecated/cldm/utils.py
ADDED
@@ -0,0 +1,89 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from itertools import repeat
|
2 |
+
import collections.abc
|
3 |
+
|
4 |
+
import torch
|
5 |
+
from torch import nn as nn
|
6 |
+
from torchvision.ops.misc import FrozenBatchNorm2d
|
7 |
+
|
8 |
+
|
9 |
+
def freeze_batch_norm_2d(module, module_match={}, name=''):
|
10 |
+
"""
|
11 |
+
Converts all `BatchNorm2d` and `SyncBatchNorm` layers of provided module into `FrozenBatchNorm2d`. If `module` is
|
12 |
+
itself an instance of either `BatchNorm2d` or `SyncBatchNorm`, it is converted into `FrozenBatchNorm2d` and
|
13 |
+
returned. Otherwise, the module is walked recursively and submodules are converted in place.
|
14 |
+
|
15 |
+
Args:
|
16 |
+
module (torch.nn.Module): Any PyTorch module.
|
17 |
+
module_match (dict): Dictionary of full module names to freeze (all if empty)
|
18 |
+
name (str): Full module name (prefix)
|
19 |
+
|
20 |
+
Returns:
|
21 |
+
torch.nn.Module: Resulting module
|
22 |
+
|
23 |
+
Inspired by https://github.com/pytorch/pytorch/blob/a5895f85be0f10212791145bfedc0261d364f103/torch/nn/modules/batchnorm.py#L762
|
24 |
+
"""
|
25 |
+
res = module
|
26 |
+
is_match = True
|
27 |
+
if module_match:
|
28 |
+
is_match = name in module_match
|
29 |
+
if is_match and isinstance(module, (nn.modules.batchnorm.BatchNorm2d, nn.modules.batchnorm.SyncBatchNorm)):
|
30 |
+
res = FrozenBatchNorm2d(module.num_features)
|
31 |
+
res.num_features = module.num_features
|
32 |
+
res.affine = module.affine
|
33 |
+
if module.affine:
|
34 |
+
res.weight.data = module.weight.data.clone().detach()
|
35 |
+
res.bias.data = module.bias.data.clone().detach()
|
36 |
+
res.running_mean.data = module.running_mean.data
|
37 |
+
res.running_var.data = module.running_var.data
|
38 |
+
res.eps = module.eps
|
39 |
+
else:
|
40 |
+
for child_name, child in module.named_children():
|
41 |
+
full_child_name = '.'.join([name, child_name]) if name else child_name
|
42 |
+
new_child = freeze_batch_norm_2d(child, module_match, full_child_name)
|
43 |
+
if new_child is not child:
|
44 |
+
res.add_module(child_name, new_child)
|
45 |
+
return res
|
46 |
+
|
47 |
+
|
48 |
+
# From PyTorch internals
|
49 |
+
def _ntuple(n):
|
50 |
+
def parse(x):
|
51 |
+
if isinstance(x, collections.abc.Iterable):
|
52 |
+
return x
|
53 |
+
return tuple(repeat(x, n))
|
54 |
+
return parse
|
55 |
+
|
56 |
+
|
57 |
+
to_1tuple = _ntuple(1)
|
58 |
+
to_2tuple = _ntuple(2)
|
59 |
+
to_3tuple = _ntuple(3)
|
60 |
+
to_4tuple = _ntuple(4)
|
61 |
+
to_ntuple = lambda n, x: _ntuple(n)(x)
|
62 |
+
|
63 |
+
# Replaces all linear layers with linear_replacement
|
64 |
+
# TODO: add int8 support for other linear layers including attn and convnets
|
65 |
+
def replace_linear(model, linear_replacement, include_modules=['c_fc', 'c_proj'], copy_weights=True):
|
66 |
+
for name, module in model.named_children():
|
67 |
+
if len(list(module.children())) > 0:
|
68 |
+
replace_linear(module, linear_replacement, include_modules, copy_weights)
|
69 |
+
|
70 |
+
if isinstance(module, torch.nn.Linear) and name in include_modules:
|
71 |
+
old_module = model._modules[name]
|
72 |
+
model._modules[name] = linear_replacement(
|
73 |
+
module.in_features,
|
74 |
+
module.out_features,
|
75 |
+
module.bias is not None,
|
76 |
+
)
|
77 |
+
if copy_weights:
|
78 |
+
model._modules[name].weight.data.copy_(old_module.weight.data)
|
79 |
+
if model._modules[name].bias is not None:
|
80 |
+
model._modules[name].bias.data.copy_(old_module.bias)
|
81 |
+
|
82 |
+
return model
|
83 |
+
|
84 |
+
def convert_int8_model_to_inference_mode(model):
|
85 |
+
for m in model.modules():
|
86 |
+
if hasattr(m, 'prepare_for_eval'):
|
87 |
+
int8_original_dtype = m.weight.dtype
|
88 |
+
m.prepare_for_eval()
|
89 |
+
m.int8_original_dtype = int8_original_dtype
|
ttts/AA_diffusion_deprecated/config.yaml
ADDED
@@ -0,0 +1,134 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
dataloader:
|
2 |
+
batch_size : 16
|
3 |
+
shuffle: true
|
4 |
+
num_workers : 64
|
5 |
+
drop_last : true
|
6 |
+
pin_memory : true
|
7 |
+
model:
|
8 |
+
target: cldm.cldm.ControlLDM
|
9 |
+
params:
|
10 |
+
# linear_start: 0.00085
|
11 |
+
# linear_end: 0.0120
|
12 |
+
num_timesteps_cond: 1
|
13 |
+
log_every_t: 200
|
14 |
+
timesteps: 1000
|
15 |
+
first_stage_key: "jpg"
|
16 |
+
cond_stage_key: "txt"
|
17 |
+
control_key: "hint"
|
18 |
+
image_size: 64
|
19 |
+
channels: 100
|
20 |
+
cond_stage_trainable: true
|
21 |
+
# conditioning_key: crossattn
|
22 |
+
monitor: val/loss_simple_ema
|
23 |
+
scale_factor: 0.18215
|
24 |
+
use_ema: False
|
25 |
+
only_mid_control: False
|
26 |
+
|
27 |
+
# control_stage_config:
|
28 |
+
# target: cldm.cldm.ControlNet
|
29 |
+
# params:
|
30 |
+
# image_size: 32 # unused
|
31 |
+
# in_channels: 100
|
32 |
+
# hint_channels: 768
|
33 |
+
# model_channels: 128
|
34 |
+
# attention_resolutions: [ 4, 2, 1 ]
|
35 |
+
# num_res_blocks: 2
|
36 |
+
# channel_mult: [ 1, 2, 4, 4 ]
|
37 |
+
# num_heads: 8
|
38 |
+
# use_spatial_transformer: True
|
39 |
+
# transformer_depth: 1
|
40 |
+
# context_dim: 768
|
41 |
+
# use_checkpoint: True
|
42 |
+
# legacy: False
|
43 |
+
refer_config:
|
44 |
+
target: cldm.cldm.ReferenceNet
|
45 |
+
params:
|
46 |
+
image_size: 32 # unused
|
47 |
+
hint_in_channels: 1024
|
48 |
+
hint_out_channels: 128
|
49 |
+
in_channels: 100
|
50 |
+
out_channels: 100
|
51 |
+
model_channels: 1024
|
52 |
+
attention_resolutions: [ 4, 2, 1 ]
|
53 |
+
num_res_blocks: 1
|
54 |
+
channel_mult: [ 1, 1 ]
|
55 |
+
num_heads: 8
|
56 |
+
use_spatial_transformer: True
|
57 |
+
transformer_depth: 1
|
58 |
+
context_dim: 512
|
59 |
+
use_checkpoint: True
|
60 |
+
dims: 1
|
61 |
+
legacy: False
|
62 |
+
|
63 |
+
|
64 |
+
unet_config:
|
65 |
+
target: tortoise_model.DiffusionTts
|
66 |
+
params:
|
67 |
+
model_channels: 512
|
68 |
+
num_layers: 8
|
69 |
+
in_channels: 100
|
70 |
+
in_latent_channels: 1024
|
71 |
+
out_channels: 100
|
72 |
+
dropout: 0
|
73 |
+
use_fp16: False
|
74 |
+
num_heads: 16
|
75 |
+
layer_drop: .1
|
76 |
+
unconditioned_percentage: .1
|
77 |
+
# target: cldm.cldm.ControlledUnetModel
|
78 |
+
# params:
|
79 |
+
# image_size: 32 # unused
|
80 |
+
# hint_in_channels: 1024
|
81 |
+
# hint_out_channels: 128
|
82 |
+
# in_channels: 100
|
83 |
+
# out_channels: 100
|
84 |
+
# model_channels: 1024
|
85 |
+
# attention_resolutions: [ 4, 2, 1 ]
|
86 |
+
# num_res_blocks: 1
|
87 |
+
# resblock_updown: True
|
88 |
+
# channel_mult: [ 1, 1]
|
89 |
+
# num_heads: 8
|
90 |
+
# use_spatial_transformer: True
|
91 |
+
# transformer_depth: 1
|
92 |
+
# context_dim: 512
|
93 |
+
# use_checkpoint: True
|
94 |
+
# dims: 1
|
95 |
+
# legacy: False
|
96 |
+
|
97 |
+
cond_stage_config:
|
98 |
+
target: cldm.cond_emb.CLIP
|
99 |
+
params:
|
100 |
+
embed_dim: 512
|
101 |
+
vision_cfg:
|
102 |
+
layers: 6
|
103 |
+
width: 512
|
104 |
+
head_width: 64
|
105 |
+
mlp_ratio: 4.0
|
106 |
+
patch_dropout: 0.4
|
107 |
+
attentional_pool: False
|
108 |
+
patch_size: 64
|
109 |
+
image_size: 1000
|
110 |
+
in_channels: 100
|
111 |
+
pool_type: 'tok'
|
112 |
+
pos_embed_type: 'learnable'
|
113 |
+
final_ln_after_pool: false
|
114 |
+
|
115 |
+
train:
|
116 |
+
train_batch_size : 32
|
117 |
+
gradient_accumulate_every : 1
|
118 |
+
train_lr : 0.0001
|
119 |
+
train_num_steps : 1000000
|
120 |
+
ema_update_every : 10
|
121 |
+
ema_decay : 0.995
|
122 |
+
adam_betas : [0.9, 0.99]
|
123 |
+
save_and_sample_every : 1000
|
124 |
+
timesteps : 1000
|
125 |
+
sampling_timesteps : 1000
|
126 |
+
results_folder : "results"
|
127 |
+
logs_folder : "ttts/AA_diffusion/logs"
|
128 |
+
num_workers : 32
|
129 |
+
eps : 0.000000001
|
130 |
+
keep_ckpts : 3
|
131 |
+
all_in_mem : false
|
132 |
+
dataset:
|
133 |
+
path : "/home/hyc/tortoise_plus_zh/ttts/datasets/databaker_data.jsonl"
|
134 |
+
gpt_path : "/home/hyc/tortoise_plus_zh/ttts/gpt/logs/2023-12-24-14-22-14/model-70.pt"
|
ttts/AA_diffusion_deprecated/dataset.py
ADDED
@@ -0,0 +1,152 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import random
|
3 |
+
|
4 |
+
import torch
|
5 |
+
import torch.nn.functional as F
|
6 |
+
import torch.utils.data
|
7 |
+
from torch import LongTensor
|
8 |
+
from tqdm import tqdm
|
9 |
+
import torchaudio
|
10 |
+
from pypinyin import Style, lazy_pinyin
|
11 |
+
import math
|
12 |
+
from ttts.gpt.voice_tokenizer import VoiceBpeTokenizer
|
13 |
+
from ttts.utils.infer_utils import load_model
|
14 |
+
import json
|
15 |
+
import os
|
16 |
+
|
17 |
+
def padding_to_8(x):
|
18 |
+
l = x.shape[-1]
|
19 |
+
l = (math.floor(l / 8) + 1) * 8
|
20 |
+
x = torch.nn.functional.pad(x, (0, l-x.shape[-1]))
|
21 |
+
return x
|
22 |
+
def read_jsonl(path):
|
23 |
+
with open(path, 'r') as f:
|
24 |
+
json_str = f.read()
|
25 |
+
data_list = []
|
26 |
+
for line in json_str.splitlines():
|
27 |
+
data = json.loads(line)
|
28 |
+
data_list.append(data)
|
29 |
+
return data_list
|
30 |
+
def write_jsonl(path, all_paths):
|
31 |
+
with open(path,'w', encoding='utf-8') as file:
|
32 |
+
for item in all_paths:
|
33 |
+
json.dump(item, file, ensure_ascii=False)
|
34 |
+
file.write('\n')
|
35 |
+
|
36 |
+
def padding_to_8(x):
|
37 |
+
l = x.shape[-1]
|
38 |
+
l = (math.floor(l / 8) + 1) * 8
|
39 |
+
x = torch.nn.functional.pad(x, (0, l-x.shape[-1]))
|
40 |
+
return x
|
41 |
+
class DiffusionDataset(torch.utils.data.Dataset):
|
42 |
+
def __init__(self, opt):
|
43 |
+
self.jsonl_path = opt['dataset']['path']
|
44 |
+
self.audiopaths_and_text = read_jsonl(self.jsonl_path)
|
45 |
+
self.tok = VoiceBpeTokenizer('ttts/gpt/gpt_tts_tokenizer.json')
|
46 |
+
def __getitem__(self, index):
|
47 |
+
# Fetch text and add start/stop tokens.
|
48 |
+
audiopath_and_text = self.audiopaths_and_text[index]
|
49 |
+
audiopath, text = audiopath_and_text['path'], audiopath_and_text['text']
|
50 |
+
text = ' '.join(lazy_pinyin(text, style=Style.TONE3, neutral_tone_with_five=True))
|
51 |
+
text = self.tok.encode(text)
|
52 |
+
text_tokens = LongTensor(text)
|
53 |
+
try:
|
54 |
+
mel_path = audiopath + '.mel.pth'
|
55 |
+
mel_raw = torch.load(mel_path)[0]
|
56 |
+
|
57 |
+
quant_path = audiopath + '.melvq.pth'
|
58 |
+
mel_codes = LongTensor(torch.load(quant_path)[0])
|
59 |
+
except:
|
60 |
+
return None
|
61 |
+
|
62 |
+
# Define the number of frames for the random crop (adjust as needed)
|
63 |
+
crop_frames = random.randint(int(mel_raw.shape[1] // 4), int(mel_raw.shape[1] // 4 * 3))
|
64 |
+
|
65 |
+
# Ensure the crop doesn't exceed the length of the original audio
|
66 |
+
max_start_frame = mel_raw.shape[1] - crop_frames
|
67 |
+
start_frame = random.randint(0, max_start_frame)
|
68 |
+
|
69 |
+
# Perform the random crop
|
70 |
+
mel_refer = mel_raw[:, start_frame: start_frame + crop_frames]
|
71 |
+
mel_refer = padding_to_8(mel_refer)
|
72 |
+
# split = random.randint(int(mel_raw.shape[1]//3), int(mel_raw.shape[1]//3*2))
|
73 |
+
# if random.random()>0.5:
|
74 |
+
# mel_refer = mel_raw[:,split:]
|
75 |
+
# else:
|
76 |
+
# mel_refer = mel_raw[:,:split]
|
77 |
+
# if mel_refer.shape[1]>200:
|
78 |
+
# mel_refer = mel_refer[:,:200]
|
79 |
+
#text_token mel_codes
|
80 |
+
|
81 |
+
if mel_raw.shape[1]>400:
|
82 |
+
mel_raw = mel_raw[:,:400]
|
83 |
+
mel_codes = mel_codes[:100]
|
84 |
+
if mel_codes.shape[-1]%2==1:
|
85 |
+
mel_codes = mel_codes[:-1]
|
86 |
+
mel_raw = mel_raw[:,:-4]
|
87 |
+
return text_tokens, mel_codes, mel_raw, mel_refer
|
88 |
+
|
89 |
+
def __len__(self):
|
90 |
+
return len(self.audiopaths_and_text)
|
91 |
+
|
92 |
+
|
93 |
+
class DiffusionCollater():
|
94 |
+
|
95 |
+
def __init__(self):
|
96 |
+
pass
|
97 |
+
def __call__(self, batch):
|
98 |
+
batch = [x for x in batch if x is not None]
|
99 |
+
if len(batch)==0:
|
100 |
+
return None
|
101 |
+
text_lens = [len(x[0]) for x in batch]
|
102 |
+
max_text_len = max(text_lens)
|
103 |
+
mel_code_lens = [len(x[1]) for x in batch]
|
104 |
+
max_mel_code_len = max(mel_code_lens)
|
105 |
+
mel_lens = [x[2].shape[1] for x in batch]
|
106 |
+
max_mel_len = max(mel_lens)
|
107 |
+
mel_refer_lens = [x[3].shape[1] for x in batch]
|
108 |
+
max_mel_refer_len = max(mel_refer_lens)
|
109 |
+
texts = []
|
110 |
+
mel_codes = []
|
111 |
+
mels = []
|
112 |
+
mel_refers = []
|
113 |
+
# This is the sequential "background" tokens that are used as padding for text tokens, as specified in the DALLE paper.
|
114 |
+
for b in batch:
|
115 |
+
text_token, mel_code, mel, mel_refer = b
|
116 |
+
texts.append(F.pad(text_token,(0,max_text_len-len(text_token)), value=0))
|
117 |
+
mel_codes.append(F.pad(mel_code,(0,max_mel_code_len-len(mel_code)), value=0))
|
118 |
+
mels.append(F.pad(mel,(0, max_mel_len-mel.shape[1]), value=0))
|
119 |
+
mel_refers.append(F.pad(mel_refer,(0, max_mel_refer_len-mel_refer.shape[1]), value=0))
|
120 |
+
|
121 |
+
padded_text = torch.stack(texts)
|
122 |
+
padded_mel_code = torch.stack(mel_codes)
|
123 |
+
padded_mel = torch.stack(mels)
|
124 |
+
padded_mel_refer = torch.stack(mel_refers)
|
125 |
+
return {
|
126 |
+
'padded_text': padded_text,
|
127 |
+
'padded_mel_code': padded_mel_code,
|
128 |
+
'padded_mel': padded_mel,
|
129 |
+
'mel_lengths': LongTensor(mel_lens),
|
130 |
+
'padded_mel_refer':padded_mel_refer,
|
131 |
+
'mel_refer_lengths':LongTensor(mel_refer_lens)
|
132 |
+
}
|
133 |
+
|
134 |
+
|
135 |
+
if __name__ == '__main__':
|
136 |
+
params = {
|
137 |
+
'mode': 'gpt_tts',
|
138 |
+
'path': 'E:\\audio\\LJSpeech-1.1\\ljs_audio_text_train_filelist.txt',
|
139 |
+
'phase': 'train',
|
140 |
+
'n_workers': 0,
|
141 |
+
'batch_size': 16,
|
142 |
+
'mel_vocab_size': 512,
|
143 |
+
}
|
144 |
+
cfg = json.load(open('ttts/diffusion/config.json'))
|
145 |
+
ds = DiffusionDataset(cfg)
|
146 |
+
dl = torch.utils.data.DataLoader(ds, **cfg['dataloader'], collate_fn=DiffusionCollater())
|
147 |
+
i = 0
|
148 |
+
m = []
|
149 |
+
max_text = 0
|
150 |
+
max_mel = 0
|
151 |
+
for b in tqdm(dl):
|
152 |
+
break
|
ttts/AA_diffusion_deprecated/ldm/data/__init__.py
ADDED
File without changes
|
ttts/AA_diffusion_deprecated/ldm/data/util.py
ADDED
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
|
3 |
+
from ldm.modules.midas.api import load_midas_transform
|
4 |
+
|
5 |
+
|
6 |
+
class AddMiDaS(object):
|
7 |
+
def __init__(self, model_type):
|
8 |
+
super().__init__()
|
9 |
+
self.transform = load_midas_transform(model_type)
|
10 |
+
|
11 |
+
def pt2np(self, x):
|
12 |
+
x = ((x + 1.0) * .5).detach().cpu().numpy()
|
13 |
+
return x
|
14 |
+
|
15 |
+
def np2pt(self, x):
|
16 |
+
x = torch.from_numpy(x) * 2 - 1.
|
17 |
+
return x
|
18 |
+
|
19 |
+
def __call__(self, sample):
|
20 |
+
# sample['jpg'] is tensor hwc in [-1, 1] at this point
|
21 |
+
x = self.pt2np(sample['jpg'])
|
22 |
+
x = self.transform({"image": x})["image"]
|
23 |
+
sample['midas_in'] = x
|
24 |
+
return sample
|
ttts/AA_diffusion_deprecated/ldm/models/autoencoder.py
ADDED
@@ -0,0 +1,219 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
import pytorch_lightning as pl
|
3 |
+
import torch.nn.functional as F
|
4 |
+
from contextlib import contextmanager
|
5 |
+
|
6 |
+
from ldm.modules.diffusionmodules.model import Encoder, Decoder
|
7 |
+
from ldm.modules.distributions.distributions import DiagonalGaussianDistribution
|
8 |
+
|
9 |
+
from ldm.util import instantiate_from_config
|
10 |
+
from ldm.modules.ema import LitEma
|
11 |
+
|
12 |
+
|
13 |
+
class AutoencoderKL(pl.LightningModule):
|
14 |
+
def __init__(self,
|
15 |
+
ddconfig,
|
16 |
+
lossconfig,
|
17 |
+
embed_dim,
|
18 |
+
ckpt_path=None,
|
19 |
+
ignore_keys=[],
|
20 |
+
image_key="image",
|
21 |
+
colorize_nlabels=None,
|
22 |
+
monitor=None,
|
23 |
+
ema_decay=None,
|
24 |
+
learn_logvar=False
|
25 |
+
):
|
26 |
+
super().__init__()
|
27 |
+
self.learn_logvar = learn_logvar
|
28 |
+
self.image_key = image_key
|
29 |
+
self.encoder = Encoder(**ddconfig)
|
30 |
+
self.decoder = Decoder(**ddconfig)
|
31 |
+
self.loss = instantiate_from_config(lossconfig)
|
32 |
+
assert ddconfig["double_z"]
|
33 |
+
self.quant_conv = torch.nn.Conv2d(2*ddconfig["z_channels"], 2*embed_dim, 1)
|
34 |
+
self.post_quant_conv = torch.nn.Conv2d(embed_dim, ddconfig["z_channels"], 1)
|
35 |
+
self.embed_dim = embed_dim
|
36 |
+
if colorize_nlabels is not None:
|
37 |
+
assert type(colorize_nlabels)==int
|
38 |
+
self.register_buffer("colorize", torch.randn(3, colorize_nlabels, 1, 1))
|
39 |
+
if monitor is not None:
|
40 |
+
self.monitor = monitor
|
41 |
+
|
42 |
+
self.use_ema = ema_decay is not None
|
43 |
+
if self.use_ema:
|
44 |
+
self.ema_decay = ema_decay
|
45 |
+
assert 0. < ema_decay < 1.
|
46 |
+
self.model_ema = LitEma(self, decay=ema_decay)
|
47 |
+
print(f"Keeping EMAs of {len(list(self.model_ema.buffers()))}.")
|
48 |
+
|
49 |
+
if ckpt_path is not None:
|
50 |
+
self.init_from_ckpt(ckpt_path, ignore_keys=ignore_keys)
|
51 |
+
|
52 |
+
def init_from_ckpt(self, path, ignore_keys=list()):
|
53 |
+
sd = torch.load(path, map_location="cpu")["state_dict"]
|
54 |
+
keys = list(sd.keys())
|
55 |
+
for k in keys:
|
56 |
+
for ik in ignore_keys:
|
57 |
+
if k.startswith(ik):
|
58 |
+
print("Deleting key {} from state_dict.".format(k))
|
59 |
+
del sd[k]
|
60 |
+
self.load_state_dict(sd, strict=False)
|
61 |
+
print(f"Restored from {path}")
|
62 |
+
|
63 |
+
@contextmanager
|
64 |
+
def ema_scope(self, context=None):
|
65 |
+
if self.use_ema:
|
66 |
+
self.model_ema.store(self.parameters())
|
67 |
+
self.model_ema.copy_to(self)
|
68 |
+
if context is not None:
|
69 |
+
print(f"{context}: Switched to EMA weights")
|
70 |
+
try:
|
71 |
+
yield None
|
72 |
+
finally:
|
73 |
+
if self.use_ema:
|
74 |
+
self.model_ema.restore(self.parameters())
|
75 |
+
if context is not None:
|
76 |
+
print(f"{context}: Restored training weights")
|
77 |
+
|
78 |
+
def on_train_batch_end(self, *args, **kwargs):
|
79 |
+
if self.use_ema:
|
80 |
+
self.model_ema(self)
|
81 |
+
|
82 |
+
def encode(self, x):
|
83 |
+
h = self.encoder(x)
|
84 |
+
moments = self.quant_conv(h)
|
85 |
+
posterior = DiagonalGaussianDistribution(moments)
|
86 |
+
return posterior
|
87 |
+
|
88 |
+
def decode(self, z):
|
89 |
+
z = self.post_quant_conv(z)
|
90 |
+
dec = self.decoder(z)
|
91 |
+
return dec
|
92 |
+
|
93 |
+
def forward(self, input, sample_posterior=True):
|
94 |
+
posterior = self.encode(input)
|
95 |
+
if sample_posterior:
|
96 |
+
z = posterior.sample()
|
97 |
+
else:
|
98 |
+
z = posterior.mode()
|
99 |
+
dec = self.decode(z)
|
100 |
+
return dec, posterior
|
101 |
+
|
102 |
+
def get_input(self, batch, k):
|
103 |
+
x = batch[k]
|
104 |
+
if len(x.shape) == 3:
|
105 |
+
x = x[..., None]
|
106 |
+
x = x.permute(0, 3, 1, 2).to(memory_format=torch.contiguous_format).float()
|
107 |
+
return x
|
108 |
+
|
109 |
+
def training_step(self, batch, batch_idx, optimizer_idx):
|
110 |
+
inputs = self.get_input(batch, self.image_key)
|
111 |
+
reconstructions, posterior = self(inputs)
|
112 |
+
|
113 |
+
if optimizer_idx == 0:
|
114 |
+
# train encoder+decoder+logvar
|
115 |
+
aeloss, log_dict_ae = self.loss(inputs, reconstructions, posterior, optimizer_idx, self.global_step,
|
116 |
+
last_layer=self.get_last_layer(), split="train")
|
117 |
+
self.log("aeloss", aeloss, prog_bar=True, logger=True, on_step=True, on_epoch=True)
|
118 |
+
self.log_dict(log_dict_ae, prog_bar=False, logger=True, on_step=True, on_epoch=False)
|
119 |
+
return aeloss
|
120 |
+
|
121 |
+
if optimizer_idx == 1:
|
122 |
+
# train the discriminator
|
123 |
+
discloss, log_dict_disc = self.loss(inputs, reconstructions, posterior, optimizer_idx, self.global_step,
|
124 |
+
last_layer=self.get_last_layer(), split="train")
|
125 |
+
|
126 |
+
self.log("discloss", discloss, prog_bar=True, logger=True, on_step=True, on_epoch=True)
|
127 |
+
self.log_dict(log_dict_disc, prog_bar=False, logger=True, on_step=True, on_epoch=False)
|
128 |
+
return discloss
|
129 |
+
|
130 |
+
def validation_step(self, batch, batch_idx):
|
131 |
+
log_dict = self._validation_step(batch, batch_idx)
|
132 |
+
with self.ema_scope():
|
133 |
+
log_dict_ema = self._validation_step(batch, batch_idx, postfix="_ema")
|
134 |
+
return log_dict
|
135 |
+
|
136 |
+
def _validation_step(self, batch, batch_idx, postfix=""):
|
137 |
+
inputs = self.get_input(batch, self.image_key)
|
138 |
+
reconstructions, posterior = self(inputs)
|
139 |
+
aeloss, log_dict_ae = self.loss(inputs, reconstructions, posterior, 0, self.global_step,
|
140 |
+
last_layer=self.get_last_layer(), split="val"+postfix)
|
141 |
+
|
142 |
+
discloss, log_dict_disc = self.loss(inputs, reconstructions, posterior, 1, self.global_step,
|
143 |
+
last_layer=self.get_last_layer(), split="val"+postfix)
|
144 |
+
|
145 |
+
self.log(f"val{postfix}/rec_loss", log_dict_ae[f"val{postfix}/rec_loss"])
|
146 |
+
self.log_dict(log_dict_ae)
|
147 |
+
self.log_dict(log_dict_disc)
|
148 |
+
return self.log_dict
|
149 |
+
|
150 |
+
def configure_optimizers(self):
|
151 |
+
lr = self.learning_rate
|
152 |
+
ae_params_list = list(self.encoder.parameters()) + list(self.decoder.parameters()) + list(
|
153 |
+
self.quant_conv.parameters()) + list(self.post_quant_conv.parameters())
|
154 |
+
if self.learn_logvar:
|
155 |
+
print(f"{self.__class__.__name__}: Learning logvar")
|
156 |
+
ae_params_list.append(self.loss.logvar)
|
157 |
+
opt_ae = torch.optim.Adam(ae_params_list,
|
158 |
+
lr=lr, betas=(0.5, 0.9))
|
159 |
+
opt_disc = torch.optim.Adam(self.loss.discriminator.parameters(),
|
160 |
+
lr=lr, betas=(0.5, 0.9))
|
161 |
+
return [opt_ae, opt_disc], []
|
162 |
+
|
163 |
+
def get_last_layer(self):
|
164 |
+
return self.decoder.conv_out.weight
|
165 |
+
|
166 |
+
@torch.no_grad()
|
167 |
+
def log_images(self, batch, only_inputs=False, log_ema=False, **kwargs):
|
168 |
+
log = dict()
|
169 |
+
x = self.get_input(batch, self.image_key)
|
170 |
+
x = x.to(self.device)
|
171 |
+
if not only_inputs:
|
172 |
+
xrec, posterior = self(x)
|
173 |
+
if x.shape[1] > 3:
|
174 |
+
# colorize with random projection
|
175 |
+
assert xrec.shape[1] > 3
|
176 |
+
x = self.to_rgb(x)
|
177 |
+
xrec = self.to_rgb(xrec)
|
178 |
+
log["samples"] = self.decode(torch.randn_like(posterior.sample()))
|
179 |
+
log["reconstructions"] = xrec
|
180 |
+
if log_ema or self.use_ema:
|
181 |
+
with self.ema_scope():
|
182 |
+
xrec_ema, posterior_ema = self(x)
|
183 |
+
if x.shape[1] > 3:
|
184 |
+
# colorize with random projection
|
185 |
+
assert xrec_ema.shape[1] > 3
|
186 |
+
xrec_ema = self.to_rgb(xrec_ema)
|
187 |
+
log["samples_ema"] = self.decode(torch.randn_like(posterior_ema.sample()))
|
188 |
+
log["reconstructions_ema"] = xrec_ema
|
189 |
+
log["inputs"] = x
|
190 |
+
return log
|
191 |
+
|
192 |
+
def to_rgb(self, x):
|
193 |
+
assert self.image_key == "segmentation"
|
194 |
+
if not hasattr(self, "colorize"):
|
195 |
+
self.register_buffer("colorize", torch.randn(3, x.shape[1], 1, 1).to(x))
|
196 |
+
x = F.conv2d(x, weight=self.colorize)
|
197 |
+
x = 2.*(x-x.min())/(x.max()-x.min()) - 1.
|
198 |
+
return x
|
199 |
+
|
200 |
+
|
201 |
+
class IdentityFirstStage(torch.nn.Module):
|
202 |
+
def __init__(self, *args, vq_interface=False, **kwargs):
|
203 |
+
self.vq_interface = vq_interface
|
204 |
+
super().__init__()
|
205 |
+
|
206 |
+
def encode(self, x, *args, **kwargs):
|
207 |
+
return x
|
208 |
+
|
209 |
+
def decode(self, x, *args, **kwargs):
|
210 |
+
return x
|
211 |
+
|
212 |
+
def quantize(self, x, *args, **kwargs):
|
213 |
+
if self.vq_interface:
|
214 |
+
return x, None, [None, None, None]
|
215 |
+
return x
|
216 |
+
|
217 |
+
def forward(self, x, *args, **kwargs):
|
218 |
+
return x
|
219 |
+
|
ttts/AA_diffusion_deprecated/ldm/models/diffusion/__init__.py
ADDED
File without changes
|
ttts/AA_diffusion_deprecated/ldm/models/diffusion/ddim.py
ADDED
@@ -0,0 +1,336 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""SAMPLING ONLY."""
|
2 |
+
|
3 |
+
import torch
|
4 |
+
import numpy as np
|
5 |
+
from tqdm import tqdm
|
6 |
+
|
7 |
+
from ldm.modules.diffusionmodules.util import make_ddim_sampling_parameters, make_ddim_timesteps, noise_like, extract_into_tensor
|
8 |
+
|
9 |
+
|
10 |
+
class DDIMSampler(object):
|
11 |
+
def __init__(self, model, schedule="linear", **kwargs):
|
12 |
+
super().__init__()
|
13 |
+
self.model = model
|
14 |
+
self.ddpm_num_timesteps = model.num_timesteps
|
15 |
+
self.schedule = schedule
|
16 |
+
|
17 |
+
def register_buffer(self, name, attr):
|
18 |
+
if type(attr) == torch.Tensor:
|
19 |
+
if attr.device != torch.device("cuda"):
|
20 |
+
attr = attr.to(torch.device("cuda"))
|
21 |
+
setattr(self, name, attr)
|
22 |
+
|
23 |
+
def make_schedule(self, ddim_num_steps, ddim_discretize="uniform", ddim_eta=0., verbose=True):
|
24 |
+
self.ddim_timesteps = make_ddim_timesteps(ddim_discr_method=ddim_discretize, num_ddim_timesteps=ddim_num_steps,
|
25 |
+
num_ddpm_timesteps=self.ddpm_num_timesteps,verbose=verbose)
|
26 |
+
alphas_cumprod = self.model.alphas_cumprod
|
27 |
+
assert alphas_cumprod.shape[0] == self.ddpm_num_timesteps, 'alphas have to be defined for each timestep'
|
28 |
+
to_torch = lambda x: x.clone().detach().to(torch.float32).to(self.model.device)
|
29 |
+
|
30 |
+
self.register_buffer('betas', to_torch(self.model.betas))
|
31 |
+
self.register_buffer('alphas_cumprod', to_torch(alphas_cumprod))
|
32 |
+
self.register_buffer('alphas_cumprod_prev', to_torch(self.model.alphas_cumprod_prev))
|
33 |
+
|
34 |
+
# calculations for diffusion q(x_t | x_{t-1}) and others
|
35 |
+
self.register_buffer('sqrt_alphas_cumprod', to_torch(np.sqrt(alphas_cumprod.cpu())))
|
36 |
+
self.register_buffer('sqrt_one_minus_alphas_cumprod', to_torch(np.sqrt(1. - alphas_cumprod.cpu())))
|
37 |
+
self.register_buffer('log_one_minus_alphas_cumprod', to_torch(np.log(1. - alphas_cumprod.cpu())))
|
38 |
+
self.register_buffer('sqrt_recip_alphas_cumprod', to_torch(np.sqrt(1. / alphas_cumprod.cpu())))
|
39 |
+
self.register_buffer('sqrt_recipm1_alphas_cumprod', to_torch(np.sqrt(1. / alphas_cumprod.cpu() - 1)))
|
40 |
+
|
41 |
+
# ddim sampling parameters
|
42 |
+
ddim_sigmas, ddim_alphas, ddim_alphas_prev = make_ddim_sampling_parameters(alphacums=alphas_cumprod.cpu(),
|
43 |
+
ddim_timesteps=self.ddim_timesteps,
|
44 |
+
eta=ddim_eta,verbose=verbose)
|
45 |
+
self.register_buffer('ddim_sigmas', ddim_sigmas)
|
46 |
+
self.register_buffer('ddim_alphas', ddim_alphas)
|
47 |
+
self.register_buffer('ddim_alphas_prev', ddim_alphas_prev)
|
48 |
+
self.register_buffer('ddim_sqrt_one_minus_alphas', np.sqrt(1. - ddim_alphas))
|
49 |
+
sigmas_for_original_sampling_steps = ddim_eta * torch.sqrt(
|
50 |
+
(1 - self.alphas_cumprod_prev) / (1 - self.alphas_cumprod) * (
|
51 |
+
1 - self.alphas_cumprod / self.alphas_cumprod_prev))
|
52 |
+
self.register_buffer('ddim_sigmas_for_original_num_steps', sigmas_for_original_sampling_steps)
|
53 |
+
|
54 |
+
@torch.no_grad()
|
55 |
+
def sample(self,
|
56 |
+
S,
|
57 |
+
batch_size,
|
58 |
+
shape,
|
59 |
+
conditioning=None,
|
60 |
+
callback=None,
|
61 |
+
normals_sequence=None,
|
62 |
+
img_callback=None,
|
63 |
+
quantize_x0=False,
|
64 |
+
eta=0.,
|
65 |
+
mask=None,
|
66 |
+
x0=None,
|
67 |
+
temperature=1.,
|
68 |
+
noise_dropout=0.,
|
69 |
+
score_corrector=None,
|
70 |
+
corrector_kwargs=None,
|
71 |
+
verbose=True,
|
72 |
+
x_T=None,
|
73 |
+
log_every_t=100,
|
74 |
+
unconditional_guidance_scale=1.,
|
75 |
+
unconditional_conditioning=None, # this has to come in the same format as the conditioning, # e.g. as encoded tokens, ...
|
76 |
+
dynamic_threshold=None,
|
77 |
+
ucg_schedule=None,
|
78 |
+
**kwargs
|
79 |
+
):
|
80 |
+
if conditioning is not None:
|
81 |
+
if isinstance(conditioning, dict):
|
82 |
+
ctmp = conditioning[list(conditioning.keys())[0]]
|
83 |
+
while isinstance(ctmp, list): ctmp = ctmp[0]
|
84 |
+
cbs = ctmp.shape[0]
|
85 |
+
if cbs != batch_size:
|
86 |
+
print(f"Warning: Got {cbs} conditionings but batch-size is {batch_size}")
|
87 |
+
|
88 |
+
elif isinstance(conditioning, list):
|
89 |
+
for ctmp in conditioning:
|
90 |
+
if ctmp.shape[0] != batch_size:
|
91 |
+
print(f"Warning: Got {cbs} conditionings but batch-size is {batch_size}")
|
92 |
+
|
93 |
+
else:
|
94 |
+
if conditioning.shape[0] != batch_size:
|
95 |
+
print(f"Warning: Got {conditioning.shape[0]} conditionings but batch-size is {batch_size}")
|
96 |
+
|
97 |
+
self.make_schedule(ddim_num_steps=S, ddim_eta=eta, verbose=verbose)
|
98 |
+
# sampling
|
99 |
+
C, T = shape
|
100 |
+
size = (batch_size, C, T)
|
101 |
+
print(f'Data shape for DDIM sampling is {size}, eta {eta}')
|
102 |
+
|
103 |
+
samples, intermediates = self.ddim_sampling(conditioning, size,
|
104 |
+
callback=callback,
|
105 |
+
img_callback=img_callback,
|
106 |
+
quantize_denoised=quantize_x0,
|
107 |
+
mask=mask, x0=x0,
|
108 |
+
ddim_use_original_steps=False,
|
109 |
+
noise_dropout=noise_dropout,
|
110 |
+
temperature=temperature,
|
111 |
+
score_corrector=score_corrector,
|
112 |
+
corrector_kwargs=corrector_kwargs,
|
113 |
+
x_T=x_T,
|
114 |
+
log_every_t=log_every_t,
|
115 |
+
unconditional_guidance_scale=unconditional_guidance_scale,
|
116 |
+
unconditional_conditioning=unconditional_conditioning,
|
117 |
+
dynamic_threshold=dynamic_threshold,
|
118 |
+
ucg_schedule=ucg_schedule
|
119 |
+
)
|
120 |
+
return samples, intermediates
|
121 |
+
|
122 |
+
@torch.no_grad()
|
123 |
+
def ddim_sampling(self, cond, shape,
|
124 |
+
x_T=None, ddim_use_original_steps=False,
|
125 |
+
callback=None, timesteps=None, quantize_denoised=False,
|
126 |
+
mask=None, x0=None, img_callback=None, log_every_t=100,
|
127 |
+
temperature=1., noise_dropout=0., score_corrector=None, corrector_kwargs=None,
|
128 |
+
unconditional_guidance_scale=1., unconditional_conditioning=None, dynamic_threshold=None,
|
129 |
+
ucg_schedule=None):
|
130 |
+
device = self.model.betas.device
|
131 |
+
b = shape[0]
|
132 |
+
if x_T is None:
|
133 |
+
img = torch.randn(shape, device=device)
|
134 |
+
else:
|
135 |
+
img = x_T
|
136 |
+
|
137 |
+
if timesteps is None:
|
138 |
+
timesteps = self.ddpm_num_timesteps if ddim_use_original_steps else self.ddim_timesteps
|
139 |
+
elif timesteps is not None and not ddim_use_original_steps:
|
140 |
+
subset_end = int(min(timesteps / self.ddim_timesteps.shape[0], 1) * self.ddim_timesteps.shape[0]) - 1
|
141 |
+
timesteps = self.ddim_timesteps[:subset_end]
|
142 |
+
|
143 |
+
intermediates = {'x_inter': [img], 'pred_x0': [img]}
|
144 |
+
time_range = reversed(range(0,timesteps)) if ddim_use_original_steps else np.flip(timesteps)
|
145 |
+
total_steps = timesteps if ddim_use_original_steps else timesteps.shape[0]
|
146 |
+
print(f"Running DDIM Sampling with {total_steps} timesteps")
|
147 |
+
|
148 |
+
iterator = tqdm(time_range, desc='DDIM Sampler', total=total_steps)
|
149 |
+
|
150 |
+
for i, step in enumerate(iterator):
|
151 |
+
index = total_steps - i - 1
|
152 |
+
ts = torch.full((b,), step, device=device, dtype=torch.long)
|
153 |
+
|
154 |
+
if mask is not None:
|
155 |
+
assert x0 is not None
|
156 |
+
img_orig = self.model.q_sample(x0, ts) # TODO: deterministic forward pass?
|
157 |
+
img = img_orig * mask + (1. - mask) * img
|
158 |
+
|
159 |
+
if ucg_schedule is not None:
|
160 |
+
assert len(ucg_schedule) == len(time_range)
|
161 |
+
unconditional_guidance_scale = ucg_schedule[i]
|
162 |
+
|
163 |
+
outs = self.p_sample_ddim(img, cond, ts, index=index, use_original_steps=ddim_use_original_steps,
|
164 |
+
quantize_denoised=quantize_denoised, temperature=temperature,
|
165 |
+
noise_dropout=noise_dropout, score_corrector=score_corrector,
|
166 |
+
corrector_kwargs=corrector_kwargs,
|
167 |
+
unconditional_guidance_scale=unconditional_guidance_scale,
|
168 |
+
unconditional_conditioning=unconditional_conditioning,
|
169 |
+
dynamic_threshold=dynamic_threshold)
|
170 |
+
img, pred_x0 = outs
|
171 |
+
if callback: callback(i)
|
172 |
+
if img_callback: img_callback(pred_x0, i)
|
173 |
+
|
174 |
+
if index % log_every_t == 0 or index == total_steps - 1:
|
175 |
+
intermediates['x_inter'].append(img)
|
176 |
+
intermediates['pred_x0'].append(pred_x0)
|
177 |
+
|
178 |
+
return img, intermediates
|
179 |
+
|
180 |
+
@torch.no_grad()
|
181 |
+
def p_sample_ddim(self, x, c, t, index, repeat_noise=False, use_original_steps=False, quantize_denoised=False,
|
182 |
+
temperature=1., noise_dropout=0., score_corrector=None, corrector_kwargs=None,
|
183 |
+
unconditional_guidance_scale=1., unconditional_conditioning=None,
|
184 |
+
dynamic_threshold=None):
|
185 |
+
b, *_, device = *x.shape, x.device
|
186 |
+
|
187 |
+
if unconditional_conditioning is None or unconditional_guidance_scale == 1.:
|
188 |
+
model_output = self.model.apply_model(x, t, c)
|
189 |
+
else:
|
190 |
+
x_in = torch.cat([x] * 2)
|
191 |
+
t_in = torch.cat([t] * 2)
|
192 |
+
if isinstance(c, dict):
|
193 |
+
assert isinstance(unconditional_conditioning, dict)
|
194 |
+
c_in = dict()
|
195 |
+
for k in c:
|
196 |
+
if isinstance(c[k], list):
|
197 |
+
c_in[k] = [torch.cat([
|
198 |
+
unconditional_conditioning[k][i],
|
199 |
+
c[k][i]]) for i in range(len(c[k]))]
|
200 |
+
else:
|
201 |
+
c_in[k] = torch.cat([
|
202 |
+
unconditional_conditioning[k],
|
203 |
+
c[k]])
|
204 |
+
elif isinstance(c, list):
|
205 |
+
c_in = list()
|
206 |
+
assert isinstance(unconditional_conditioning, list)
|
207 |
+
for i in range(len(c)):
|
208 |
+
c_in.append(torch.cat([unconditional_conditioning[i], c[i]]))
|
209 |
+
else:
|
210 |
+
c_in = torch.cat([unconditional_conditioning, c])
|
211 |
+
model_uncond, model_t = self.model.apply_model(x_in, t_in, c_in).chunk(2)
|
212 |
+
model_output = model_uncond + unconditional_guidance_scale * (model_t - model_uncond)
|
213 |
+
|
214 |
+
if self.model.parameterization == "v":
|
215 |
+
e_t = self.model.predict_eps_from_z_and_v(x, t, model_output)
|
216 |
+
else:
|
217 |
+
e_t = model_output
|
218 |
+
|
219 |
+
if score_corrector is not None:
|
220 |
+
assert self.model.parameterization == "eps", 'not implemented'
|
221 |
+
e_t = score_corrector.modify_score(self.model, e_t, x, t, c, **corrector_kwargs)
|
222 |
+
|
223 |
+
alphas = self.model.alphas_cumprod if use_original_steps else self.ddim_alphas
|
224 |
+
alphas_prev = self.model.alphas_cumprod_prev if use_original_steps else self.ddim_alphas_prev
|
225 |
+
sqrt_one_minus_alphas = self.model.sqrt_one_minus_alphas_cumprod if use_original_steps else self.ddim_sqrt_one_minus_alphas
|
226 |
+
sigmas = self.model.ddim_sigmas_for_original_num_steps if use_original_steps else self.ddim_sigmas
|
227 |
+
# select parameters corresponding to the currently considered timestep
|
228 |
+
a_t = torch.full((b, 1, 1), alphas[index], device=device)
|
229 |
+
a_prev = torch.full((b, 1, 1), alphas_prev[index], device=device)
|
230 |
+
sigma_t = torch.full((b, 1, 1), sigmas[index], device=device)
|
231 |
+
sqrt_one_minus_at = torch.full((b, 1, 1), sqrt_one_minus_alphas[index],device=device)
|
232 |
+
|
233 |
+
# current prediction for x_0
|
234 |
+
if self.model.parameterization != "v":
|
235 |
+
pred_x0 = (x - sqrt_one_minus_at * e_t) / a_t.sqrt()
|
236 |
+
else:
|
237 |
+
pred_x0 = self.model.predict_start_from_z_and_v(x, t, model_output)
|
238 |
+
|
239 |
+
if quantize_denoised:
|
240 |
+
pred_x0, _, *_ = self.model.first_stage_model.quantize(pred_x0)
|
241 |
+
|
242 |
+
if dynamic_threshold is not None:
|
243 |
+
raise NotImplementedError()
|
244 |
+
pred_x0 = pred_x0.clamp(-1, 1)
|
245 |
+
# direction pointing to x_t
|
246 |
+
dir_xt = (1. - a_prev - sigma_t**2).sqrt() * e_t
|
247 |
+
noise = sigma_t * noise_like(x.shape, device, repeat_noise) * temperature
|
248 |
+
if noise_dropout > 0.:
|
249 |
+
noise = torch.nn.functional.dropout(noise, p=noise_dropout)
|
250 |
+
x_prev = a_prev.sqrt() * pred_x0 + dir_xt + noise
|
251 |
+
return x_prev, pred_x0
|
252 |
+
|
253 |
+
@torch.no_grad()
|
254 |
+
def encode(self, x0, c, t_enc, use_original_steps=False, return_intermediates=None,
|
255 |
+
unconditional_guidance_scale=1.0, unconditional_conditioning=None, callback=None):
|
256 |
+
num_reference_steps = self.ddpm_num_timesteps if use_original_steps else self.ddim_timesteps.shape[0]
|
257 |
+
|
258 |
+
assert t_enc <= num_reference_steps
|
259 |
+
num_steps = t_enc
|
260 |
+
|
261 |
+
if use_original_steps:
|
262 |
+
alphas_next = self.alphas_cumprod[:num_steps]
|
263 |
+
alphas = self.alphas_cumprod_prev[:num_steps]
|
264 |
+
else:
|
265 |
+
alphas_next = self.ddim_alphas[:num_steps]
|
266 |
+
alphas = torch.tensor(self.ddim_alphas_prev[:num_steps])
|
267 |
+
|
268 |
+
x_next = x0
|
269 |
+
intermediates = []
|
270 |
+
inter_steps = []
|
271 |
+
for i in tqdm(range(num_steps), desc='Encoding Image'):
|
272 |
+
t = torch.full((x0.shape[0],), i, device=self.model.device, dtype=torch.long)
|
273 |
+
if unconditional_guidance_scale == 1.:
|
274 |
+
noise_pred = self.model.apply_model(x_next, t, c)
|
275 |
+
else:
|
276 |
+
assert unconditional_conditioning is not None
|
277 |
+
e_t_uncond, noise_pred = torch.chunk(
|
278 |
+
self.model.apply_model(torch.cat((x_next, x_next)), torch.cat((t, t)),
|
279 |
+
torch.cat((unconditional_conditioning, c))), 2)
|
280 |
+
noise_pred = e_t_uncond + unconditional_guidance_scale * (noise_pred - e_t_uncond)
|
281 |
+
|
282 |
+
xt_weighted = (alphas_next[i] / alphas[i]).sqrt() * x_next
|
283 |
+
weighted_noise_pred = alphas_next[i].sqrt() * (
|
284 |
+
(1 / alphas_next[i] - 1).sqrt() - (1 / alphas[i] - 1).sqrt()) * noise_pred
|
285 |
+
x_next = xt_weighted + weighted_noise_pred
|
286 |
+
if return_intermediates and i % (
|
287 |
+
num_steps // return_intermediates) == 0 and i < num_steps - 1:
|
288 |
+
intermediates.append(x_next)
|
289 |
+
inter_steps.append(i)
|
290 |
+
elif return_intermediates and i >= num_steps - 2:
|
291 |
+
intermediates.append(x_next)
|
292 |
+
inter_steps.append(i)
|
293 |
+
if callback: callback(i)
|
294 |
+
|
295 |
+
out = {'x_encoded': x_next, 'intermediate_steps': inter_steps}
|
296 |
+
if return_intermediates:
|
297 |
+
out.update({'intermediates': intermediates})
|
298 |
+
return x_next, out
|
299 |
+
|
300 |
+
@torch.no_grad()
|
301 |
+
def stochastic_encode(self, x0, t, use_original_steps=False, noise=None):
|
302 |
+
# fast, but does not allow for exact reconstruction
|
303 |
+
# t serves as an index to gather the correct alphas
|
304 |
+
if use_original_steps:
|
305 |
+
sqrt_alphas_cumprod = self.sqrt_alphas_cumprod
|
306 |
+
sqrt_one_minus_alphas_cumprod = self.sqrt_one_minus_alphas_cumprod
|
307 |
+
else:
|
308 |
+
sqrt_alphas_cumprod = torch.sqrt(self.ddim_alphas)
|
309 |
+
sqrt_one_minus_alphas_cumprod = self.ddim_sqrt_one_minus_alphas
|
310 |
+
|
311 |
+
if noise is None:
|
312 |
+
noise = torch.randn_like(x0)
|
313 |
+
return (extract_into_tensor(sqrt_alphas_cumprod, t, x0.shape) * x0 +
|
314 |
+
extract_into_tensor(sqrt_one_minus_alphas_cumprod, t, x0.shape) * noise)
|
315 |
+
|
316 |
+
@torch.no_grad()
|
317 |
+
def decode(self, x_latent, cond, t_start, unconditional_guidance_scale=1.0, unconditional_conditioning=None,
|
318 |
+
use_original_steps=False, callback=None):
|
319 |
+
|
320 |
+
timesteps = np.arange(self.ddpm_num_timesteps) if use_original_steps else self.ddim_timesteps
|
321 |
+
timesteps = timesteps[:t_start]
|
322 |
+
|
323 |
+
time_range = np.flip(timesteps)
|
324 |
+
total_steps = timesteps.shape[0]
|
325 |
+
print(f"Running DDIM Sampling with {total_steps} timesteps")
|
326 |
+
|
327 |
+
iterator = tqdm(time_range, desc='Decoding image', total=total_steps)
|
328 |
+
x_dec = x_latent
|
329 |
+
for i, step in enumerate(iterator):
|
330 |
+
index = total_steps - i - 1
|
331 |
+
ts = torch.full((x_latent.shape[0],), step, device=x_latent.device, dtype=torch.long)
|
332 |
+
x_dec, _ = self.p_sample_ddim(x_dec, cond, ts, index=index, use_original_steps=use_original_steps,
|
333 |
+
unconditional_guidance_scale=unconditional_guidance_scale,
|
334 |
+
unconditional_conditioning=unconditional_conditioning)
|
335 |
+
if callback: callback(i)
|
336 |
+
return x_dec
|
ttts/AA_diffusion_deprecated/ldm/models/diffusion/ddpm.py
ADDED
@@ -0,0 +1,1827 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
wild mixture of
|
3 |
+
https://github.com/lucidrains/denoising-diffusion-pytorch/blob/7706bdfc6f527f58d33f84b7b522e61e6e3164b3/denoising_diffusion_pytorch/denoising_diffusion_pytorch.py
|
4 |
+
https://github.com/openai/improved-diffusion/blob/e94489283bb876ac1477d5dd7709bbbd2d9902ce/improved_diffusion/gaussian_diffusion.py
|
5 |
+
https://github.com/CompVis/taming-transformers
|
6 |
+
-- merci
|
7 |
+
"""
|
8 |
+
|
9 |
+
import random
|
10 |
+
import torch
|
11 |
+
import torch.nn as nn
|
12 |
+
import numpy as np
|
13 |
+
# import pytorch_lightning as pl
|
14 |
+
from torch.optim.lr_scheduler import LambdaLR
|
15 |
+
from einops import rearrange, repeat
|
16 |
+
from contextlib import contextmanager, nullcontext
|
17 |
+
from functools import partial
|
18 |
+
import itertools
|
19 |
+
from tqdm import tqdm
|
20 |
+
from torchvision.utils import make_grid
|
21 |
+
# from pytorch_lightning.utilities.distributed import rank_zero_only
|
22 |
+
from omegaconf import ListConfig
|
23 |
+
|
24 |
+
from ldm.util import log_txt_as_img, exists, default, ismap, isimage, mean_flat, count_params, instantiate_from_config
|
25 |
+
from ldm.modules.ema import LitEma
|
26 |
+
from ldm.modules.distributions.distributions import normal_kl, DiagonalGaussianDistribution
|
27 |
+
# from ldm.models.autoencoder import IdentityFirstStage, AutoencoderKL
|
28 |
+
from ldm.modules.diffusionmodules.util import make_beta_schedule, extract_into_tensor, noise_like
|
29 |
+
from ldm.models.diffusion.ddim import DDIMSampler
|
30 |
+
|
31 |
+
|
32 |
+
__conditioning_keys__ = {'concat': 'c_concat',
|
33 |
+
'crossattn': 'c_crossattn',
|
34 |
+
'adm': 'y'}
|
35 |
+
|
36 |
+
|
37 |
+
def disabled_train(self, mode=True):
|
38 |
+
"""Overwrite model.train with this function to make sure train/eval mode
|
39 |
+
does not change anymore."""
|
40 |
+
return self
|
41 |
+
|
42 |
+
|
43 |
+
def uniform_on_device(r1, r2, shape, device):
|
44 |
+
return (r1 - r2) * torch.rand(*shape, device=device) + r2
|
45 |
+
|
46 |
+
# https://www.crosslabs.org//blog/diffusion-with-offset-noise
|
47 |
+
def apply_noise_offset(latents, noise, noise_offset, adaptive_noise_scale):
|
48 |
+
if noise_offset is None:
|
49 |
+
return noise
|
50 |
+
if adaptive_noise_scale is not None:
|
51 |
+
# latent shape: (batch_size, channels, height, width)
|
52 |
+
# abs mean value for each channel
|
53 |
+
latent_mean = torch.abs(latents.mean(dim=(2, 3), keepdim=True))
|
54 |
+
|
55 |
+
# multiply adaptive noise scale to the mean value and add it to the noise offset
|
56 |
+
noise_offset = noise_offset + adaptive_noise_scale * latent_mean
|
57 |
+
noise_offset = torch.clamp(noise_offset, 0.0, None) # in case of adaptive noise scale is negative
|
58 |
+
|
59 |
+
noise = noise + noise_offset * torch.randn((latents.shape[0], latents.shape[1], 1), device=latents.device)
|
60 |
+
return noise
|
61 |
+
|
62 |
+
class DDPM(nn.Module):
|
63 |
+
# classic DDPM with Gaussian diffusion, in image space
|
64 |
+
def __init__(self,
|
65 |
+
unet_config,
|
66 |
+
timesteps=1000,
|
67 |
+
beta_schedule="linear",
|
68 |
+
loss_type="l2",
|
69 |
+
ckpt_path=None,
|
70 |
+
ignore_keys=[],
|
71 |
+
load_only_unet=False,
|
72 |
+
monitor="val/loss",
|
73 |
+
use_ema=True,
|
74 |
+
first_stage_key="image",
|
75 |
+
image_size=256,
|
76 |
+
channels=3,
|
77 |
+
log_every_t=100,
|
78 |
+
clip_denoised=True,
|
79 |
+
linear_start=1e-4,
|
80 |
+
linear_end=2e-2,
|
81 |
+
cosine_s=8e-3,
|
82 |
+
given_betas=None,
|
83 |
+
original_elbo_weight=0.,
|
84 |
+
v_posterior=0., # weight for choosing posterior variance as sigma = (1-v) * beta_tilde + v * beta
|
85 |
+
l_simple_weight=1.,
|
86 |
+
conditioning_key=None,
|
87 |
+
parameterization="eps", # all assuming fixed variance schedules
|
88 |
+
scheduler_config=None,
|
89 |
+
use_positional_encodings=False,
|
90 |
+
learn_logvar=False,
|
91 |
+
logvar_init=0.,
|
92 |
+
make_it_fit=False,
|
93 |
+
ucg_training=None,
|
94 |
+
reset_ema=False,
|
95 |
+
reset_num_ema_updates=False,
|
96 |
+
):
|
97 |
+
super().__init__()
|
98 |
+
assert parameterization in ["eps", "x0", "v"], 'currently only supporting "eps" and "x0" and "v"'
|
99 |
+
self.parameterization = parameterization
|
100 |
+
print(f"{self.__class__.__name__}: Running in {self.parameterization}-prediction mode")
|
101 |
+
self.cond_stage_model = None
|
102 |
+
self.clip_denoised = clip_denoised
|
103 |
+
self.log_every_t = log_every_t
|
104 |
+
self.first_stage_key = first_stage_key
|
105 |
+
self.image_size = image_size # try conv?
|
106 |
+
self.channels = channels
|
107 |
+
self.use_positional_encodings = use_positional_encodings
|
108 |
+
self.model = DiffusionWrapper(unet_config, conditioning_key)
|
109 |
+
count_params(self.model, verbose=True)
|
110 |
+
self.use_ema = use_ema
|
111 |
+
if self.use_ema:
|
112 |
+
self.model_ema = LitEma(self.model)
|
113 |
+
print(f"Keeping EMAs of {len(list(self.model_ema.buffers()))}.")
|
114 |
+
|
115 |
+
self.use_scheduler = scheduler_config is not None
|
116 |
+
if self.use_scheduler:
|
117 |
+
self.scheduler_config = scheduler_config
|
118 |
+
|
119 |
+
self.v_posterior = v_posterior
|
120 |
+
self.original_elbo_weight = original_elbo_weight
|
121 |
+
self.l_simple_weight = l_simple_weight
|
122 |
+
|
123 |
+
if monitor is not None:
|
124 |
+
self.monitor = monitor
|
125 |
+
self.make_it_fit = make_it_fit
|
126 |
+
if reset_ema: assert exists(ckpt_path)
|
127 |
+
if ckpt_path is not None:
|
128 |
+
self.init_from_ckpt(ckpt_path, ignore_keys=ignore_keys, only_model=load_only_unet)
|
129 |
+
if reset_ema:
|
130 |
+
assert self.use_ema
|
131 |
+
print(f"Resetting ema to pure model weights. This is useful when restoring from an ema-only checkpoint.")
|
132 |
+
self.model_ema = LitEma(self.model)
|
133 |
+
if reset_num_ema_updates:
|
134 |
+
print(" +++++++++++ WARNING: RESETTING NUM_EMA UPDATES TO ZERO +++++++++++ ")
|
135 |
+
assert self.use_ema
|
136 |
+
self.model_ema.reset_num_updates()
|
137 |
+
|
138 |
+
self.register_schedule(given_betas=given_betas, beta_schedule=beta_schedule, timesteps=timesteps,
|
139 |
+
linear_start=linear_start, linear_end=linear_end, cosine_s=cosine_s)
|
140 |
+
|
141 |
+
self.loss_type = loss_type
|
142 |
+
|
143 |
+
self.learn_logvar = learn_logvar
|
144 |
+
logvar = torch.full(fill_value=logvar_init, size=(self.num_timesteps,))
|
145 |
+
if self.learn_logvar:
|
146 |
+
self.logvar = nn.Parameter(self.logvar, requires_grad=True)
|
147 |
+
else:
|
148 |
+
self.register_buffer('logvar', logvar)
|
149 |
+
|
150 |
+
self.ucg_training = ucg_training or dict()
|
151 |
+
if self.ucg_training:
|
152 |
+
self.ucg_prng = np.random.RandomState()
|
153 |
+
|
154 |
+
def register_schedule(self, given_betas=None, beta_schedule="linear", timesteps=1000,
|
155 |
+
linear_start=1e-4, linear_end=2e-2, cosine_s=8e-3):
|
156 |
+
if exists(given_betas):
|
157 |
+
betas = given_betas
|
158 |
+
else:
|
159 |
+
betas = make_beta_schedule(beta_schedule, timesteps, linear_start=linear_start, linear_end=linear_end,
|
160 |
+
cosine_s=cosine_s)
|
161 |
+
alphas = 1. - betas
|
162 |
+
alphas_cumprod = np.cumprod(alphas, axis=0)
|
163 |
+
alphas_cumprod_prev = np.append(1., alphas_cumprod[:-1])
|
164 |
+
|
165 |
+
timesteps, = betas.shape
|
166 |
+
self.num_timesteps = int(timesteps)
|
167 |
+
self.linear_start = linear_start
|
168 |
+
self.linear_end = linear_end
|
169 |
+
assert alphas_cumprod.shape[0] == self.num_timesteps, 'alphas have to be defined for each timestep'
|
170 |
+
|
171 |
+
to_torch = partial(torch.tensor, dtype=torch.float32)
|
172 |
+
|
173 |
+
self.register_buffer('betas', to_torch(betas))
|
174 |
+
self.register_buffer('alphas_cumprod', to_torch(alphas_cumprod))
|
175 |
+
self.register_buffer('alphas_cumprod_prev', to_torch(alphas_cumprod_prev))
|
176 |
+
|
177 |
+
# calculations for diffusion q(x_t | x_{t-1}) and others
|
178 |
+
self.register_buffer('sqrt_alphas_cumprod', to_torch(np.sqrt(alphas_cumprod)))
|
179 |
+
self.register_buffer('sqrt_one_minus_alphas_cumprod', to_torch(np.sqrt(1. - alphas_cumprod)))
|
180 |
+
self.register_buffer('log_one_minus_alphas_cumprod', to_torch(np.log(1. - alphas_cumprod)))
|
181 |
+
self.register_buffer('sqrt_recip_alphas_cumprod', to_torch(np.sqrt(1. / alphas_cumprod)))
|
182 |
+
self.register_buffer('sqrt_recipm1_alphas_cumprod', to_torch(np.sqrt(1. / alphas_cumprod - 1)))
|
183 |
+
|
184 |
+
# calculations for posterior q(x_{t-1} | x_t, x_0)
|
185 |
+
posterior_variance = (1 - self.v_posterior) * betas * (1. - alphas_cumprod_prev) / (
|
186 |
+
1. - alphas_cumprod) + self.v_posterior * betas
|
187 |
+
# above: equal to 1. / (1. / (1. - alpha_cumprod_tm1) + alpha_t / beta_t)
|
188 |
+
self.register_buffer('posterior_variance', to_torch(posterior_variance))
|
189 |
+
# below: log calculation clipped because the posterior variance is 0 at the beginning of the diffusion chain
|
190 |
+
self.register_buffer('posterior_log_variance_clipped', to_torch(np.log(np.maximum(posterior_variance, 1e-20))))
|
191 |
+
self.register_buffer('posterior_mean_coef1', to_torch(
|
192 |
+
betas * np.sqrt(alphas_cumprod_prev) / (1. - alphas_cumprod)))
|
193 |
+
self.register_buffer('posterior_mean_coef2', to_torch(
|
194 |
+
(1. - alphas_cumprod_prev) * np.sqrt(alphas) / (1. - alphas_cumprod)))
|
195 |
+
|
196 |
+
if self.parameterization == "eps":
|
197 |
+
lvlb_weights = self.betas ** 2 / (
|
198 |
+
2 * self.posterior_variance * to_torch(alphas) * (1 - self.alphas_cumprod))
|
199 |
+
elif self.parameterization == "x0":
|
200 |
+
lvlb_weights = 0.5 * np.sqrt(torch.Tensor(alphas_cumprod)) / (2. * 1 - torch.Tensor(alphas_cumprod))
|
201 |
+
elif self.parameterization == "v":
|
202 |
+
lvlb_weights = torch.ones_like(self.betas ** 2 / (
|
203 |
+
2 * self.posterior_variance * to_torch(alphas) * (1 - self.alphas_cumprod)))
|
204 |
+
else:
|
205 |
+
raise NotImplementedError("mu not supported")
|
206 |
+
lvlb_weights[0] = lvlb_weights[1]
|
207 |
+
self.register_buffer('lvlb_weights', lvlb_weights, persistent=False)
|
208 |
+
assert not torch.isnan(self.lvlb_weights).all()
|
209 |
+
|
210 |
+
@contextmanager
|
211 |
+
def ema_scope(self, context=None):
|
212 |
+
if self.use_ema:
|
213 |
+
self.model_ema.store(self.model.parameters())
|
214 |
+
self.model_ema.copy_to(self.model)
|
215 |
+
if context is not None:
|
216 |
+
print(f"{context}: Switched to EMA weights")
|
217 |
+
try:
|
218 |
+
yield None
|
219 |
+
finally:
|
220 |
+
if self.use_ema:
|
221 |
+
self.model_ema.restore(self.model.parameters())
|
222 |
+
if context is not None:
|
223 |
+
print(f"{context}: Restored training weights")
|
224 |
+
|
225 |
+
@torch.no_grad()
|
226 |
+
def init_from_ckpt(self, path, ignore_keys=list(), only_model=False):
|
227 |
+
sd = torch.load(path, map_location="cpu")
|
228 |
+
if "state_dict" in list(sd.keys()):
|
229 |
+
sd = sd["state_dict"]
|
230 |
+
keys = list(sd.keys())
|
231 |
+
for k in keys:
|
232 |
+
for ik in ignore_keys:
|
233 |
+
if k.startswith(ik):
|
234 |
+
print("Deleting key {} from state_dict.".format(k))
|
235 |
+
del sd[k]
|
236 |
+
if self.make_it_fit:
|
237 |
+
n_params = len([name for name, _ in
|
238 |
+
itertools.chain(self.named_parameters(),
|
239 |
+
self.named_buffers())])
|
240 |
+
for name, param in tqdm(
|
241 |
+
itertools.chain(self.named_parameters(),
|
242 |
+
self.named_buffers()),
|
243 |
+
desc="Fitting old weights to new weights",
|
244 |
+
total=n_params
|
245 |
+
):
|
246 |
+
if not name in sd:
|
247 |
+
continue
|
248 |
+
old_shape = sd[name].shape
|
249 |
+
new_shape = param.shape
|
250 |
+
assert len(old_shape) == len(new_shape)
|
251 |
+
if len(new_shape) > 2:
|
252 |
+
# we only modify first two axes
|
253 |
+
assert new_shape[2:] == old_shape[2:]
|
254 |
+
# assumes first axis corresponds to output dim
|
255 |
+
if not new_shape == old_shape:
|
256 |
+
new_param = param.clone()
|
257 |
+
old_param = sd[name]
|
258 |
+
if len(new_shape) == 1:
|
259 |
+
for i in range(new_param.shape[0]):
|
260 |
+
new_param[i] = old_param[i % old_shape[0]]
|
261 |
+
elif len(new_shape) >= 2:
|
262 |
+
for i in range(new_param.shape[0]):
|
263 |
+
for j in range(new_param.shape[1]):
|
264 |
+
new_param[i, j] = old_param[i % old_shape[0], j % old_shape[1]]
|
265 |
+
|
266 |
+
n_used_old = torch.ones(old_shape[1])
|
267 |
+
for j in range(new_param.shape[1]):
|
268 |
+
n_used_old[j % old_shape[1]] += 1
|
269 |
+
n_used_new = torch.zeros(new_shape[1])
|
270 |
+
for j in range(new_param.shape[1]):
|
271 |
+
n_used_new[j] = n_used_old[j % old_shape[1]]
|
272 |
+
|
273 |
+
n_used_new = n_used_new[None, :]
|
274 |
+
while len(n_used_new.shape) < len(new_shape):
|
275 |
+
n_used_new = n_used_new.unsqueeze(-1)
|
276 |
+
new_param /= n_used_new
|
277 |
+
|
278 |
+
sd[name] = new_param
|
279 |
+
|
280 |
+
missing, unexpected = self.load_state_dict(sd, strict=False) if not only_model else self.model.load_state_dict(
|
281 |
+
sd, strict=False)
|
282 |
+
print(f"Restored from {path} with {len(missing)} missing and {len(unexpected)} unexpected keys")
|
283 |
+
if len(missing) > 0:
|
284 |
+
print(f"Missing Keys:\n {missing}")
|
285 |
+
if len(unexpected) > 0:
|
286 |
+
print(f"\nUnexpected Keys:\n {unexpected}")
|
287 |
+
|
288 |
+
def q_mean_variance(self, x_start, t):
|
289 |
+
"""
|
290 |
+
Get the distribution q(x_t | x_0).
|
291 |
+
:param x_start: the [N x C x ...] tensor of noiseless inputs.
|
292 |
+
:param t: the number of diffusion steps (minus 1). Here, 0 means one step.
|
293 |
+
:return: A tuple (mean, variance, log_variance), all of x_start's shape.
|
294 |
+
"""
|
295 |
+
mean = (extract_into_tensor(self.sqrt_alphas_cumprod, t, x_start.shape) * x_start)
|
296 |
+
variance = extract_into_tensor(1.0 - self.alphas_cumprod, t, x_start.shape)
|
297 |
+
log_variance = extract_into_tensor(self.log_one_minus_alphas_cumprod, t, x_start.shape)
|
298 |
+
return mean, variance, log_variance
|
299 |
+
|
300 |
+
def predict_start_from_noise(self, x_t, t, noise):
|
301 |
+
return (
|
302 |
+
extract_into_tensor(self.sqrt_recip_alphas_cumprod, t, x_t.shape) * x_t -
|
303 |
+
extract_into_tensor(self.sqrt_recipm1_alphas_cumprod, t, x_t.shape) * noise
|
304 |
+
)
|
305 |
+
|
306 |
+
def predict_start_from_z_and_v(self, x_t, t, v):
|
307 |
+
# self.register_buffer('sqrt_alphas_cumprod', to_torch(np.sqrt(alphas_cumprod)))
|
308 |
+
# self.register_buffer('sqrt_one_minus_alphas_cumprod', to_torch(np.sqrt(1. - alphas_cumprod)))
|
309 |
+
return (
|
310 |
+
extract_into_tensor(self.sqrt_alphas_cumprod, t, x_t.shape) * x_t -
|
311 |
+
extract_into_tensor(self.sqrt_one_minus_alphas_cumprod, t, x_t.shape) * v
|
312 |
+
)
|
313 |
+
|
314 |
+
def predict_eps_from_z_and_v(self, x_t, t, v):
|
315 |
+
return (
|
316 |
+
extract_into_tensor(self.sqrt_alphas_cumprod, t, x_t.shape) * v +
|
317 |
+
extract_into_tensor(self.sqrt_one_minus_alphas_cumprod, t, x_t.shape) * x_t
|
318 |
+
)
|
319 |
+
|
320 |
+
def q_posterior(self, x_start, x_t, t):
|
321 |
+
posterior_mean = (
|
322 |
+
extract_into_tensor(self.posterior_mean_coef1, t, x_t.shape) * x_start +
|
323 |
+
extract_into_tensor(self.posterior_mean_coef2, t, x_t.shape) * x_t
|
324 |
+
)
|
325 |
+
posterior_variance = extract_into_tensor(self.posterior_variance, t, x_t.shape)
|
326 |
+
posterior_log_variance_clipped = extract_into_tensor(self.posterior_log_variance_clipped, t, x_t.shape)
|
327 |
+
return posterior_mean, posterior_variance, posterior_log_variance_clipped
|
328 |
+
|
329 |
+
def p_mean_variance(self, x, t, clip_denoised: bool):
|
330 |
+
model_out = self.model(x, t)
|
331 |
+
if self.parameterization == "eps":
|
332 |
+
x_recon = self.predict_start_from_noise(x, t=t, noise=model_out)
|
333 |
+
elif self.parameterization == "x0":
|
334 |
+
x_recon = model_out
|
335 |
+
if clip_denoised:
|
336 |
+
x_recon.clamp_(-1., 1.)
|
337 |
+
|
338 |
+
model_mean, posterior_variance, posterior_log_variance = self.q_posterior(x_start=x_recon, x_t=x, t=t)
|
339 |
+
return model_mean, posterior_variance, posterior_log_variance
|
340 |
+
|
341 |
+
@torch.no_grad()
|
342 |
+
def p_sample(self, x, t, clip_denoised=True, repeat_noise=False):
|
343 |
+
b, *_, device = *x.shape, x.device
|
344 |
+
model_mean, _, model_log_variance = self.p_mean_variance(x=x, t=t, clip_denoised=clip_denoised)
|
345 |
+
noise = noise_like(x.shape, device, repeat_noise)
|
346 |
+
# no noise when t == 0
|
347 |
+
nonzero_mask = (1 - (t == 0).float()).reshape(b, *((1,) * (len(x.shape) - 1)))
|
348 |
+
return model_mean + nonzero_mask * (0.5 * model_log_variance).exp() * noise
|
349 |
+
|
350 |
+
@torch.no_grad()
|
351 |
+
def p_sample_loop(self, shape, return_intermediates=False):
|
352 |
+
device = self.betas.device
|
353 |
+
b = shape[0]
|
354 |
+
img = torch.randn(shape, device=device)
|
355 |
+
intermediates = [img]
|
356 |
+
for i in tqdm(reversed(range(0, self.num_timesteps)), desc='Sampling t', total=self.num_timesteps):
|
357 |
+
img = self.p_sample(img, torch.full((b,), i, device=device, dtype=torch.long),
|
358 |
+
clip_denoised=self.clip_denoised)
|
359 |
+
if i % self.log_every_t == 0 or i == self.num_timesteps - 1:
|
360 |
+
intermediates.append(img)
|
361 |
+
if return_intermediates:
|
362 |
+
return img, intermediates
|
363 |
+
return img
|
364 |
+
|
365 |
+
@torch.no_grad()
|
366 |
+
def sample(self, batch_size=16, return_intermediates=False):
|
367 |
+
image_size = self.image_size
|
368 |
+
channels = self.channels
|
369 |
+
return self.p_sample_loop((batch_size, channels, image_size, image_size),
|
370 |
+
return_intermediates=return_intermediates)
|
371 |
+
|
372 |
+
def q_sample(self, x_start, t, noise=None):
|
373 |
+
noise = default(noise, lambda: torch.randn_like(x_start))
|
374 |
+
return (extract_into_tensor(self.sqrt_alphas_cumprod, t, x_start.shape) * x_start +
|
375 |
+
extract_into_tensor(self.sqrt_one_minus_alphas_cumprod, t, x_start.shape) * noise)
|
376 |
+
|
377 |
+
def get_v(self, x, noise, t):
|
378 |
+
return (
|
379 |
+
extract_into_tensor(self.sqrt_alphas_cumprod, t, x.shape) * noise -
|
380 |
+
extract_into_tensor(self.sqrt_one_minus_alphas_cumprod, t, x.shape) * x
|
381 |
+
)
|
382 |
+
|
383 |
+
def get_loss(self, pred, target, mean=True):
|
384 |
+
if self.loss_type == 'l1':
|
385 |
+
loss = (target - pred).abs()
|
386 |
+
if mean:
|
387 |
+
loss = loss.mean()
|
388 |
+
elif self.loss_type == 'l2':
|
389 |
+
if mean:
|
390 |
+
loss = torch.nn.functional.mse_loss(target, pred)
|
391 |
+
else:
|
392 |
+
loss = torch.nn.functional.mse_loss(target, pred, reduction='none')
|
393 |
+
else:
|
394 |
+
raise NotImplementedError("unknown loss type '{loss_type}'")
|
395 |
+
|
396 |
+
return loss
|
397 |
+
|
398 |
+
def p_losses(self, x_start, t, noise=None):
|
399 |
+
noise = default(noise, lambda: torch.randn_like(x_start))
|
400 |
+
#add offset noise
|
401 |
+
# noise = apply_noise_offset(x_start, noise, 0.1, None)
|
402 |
+
x_noisy = self.q_sample(x_start=x_start, t=t, noise=noise)
|
403 |
+
model_out = self.model(x_noisy, t)
|
404 |
+
|
405 |
+
loss_dict = {}
|
406 |
+
if self.parameterization == "eps":
|
407 |
+
target = noise
|
408 |
+
elif self.parameterization == "x0":
|
409 |
+
target = x_start
|
410 |
+
elif self.parameterization == "v":
|
411 |
+
target = self.get_v(x_start, noise, t)
|
412 |
+
else:
|
413 |
+
raise NotImplementedError(f"Parameterization {self.parameterization} not yet supported")
|
414 |
+
|
415 |
+
loss = self.get_loss(model_out, target, mean=False).mean(dim=[1, 2, 3])
|
416 |
+
|
417 |
+
log_prefix = 'train' if self.training else 'val'
|
418 |
+
|
419 |
+
loss_dict.update({f'{log_prefix}/loss_simple': loss.mean()})
|
420 |
+
loss_simple = loss.mean() * self.l_simple_weight
|
421 |
+
|
422 |
+
loss_vlb = (self.lvlb_weights[t] * loss).mean()
|
423 |
+
loss_dict.update({f'{log_prefix}/loss_vlb': loss_vlb})
|
424 |
+
|
425 |
+
loss = loss_simple + self.original_elbo_weight * loss_vlb
|
426 |
+
|
427 |
+
loss_dict.update({f'{log_prefix}/loss': loss})
|
428 |
+
|
429 |
+
return loss, loss_dict
|
430 |
+
|
431 |
+
def forward(self, x, *args, **kwargs):
|
432 |
+
# b, c, h, w, device, img_size, = *x.shape, x.device, self.image_size
|
433 |
+
# assert h == img_size and w == img_size, f'height and width of image must be {img_size}'
|
434 |
+
t = torch.randint(0, self.num_timesteps, (x.shape[0],), device=self.device).long()
|
435 |
+
return self.p_losses(x, t, *args, **kwargs)
|
436 |
+
|
437 |
+
def get_input(self, batch, k):
|
438 |
+
x = batch[k]
|
439 |
+
# if len(x.shape) == 3:
|
440 |
+
# x = x[..., None]
|
441 |
+
# x = rearrange(x, 'b h w c -> b c h w')
|
442 |
+
x = x.to(memory_format=torch.contiguous_format).float()
|
443 |
+
return x
|
444 |
+
|
445 |
+
def shared_step(self, batch):
|
446 |
+
x = self.get_input(batch, self.first_stage_key)
|
447 |
+
loss, loss_dict = self(x)
|
448 |
+
return loss, loss_dict
|
449 |
+
|
450 |
+
def training_step(self, batch):
|
451 |
+
for k in self.ucg_training:
|
452 |
+
p = self.ucg_training[k]["p"]
|
453 |
+
val = self.ucg_training[k]["val"]
|
454 |
+
if val is None:
|
455 |
+
val = ""
|
456 |
+
for i in range(len(batch[k])):
|
457 |
+
if self.ucg_prng.choice(2, p=[1 - p, p]):
|
458 |
+
batch[k][i] = val
|
459 |
+
|
460 |
+
loss, loss_dict = self.shared_step(batch)
|
461 |
+
|
462 |
+
# self.log_dict(loss_dict, prog_bar=True,
|
463 |
+
# logger=True, on_step=True, on_epoch=True)
|
464 |
+
|
465 |
+
# self.log("global_step", self.global_step,
|
466 |
+
# prog_bar=True, logger=True, on_step=True, on_epoch=False)
|
467 |
+
|
468 |
+
# if self.use_scheduler:
|
469 |
+
# lr = self.optimizers().param_groups[0]['lr']
|
470 |
+
# self.log('lr_abs', lr, prog_bar=True, logger=True, on_step=True, on_epoch=False)
|
471 |
+
|
472 |
+
return loss
|
473 |
+
|
474 |
+
@torch.no_grad()
|
475 |
+
def validation_step(self, batch, batch_idx):
|
476 |
+
_, loss_dict_no_ema = self.shared_step(batch)
|
477 |
+
with self.ema_scope():
|
478 |
+
_, loss_dict_ema = self.shared_step(batch)
|
479 |
+
loss_dict_ema = {key + '_ema': loss_dict_ema[key] for key in loss_dict_ema}
|
480 |
+
self.log_dict(loss_dict_no_ema, prog_bar=False, logger=True, on_step=False, on_epoch=True)
|
481 |
+
self.log_dict(loss_dict_ema, prog_bar=False, logger=True, on_step=False, on_epoch=True)
|
482 |
+
|
483 |
+
def on_train_batch_end(self, *args, **kwargs):
|
484 |
+
if self.use_ema:
|
485 |
+
self.model_ema(self.model)
|
486 |
+
|
487 |
+
def _get_rows_from_list(self, samples):
|
488 |
+
n_imgs_per_row = len(samples)
|
489 |
+
denoise_grid = rearrange(samples, 'n b c h w -> b n c h w')
|
490 |
+
denoise_grid = rearrange(denoise_grid, 'b n c h w -> (b n) c h w')
|
491 |
+
denoise_grid = make_grid(denoise_grid, nrow=n_imgs_per_row)
|
492 |
+
return denoise_grid
|
493 |
+
|
494 |
+
@torch.no_grad()
|
495 |
+
def log_images(self, batch, N=8, n_row=2, sample=True, return_keys=None, **kwargs):
|
496 |
+
log = dict()
|
497 |
+
x = self.get_input(batch, self.first_stage_key)
|
498 |
+
N = min(x.shape[0], N)
|
499 |
+
n_row = min(x.shape[0], n_row)
|
500 |
+
x = x.to(self.device)[:N]
|
501 |
+
log["inputs"] = x
|
502 |
+
|
503 |
+
# get diffusion row
|
504 |
+
diffusion_row = list()
|
505 |
+
x_start = x[:n_row]
|
506 |
+
|
507 |
+
for t in range(self.num_timesteps):
|
508 |
+
if t % self.log_every_t == 0 or t == self.num_timesteps - 1:
|
509 |
+
t = repeat(torch.tensor([t]), '1 -> b', b=n_row)
|
510 |
+
t = t.to(self.device).long()
|
511 |
+
noise = torch.randn_like(x_start)
|
512 |
+
x_noisy = self.q_sample(x_start=x_start, t=t, noise=noise)
|
513 |
+
diffusion_row.append(x_noisy)
|
514 |
+
|
515 |
+
log["diffusion_row"] = self._get_rows_from_list(diffusion_row)
|
516 |
+
|
517 |
+
if sample:
|
518 |
+
# get denoise row
|
519 |
+
with self.ema_scope("Plotting"):
|
520 |
+
samples, denoise_row = self.sample(batch_size=N, return_intermediates=True)
|
521 |
+
|
522 |
+
log["samples"] = samples
|
523 |
+
log["denoise_row"] = self._get_rows_from_list(denoise_row)
|
524 |
+
|
525 |
+
if return_keys:
|
526 |
+
if np.intersect1d(list(log.keys()), return_keys).shape[0] == 0:
|
527 |
+
return log
|
528 |
+
else:
|
529 |
+
return {key: log[key] for key in return_keys}
|
530 |
+
return log
|
531 |
+
|
532 |
+
def configure_optimizers(self):
|
533 |
+
lr = self.learning_rate
|
534 |
+
params = list(self.model.parameters())
|
535 |
+
if self.learn_logvar:
|
536 |
+
params = params + [self.logvar]
|
537 |
+
opt = torch.optim.AdamW(params, lr=lr)
|
538 |
+
return opt
|
539 |
+
|
540 |
+
|
541 |
+
class LatentDiffusion(DDPM):
|
542 |
+
"""main class"""
|
543 |
+
|
544 |
+
def __init__(self,
|
545 |
+
first_stage_config,
|
546 |
+
cond_stage_config,
|
547 |
+
num_timesteps_cond=None,
|
548 |
+
cond_stage_key="image",
|
549 |
+
cond_stage_trainable=False,
|
550 |
+
concat_mode=True,
|
551 |
+
cond_stage_forward=None,
|
552 |
+
conditioning_key=None,
|
553 |
+
scale_factor=1.0,
|
554 |
+
scale_by_std=False,
|
555 |
+
force_null_conditioning=False,
|
556 |
+
*args, **kwargs):
|
557 |
+
self.force_null_conditioning = force_null_conditioning
|
558 |
+
self.num_timesteps_cond = default(num_timesteps_cond, 1)
|
559 |
+
self.scale_by_std = scale_by_std
|
560 |
+
assert self.num_timesteps_cond <= kwargs['timesteps']
|
561 |
+
# for backwards compatibility after implementation of DiffusionWrapper
|
562 |
+
if conditioning_key is None:
|
563 |
+
conditioning_key = 'concat' if concat_mode else 'crossattn'
|
564 |
+
if cond_stage_config == '__is_unconditional__' and not self.force_null_conditioning:
|
565 |
+
conditioning_key = None
|
566 |
+
ckpt_path = kwargs.pop("ckpt_path", None)
|
567 |
+
reset_ema = kwargs.pop("reset_ema", False)
|
568 |
+
reset_num_ema_updates = kwargs.pop("reset_num_ema_updates", False)
|
569 |
+
ignore_keys = kwargs.pop("ignore_keys", [])
|
570 |
+
super().__init__(conditioning_key=conditioning_key, *args, **kwargs)
|
571 |
+
self.concat_mode = concat_mode
|
572 |
+
self.cond_stage_trainable = cond_stage_trainable
|
573 |
+
self.cond_stage_key = cond_stage_key
|
574 |
+
try:
|
575 |
+
self.num_downs = len(first_stage_config.params.ddconfig.ch_mult) - 1
|
576 |
+
except:
|
577 |
+
self.num_downs = 0
|
578 |
+
if not scale_by_std:
|
579 |
+
self.scale_factor = scale_factor
|
580 |
+
else:
|
581 |
+
self.register_buffer('scale_factor', torch.tensor(scale_factor))
|
582 |
+
# self.instantiate_first_stage(first_stage_config)
|
583 |
+
self.instantiate_cond_stage(cond_stage_config)
|
584 |
+
self.cond_stage_forward = cond_stage_forward
|
585 |
+
self.clip_denoised = False
|
586 |
+
self.bbox_tokenizer = None
|
587 |
+
|
588 |
+
self.restarted_from_ckpt = False
|
589 |
+
if ckpt_path is not None:
|
590 |
+
self.init_from_ckpt(ckpt_path, ignore_keys)
|
591 |
+
self.restarted_from_ckpt = True
|
592 |
+
if reset_ema:
|
593 |
+
assert self.use_ema
|
594 |
+
print(
|
595 |
+
f"Resetting ema to pure model weights. This is useful when restoring from an ema-only checkpoint.")
|
596 |
+
self.model_ema = LitEma(self.model)
|
597 |
+
if reset_num_ema_updates:
|
598 |
+
print(" +++++++++++ WARNING: RESETTING NUM_EMA UPDATES TO ZERO +++++++++++ ")
|
599 |
+
assert self.use_ema
|
600 |
+
self.model_ema.reset_num_updates()
|
601 |
+
|
602 |
+
def make_cond_schedule(self, ):
|
603 |
+
self.cond_ids = torch.full(size=(self.num_timesteps,), fill_value=self.num_timesteps - 1, dtype=torch.long)
|
604 |
+
ids = torch.round(torch.linspace(0, self.num_timesteps - 1, self.num_timesteps_cond)).long()
|
605 |
+
self.cond_ids[:self.num_timesteps_cond] = ids
|
606 |
+
|
607 |
+
# @rank_zero_only
|
608 |
+
@torch.no_grad()
|
609 |
+
def on_train_batch_start(self, batch, batch_idx, dataloader_idx):
|
610 |
+
# only for very first batch
|
611 |
+
if self.scale_by_std and self.current_epoch == 0 and self.global_step == 0 and batch_idx == 0 and not self.restarted_from_ckpt:
|
612 |
+
assert self.scale_factor == 1., 'rather not use custom rescaling and std-rescaling simultaneously'
|
613 |
+
# set rescale weight to 1./std of encodings
|
614 |
+
print("### USING STD-RESCALING ###")
|
615 |
+
x = super().get_input(batch, self.first_stage_key)
|
616 |
+
x = x.to(self.device)
|
617 |
+
encoder_posterior = self.encode_first_stage(x)
|
618 |
+
z = self.get_first_stage_encoding(encoder_posterior).detach()
|
619 |
+
del self.scale_factor
|
620 |
+
self.register_buffer('scale_factor', 1. / z.flatten().std())
|
621 |
+
print(f"setting self.scale_factor to {self.scale_factor}")
|
622 |
+
print("### USING STD-RESCALING ###")
|
623 |
+
|
624 |
+
def register_schedule(self,
|
625 |
+
given_betas=None, beta_schedule="linear", timesteps=1000,
|
626 |
+
linear_start=1e-4, linear_end=2e-2, cosine_s=8e-3):
|
627 |
+
super().register_schedule(given_betas, beta_schedule, timesteps, linear_start, linear_end, cosine_s)
|
628 |
+
|
629 |
+
self.shorten_cond_schedule = self.num_timesteps_cond > 1
|
630 |
+
if self.shorten_cond_schedule:
|
631 |
+
self.make_cond_schedule()
|
632 |
+
|
633 |
+
def instantiate_first_stage(self, config):
|
634 |
+
model = instantiate_from_config(config)
|
635 |
+
self.first_stage_model = model.eval()
|
636 |
+
self.first_stage_model.train = disabled_train
|
637 |
+
for param in self.first_stage_model.parameters():
|
638 |
+
param.requires_grad = False
|
639 |
+
|
640 |
+
def instantiate_cond_stage(self, config):
|
641 |
+
if not self.cond_stage_trainable:
|
642 |
+
if config == "__is_first_stage__":
|
643 |
+
print("Using first stage also as cond stage.")
|
644 |
+
self.cond_stage_model = self.first_stage_model
|
645 |
+
elif config == "__is_unconditional__":
|
646 |
+
print(f"Training {self.__class__.__name__} as an unconditional model.")
|
647 |
+
self.cond_stage_model = None
|
648 |
+
# self.be_unconditional = True
|
649 |
+
else:
|
650 |
+
model = instantiate_from_config(config)
|
651 |
+
self.cond_stage_model = model.eval()
|
652 |
+
self.cond_stage_model.train = disabled_train
|
653 |
+
for param in self.cond_stage_model.parameters():
|
654 |
+
param.requires_grad = False
|
655 |
+
else:
|
656 |
+
assert config != '__is_first_stage__'
|
657 |
+
assert config != '__is_unconditional__'
|
658 |
+
model = instantiate_from_config(config)
|
659 |
+
self.cond_stage_model = model
|
660 |
+
|
661 |
+
def _get_denoise_row_from_list(self, samples, desc='', force_no_decoder_quantization=False):
|
662 |
+
denoise_row = []
|
663 |
+
for zd in tqdm(samples, desc=desc):
|
664 |
+
denoise_row.append(self.decode_first_stage(zd.to(self.device),
|
665 |
+
force_not_quantize=force_no_decoder_quantization))
|
666 |
+
n_imgs_per_row = len(denoise_row)
|
667 |
+
denoise_row = torch.stack(denoise_row) # n_log_step, n_row, C, H, W
|
668 |
+
denoise_grid = rearrange(denoise_row, 'n b c h w -> b n c h w')
|
669 |
+
denoise_grid = rearrange(denoise_grid, 'b n c h w -> (b n) c h w')
|
670 |
+
denoise_grid = make_grid(denoise_grid, nrow=n_imgs_per_row)
|
671 |
+
return denoise_grid
|
672 |
+
|
673 |
+
def get_first_stage_encoding(self, encoder_posterior):
|
674 |
+
if isinstance(encoder_posterior, DiagonalGaussianDistribution):
|
675 |
+
z = encoder_posterior.sample()
|
676 |
+
elif isinstance(encoder_posterior, torch.Tensor):
|
677 |
+
z = encoder_posterior
|
678 |
+
else:
|
679 |
+
raise NotImplementedError(f"encoder_posterior of type '{type(encoder_posterior)}' not yet implemented")
|
680 |
+
return self.scale_factor * z
|
681 |
+
|
682 |
+
def get_learned_conditioning(self, c):
|
683 |
+
if self.cond_stage_forward is None:
|
684 |
+
if hasattr(self.cond_stage_model, 'encode') and callable(self.cond_stage_model.encode):
|
685 |
+
c = self.cond_stage_model.encode(c)
|
686 |
+
if isinstance(c, DiagonalGaussianDistribution):
|
687 |
+
c = c.mode()
|
688 |
+
else:
|
689 |
+
c = self.cond_stage_model(c)
|
690 |
+
else:
|
691 |
+
assert hasattr(self.cond_stage_model, self.cond_stage_forward)
|
692 |
+
c = getattr(self.cond_stage_model, self.cond_stage_forward)(c)
|
693 |
+
return c
|
694 |
+
|
695 |
+
def meshgrid(self, h, w):
|
696 |
+
y = torch.arange(0, h).view(h, 1, 1).repeat(1, w, 1)
|
697 |
+
x = torch.arange(0, w).view(1, w, 1).repeat(h, 1, 1)
|
698 |
+
|
699 |
+
arr = torch.cat([y, x], dim=-1)
|
700 |
+
return arr
|
701 |
+
|
702 |
+
def delta_border(self, h, w):
|
703 |
+
"""
|
704 |
+
:param h: height
|
705 |
+
:param w: width
|
706 |
+
:return: normalized distance to image border,
|
707 |
+
wtith min distance = 0 at border and max dist = 0.5 at image center
|
708 |
+
"""
|
709 |
+
lower_right_corner = torch.tensor([h - 1, w - 1]).view(1, 1, 2)
|
710 |
+
arr = self.meshgrid(h, w) / lower_right_corner
|
711 |
+
dist_left_up = torch.min(arr, dim=-1, keepdims=True)[0]
|
712 |
+
dist_right_down = torch.min(1 - arr, dim=-1, keepdims=True)[0]
|
713 |
+
edge_dist = torch.min(torch.cat([dist_left_up, dist_right_down], dim=-1), dim=-1)[0]
|
714 |
+
return edge_dist
|
715 |
+
|
716 |
+
def get_weighting(self, h, w, Ly, Lx, device):
|
717 |
+
weighting = self.delta_border(h, w)
|
718 |
+
weighting = torch.clip(weighting, self.split_input_params["clip_min_weight"],
|
719 |
+
self.split_input_params["clip_max_weight"], )
|
720 |
+
weighting = weighting.view(1, h * w, 1).repeat(1, 1, Ly * Lx).to(device)
|
721 |
+
|
722 |
+
if self.split_input_params["tie_braker"]:
|
723 |
+
L_weighting = self.delta_border(Ly, Lx)
|
724 |
+
L_weighting = torch.clip(L_weighting,
|
725 |
+
self.split_input_params["clip_min_tie_weight"],
|
726 |
+
self.split_input_params["clip_max_tie_weight"])
|
727 |
+
|
728 |
+
L_weighting = L_weighting.view(1, 1, Ly * Lx).to(device)
|
729 |
+
weighting = weighting * L_weighting
|
730 |
+
return weighting
|
731 |
+
|
732 |
+
def get_fold_unfold(self, x, kernel_size, stride, uf=1, df=1): # todo load once not every time, shorten code
|
733 |
+
"""
|
734 |
+
:param x: img of size (bs, c, h, w)
|
735 |
+
:return: n img crops of size (n, bs, c, kernel_size[0], kernel_size[1])
|
736 |
+
"""
|
737 |
+
bs, nc, h, w = x.shape
|
738 |
+
|
739 |
+
# number of crops in image
|
740 |
+
Ly = (h - kernel_size[0]) // stride[0] + 1
|
741 |
+
Lx = (w - kernel_size[1]) // stride[1] + 1
|
742 |
+
|
743 |
+
if uf == 1 and df == 1:
|
744 |
+
fold_params = dict(kernel_size=kernel_size, dilation=1, padding=0, stride=stride)
|
745 |
+
unfold = torch.nn.Unfold(**fold_params)
|
746 |
+
|
747 |
+
fold = torch.nn.Fold(output_size=x.shape[2:], **fold_params)
|
748 |
+
|
749 |
+
weighting = self.get_weighting(kernel_size[0], kernel_size[1], Ly, Lx, x.device).to(x.dtype)
|
750 |
+
normalization = fold(weighting).view(1, 1, h, w) # normalizes the overlap
|
751 |
+
weighting = weighting.view((1, 1, kernel_size[0], kernel_size[1], Ly * Lx))
|
752 |
+
|
753 |
+
elif uf > 1 and df == 1:
|
754 |
+
fold_params = dict(kernel_size=kernel_size, dilation=1, padding=0, stride=stride)
|
755 |
+
unfold = torch.nn.Unfold(**fold_params)
|
756 |
+
|
757 |
+
fold_params2 = dict(kernel_size=(kernel_size[0] * uf, kernel_size[0] * uf),
|
758 |
+
dilation=1, padding=0,
|
759 |
+
stride=(stride[0] * uf, stride[1] * uf))
|
760 |
+
fold = torch.nn.Fold(output_size=(x.shape[2] * uf, x.shape[3] * uf), **fold_params2)
|
761 |
+
|
762 |
+
weighting = self.get_weighting(kernel_size[0] * uf, kernel_size[1] * uf, Ly, Lx, x.device).to(x.dtype)
|
763 |
+
normalization = fold(weighting).view(1, 1, h * uf, w * uf) # normalizes the overlap
|
764 |
+
weighting = weighting.view((1, 1, kernel_size[0] * uf, kernel_size[1] * uf, Ly * Lx))
|
765 |
+
|
766 |
+
elif df > 1 and uf == 1:
|
767 |
+
fold_params = dict(kernel_size=kernel_size, dilation=1, padding=0, stride=stride)
|
768 |
+
unfold = torch.nn.Unfold(**fold_params)
|
769 |
+
|
770 |
+
fold_params2 = dict(kernel_size=(kernel_size[0] // df, kernel_size[0] // df),
|
771 |
+
dilation=1, padding=0,
|
772 |
+
stride=(stride[0] // df, stride[1] // df))
|
773 |
+
fold = torch.nn.Fold(output_size=(x.shape[2] // df, x.shape[3] // df), **fold_params2)
|
774 |
+
|
775 |
+
weighting = self.get_weighting(kernel_size[0] // df, kernel_size[1] // df, Ly, Lx, x.device).to(x.dtype)
|
776 |
+
normalization = fold(weighting).view(1, 1, h // df, w // df) # normalizes the overlap
|
777 |
+
weighting = weighting.view((1, 1, kernel_size[0] // df, kernel_size[1] // df, Ly * Lx))
|
778 |
+
|
779 |
+
else:
|
780 |
+
raise NotImplementedError
|
781 |
+
|
782 |
+
return fold, unfold, normalization, weighting
|
783 |
+
|
784 |
+
@torch.no_grad()
|
785 |
+
def get_input(self, batch, k, return_first_stage_outputs=False, force_c_encode=False,
|
786 |
+
cond_key=None, return_original_cond=False, bs=None, return_x=False):
|
787 |
+
x = super().get_input(batch, k)
|
788 |
+
self.device = x.device
|
789 |
+
if bs is not None:
|
790 |
+
x = x[:bs]
|
791 |
+
x = x.to(self.device)
|
792 |
+
# encoder_posterior = self.encode_first_stage(x)
|
793 |
+
# z = self.get_first_stage_encoding(encoder_posterior).detach()
|
794 |
+
z = x
|
795 |
+
|
796 |
+
if self.model.conditioning_key is not None and not self.force_null_conditioning:
|
797 |
+
if cond_key is None:
|
798 |
+
cond_key = self.cond_stage_key
|
799 |
+
if cond_key != self.first_stage_key:
|
800 |
+
if cond_key in ['caption', 'coordinates_bbox', "txt"]:
|
801 |
+
xc = batch[cond_key]
|
802 |
+
elif cond_key in ['class_label', 'cls']:
|
803 |
+
xc = batch
|
804 |
+
else:
|
805 |
+
xc = super().get_input(batch, cond_key).to(self.device)
|
806 |
+
else:
|
807 |
+
xc = x
|
808 |
+
if not self.cond_stage_trainable or force_c_encode:
|
809 |
+
if isinstance(xc, dict) or isinstance(xc, list):
|
810 |
+
c = self.get_learned_conditioning(xc)
|
811 |
+
else:
|
812 |
+
c = self.get_learned_conditioning(xc.to(self.device))
|
813 |
+
else:
|
814 |
+
c = xc
|
815 |
+
if bs is not None:
|
816 |
+
c = c[:bs]
|
817 |
+
|
818 |
+
if self.use_positional_encodings:
|
819 |
+
pos_x, pos_y = self.compute_latent_shifts(batch)
|
820 |
+
ckey = __conditioning_keys__[self.model.conditioning_key]
|
821 |
+
c = {ckey: c, 'pos_x': pos_x, 'pos_y': pos_y}
|
822 |
+
|
823 |
+
else:
|
824 |
+
c = None
|
825 |
+
xc = None
|
826 |
+
if self.use_positional_encodings:
|
827 |
+
pos_x, pos_y = self.compute_latent_shifts(batch)
|
828 |
+
c = {'pos_x': pos_x, 'pos_y': pos_y}
|
829 |
+
out = [z, c]
|
830 |
+
if return_first_stage_outputs:
|
831 |
+
xrec = self.decode_first_stage(z)
|
832 |
+
out.extend([x, xrec])
|
833 |
+
if return_x:
|
834 |
+
out.extend([x])
|
835 |
+
if return_original_cond:
|
836 |
+
out.append(xc)
|
837 |
+
return out
|
838 |
+
|
839 |
+
@torch.no_grad()
|
840 |
+
def decode_first_stage(self, z, predict_cids=False, force_not_quantize=False):
|
841 |
+
if predict_cids:
|
842 |
+
if z.dim() == 4:
|
843 |
+
z = torch.argmax(z.exp(), dim=1).long()
|
844 |
+
z = self.first_stage_model.quantize.get_codebook_entry(z, shape=None)
|
845 |
+
z = rearrange(z, 'b h w c -> b c h w').contiguous()
|
846 |
+
|
847 |
+
z = 1. / self.scale_factor * z
|
848 |
+
return self.first_stage_model.decode(z)
|
849 |
+
|
850 |
+
@torch.no_grad()
|
851 |
+
def encode_first_stage(self, x):
|
852 |
+
return self.first_stage_model.encode(x)
|
853 |
+
|
854 |
+
def shared_step(self, batch, **kwargs):
|
855 |
+
x, c = self.get_input(batch, self.first_stage_key)
|
856 |
+
loss = self(x, c)
|
857 |
+
return loss
|
858 |
+
def random_mask_batch_torch(self, cross, cat, mask_probability=0.1):
|
859 |
+
unconditioned_batches = torch.rand((cross.shape[0], 1, 1),
|
860 |
+
device=cross.device) < mask_probability
|
861 |
+
# cross = torch.where(unconditioned_batches, self.unconditioned_embedding.repeat(cross.shape[0], 1, cross.shape[-1]), cross)
|
862 |
+
cat = torch.where(unconditioned_batches, self.unconditioned_cat_embedding.repeat(cat.shape[0], 1, cat.shape[-1]), cat)
|
863 |
+
return cross, cat
|
864 |
+
def forward(self, x, c, *args, **kwargs):
|
865 |
+
t = torch.randint(0, self.num_timesteps, (x.shape[0],), device=self.device).long()
|
866 |
+
#classifier-free guidance
|
867 |
+
# c['c_crossattn'][0], c['c_concat'][0] = self.random_mask_batch_torch(c['c_crossattn'][0], c['c_concat'][0])
|
868 |
+
if self.model.conditioning_key is not None:
|
869 |
+
assert c is not None
|
870 |
+
if self.cond_stage_trainable:
|
871 |
+
c['c_refer'] = c['c_crossattn']
|
872 |
+
# c['c_crossattn'] = [self.get_learned_conditioning(c['c_crossattn'][0])]
|
873 |
+
c['c_crossattn'] = c['c_crossattn']
|
874 |
+
if self.shorten_cond_schedule: # TODO: drop this option
|
875 |
+
tc = self.cond_ids[t].to(self.device)
|
876 |
+
c = self.q_sample(x_start=c, t=tc, noise=torch.randn_like(c.float()))
|
877 |
+
return self.p_losses(x, c, t, *args, **kwargs)
|
878 |
+
|
879 |
+
def apply_model(self, x_noisy, t, cond, return_ids=False):
|
880 |
+
if isinstance(cond, dict):
|
881 |
+
# hybrid case, cond is expected to be a dict
|
882 |
+
pass
|
883 |
+
else:
|
884 |
+
if not isinstance(cond, list):
|
885 |
+
cond = [cond]
|
886 |
+
key = 'c_concat' if self.model.conditioning_key == 'concat' else 'c_crossattn'
|
887 |
+
cond = {key: cond}
|
888 |
+
|
889 |
+
x_recon = self.model(x_noisy, t, **cond)
|
890 |
+
|
891 |
+
if isinstance(x_recon, tuple) and not return_ids:
|
892 |
+
return x_recon[0]
|
893 |
+
else:
|
894 |
+
return x_recon
|
895 |
+
|
896 |
+
def _predict_eps_from_xstart(self, x_t, t, pred_xstart):
|
897 |
+
return (extract_into_tensor(self.sqrt_recip_alphas_cumprod, t, x_t.shape) * x_t - pred_xstart) / \
|
898 |
+
extract_into_tensor(self.sqrt_recipm1_alphas_cumprod, t, x_t.shape)
|
899 |
+
|
900 |
+
def _prior_bpd(self, x_start):
|
901 |
+
"""
|
902 |
+
Get the prior KL term for the variational lower-bound, measured in
|
903 |
+
bits-per-dim.
|
904 |
+
This term can't be optimized, as it only depends on the encoder.
|
905 |
+
:param x_start: the [N x C x ...] tensor of inputs.
|
906 |
+
:return: a batch of [N] KL values (in bits), one per batch element.
|
907 |
+
"""
|
908 |
+
batch_size = x_start.shape[0]
|
909 |
+
t = torch.tensor([self.num_timesteps - 1] * batch_size, device=x_start.device)
|
910 |
+
qt_mean, _, qt_log_variance = self.q_mean_variance(x_start, t)
|
911 |
+
kl_prior = normal_kl(mean1=qt_mean, logvar1=qt_log_variance, mean2=0.0, logvar2=0.0)
|
912 |
+
return mean_flat(kl_prior) / np.log(2.0)
|
913 |
+
|
914 |
+
def p_losses(self, x_start, cond, t, noise=None):
|
915 |
+
noise = default(noise, lambda: torch.randn_like(x_start))
|
916 |
+
x_noisy = self.q_sample(x_start=x_start, t=t, noise=noise)
|
917 |
+
model_output = self.apply_model(x_noisy, t, cond)
|
918 |
+
|
919 |
+
loss_dict = {}
|
920 |
+
prefix = 'train' if self.training else 'val'
|
921 |
+
|
922 |
+
if self.parameterization == "x0":
|
923 |
+
target = x_start
|
924 |
+
elif self.parameterization == "eps":
|
925 |
+
target = noise
|
926 |
+
elif self.parameterization == "v":
|
927 |
+
target = self.get_v(x_start, noise, t)
|
928 |
+
else:
|
929 |
+
raise NotImplementedError()
|
930 |
+
|
931 |
+
loss_simple = self.get_loss(model_output, target, mean=False).mean([1, 2])
|
932 |
+
loss_dict.update({f'{prefix}/loss_simple': loss_simple.mean()})
|
933 |
+
|
934 |
+
logvar_t = self.logvar[t].to(self.device)
|
935 |
+
loss = loss_simple / torch.exp(logvar_t) + logvar_t
|
936 |
+
# loss = loss_simple / torch.exp(self.logvar) + self.logvar
|
937 |
+
if self.learn_logvar:
|
938 |
+
loss_dict.update({f'{prefix}/loss_gamma': loss.mean()})
|
939 |
+
loss_dict.update({'logvar': self.logvar.data.mean()})
|
940 |
+
|
941 |
+
loss = self.l_simple_weight * loss.mean()
|
942 |
+
|
943 |
+
loss_vlb = self.get_loss(model_output, target, mean=False).mean(dim=(1, 2))
|
944 |
+
loss_vlb = (self.lvlb_weights[t] * loss_vlb).mean()
|
945 |
+
loss_dict.update({f'{prefix}/loss_vlb': loss_vlb})
|
946 |
+
loss += (self.original_elbo_weight * loss_vlb)
|
947 |
+
loss_dict.update({f'{prefix}/loss': loss})
|
948 |
+
|
949 |
+
return loss, loss_dict
|
950 |
+
|
951 |
+
def p_mean_variance(self, x, c, t, clip_denoised: bool, return_codebook_ids=False, quantize_denoised=False,
|
952 |
+
return_x0=False, score_corrector=None, corrector_kwargs=None):
|
953 |
+
t_in = t
|
954 |
+
model_out = self.apply_model(x, t_in, c, return_ids=return_codebook_ids)
|
955 |
+
|
956 |
+
if score_corrector is not None:
|
957 |
+
assert self.parameterization == "eps"
|
958 |
+
model_out = score_corrector.modify_score(self, model_out, x, t, c, **corrector_kwargs)
|
959 |
+
|
960 |
+
if return_codebook_ids:
|
961 |
+
model_out, logits = model_out
|
962 |
+
|
963 |
+
if self.parameterization == "eps":
|
964 |
+
x_recon = self.predict_start_from_noise(x, t=t, noise=model_out)
|
965 |
+
elif self.parameterization == "x0":
|
966 |
+
x_recon = model_out
|
967 |
+
else:
|
968 |
+
raise NotImplementedError()
|
969 |
+
|
970 |
+
if clip_denoised:
|
971 |
+
x_recon.clamp_(-1., 1.)
|
972 |
+
if quantize_denoised:
|
973 |
+
x_recon, _, [_, _, indices] = self.first_stage_model.quantize(x_recon)
|
974 |
+
model_mean, posterior_variance, posterior_log_variance = self.q_posterior(x_start=x_recon, x_t=x, t=t)
|
975 |
+
if return_codebook_ids:
|
976 |
+
return model_mean, posterior_variance, posterior_log_variance, logits
|
977 |
+
elif return_x0:
|
978 |
+
return model_mean, posterior_variance, posterior_log_variance, x_recon
|
979 |
+
else:
|
980 |
+
return model_mean, posterior_variance, posterior_log_variance
|
981 |
+
|
982 |
+
@torch.no_grad()
|
983 |
+
def p_sample(self, x, c, t, clip_denoised=False, repeat_noise=False,
|
984 |
+
return_codebook_ids=False, quantize_denoised=False, return_x0=False,
|
985 |
+
temperature=1., noise_dropout=0., score_corrector=None, corrector_kwargs=None):
|
986 |
+
b, *_, device = *x.shape, x.device
|
987 |
+
outputs = self.p_mean_variance(x=x, c=c, t=t, clip_denoised=clip_denoised,
|
988 |
+
return_codebook_ids=return_codebook_ids,
|
989 |
+
quantize_denoised=quantize_denoised,
|
990 |
+
return_x0=return_x0,
|
991 |
+
score_corrector=score_corrector, corrector_kwargs=corrector_kwargs)
|
992 |
+
if return_codebook_ids:
|
993 |
+
raise DeprecationWarning("Support dropped.")
|
994 |
+
model_mean, _, model_log_variance, logits = outputs
|
995 |
+
elif return_x0:
|
996 |
+
model_mean, _, model_log_variance, x0 = outputs
|
997 |
+
else:
|
998 |
+
model_mean, _, model_log_variance = outputs
|
999 |
+
|
1000 |
+
noise = noise_like(x.shape, device, repeat_noise) * temperature
|
1001 |
+
if noise_dropout > 0.:
|
1002 |
+
noise = torch.nn.functional.dropout(noise, p=noise_dropout)
|
1003 |
+
# no noise when t == 0
|
1004 |
+
nonzero_mask = (1 - (t == 0).float()).reshape(b, *((1,) * (len(x.shape) - 1)))
|
1005 |
+
|
1006 |
+
if return_codebook_ids:
|
1007 |
+
raise DeprecationWarning("Support dropped.")
|
1008 |
+
return model_mean + nonzero_mask * (0.5 * model_log_variance).exp() * noise, logits.argmax(dim=1)
|
1009 |
+
if return_x0:
|
1010 |
+
return model_mean + nonzero_mask * (0.5 * model_log_variance).exp() * noise, x0
|
1011 |
+
else:
|
1012 |
+
return model_mean + nonzero_mask * (0.5 * model_log_variance).exp() * noise
|
1013 |
+
|
1014 |
+
@torch.no_grad()
|
1015 |
+
def progressive_denoising(self, cond, shape, verbose=True, callback=None, quantize_denoised=False,
|
1016 |
+
img_callback=None, mask=None, x0=None, temperature=1., noise_dropout=0.,
|
1017 |
+
score_corrector=None, corrector_kwargs=None, batch_size=None, x_T=None, start_T=None,
|
1018 |
+
log_every_t=None):
|
1019 |
+
if not log_every_t:
|
1020 |
+
log_every_t = self.log_every_t
|
1021 |
+
timesteps = self.num_timesteps
|
1022 |
+
if batch_size is not None:
|
1023 |
+
b = batch_size if batch_size is not None else shape[0]
|
1024 |
+
shape = [batch_size] + list(shape)
|
1025 |
+
else:
|
1026 |
+
b = batch_size = shape[0]
|
1027 |
+
if x_T is None:
|
1028 |
+
img = torch.randn(shape, device=self.device)
|
1029 |
+
else:
|
1030 |
+
img = x_T
|
1031 |
+
intermediates = []
|
1032 |
+
if cond is not None:
|
1033 |
+
if isinstance(cond, dict):
|
1034 |
+
cond = {key: cond[key][:batch_size] if not isinstance(cond[key], list) else
|
1035 |
+
list(map(lambda x: x[:batch_size], cond[key])) for key in cond}
|
1036 |
+
else:
|
1037 |
+
cond = [c[:batch_size] for c in cond] if isinstance(cond, list) else cond[:batch_size]
|
1038 |
+
|
1039 |
+
if start_T is not None:
|
1040 |
+
timesteps = min(timesteps, start_T)
|
1041 |
+
iterator = tqdm(reversed(range(0, timesteps)), desc='Progressive Generation',
|
1042 |
+
total=timesteps) if verbose else reversed(
|
1043 |
+
range(0, timesteps))
|
1044 |
+
if type(temperature) == float:
|
1045 |
+
temperature = [temperature] * timesteps
|
1046 |
+
|
1047 |
+
for i in iterator:
|
1048 |
+
ts = torch.full((b,), i, device=self.device, dtype=torch.long)
|
1049 |
+
if self.shorten_cond_schedule:
|
1050 |
+
assert self.model.conditioning_key != 'hybrid'
|
1051 |
+
tc = self.cond_ids[ts].to(cond.device)
|
1052 |
+
cond = self.q_sample(x_start=cond, t=tc, noise=torch.randn_like(cond))
|
1053 |
+
|
1054 |
+
img, x0_partial = self.p_sample(img, cond, ts,
|
1055 |
+
clip_denoised=self.clip_denoised,
|
1056 |
+
quantize_denoised=quantize_denoised, return_x0=True,
|
1057 |
+
temperature=temperature[i], noise_dropout=noise_dropout,
|
1058 |
+
score_corrector=score_corrector, corrector_kwargs=corrector_kwargs)
|
1059 |
+
if mask is not None:
|
1060 |
+
assert x0 is not None
|
1061 |
+
img_orig = self.q_sample(x0, ts)
|
1062 |
+
img = img_orig * mask + (1. - mask) * img
|
1063 |
+
|
1064 |
+
if i % log_every_t == 0 or i == timesteps - 1:
|
1065 |
+
intermediates.append(x0_partial)
|
1066 |
+
if callback: callback(i)
|
1067 |
+
if img_callback: img_callback(img, i)
|
1068 |
+
return img, intermediates
|
1069 |
+
|
1070 |
+
@torch.no_grad()
|
1071 |
+
def p_sample_loop(self, cond, shape, return_intermediates=False,
|
1072 |
+
x_T=None, verbose=True, callback=None, timesteps=None, quantize_denoised=False,
|
1073 |
+
mask=None, x0=None, img_callback=None, start_T=None,
|
1074 |
+
log_every_t=None):
|
1075 |
+
|
1076 |
+
if not log_every_t:
|
1077 |
+
log_every_t = self.log_every_t
|
1078 |
+
device = self.betas.device
|
1079 |
+
b = shape[0]
|
1080 |
+
if x_T is None:
|
1081 |
+
img = torch.randn(shape, device=device)
|
1082 |
+
else:
|
1083 |
+
img = x_T
|
1084 |
+
|
1085 |
+
intermediates = [img]
|
1086 |
+
if timesteps is None:
|
1087 |
+
timesteps = self.num_timesteps
|
1088 |
+
|
1089 |
+
if start_T is not None:
|
1090 |
+
timesteps = min(timesteps, start_T)
|
1091 |
+
iterator = tqdm(reversed(range(0, timesteps)), desc='Sampling t', total=timesteps) if verbose else reversed(
|
1092 |
+
range(0, timesteps))
|
1093 |
+
|
1094 |
+
if mask is not None:
|
1095 |
+
assert x0 is not None
|
1096 |
+
assert x0.shape[2:3] == mask.shape[2:3] # spatial size has to match
|
1097 |
+
|
1098 |
+
for i in iterator:
|
1099 |
+
ts = torch.full((b,), i, device=device, dtype=torch.long)
|
1100 |
+
if self.shorten_cond_schedule:
|
1101 |
+
assert self.model.conditioning_key != 'hybrid'
|
1102 |
+
tc = self.cond_ids[ts].to(cond.device)
|
1103 |
+
cond = self.q_sample(x_start=cond, t=tc, noise=torch.randn_like(cond))
|
1104 |
+
|
1105 |
+
img = self.p_sample(img, cond, ts,
|
1106 |
+
clip_denoised=self.clip_denoised,
|
1107 |
+
quantize_denoised=quantize_denoised)
|
1108 |
+
if mask is not None:
|
1109 |
+
img_orig = self.q_sample(x0, ts)
|
1110 |
+
img = img_orig * mask + (1. - mask) * img
|
1111 |
+
|
1112 |
+
if i % log_every_t == 0 or i == timesteps - 1:
|
1113 |
+
intermediates.append(img)
|
1114 |
+
if callback: callback(i)
|
1115 |
+
if img_callback: img_callback(img, i)
|
1116 |
+
|
1117 |
+
if return_intermediates:
|
1118 |
+
return img, intermediates
|
1119 |
+
return img
|
1120 |
+
|
1121 |
+
@torch.no_grad()
|
1122 |
+
def sample(self, cond, batch_size=16, return_intermediates=False, x_T=None,
|
1123 |
+
verbose=True, timesteps=None, quantize_denoised=False,
|
1124 |
+
mask=None, x0=None, shape=None, **kwargs):
|
1125 |
+
if shape is None:
|
1126 |
+
shape = (batch_size, self.channels, self.image_size, self.image_size)
|
1127 |
+
if cond is not None:
|
1128 |
+
if isinstance(cond, dict):
|
1129 |
+
cond = {key: cond[key][:batch_size] if not isinstance(cond[key], list) else
|
1130 |
+
list(map(lambda x: x[:batch_size], cond[key])) for key in cond}
|
1131 |
+
else:
|
1132 |
+
cond = [c[:batch_size] for c in cond] if isinstance(cond, list) else cond[:batch_size]
|
1133 |
+
return self.p_sample_loop(cond,
|
1134 |
+
shape,
|
1135 |
+
return_intermediates=return_intermediates, x_T=x_T,
|
1136 |
+
verbose=verbose, timesteps=timesteps, quantize_denoised=quantize_denoised,
|
1137 |
+
mask=mask, x0=x0)
|
1138 |
+
|
1139 |
+
@torch.no_grad()
|
1140 |
+
def sample_log(self, cond, batch_size, ddim, ddim_steps, **kwargs):
|
1141 |
+
if ddim:
|
1142 |
+
ddim_sampler = DDIMSampler(self)
|
1143 |
+
shape = (self.channels, self.image_size, self.image_size)
|
1144 |
+
samples, intermediates = ddim_sampler.sample(ddim_steps, batch_size,
|
1145 |
+
shape, cond, verbose=False, **kwargs)
|
1146 |
+
|
1147 |
+
else:
|
1148 |
+
samples, intermediates = self.sample(cond=cond, batch_size=batch_size,
|
1149 |
+
return_intermediates=True, **kwargs)
|
1150 |
+
|
1151 |
+
return samples, intermediates
|
1152 |
+
|
1153 |
+
@torch.no_grad()
|
1154 |
+
def get_unconditional_conditioning(self, batch_size, null_label=None):
|
1155 |
+
if null_label is not None:
|
1156 |
+
xc = null_label
|
1157 |
+
if isinstance(xc, ListConfig):
|
1158 |
+
xc = list(xc)
|
1159 |
+
if isinstance(xc, dict) or isinstance(xc, list):
|
1160 |
+
c = self.get_learned_conditioning(xc)
|
1161 |
+
else:
|
1162 |
+
if hasattr(xc, "to"):
|
1163 |
+
xc = xc.to(self.device)
|
1164 |
+
c = self.get_learned_conditioning(xc)
|
1165 |
+
else:
|
1166 |
+
if self.cond_stage_key in ["class_label", "cls"]:
|
1167 |
+
xc = self.cond_stage_model.get_unconditional_conditioning(batch_size, device=self.device)
|
1168 |
+
return self.get_learned_conditioning(xc)
|
1169 |
+
else:
|
1170 |
+
raise NotImplementedError("todo")
|
1171 |
+
if isinstance(c, list): # in case the encoder gives us a list
|
1172 |
+
for i in range(len(c)):
|
1173 |
+
c[i] = repeat(c[i], '1 ... -> b ...', b=batch_size).to(self.device)
|
1174 |
+
else:
|
1175 |
+
c = repeat(c, '1 ... -> b ...', b=batch_size).to(self.device)
|
1176 |
+
return c
|
1177 |
+
|
1178 |
+
@torch.no_grad()
|
1179 |
+
def log_images(self, batch, N=8, n_row=4, sample=True, ddim_steps=50, ddim_eta=0., return_keys=None,
|
1180 |
+
quantize_denoised=True, inpaint=True, plot_denoise_rows=False, plot_progressive_rows=True,
|
1181 |
+
plot_diffusion_rows=True, unconditional_guidance_scale=1., unconditional_guidance_label=None,
|
1182 |
+
use_ema_scope=True,
|
1183 |
+
**kwargs):
|
1184 |
+
ema_scope = self.ema_scope if use_ema_scope else nullcontext
|
1185 |
+
use_ddim = ddim_steps is not None
|
1186 |
+
|
1187 |
+
log = dict()
|
1188 |
+
z, c, x, xrec, xc = self.get_input(batch, self.first_stage_key,
|
1189 |
+
return_first_stage_outputs=True,
|
1190 |
+
force_c_encode=True,
|
1191 |
+
return_original_cond=True,
|
1192 |
+
bs=N)
|
1193 |
+
N = min(x.shape[0], N)
|
1194 |
+
n_row = min(x.shape[0], n_row)
|
1195 |
+
log["inputs"] = x
|
1196 |
+
log["reconstruction"] = xrec
|
1197 |
+
if self.model.conditioning_key is not None:
|
1198 |
+
if hasattr(self.cond_stage_model, "decode"):
|
1199 |
+
xc = self.cond_stage_model.decode(c)
|
1200 |
+
log["conditioning"] = xc
|
1201 |
+
elif self.cond_stage_key in ["caption", "txt"]:
|
1202 |
+
xc = log_txt_as_img((x.shape[2], x.shape[3]), batch[self.cond_stage_key], size=x.shape[2] // 25)
|
1203 |
+
log["conditioning"] = xc
|
1204 |
+
elif self.cond_stage_key in ['class_label', "cls"]:
|
1205 |
+
try:
|
1206 |
+
xc = log_txt_as_img((x.shape[2], x.shape[3]), batch["human_label"], size=x.shape[2] // 25)
|
1207 |
+
log['conditioning'] = xc
|
1208 |
+
except KeyError:
|
1209 |
+
# probably no "human_label" in batch
|
1210 |
+
pass
|
1211 |
+
elif isimage(xc):
|
1212 |
+
log["conditioning"] = xc
|
1213 |
+
if ismap(xc):
|
1214 |
+
log["original_conditioning"] = self.to_rgb(xc)
|
1215 |
+
|
1216 |
+
if plot_diffusion_rows:
|
1217 |
+
# get diffusion row
|
1218 |
+
diffusion_row = list()
|
1219 |
+
z_start = z[:n_row]
|
1220 |
+
for t in range(self.num_timesteps):
|
1221 |
+
if t % self.log_every_t == 0 or t == self.num_timesteps - 1:
|
1222 |
+
t = repeat(torch.tensor([t]), '1 -> b', b=n_row)
|
1223 |
+
t = t.to(self.device).long()
|
1224 |
+
noise = torch.randn_like(z_start)
|
1225 |
+
z_noisy = self.q_sample(x_start=z_start, t=t, noise=noise)
|
1226 |
+
diffusion_row.append(self.decode_first_stage(z_noisy))
|
1227 |
+
|
1228 |
+
diffusion_row = torch.stack(diffusion_row) # n_log_step, n_row, C, H, W
|
1229 |
+
diffusion_grid = rearrange(diffusion_row, 'n b c h w -> b n c h w')
|
1230 |
+
diffusion_grid = rearrange(diffusion_grid, 'b n c h w -> (b n) c h w')
|
1231 |
+
diffusion_grid = make_grid(diffusion_grid, nrow=diffusion_row.shape[0])
|
1232 |
+
log["diffusion_row"] = diffusion_grid
|
1233 |
+
|
1234 |
+
if sample:
|
1235 |
+
# get denoise row
|
1236 |
+
with ema_scope("Sampling"):
|
1237 |
+
samples, z_denoise_row = self.sample_log(cond=c, batch_size=N, ddim=use_ddim,
|
1238 |
+
ddim_steps=ddim_steps, eta=ddim_eta)
|
1239 |
+
# samples, z_denoise_row = self.sample(cond=c, batch_size=N, return_intermediates=True)
|
1240 |
+
x_samples = self.decode_first_stage(samples)
|
1241 |
+
log["samples"] = x_samples
|
1242 |
+
if plot_denoise_rows:
|
1243 |
+
denoise_grid = self._get_denoise_row_from_list(z_denoise_row)
|
1244 |
+
log["denoise_row"] = denoise_grid
|
1245 |
+
|
1246 |
+
# if quantize_denoised and not isinstance(self.first_stage_model, AutoencoderKL) and not isinstance(
|
1247 |
+
# self.first_stage_model, IdentityFirstStage):
|
1248 |
+
# # also display when quantizing x0 while sampling
|
1249 |
+
# with ema_scope("Plotting Quantized Denoised"):
|
1250 |
+
# samples, z_denoise_row = self.sample_log(cond=c, batch_size=N, ddim=use_ddim,
|
1251 |
+
# ddim_steps=ddim_steps, eta=ddim_eta,
|
1252 |
+
# quantize_denoised=True)
|
1253 |
+
# # samples, z_denoise_row = self.sample(cond=c, batch_size=N, return_intermediates=True,
|
1254 |
+
# # quantize_denoised=True)
|
1255 |
+
# x_samples = self.decode_first_stage(samples.to(self.device))
|
1256 |
+
# log["samples_x0_quantized"] = x_samples
|
1257 |
+
|
1258 |
+
if unconditional_guidance_scale > 1.0:
|
1259 |
+
uc = self.get_unconditional_conditioning(N, unconditional_guidance_label)
|
1260 |
+
if self.model.conditioning_key == "crossattn-adm":
|
1261 |
+
uc = {"c_crossattn": [uc], "c_adm": c["c_adm"]}
|
1262 |
+
with ema_scope("Sampling with classifier-free guidance"):
|
1263 |
+
samples_cfg, _ = self.sample_log(cond=c, batch_size=N, ddim=use_ddim,
|
1264 |
+
ddim_steps=ddim_steps, eta=ddim_eta,
|
1265 |
+
unconditional_guidance_scale=unconditional_guidance_scale,
|
1266 |
+
unconditional_conditioning=uc,
|
1267 |
+
)
|
1268 |
+
x_samples_cfg = self.decode_first_stage(samples_cfg)
|
1269 |
+
log[f"samples_cfg_scale_{unconditional_guidance_scale:.2f}"] = x_samples_cfg
|
1270 |
+
|
1271 |
+
if inpaint:
|
1272 |
+
# make a simple center square
|
1273 |
+
b, h, w = z.shape[0], z.shape[2], z.shape[3]
|
1274 |
+
mask = torch.ones(N, h, w).to(self.device)
|
1275 |
+
# zeros will be filled in
|
1276 |
+
mask[:, h // 4:3 * h // 4, w // 4:3 * w // 4] = 0.
|
1277 |
+
mask = mask[:, None, ...]
|
1278 |
+
with ema_scope("Plotting Inpaint"):
|
1279 |
+
samples, _ = self.sample_log(cond=c, batch_size=N, ddim=use_ddim, eta=ddim_eta,
|
1280 |
+
ddim_steps=ddim_steps, x0=z[:N], mask=mask)
|
1281 |
+
x_samples = self.decode_first_stage(samples.to(self.device))
|
1282 |
+
log["samples_inpainting"] = x_samples
|
1283 |
+
log["mask"] = mask
|
1284 |
+
|
1285 |
+
# outpaint
|
1286 |
+
mask = 1. - mask
|
1287 |
+
with ema_scope("Plotting Outpaint"):
|
1288 |
+
samples, _ = self.sample_log(cond=c, batch_size=N, ddim=use_ddim, eta=ddim_eta,
|
1289 |
+
ddim_steps=ddim_steps, x0=z[:N], mask=mask)
|
1290 |
+
x_samples = self.decode_first_stage(samples.to(self.device))
|
1291 |
+
log["samples_outpainting"] = x_samples
|
1292 |
+
|
1293 |
+
if plot_progressive_rows:
|
1294 |
+
with ema_scope("Plotting Progressives"):
|
1295 |
+
img, progressives = self.progressive_denoising(c,
|
1296 |
+
shape=(self.channels, self.image_size, self.image_size),
|
1297 |
+
batch_size=N)
|
1298 |
+
prog_row = self._get_denoise_row_from_list(progressives, desc="Progressive Generation")
|
1299 |
+
log["progressive_row"] = prog_row
|
1300 |
+
|
1301 |
+
if return_keys:
|
1302 |
+
if np.intersect1d(list(log.keys()), return_keys).shape[0] == 0:
|
1303 |
+
return log
|
1304 |
+
else:
|
1305 |
+
return {key: log[key] for key in return_keys}
|
1306 |
+
return log
|
1307 |
+
|
1308 |
+
def configure_optimizers(self):
|
1309 |
+
lr = self.learning_rate
|
1310 |
+
params = list(self.model.parameters())
|
1311 |
+
if self.cond_stage_trainable:
|
1312 |
+
print(f"{self.__class__.__name__}: Also optimizing conditioner params!")
|
1313 |
+
params = params + list(self.cond_stage_model.parameters())
|
1314 |
+
if self.learn_logvar:
|
1315 |
+
print('Diffusion model optimizing logvar')
|
1316 |
+
params.append(self.logvar)
|
1317 |
+
opt = torch.optim.AdamW(params, lr=lr)
|
1318 |
+
if self.use_scheduler:
|
1319 |
+
assert 'target' in self.scheduler_config
|
1320 |
+
scheduler = instantiate_from_config(self.scheduler_config)
|
1321 |
+
|
1322 |
+
print("Setting up LambdaLR scheduler...")
|
1323 |
+
scheduler = [
|
1324 |
+
{
|
1325 |
+
'scheduler': LambdaLR(opt, lr_lambda=scheduler.schedule),
|
1326 |
+
'interval': 'step',
|
1327 |
+
'frequency': 1
|
1328 |
+
}]
|
1329 |
+
return [opt], scheduler
|
1330 |
+
return opt
|
1331 |
+
|
1332 |
+
@torch.no_grad()
|
1333 |
+
def to_rgb(self, x):
|
1334 |
+
x = x.float()
|
1335 |
+
if not hasattr(self, "colorize"):
|
1336 |
+
self.colorize = torch.randn(3, x.shape[1], 1, 1).to(x)
|
1337 |
+
x = nn.functional.conv2d(x, weight=self.colorize)
|
1338 |
+
x = 2. * (x - x.min()) / (x.max() - x.min()) - 1.
|
1339 |
+
return x
|
1340 |
+
|
1341 |
+
|
1342 |
+
class DiffusionWrapper(nn.Module):
|
1343 |
+
def __init__(self, diff_model_config, conditioning_key):
|
1344 |
+
super().__init__()
|
1345 |
+
self.sequential_cross_attn = diff_model_config.pop("sequential_crossattn", False)
|
1346 |
+
self.diffusion_model = instantiate_from_config(diff_model_config)
|
1347 |
+
self.conditioning_key = conditioning_key
|
1348 |
+
assert self.conditioning_key in [None, 'concat', 'crossattn', 'hybrid', 'adm', 'hybrid-adm', 'crossattn-adm']
|
1349 |
+
|
1350 |
+
def forward(self, x, t, c_concat: list = None, c_crossattn: list = None, c_adm=None):
|
1351 |
+
if self.conditioning_key is None:
|
1352 |
+
out = self.diffusion_model(x, t)
|
1353 |
+
elif self.conditioning_key == 'concat':
|
1354 |
+
xc = torch.cat([x] + c_concat, dim=1)
|
1355 |
+
out = self.diffusion_model(xc, t)
|
1356 |
+
elif self.conditioning_key == 'crossattn':
|
1357 |
+
if not self.sequential_cross_attn:
|
1358 |
+
cc = torch.cat(c_crossattn, 1)
|
1359 |
+
else:
|
1360 |
+
cc = c_crossattn
|
1361 |
+
out = self.diffusion_model(x, t, context=cc)
|
1362 |
+
elif self.conditioning_key == 'hybrid':
|
1363 |
+
xc = torch.cat([x] + c_concat, dim=1)
|
1364 |
+
cc = torch.cat(c_crossattn, 1)
|
1365 |
+
out = self.diffusion_model(xc, t, context=cc)
|
1366 |
+
elif self.conditioning_key == 'hybrid-adm':
|
1367 |
+
assert c_adm is not None
|
1368 |
+
xc = torch.cat([x] + c_concat, dim=1)
|
1369 |
+
cc = torch.cat(c_crossattn, 1)
|
1370 |
+
out = self.diffusion_model(xc, t, context=cc, y=c_adm)
|
1371 |
+
elif self.conditioning_key == 'crossattn-adm':
|
1372 |
+
assert c_adm is not None
|
1373 |
+
cc = torch.cat(c_crossattn, 1)
|
1374 |
+
out = self.diffusion_model(x, t, context=cc, y=c_adm)
|
1375 |
+
elif self.conditioning_key == 'adm':
|
1376 |
+
cc = c_crossattn[0]
|
1377 |
+
out = self.diffusion_model(x, t, y=cc)
|
1378 |
+
else:
|
1379 |
+
raise NotImplementedError()
|
1380 |
+
|
1381 |
+
return out
|
1382 |
+
|
1383 |
+
|
1384 |
+
class LatentUpscaleDiffusion(LatentDiffusion):
|
1385 |
+
def __init__(self, *args, low_scale_config, low_scale_key="LR", noise_level_key=None, **kwargs):
|
1386 |
+
super().__init__(*args, **kwargs)
|
1387 |
+
# assumes that neither the cond_stage nor the low_scale_model contain trainable params
|
1388 |
+
assert not self.cond_stage_trainable
|
1389 |
+
self.instantiate_low_stage(low_scale_config)
|
1390 |
+
self.low_scale_key = low_scale_key
|
1391 |
+
self.noise_level_key = noise_level_key
|
1392 |
+
|
1393 |
+
def instantiate_low_stage(self, config):
|
1394 |
+
model = instantiate_from_config(config)
|
1395 |
+
self.low_scale_model = model.eval()
|
1396 |
+
self.low_scale_model.train = disabled_train
|
1397 |
+
for param in self.low_scale_model.parameters():
|
1398 |
+
param.requires_grad = False
|
1399 |
+
|
1400 |
+
@torch.no_grad()
|
1401 |
+
def get_input(self, batch, k, cond_key=None, bs=None, log_mode=False):
|
1402 |
+
if not log_mode:
|
1403 |
+
z, c = super().get_input(batch, k, force_c_encode=True, bs=bs)
|
1404 |
+
else:
|
1405 |
+
z, c, x, xrec, xc = super().get_input(batch, self.first_stage_key, return_first_stage_outputs=True,
|
1406 |
+
force_c_encode=True, return_original_cond=True, bs=bs)
|
1407 |
+
x_low = batch[self.low_scale_key][:bs]
|
1408 |
+
x_low = rearrange(x_low, 'b h w c -> b c h w')
|
1409 |
+
x_low = x_low.to(memory_format=torch.contiguous_format).float()
|
1410 |
+
zx, noise_level = self.low_scale_model(x_low)
|
1411 |
+
if self.noise_level_key is not None:
|
1412 |
+
# get noise level from batch instead, e.g. when extracting a custom noise level for bsr
|
1413 |
+
raise NotImplementedError('TODO')
|
1414 |
+
|
1415 |
+
all_conds = {"c_concat": [zx], "c_crossattn": [c], "c_adm": noise_level}
|
1416 |
+
if log_mode:
|
1417 |
+
# TODO: maybe disable if too expensive
|
1418 |
+
x_low_rec = self.low_scale_model.decode(zx)
|
1419 |
+
return z, all_conds, x, xrec, xc, x_low, x_low_rec, noise_level
|
1420 |
+
return z, all_conds
|
1421 |
+
|
1422 |
+
@torch.no_grad()
|
1423 |
+
def log_images(self, batch, N=8, n_row=4, sample=True, ddim_steps=200, ddim_eta=1., return_keys=None,
|
1424 |
+
plot_denoise_rows=False, plot_progressive_rows=True, plot_diffusion_rows=True,
|
1425 |
+
unconditional_guidance_scale=1., unconditional_guidance_label=None, use_ema_scope=True,
|
1426 |
+
**kwargs):
|
1427 |
+
ema_scope = self.ema_scope if use_ema_scope else nullcontext
|
1428 |
+
use_ddim = ddim_steps is not None
|
1429 |
+
|
1430 |
+
log = dict()
|
1431 |
+
z, c, x, xrec, xc, x_low, x_low_rec, noise_level = self.get_input(batch, self.first_stage_key, bs=N,
|
1432 |
+
log_mode=True)
|
1433 |
+
N = min(x.shape[0], N)
|
1434 |
+
n_row = min(x.shape[0], n_row)
|
1435 |
+
log["inputs"] = x
|
1436 |
+
log["reconstruction"] = xrec
|
1437 |
+
log["x_lr"] = x_low
|
1438 |
+
log[f"x_lr_rec_@noise_levels{'-'.join(map(lambda x: str(x), list(noise_level.cpu().numpy())))}"] = x_low_rec
|
1439 |
+
if self.model.conditioning_key is not None:
|
1440 |
+
if hasattr(self.cond_stage_model, "decode"):
|
1441 |
+
xc = self.cond_stage_model.decode(c)
|
1442 |
+
log["conditioning"] = xc
|
1443 |
+
elif self.cond_stage_key in ["caption", "txt"]:
|
1444 |
+
xc = log_txt_as_img((x.shape[2], x.shape[3]), batch[self.cond_stage_key], size=x.shape[2] // 25)
|
1445 |
+
log["conditioning"] = xc
|
1446 |
+
elif self.cond_stage_key in ['class_label', 'cls']:
|
1447 |
+
xc = log_txt_as_img((x.shape[2], x.shape[3]), batch["human_label"], size=x.shape[2] // 25)
|
1448 |
+
log['conditioning'] = xc
|
1449 |
+
elif isimage(xc):
|
1450 |
+
log["conditioning"] = xc
|
1451 |
+
if ismap(xc):
|
1452 |
+
log["original_conditioning"] = self.to_rgb(xc)
|
1453 |
+
|
1454 |
+
if plot_diffusion_rows:
|
1455 |
+
# get diffusion row
|
1456 |
+
diffusion_row = list()
|
1457 |
+
z_start = z[:n_row]
|
1458 |
+
for t in range(self.num_timesteps):
|
1459 |
+
if t % self.log_every_t == 0 or t == self.num_timesteps - 1:
|
1460 |
+
t = repeat(torch.tensor([t]), '1 -> b', b=n_row)
|
1461 |
+
t = t.to(self.device).long()
|
1462 |
+
noise = torch.randn_like(z_start)
|
1463 |
+
z_noisy = self.q_sample(x_start=z_start, t=t, noise=noise)
|
1464 |
+
diffusion_row.append(self.decode_first_stage(z_noisy))
|
1465 |
+
|
1466 |
+
diffusion_row = torch.stack(diffusion_row) # n_log_step, n_row, C, H, W
|
1467 |
+
diffusion_grid = rearrange(diffusion_row, 'n b c h w -> b n c h w')
|
1468 |
+
diffusion_grid = rearrange(diffusion_grid, 'b n c h w -> (b n) c h w')
|
1469 |
+
diffusion_grid = make_grid(diffusion_grid, nrow=diffusion_row.shape[0])
|
1470 |
+
log["diffusion_row"] = diffusion_grid
|
1471 |
+
|
1472 |
+
if sample:
|
1473 |
+
# get denoise row
|
1474 |
+
with ema_scope("Sampling"):
|
1475 |
+
samples, z_denoise_row = self.sample_log(cond=c, batch_size=N, ddim=use_ddim,
|
1476 |
+
ddim_steps=ddim_steps, eta=ddim_eta)
|
1477 |
+
# samples, z_denoise_row = self.sample(cond=c, batch_size=N, return_intermediates=True)
|
1478 |
+
x_samples = self.decode_first_stage(samples)
|
1479 |
+
log["samples"] = x_samples
|
1480 |
+
if plot_denoise_rows:
|
1481 |
+
denoise_grid = self._get_denoise_row_from_list(z_denoise_row)
|
1482 |
+
log["denoise_row"] = denoise_grid
|
1483 |
+
|
1484 |
+
if unconditional_guidance_scale > 1.0:
|
1485 |
+
uc_tmp = self.get_unconditional_conditioning(N, unconditional_guidance_label)
|
1486 |
+
# TODO explore better "unconditional" choices for the other keys
|
1487 |
+
# maybe guide away from empty text label and highest noise level and maximally degraded zx?
|
1488 |
+
uc = dict()
|
1489 |
+
for k in c:
|
1490 |
+
if k == "c_crossattn":
|
1491 |
+
assert isinstance(c[k], list) and len(c[k]) == 1
|
1492 |
+
uc[k] = [uc_tmp]
|
1493 |
+
elif k == "c_adm": # todo: only run with text-based guidance?
|
1494 |
+
assert isinstance(c[k], torch.Tensor)
|
1495 |
+
#uc[k] = torch.ones_like(c[k]) * self.low_scale_model.max_noise_level
|
1496 |
+
uc[k] = c[k]
|
1497 |
+
elif isinstance(c[k], list):
|
1498 |
+
uc[k] = [c[k][i] for i in range(len(c[k]))]
|
1499 |
+
else:
|
1500 |
+
uc[k] = c[k]
|
1501 |
+
|
1502 |
+
with ema_scope("Sampling with classifier-free guidance"):
|
1503 |
+
samples_cfg, _ = self.sample_log(cond=c, batch_size=N, ddim=use_ddim,
|
1504 |
+
ddim_steps=ddim_steps, eta=ddim_eta,
|
1505 |
+
unconditional_guidance_scale=unconditional_guidance_scale,
|
1506 |
+
unconditional_conditioning=uc,
|
1507 |
+
)
|
1508 |
+
x_samples_cfg = self.decode_first_stage(samples_cfg)
|
1509 |
+
log[f"samples_cfg_scale_{unconditional_guidance_scale:.2f}"] = x_samples_cfg
|
1510 |
+
|
1511 |
+
if plot_progressive_rows:
|
1512 |
+
with ema_scope("Plotting Progressives"):
|
1513 |
+
img, progressives = self.progressive_denoising(c,
|
1514 |
+
shape=(self.channels, self.image_size, self.image_size),
|
1515 |
+
batch_size=N)
|
1516 |
+
prog_row = self._get_denoise_row_from_list(progressives, desc="Progressive Generation")
|
1517 |
+
log["progressive_row"] = prog_row
|
1518 |
+
|
1519 |
+
return log
|
1520 |
+
|
1521 |
+
|
1522 |
+
class LatentFinetuneDiffusion(LatentDiffusion):
|
1523 |
+
"""
|
1524 |
+
Basis for different finetunas, such as inpainting or depth2image
|
1525 |
+
To disable finetuning mode, set finetune_keys to None
|
1526 |
+
"""
|
1527 |
+
|
1528 |
+
def __init__(self,
|
1529 |
+
concat_keys: tuple,
|
1530 |
+
finetune_keys=("model.diffusion_model.input_blocks.0.0.weight",
|
1531 |
+
"model_ema.diffusion_modelinput_blocks00weight"
|
1532 |
+
),
|
1533 |
+
keep_finetune_dims=4,
|
1534 |
+
# if model was trained without concat mode before and we would like to keep these channels
|
1535 |
+
c_concat_log_start=None, # to log reconstruction of c_concat codes
|
1536 |
+
c_concat_log_end=None,
|
1537 |
+
*args, **kwargs
|
1538 |
+
):
|
1539 |
+
ckpt_path = kwargs.pop("ckpt_path", None)
|
1540 |
+
ignore_keys = kwargs.pop("ignore_keys", list())
|
1541 |
+
super().__init__(*args, **kwargs)
|
1542 |
+
self.finetune_keys = finetune_keys
|
1543 |
+
self.concat_keys = concat_keys
|
1544 |
+
self.keep_dims = keep_finetune_dims
|
1545 |
+
self.c_concat_log_start = c_concat_log_start
|
1546 |
+
self.c_concat_log_end = c_concat_log_end
|
1547 |
+
if exists(self.finetune_keys): assert exists(ckpt_path), 'can only finetune from a given checkpoint'
|
1548 |
+
if exists(ckpt_path):
|
1549 |
+
self.init_from_ckpt(ckpt_path, ignore_keys)
|
1550 |
+
|
1551 |
+
def init_from_ckpt(self, path, ignore_keys=list(), only_model=False):
|
1552 |
+
sd = torch.load(path, map_location="cpu")
|
1553 |
+
if "state_dict" in list(sd.keys()):
|
1554 |
+
sd = sd["state_dict"]
|
1555 |
+
keys = list(sd.keys())
|
1556 |
+
for k in keys:
|
1557 |
+
for ik in ignore_keys:
|
1558 |
+
if k.startswith(ik):
|
1559 |
+
print("Deleting key {} from state_dict.".format(k))
|
1560 |
+
del sd[k]
|
1561 |
+
|
1562 |
+
# make it explicit, finetune by including extra input channels
|
1563 |
+
if exists(self.finetune_keys) and k in self.finetune_keys:
|
1564 |
+
new_entry = None
|
1565 |
+
for name, param in self.named_parameters():
|
1566 |
+
if name in self.finetune_keys:
|
1567 |
+
print(
|
1568 |
+
f"modifying key '{name}' and keeping its original {self.keep_dims} (channels) dimensions only")
|
1569 |
+
new_entry = torch.zeros_like(param) # zero init
|
1570 |
+
assert exists(new_entry), 'did not find matching parameter to modify'
|
1571 |
+
new_entry[:, :self.keep_dims, ...] = sd[k]
|
1572 |
+
sd[k] = new_entry
|
1573 |
+
|
1574 |
+
missing, unexpected = self.load_state_dict(sd, strict=False) if not only_model else self.model.load_state_dict(
|
1575 |
+
sd, strict=False)
|
1576 |
+
print(f"Restored from {path} with {len(missing)} missing and {len(unexpected)} unexpected keys")
|
1577 |
+
if len(missing) > 0:
|
1578 |
+
print(f"Missing Keys: {missing}")
|
1579 |
+
if len(unexpected) > 0:
|
1580 |
+
print(f"Unexpected Keys: {unexpected}")
|
1581 |
+
|
1582 |
+
@torch.no_grad()
|
1583 |
+
def log_images(self, batch, N=8, n_row=4, sample=True, ddim_steps=200, ddim_eta=1., return_keys=None,
|
1584 |
+
quantize_denoised=True, inpaint=True, plot_denoise_rows=False, plot_progressive_rows=True,
|
1585 |
+
plot_diffusion_rows=True, unconditional_guidance_scale=1., unconditional_guidance_label=None,
|
1586 |
+
use_ema_scope=True,
|
1587 |
+
**kwargs):
|
1588 |
+
ema_scope = self.ema_scope if use_ema_scope else nullcontext
|
1589 |
+
use_ddim = ddim_steps is not None
|
1590 |
+
|
1591 |
+
log = dict()
|
1592 |
+
z, c, x, xrec, xc = self.get_input(batch, self.first_stage_key, bs=N, return_first_stage_outputs=True)
|
1593 |
+
c_cat, c = c["c_concat"][0], c["c_crossattn"][0]
|
1594 |
+
N = min(x.shape[0], N)
|
1595 |
+
n_row = min(x.shape[0], n_row)
|
1596 |
+
log["inputs"] = x
|
1597 |
+
log["reconstruction"] = xrec
|
1598 |
+
if self.model.conditioning_key is not None:
|
1599 |
+
if hasattr(self.cond_stage_model, "decode"):
|
1600 |
+
xc = self.cond_stage_model.decode(c)
|
1601 |
+
log["conditioning"] = xc
|
1602 |
+
elif self.cond_stage_key in ["caption", "txt"]:
|
1603 |
+
xc = log_txt_as_img((x.shape[2], x.shape[3]), batch[self.cond_stage_key], size=x.shape[2] // 25)
|
1604 |
+
log["conditioning"] = xc
|
1605 |
+
elif self.cond_stage_key in ['class_label', 'cls']:
|
1606 |
+
xc = log_txt_as_img((x.shape[2], x.shape[3]), batch["human_label"], size=x.shape[2] // 25)
|
1607 |
+
log['conditioning'] = xc
|
1608 |
+
elif isimage(xc):
|
1609 |
+
log["conditioning"] = xc
|
1610 |
+
if ismap(xc):
|
1611 |
+
log["original_conditioning"] = self.to_rgb(xc)
|
1612 |
+
|
1613 |
+
if not (self.c_concat_log_start is None and self.c_concat_log_end is None):
|
1614 |
+
log["c_concat_decoded"] = self.decode_first_stage(c_cat[:, self.c_concat_log_start:self.c_concat_log_end])
|
1615 |
+
|
1616 |
+
if plot_diffusion_rows:
|
1617 |
+
# get diffusion row
|
1618 |
+
diffusion_row = list()
|
1619 |
+
z_start = z[:n_row]
|
1620 |
+
for t in range(self.num_timesteps):
|
1621 |
+
if t % self.log_every_t == 0 or t == self.num_timesteps - 1:
|
1622 |
+
t = repeat(torch.tensor([t]), '1 -> b', b=n_row)
|
1623 |
+
t = t.to(self.device).long()
|
1624 |
+
noise = torch.randn_like(z_start)
|
1625 |
+
z_noisy = self.q_sample(x_start=z_start, t=t, noise=noise)
|
1626 |
+
diffusion_row.append(self.decode_first_stage(z_noisy))
|
1627 |
+
|
1628 |
+
diffusion_row = torch.stack(diffusion_row) # n_log_step, n_row, C, H, W
|
1629 |
+
diffusion_grid = rearrange(diffusion_row, 'n b c h w -> b n c h w')
|
1630 |
+
diffusion_grid = rearrange(diffusion_grid, 'b n c h w -> (b n) c h w')
|
1631 |
+
diffusion_grid = make_grid(diffusion_grid, nrow=diffusion_row.shape[0])
|
1632 |
+
log["diffusion_row"] = diffusion_grid
|
1633 |
+
|
1634 |
+
if sample:
|
1635 |
+
# get denoise row
|
1636 |
+
with ema_scope("Sampling"):
|
1637 |
+
samples, z_denoise_row = self.sample_log(cond={"c_concat": [c_cat], "c_crossattn": [c]},
|
1638 |
+
batch_size=N, ddim=use_ddim,
|
1639 |
+
ddim_steps=ddim_steps, eta=ddim_eta)
|
1640 |
+
# samples, z_denoise_row = self.sample(cond=c, batch_size=N, return_intermediates=True)
|
1641 |
+
x_samples = self.decode_first_stage(samples)
|
1642 |
+
log["samples"] = x_samples
|
1643 |
+
if plot_denoise_rows:
|
1644 |
+
denoise_grid = self._get_denoise_row_from_list(z_denoise_row)
|
1645 |
+
log["denoise_row"] = denoise_grid
|
1646 |
+
|
1647 |
+
if unconditional_guidance_scale > 1.0:
|
1648 |
+
uc_cross = self.get_unconditional_conditioning(N, unconditional_guidance_label)
|
1649 |
+
uc_cat = c_cat
|
1650 |
+
uc_full = {"c_concat": [uc_cat], "c_crossattn": [uc_cross]}
|
1651 |
+
with ema_scope("Sampling with classifier-free guidance"):
|
1652 |
+
samples_cfg, _ = self.sample_log(cond={"c_concat": [c_cat], "c_crossattn": [c]},
|
1653 |
+
batch_size=N, ddim=use_ddim,
|
1654 |
+
ddim_steps=ddim_steps, eta=ddim_eta,
|
1655 |
+
unconditional_guidance_scale=unconditional_guidance_scale,
|
1656 |
+
unconditional_conditioning=uc_full,
|
1657 |
+
)
|
1658 |
+
x_samples_cfg = self.decode_first_stage(samples_cfg)
|
1659 |
+
log[f"samples_cfg_scale_{unconditional_guidance_scale:.2f}"] = x_samples_cfg
|
1660 |
+
|
1661 |
+
return log
|
1662 |
+
|
1663 |
+
|
1664 |
+
class LatentInpaintDiffusion(LatentFinetuneDiffusion):
|
1665 |
+
"""
|
1666 |
+
can either run as pure inpainting model (only concat mode) or with mixed conditionings,
|
1667 |
+
e.g. mask as concat and text via cross-attn.
|
1668 |
+
To disable finetuning mode, set finetune_keys to None
|
1669 |
+
"""
|
1670 |
+
|
1671 |
+
def __init__(self,
|
1672 |
+
concat_keys=("mask", "masked_image"),
|
1673 |
+
masked_image_key="masked_image",
|
1674 |
+
*args, **kwargs
|
1675 |
+
):
|
1676 |
+
super().__init__(concat_keys, *args, **kwargs)
|
1677 |
+
self.masked_image_key = masked_image_key
|
1678 |
+
assert self.masked_image_key in concat_keys
|
1679 |
+
|
1680 |
+
@torch.no_grad()
|
1681 |
+
def get_input(self, batch, k, cond_key=None, bs=None, return_first_stage_outputs=False):
|
1682 |
+
# note: restricted to non-trainable encoders currently
|
1683 |
+
assert not self.cond_stage_trainable, 'trainable cond stages not yet supported for inpainting'
|
1684 |
+
z, c, x, xrec, xc = super().get_input(batch, self.first_stage_key, return_first_stage_outputs=True,
|
1685 |
+
force_c_encode=True, return_original_cond=True, bs=bs)
|
1686 |
+
|
1687 |
+
assert exists(self.concat_keys)
|
1688 |
+
c_cat = list()
|
1689 |
+
for ck in self.concat_keys:
|
1690 |
+
cc = rearrange(batch[ck], 'b h w c -> b c h w').to(memory_format=torch.contiguous_format).float()
|
1691 |
+
if bs is not None:
|
1692 |
+
cc = cc[:bs]
|
1693 |
+
cc = cc.to(self.device)
|
1694 |
+
bchw = z.shape
|
1695 |
+
if ck != self.masked_image_key:
|
1696 |
+
cc = torch.nn.functional.interpolate(cc, size=bchw[-2:])
|
1697 |
+
else:
|
1698 |
+
cc = self.get_first_stage_encoding(self.encode_first_stage(cc))
|
1699 |
+
c_cat.append(cc)
|
1700 |
+
c_cat = torch.cat(c_cat, dim=1)
|
1701 |
+
all_conds = {"c_concat": [c_cat], "c_crossattn": [c]}
|
1702 |
+
if return_first_stage_outputs:
|
1703 |
+
return z, all_conds, x, xrec, xc
|
1704 |
+
return z, all_conds
|
1705 |
+
|
1706 |
+
@torch.no_grad()
|
1707 |
+
def log_images(self, *args, **kwargs):
|
1708 |
+
log = super(LatentInpaintDiffusion, self).log_images(*args, **kwargs)
|
1709 |
+
log["masked_image"] = rearrange(args[0]["masked_image"],
|
1710 |
+
'b h w c -> b c h w').to(memory_format=torch.contiguous_format).float()
|
1711 |
+
return log
|
1712 |
+
|
1713 |
+
|
1714 |
+
class LatentDepth2ImageDiffusion(LatentFinetuneDiffusion):
|
1715 |
+
"""
|
1716 |
+
condition on monocular depth estimation
|
1717 |
+
"""
|
1718 |
+
|
1719 |
+
def __init__(self, depth_stage_config, concat_keys=("midas_in",), *args, **kwargs):
|
1720 |
+
super().__init__(concat_keys=concat_keys, *args, **kwargs)
|
1721 |
+
self.depth_model = instantiate_from_config(depth_stage_config)
|
1722 |
+
self.depth_stage_key = concat_keys[0]
|
1723 |
+
|
1724 |
+
@torch.no_grad()
|
1725 |
+
def get_input(self, batch, k, cond_key=None, bs=None, return_first_stage_outputs=False):
|
1726 |
+
# note: restricted to non-trainable encoders currently
|
1727 |
+
assert not self.cond_stage_trainable, 'trainable cond stages not yet supported for depth2img'
|
1728 |
+
z, c, x, xrec, xc = super().get_input(batch, self.first_stage_key, return_first_stage_outputs=True,
|
1729 |
+
force_c_encode=True, return_original_cond=True, bs=bs)
|
1730 |
+
|
1731 |
+
assert exists(self.concat_keys)
|
1732 |
+
assert len(self.concat_keys) == 1
|
1733 |
+
c_cat = list()
|
1734 |
+
for ck in self.concat_keys:
|
1735 |
+
cc = batch[ck]
|
1736 |
+
if bs is not None:
|
1737 |
+
cc = cc[:bs]
|
1738 |
+
cc = cc.to(self.device)
|
1739 |
+
cc = self.depth_model(cc)
|
1740 |
+
cc = torch.nn.functional.interpolate(
|
1741 |
+
cc,
|
1742 |
+
size=z.shape[2:],
|
1743 |
+
mode="bicubic",
|
1744 |
+
align_corners=False,
|
1745 |
+
)
|
1746 |
+
|
1747 |
+
depth_min, depth_max = torch.amin(cc, dim=[1, 2, 3], keepdim=True), torch.amax(cc, dim=[1, 2, 3],
|
1748 |
+
keepdim=True)
|
1749 |
+
cc = 2. * (cc - depth_min) / (depth_max - depth_min + 0.001) - 1.
|
1750 |
+
c_cat.append(cc)
|
1751 |
+
c_cat = torch.cat(c_cat, dim=1)
|
1752 |
+
all_conds = {"c_concat": [c_cat], "c_crossattn": [c]}
|
1753 |
+
if return_first_stage_outputs:
|
1754 |
+
return z, all_conds, x, xrec, xc
|
1755 |
+
return z, all_conds
|
1756 |
+
|
1757 |
+
@torch.no_grad()
|
1758 |
+
def log_images(self, *args, **kwargs):
|
1759 |
+
log = super().log_images(*args, **kwargs)
|
1760 |
+
depth = self.depth_model(args[0][self.depth_stage_key])
|
1761 |
+
depth_min, depth_max = torch.amin(depth, dim=[1, 2, 3], keepdim=True), \
|
1762 |
+
torch.amax(depth, dim=[1, 2, 3], keepdim=True)
|
1763 |
+
log["depth"] = 2. * (depth - depth_min) / (depth_max - depth_min) - 1.
|
1764 |
+
return log
|
1765 |
+
|
1766 |
+
|
1767 |
+
class LatentUpscaleFinetuneDiffusion(LatentFinetuneDiffusion):
|
1768 |
+
"""
|
1769 |
+
condition on low-res image (and optionally on some spatial noise augmentation)
|
1770 |
+
"""
|
1771 |
+
def __init__(self, concat_keys=("lr",), reshuffle_patch_size=None,
|
1772 |
+
low_scale_config=None, low_scale_key=None, *args, **kwargs):
|
1773 |
+
super().__init__(concat_keys=concat_keys, *args, **kwargs)
|
1774 |
+
self.reshuffle_patch_size = reshuffle_patch_size
|
1775 |
+
self.low_scale_model = None
|
1776 |
+
if low_scale_config is not None:
|
1777 |
+
print("Initializing a low-scale model")
|
1778 |
+
assert exists(low_scale_key)
|
1779 |
+
self.instantiate_low_stage(low_scale_config)
|
1780 |
+
self.low_scale_key = low_scale_key
|
1781 |
+
|
1782 |
+
def instantiate_low_stage(self, config):
|
1783 |
+
model = instantiate_from_config(config)
|
1784 |
+
self.low_scale_model = model.eval()
|
1785 |
+
self.low_scale_model.train = disabled_train
|
1786 |
+
for param in self.low_scale_model.parameters():
|
1787 |
+
param.requires_grad = False
|
1788 |
+
|
1789 |
+
@torch.no_grad()
|
1790 |
+
def get_input(self, batch, k, cond_key=None, bs=None, return_first_stage_outputs=False):
|
1791 |
+
# note: restricted to non-trainable encoders currently
|
1792 |
+
assert not self.cond_stage_trainable, 'trainable cond stages not yet supported for upscaling-ft'
|
1793 |
+
z, c, x, xrec, xc = super().get_input(batch, self.first_stage_key, return_first_stage_outputs=True,
|
1794 |
+
force_c_encode=True, return_original_cond=True, bs=bs)
|
1795 |
+
|
1796 |
+
assert exists(self.concat_keys)
|
1797 |
+
assert len(self.concat_keys) == 1
|
1798 |
+
# optionally make spatial noise_level here
|
1799 |
+
c_cat = list()
|
1800 |
+
noise_level = None
|
1801 |
+
for ck in self.concat_keys:
|
1802 |
+
cc = batch[ck]
|
1803 |
+
cc = rearrange(cc, 'b h w c -> b c h w')
|
1804 |
+
if exists(self.reshuffle_patch_size):
|
1805 |
+
assert isinstance(self.reshuffle_patch_size, int)
|
1806 |
+
cc = rearrange(cc, 'b c (p1 h) (p2 w) -> b (p1 p2 c) h w',
|
1807 |
+
p1=self.reshuffle_patch_size, p2=self.reshuffle_patch_size)
|
1808 |
+
if bs is not None:
|
1809 |
+
cc = cc[:bs]
|
1810 |
+
cc = cc.to(self.device)
|
1811 |
+
if exists(self.low_scale_model) and ck == self.low_scale_key:
|
1812 |
+
cc, noise_level = self.low_scale_model(cc)
|
1813 |
+
c_cat.append(cc)
|
1814 |
+
c_cat = torch.cat(c_cat, dim=1)
|
1815 |
+
if exists(noise_level):
|
1816 |
+
all_conds = {"c_concat": [c_cat], "c_crossattn": [c], "c_adm": noise_level}
|
1817 |
+
else:
|
1818 |
+
all_conds = {"c_concat": [c_cat], "c_crossattn": [c]}
|
1819 |
+
if return_first_stage_outputs:
|
1820 |
+
return z, all_conds, x, xrec, xc
|
1821 |
+
return z, all_conds
|
1822 |
+
|
1823 |
+
@torch.no_grad()
|
1824 |
+
def log_images(self, *args, **kwargs):
|
1825 |
+
log = super().log_images(*args, **kwargs)
|
1826 |
+
log["lr"] = rearrange(args[0]["lr"], 'b h w c -> b c h w')
|
1827 |
+
return log
|
ttts/AA_diffusion_deprecated/ldm/models/diffusion/dpm_solver/__init__.py
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
from .sampler import DPMSolverSampler
|
ttts/AA_diffusion_deprecated/ldm/models/diffusion/dpm_solver/dpm_solver.py
ADDED
@@ -0,0 +1,1154 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
import torch.nn.functional as F
|
3 |
+
import math
|
4 |
+
from tqdm import tqdm
|
5 |
+
|
6 |
+
|
7 |
+
class NoiseScheduleVP:
|
8 |
+
def __init__(
|
9 |
+
self,
|
10 |
+
schedule='discrete',
|
11 |
+
betas=None,
|
12 |
+
alphas_cumprod=None,
|
13 |
+
continuous_beta_0=0.1,
|
14 |
+
continuous_beta_1=20.,
|
15 |
+
):
|
16 |
+
"""Create a wrapper class for the forward SDE (VP type).
|
17 |
+
***
|
18 |
+
Update: We support discrete-time diffusion models by implementing a picewise linear interpolation for log_alpha_t.
|
19 |
+
We recommend to use schedule='discrete' for the discrete-time diffusion models, especially for high-resolution images.
|
20 |
+
***
|
21 |
+
The forward SDE ensures that the condition distribution q_{t|0}(x_t | x_0) = N ( alpha_t * x_0, sigma_t^2 * I ).
|
22 |
+
We further define lambda_t = log(alpha_t) - log(sigma_t), which is the half-logSNR (described in the DPM-Solver paper).
|
23 |
+
Therefore, we implement the functions for computing alpha_t, sigma_t and lambda_t. For t in [0, T], we have:
|
24 |
+
log_alpha_t = self.marginal_log_mean_coeff(t)
|
25 |
+
sigma_t = self.marginal_std(t)
|
26 |
+
lambda_t = self.marginal_lambda(t)
|
27 |
+
Moreover, as lambda(t) is an invertible function, we also support its inverse function:
|
28 |
+
t = self.inverse_lambda(lambda_t)
|
29 |
+
===============================================================
|
30 |
+
We support both discrete-time DPMs (trained on n = 0, 1, ..., N-1) and continuous-time DPMs (trained on t in [t_0, T]).
|
31 |
+
1. For discrete-time DPMs:
|
32 |
+
For discrete-time DPMs trained on n = 0, 1, ..., N-1, we convert the discrete steps to continuous time steps by:
|
33 |
+
t_i = (i + 1) / N
|
34 |
+
e.g. for N = 1000, we have t_0 = 1e-3 and T = t_{N-1} = 1.
|
35 |
+
We solve the corresponding diffusion ODE from time T = 1 to time t_0 = 1e-3.
|
36 |
+
Args:
|
37 |
+
betas: A `torch.Tensor`. The beta array for the discrete-time DPM. (See the original DDPM paper for details)
|
38 |
+
alphas_cumprod: A `torch.Tensor`. The cumprod alphas for the discrete-time DPM. (See the original DDPM paper for details)
|
39 |
+
Note that we always have alphas_cumprod = cumprod(betas). Therefore, we only need to set one of `betas` and `alphas_cumprod`.
|
40 |
+
**Important**: Please pay special attention for the args for `alphas_cumprod`:
|
41 |
+
The `alphas_cumprod` is the \hat{alpha_n} arrays in the notations of DDPM. Specifically, DDPMs assume that
|
42 |
+
q_{t_n | 0}(x_{t_n} | x_0) = N ( \sqrt{\hat{alpha_n}} * x_0, (1 - \hat{alpha_n}) * I ).
|
43 |
+
Therefore, the notation \hat{alpha_n} is different from the notation alpha_t in DPM-Solver. In fact, we have
|
44 |
+
alpha_{t_n} = \sqrt{\hat{alpha_n}},
|
45 |
+
and
|
46 |
+
log(alpha_{t_n}) = 0.5 * log(\hat{alpha_n}).
|
47 |
+
2. For continuous-time DPMs:
|
48 |
+
We support two types of VPSDEs: linear (DDPM) and cosine (improved-DDPM). The hyperparameters for the noise
|
49 |
+
schedule are the default settings in DDPM and improved-DDPM:
|
50 |
+
Args:
|
51 |
+
beta_min: A `float` number. The smallest beta for the linear schedule.
|
52 |
+
beta_max: A `float` number. The largest beta for the linear schedule.
|
53 |
+
cosine_s: A `float` number. The hyperparameter in the cosine schedule.
|
54 |
+
cosine_beta_max: A `float` number. The hyperparameter in the cosine schedule.
|
55 |
+
T: A `float` number. The ending time of the forward process.
|
56 |
+
===============================================================
|
57 |
+
Args:
|
58 |
+
schedule: A `str`. The noise schedule of the forward SDE. 'discrete' for discrete-time DPMs,
|
59 |
+
'linear' or 'cosine' for continuous-time DPMs.
|
60 |
+
Returns:
|
61 |
+
A wrapper object of the forward SDE (VP type).
|
62 |
+
|
63 |
+
===============================================================
|
64 |
+
Example:
|
65 |
+
# For discrete-time DPMs, given betas (the beta array for n = 0, 1, ..., N - 1):
|
66 |
+
>>> ns = NoiseScheduleVP('discrete', betas=betas)
|
67 |
+
# For discrete-time DPMs, given alphas_cumprod (the \hat{alpha_n} array for n = 0, 1, ..., N - 1):
|
68 |
+
>>> ns = NoiseScheduleVP('discrete', alphas_cumprod=alphas_cumprod)
|
69 |
+
# For continuous-time DPMs (VPSDE), linear schedule:
|
70 |
+
>>> ns = NoiseScheduleVP('linear', continuous_beta_0=0.1, continuous_beta_1=20.)
|
71 |
+
"""
|
72 |
+
|
73 |
+
if schedule not in ['discrete', 'linear', 'cosine']:
|
74 |
+
raise ValueError(
|
75 |
+
"Unsupported noise schedule {}. The schedule needs to be 'discrete' or 'linear' or 'cosine'".format(
|
76 |
+
schedule))
|
77 |
+
|
78 |
+
self.schedule = schedule
|
79 |
+
if schedule == 'discrete':
|
80 |
+
if betas is not None:
|
81 |
+
log_alphas = 0.5 * torch.log(1 - betas).cumsum(dim=0)
|
82 |
+
else:
|
83 |
+
assert alphas_cumprod is not None
|
84 |
+
log_alphas = 0.5 * torch.log(alphas_cumprod)
|
85 |
+
self.total_N = len(log_alphas)
|
86 |
+
self.T = 1.
|
87 |
+
self.t_array = torch.linspace(0., 1., self.total_N + 1)[1:].reshape((1, -1))
|
88 |
+
self.log_alpha_array = log_alphas.reshape((1, -1,))
|
89 |
+
else:
|
90 |
+
self.total_N = 1000
|
91 |
+
self.beta_0 = continuous_beta_0
|
92 |
+
self.beta_1 = continuous_beta_1
|
93 |
+
self.cosine_s = 0.008
|
94 |
+
self.cosine_beta_max = 999.
|
95 |
+
self.cosine_t_max = math.atan(self.cosine_beta_max * (1. + self.cosine_s) / math.pi) * 2. * (
|
96 |
+
1. + self.cosine_s) / math.pi - self.cosine_s
|
97 |
+
self.cosine_log_alpha_0 = math.log(math.cos(self.cosine_s / (1. + self.cosine_s) * math.pi / 2.))
|
98 |
+
self.schedule = schedule
|
99 |
+
if schedule == 'cosine':
|
100 |
+
# For the cosine schedule, T = 1 will have numerical issues. So we manually set the ending time T.
|
101 |
+
# Note that T = 0.9946 may be not the optimal setting. However, we find it works well.
|
102 |
+
self.T = 0.9946
|
103 |
+
else:
|
104 |
+
self.T = 1.
|
105 |
+
|
106 |
+
def marginal_log_mean_coeff(self, t):
|
107 |
+
"""
|
108 |
+
Compute log(alpha_t) of a given continuous-time label t in [0, T].
|
109 |
+
"""
|
110 |
+
if self.schedule == 'discrete':
|
111 |
+
return interpolate_fn(t.reshape((-1, 1)), self.t_array.to(t.device),
|
112 |
+
self.log_alpha_array.to(t.device)).reshape((-1))
|
113 |
+
elif self.schedule == 'linear':
|
114 |
+
return -0.25 * t ** 2 * (self.beta_1 - self.beta_0) - 0.5 * t * self.beta_0
|
115 |
+
elif self.schedule == 'cosine':
|
116 |
+
log_alpha_fn = lambda s: torch.log(torch.cos((s + self.cosine_s) / (1. + self.cosine_s) * math.pi / 2.))
|
117 |
+
log_alpha_t = log_alpha_fn(t) - self.cosine_log_alpha_0
|
118 |
+
return log_alpha_t
|
119 |
+
|
120 |
+
def marginal_alpha(self, t):
|
121 |
+
"""
|
122 |
+
Compute alpha_t of a given continuous-time label t in [0, T].
|
123 |
+
"""
|
124 |
+
return torch.exp(self.marginal_log_mean_coeff(t))
|
125 |
+
|
126 |
+
def marginal_std(self, t):
|
127 |
+
"""
|
128 |
+
Compute sigma_t of a given continuous-time label t in [0, T].
|
129 |
+
"""
|
130 |
+
return torch.sqrt(1. - torch.exp(2. * self.marginal_log_mean_coeff(t)))
|
131 |
+
|
132 |
+
def marginal_lambda(self, t):
|
133 |
+
"""
|
134 |
+
Compute lambda_t = log(alpha_t) - log(sigma_t) of a given continuous-time label t in [0, T].
|
135 |
+
"""
|
136 |
+
log_mean_coeff = self.marginal_log_mean_coeff(t)
|
137 |
+
log_std = 0.5 * torch.log(1. - torch.exp(2. * log_mean_coeff))
|
138 |
+
return log_mean_coeff - log_std
|
139 |
+
|
140 |
+
def inverse_lambda(self, lamb):
|
141 |
+
"""
|
142 |
+
Compute the continuous-time label t in [0, T] of a given half-logSNR lambda_t.
|
143 |
+
"""
|
144 |
+
if self.schedule == 'linear':
|
145 |
+
tmp = 2. * (self.beta_1 - self.beta_0) * torch.logaddexp(-2. * lamb, torch.zeros((1,)).to(lamb))
|
146 |
+
Delta = self.beta_0 ** 2 + tmp
|
147 |
+
return tmp / (torch.sqrt(Delta) + self.beta_0) / (self.beta_1 - self.beta_0)
|
148 |
+
elif self.schedule == 'discrete':
|
149 |
+
log_alpha = -0.5 * torch.logaddexp(torch.zeros((1,)).to(lamb.device), -2. * lamb)
|
150 |
+
t = interpolate_fn(log_alpha.reshape((-1, 1)), torch.flip(self.log_alpha_array.to(lamb.device), [1]),
|
151 |
+
torch.flip(self.t_array.to(lamb.device), [1]))
|
152 |
+
return t.reshape((-1,))
|
153 |
+
else:
|
154 |
+
log_alpha = -0.5 * torch.logaddexp(-2. * lamb, torch.zeros((1,)).to(lamb))
|
155 |
+
t_fn = lambda log_alpha_t: torch.arccos(torch.exp(log_alpha_t + self.cosine_log_alpha_0)) * 2. * (
|
156 |
+
1. + self.cosine_s) / math.pi - self.cosine_s
|
157 |
+
t = t_fn(log_alpha)
|
158 |
+
return t
|
159 |
+
|
160 |
+
|
161 |
+
def model_wrapper(
|
162 |
+
model,
|
163 |
+
noise_schedule,
|
164 |
+
model_type="noise",
|
165 |
+
model_kwargs={},
|
166 |
+
guidance_type="uncond",
|
167 |
+
condition=None,
|
168 |
+
unconditional_condition=None,
|
169 |
+
guidance_scale=1.,
|
170 |
+
classifier_fn=None,
|
171 |
+
classifier_kwargs={},
|
172 |
+
):
|
173 |
+
"""Create a wrapper function for the noise prediction model.
|
174 |
+
DPM-Solver needs to solve the continuous-time diffusion ODEs. For DPMs trained on discrete-time labels, we need to
|
175 |
+
firstly wrap the model function to a noise prediction model that accepts the continuous time as the input.
|
176 |
+
We support four types of the diffusion model by setting `model_type`:
|
177 |
+
1. "noise": noise prediction model. (Trained by predicting noise).
|
178 |
+
2. "x_start": data prediction model. (Trained by predicting the data x_0 at time 0).
|
179 |
+
3. "v": velocity prediction model. (Trained by predicting the velocity).
|
180 |
+
The "v" prediction is derivation detailed in Appendix D of [1], and is used in Imagen-Video [2].
|
181 |
+
[1] Salimans, Tim, and Jonathan Ho. "Progressive distillation for fast sampling of diffusion models."
|
182 |
+
arXiv preprint arXiv:2202.00512 (2022).
|
183 |
+
[2] Ho, Jonathan, et al. "Imagen Video: High Definition Video Generation with Diffusion Models."
|
184 |
+
arXiv preprint arXiv:2210.02303 (2022).
|
185 |
+
|
186 |
+
4. "score": marginal score function. (Trained by denoising score matching).
|
187 |
+
Note that the score function and the noise prediction model follows a simple relationship:
|
188 |
+
```
|
189 |
+
noise(x_t, t) = -sigma_t * score(x_t, t)
|
190 |
+
```
|
191 |
+
We support three types of guided sampling by DPMs by setting `guidance_type`:
|
192 |
+
1. "uncond": unconditional sampling by DPMs.
|
193 |
+
The input `model` has the following format:
|
194 |
+
``
|
195 |
+
model(x, t_input, **model_kwargs) -> noise | x_start | v | score
|
196 |
+
``
|
197 |
+
2. "classifier": classifier guidance sampling [3] by DPMs and another classifier.
|
198 |
+
The input `model` has the following format:
|
199 |
+
``
|
200 |
+
model(x, t_input, **model_kwargs) -> noise | x_start | v | score
|
201 |
+
``
|
202 |
+
The input `classifier_fn` has the following format:
|
203 |
+
``
|
204 |
+
classifier_fn(x, t_input, cond, **classifier_kwargs) -> logits(x, t_input, cond)
|
205 |
+
``
|
206 |
+
[3] P. Dhariwal and A. Q. Nichol, "Diffusion models beat GANs on image synthesis,"
|
207 |
+
in Advances in Neural Information Processing Systems, vol. 34, 2021, pp. 8780-8794.
|
208 |
+
3. "classifier-free": classifier-free guidance sampling by conditional DPMs.
|
209 |
+
The input `model` has the following format:
|
210 |
+
``
|
211 |
+
model(x, t_input, cond, **model_kwargs) -> noise | x_start | v | score
|
212 |
+
``
|
213 |
+
And if cond == `unconditional_condition`, the model output is the unconditional DPM output.
|
214 |
+
[4] Ho, Jonathan, and Tim Salimans. "Classifier-free diffusion guidance."
|
215 |
+
arXiv preprint arXiv:2207.12598 (2022).
|
216 |
+
|
217 |
+
The `t_input` is the time label of the model, which may be discrete-time labels (i.e. 0 to 999)
|
218 |
+
or continuous-time labels (i.e. epsilon to T).
|
219 |
+
We wrap the model function to accept only `x` and `t_continuous` as inputs, and outputs the predicted noise:
|
220 |
+
``
|
221 |
+
def model_fn(x, t_continuous) -> noise:
|
222 |
+
t_input = get_model_input_time(t_continuous)
|
223 |
+
return noise_pred(model, x, t_input, **model_kwargs)
|
224 |
+
``
|
225 |
+
where `t_continuous` is the continuous time labels (i.e. epsilon to T). And we use `model_fn` for DPM-Solver.
|
226 |
+
===============================================================
|
227 |
+
Args:
|
228 |
+
model: A diffusion model with the corresponding format described above.
|
229 |
+
noise_schedule: A noise schedule object, such as NoiseScheduleVP.
|
230 |
+
model_type: A `str`. The parameterization type of the diffusion model.
|
231 |
+
"noise" or "x_start" or "v" or "score".
|
232 |
+
model_kwargs: A `dict`. A dict for the other inputs of the model function.
|
233 |
+
guidance_type: A `str`. The type of the guidance for sampling.
|
234 |
+
"uncond" or "classifier" or "classifier-free".
|
235 |
+
condition: A pytorch tensor. The condition for the guided sampling.
|
236 |
+
Only used for "classifier" or "classifier-free" guidance type.
|
237 |
+
unconditional_condition: A pytorch tensor. The condition for the unconditional sampling.
|
238 |
+
Only used for "classifier-free" guidance type.
|
239 |
+
guidance_scale: A `float`. The scale for the guided sampling.
|
240 |
+
classifier_fn: A classifier function. Only used for the classifier guidance.
|
241 |
+
classifier_kwargs: A `dict`. A dict for the other inputs of the classifier function.
|
242 |
+
Returns:
|
243 |
+
A noise prediction model that accepts the noised data and the continuous time as the inputs.
|
244 |
+
"""
|
245 |
+
|
246 |
+
def get_model_input_time(t_continuous):
|
247 |
+
"""
|
248 |
+
Convert the continuous-time `t_continuous` (in [epsilon, T]) to the model input time.
|
249 |
+
For discrete-time DPMs, we convert `t_continuous` in [1 / N, 1] to `t_input` in [0, 1000 * (N - 1) / N].
|
250 |
+
For continuous-time DPMs, we just use `t_continuous`.
|
251 |
+
"""
|
252 |
+
if noise_schedule.schedule == 'discrete':
|
253 |
+
return (t_continuous - 1. / noise_schedule.total_N) * 1000.
|
254 |
+
else:
|
255 |
+
return t_continuous
|
256 |
+
|
257 |
+
def noise_pred_fn(x, t_continuous, cond=None):
|
258 |
+
if t_continuous.reshape((-1,)).shape[0] == 1:
|
259 |
+
t_continuous = t_continuous.expand((x.shape[0]))
|
260 |
+
t_input = get_model_input_time(t_continuous)
|
261 |
+
if cond is None:
|
262 |
+
output = model(x, t_input, **model_kwargs)
|
263 |
+
else:
|
264 |
+
output = model(x, t_input, cond, **model_kwargs)
|
265 |
+
if model_type == "noise":
|
266 |
+
return output
|
267 |
+
elif model_type == "x_start":
|
268 |
+
alpha_t, sigma_t = noise_schedule.marginal_alpha(t_continuous), noise_schedule.marginal_std(t_continuous)
|
269 |
+
dims = x.dim()
|
270 |
+
return (x - expand_dims(alpha_t, dims) * output) / expand_dims(sigma_t, dims)
|
271 |
+
elif model_type == "v":
|
272 |
+
alpha_t, sigma_t = noise_schedule.marginal_alpha(t_continuous), noise_schedule.marginal_std(t_continuous)
|
273 |
+
dims = x.dim()
|
274 |
+
return expand_dims(alpha_t, dims) * output + expand_dims(sigma_t, dims) * x
|
275 |
+
elif model_type == "score":
|
276 |
+
sigma_t = noise_schedule.marginal_std(t_continuous)
|
277 |
+
dims = x.dim()
|
278 |
+
return -expand_dims(sigma_t, dims) * output
|
279 |
+
|
280 |
+
def cond_grad_fn(x, t_input):
|
281 |
+
"""
|
282 |
+
Compute the gradient of the classifier, i.e. nabla_{x} log p_t(cond | x_t).
|
283 |
+
"""
|
284 |
+
with torch.enable_grad():
|
285 |
+
x_in = x.detach().requires_grad_(True)
|
286 |
+
log_prob = classifier_fn(x_in, t_input, condition, **classifier_kwargs)
|
287 |
+
return torch.autograd.grad(log_prob.sum(), x_in)[0]
|
288 |
+
|
289 |
+
def model_fn(x, t_continuous):
|
290 |
+
"""
|
291 |
+
The noise predicition model function that is used for DPM-Solver.
|
292 |
+
"""
|
293 |
+
if t_continuous.reshape((-1,)).shape[0] == 1:
|
294 |
+
t_continuous = t_continuous.expand((x.shape[0]))
|
295 |
+
if guidance_type == "uncond":
|
296 |
+
return noise_pred_fn(x, t_continuous)
|
297 |
+
elif guidance_type == "classifier":
|
298 |
+
assert classifier_fn is not None
|
299 |
+
t_input = get_model_input_time(t_continuous)
|
300 |
+
cond_grad = cond_grad_fn(x, t_input)
|
301 |
+
sigma_t = noise_schedule.marginal_std(t_continuous)
|
302 |
+
noise = noise_pred_fn(x, t_continuous)
|
303 |
+
return noise - guidance_scale * expand_dims(sigma_t, dims=cond_grad.dim()) * cond_grad
|
304 |
+
elif guidance_type == "classifier-free":
|
305 |
+
if guidance_scale == 1. or unconditional_condition is None:
|
306 |
+
return noise_pred_fn(x, t_continuous, cond=condition)
|
307 |
+
else:
|
308 |
+
x_in = torch.cat([x] * 2)
|
309 |
+
t_in = torch.cat([t_continuous] * 2)
|
310 |
+
c_in = torch.cat([unconditional_condition, condition])
|
311 |
+
noise_uncond, noise = noise_pred_fn(x_in, t_in, cond=c_in).chunk(2)
|
312 |
+
return noise_uncond + guidance_scale * (noise - noise_uncond)
|
313 |
+
|
314 |
+
assert model_type in ["noise", "x_start", "v"]
|
315 |
+
assert guidance_type in ["uncond", "classifier", "classifier-free"]
|
316 |
+
return model_fn
|
317 |
+
|
318 |
+
|
319 |
+
class DPM_Solver:
|
320 |
+
def __init__(self, model_fn, noise_schedule, predict_x0=False, thresholding=False, max_val=1.):
|
321 |
+
"""Construct a DPM-Solver.
|
322 |
+
We support both the noise prediction model ("predicting epsilon") and the data prediction model ("predicting x0").
|
323 |
+
If `predict_x0` is False, we use the solver for the noise prediction model (DPM-Solver).
|
324 |
+
If `predict_x0` is True, we use the solver for the data prediction model (DPM-Solver++).
|
325 |
+
In such case, we further support the "dynamic thresholding" in [1] when `thresholding` is True.
|
326 |
+
The "dynamic thresholding" can greatly improve the sample quality for pixel-space DPMs with large guidance scales.
|
327 |
+
Args:
|
328 |
+
model_fn: A noise prediction model function which accepts the continuous-time input (t in [epsilon, T]):
|
329 |
+
``
|
330 |
+
def model_fn(x, t_continuous):
|
331 |
+
return noise
|
332 |
+
``
|
333 |
+
noise_schedule: A noise schedule object, such as NoiseScheduleVP.
|
334 |
+
predict_x0: A `bool`. If true, use the data prediction model; else, use the noise prediction model.
|
335 |
+
thresholding: A `bool`. Valid when `predict_x0` is True. Whether to use the "dynamic thresholding" in [1].
|
336 |
+
max_val: A `float`. Valid when both `predict_x0` and `thresholding` are True. The max value for thresholding.
|
337 |
+
|
338 |
+
[1] Chitwan Saharia, William Chan, Saurabh Saxena, Lala Li, Jay Whang, Emily Denton, Seyed Kamyar Seyed Ghasemipour, Burcu Karagol Ayan, S Sara Mahdavi, Rapha Gontijo Lopes, et al. Photorealistic text-to-image diffusion models with deep language understanding. arXiv preprint arXiv:2205.11487, 2022b.
|
339 |
+
"""
|
340 |
+
self.model = model_fn
|
341 |
+
self.noise_schedule = noise_schedule
|
342 |
+
self.predict_x0 = predict_x0
|
343 |
+
self.thresholding = thresholding
|
344 |
+
self.max_val = max_val
|
345 |
+
|
346 |
+
def noise_prediction_fn(self, x, t):
|
347 |
+
"""
|
348 |
+
Return the noise prediction model.
|
349 |
+
"""
|
350 |
+
return self.model(x, t)
|
351 |
+
|
352 |
+
def data_prediction_fn(self, x, t):
|
353 |
+
"""
|
354 |
+
Return the data prediction model (with thresholding).
|
355 |
+
"""
|
356 |
+
noise = self.noise_prediction_fn(x, t)
|
357 |
+
dims = x.dim()
|
358 |
+
alpha_t, sigma_t = self.noise_schedule.marginal_alpha(t), self.noise_schedule.marginal_std(t)
|
359 |
+
x0 = (x - expand_dims(sigma_t, dims) * noise) / expand_dims(alpha_t, dims)
|
360 |
+
if self.thresholding:
|
361 |
+
p = 0.995 # A hyperparameter in the paper of "Imagen" [1].
|
362 |
+
s = torch.quantile(torch.abs(x0).reshape((x0.shape[0], -1)), p, dim=1)
|
363 |
+
s = expand_dims(torch.maximum(s, self.max_val * torch.ones_like(s).to(s.device)), dims)
|
364 |
+
x0 = torch.clamp(x0, -s, s) / s
|
365 |
+
return x0
|
366 |
+
|
367 |
+
def model_fn(self, x, t):
|
368 |
+
"""
|
369 |
+
Convert the model to the noise prediction model or the data prediction model.
|
370 |
+
"""
|
371 |
+
if self.predict_x0:
|
372 |
+
return self.data_prediction_fn(x, t)
|
373 |
+
else:
|
374 |
+
return self.noise_prediction_fn(x, t)
|
375 |
+
|
376 |
+
def get_time_steps(self, skip_type, t_T, t_0, N, device):
|
377 |
+
"""Compute the intermediate time steps for sampling.
|
378 |
+
Args:
|
379 |
+
skip_type: A `str`. The type for the spacing of the time steps. We support three types:
|
380 |
+
- 'logSNR': uniform logSNR for the time steps.
|
381 |
+
- 'time_uniform': uniform time for the time steps. (**Recommended for high-resolutional data**.)
|
382 |
+
- 'time_quadratic': quadratic time for the time steps. (Used in DDIM for low-resolutional data.)
|
383 |
+
t_T: A `float`. The starting time of the sampling (default is T).
|
384 |
+
t_0: A `float`. The ending time of the sampling (default is epsilon).
|
385 |
+
N: A `int`. The total number of the spacing of the time steps.
|
386 |
+
device: A torch device.
|
387 |
+
Returns:
|
388 |
+
A pytorch tensor of the time steps, with the shape (N + 1,).
|
389 |
+
"""
|
390 |
+
if skip_type == 'logSNR':
|
391 |
+
lambda_T = self.noise_schedule.marginal_lambda(torch.tensor(t_T).to(device))
|
392 |
+
lambda_0 = self.noise_schedule.marginal_lambda(torch.tensor(t_0).to(device))
|
393 |
+
logSNR_steps = torch.linspace(lambda_T.cpu().item(), lambda_0.cpu().item(), N + 1).to(device)
|
394 |
+
return self.noise_schedule.inverse_lambda(logSNR_steps)
|
395 |
+
elif skip_type == 'time_uniform':
|
396 |
+
return torch.linspace(t_T, t_0, N + 1).to(device)
|
397 |
+
elif skip_type == 'time_quadratic':
|
398 |
+
t_order = 2
|
399 |
+
t = torch.linspace(t_T ** (1. / t_order), t_0 ** (1. / t_order), N + 1).pow(t_order).to(device)
|
400 |
+
return t
|
401 |
+
else:
|
402 |
+
raise ValueError(
|
403 |
+
"Unsupported skip_type {}, need to be 'logSNR' or 'time_uniform' or 'time_quadratic'".format(skip_type))
|
404 |
+
|
405 |
+
def get_orders_and_timesteps_for_singlestep_solver(self, steps, order, skip_type, t_T, t_0, device):
|
406 |
+
"""
|
407 |
+
Get the order of each step for sampling by the singlestep DPM-Solver.
|
408 |
+
We combine both DPM-Solver-1,2,3 to use all the function evaluations, which is named as "DPM-Solver-fast".
|
409 |
+
Given a fixed number of function evaluations by `steps`, the sampling procedure by DPM-Solver-fast is:
|
410 |
+
- If order == 1:
|
411 |
+
We take `steps` of DPM-Solver-1 (i.e. DDIM).
|
412 |
+
- If order == 2:
|
413 |
+
- Denote K = (steps // 2). We take K or (K + 1) intermediate time steps for sampling.
|
414 |
+
- If steps % 2 == 0, we use K steps of DPM-Solver-2.
|
415 |
+
- If steps % 2 == 1, we use K steps of DPM-Solver-2 and 1 step of DPM-Solver-1.
|
416 |
+
- If order == 3:
|
417 |
+
- Denote K = (steps // 3 + 1). We take K intermediate time steps for sampling.
|
418 |
+
- If steps % 3 == 0, we use (K - 2) steps of DPM-Solver-3, and 1 step of DPM-Solver-2 and 1 step of DPM-Solver-1.
|
419 |
+
- If steps % 3 == 1, we use (K - 1) steps of DPM-Solver-3 and 1 step of DPM-Solver-1.
|
420 |
+
- If steps % 3 == 2, we use (K - 1) steps of DPM-Solver-3 and 1 step of DPM-Solver-2.
|
421 |
+
============================================
|
422 |
+
Args:
|
423 |
+
order: A `int`. The max order for the solver (2 or 3).
|
424 |
+
steps: A `int`. The total number of function evaluations (NFE).
|
425 |
+
skip_type: A `str`. The type for the spacing of the time steps. We support three types:
|
426 |
+
- 'logSNR': uniform logSNR for the time steps.
|
427 |
+
- 'time_uniform': uniform time for the time steps. (**Recommended for high-resolutional data**.)
|
428 |
+
- 'time_quadratic': quadratic time for the time steps. (Used in DDIM for low-resolutional data.)
|
429 |
+
t_T: A `float`. The starting time of the sampling (default is T).
|
430 |
+
t_0: A `float`. The ending time of the sampling (default is epsilon).
|
431 |
+
device: A torch device.
|
432 |
+
Returns:
|
433 |
+
orders: A list of the solver order of each step.
|
434 |
+
"""
|
435 |
+
if order == 3:
|
436 |
+
K = steps // 3 + 1
|
437 |
+
if steps % 3 == 0:
|
438 |
+
orders = [3, ] * (K - 2) + [2, 1]
|
439 |
+
elif steps % 3 == 1:
|
440 |
+
orders = [3, ] * (K - 1) + [1]
|
441 |
+
else:
|
442 |
+
orders = [3, ] * (K - 1) + [2]
|
443 |
+
elif order == 2:
|
444 |
+
if steps % 2 == 0:
|
445 |
+
K = steps // 2
|
446 |
+
orders = [2, ] * K
|
447 |
+
else:
|
448 |
+
K = steps // 2 + 1
|
449 |
+
orders = [2, ] * (K - 1) + [1]
|
450 |
+
elif order == 1:
|
451 |
+
K = 1
|
452 |
+
orders = [1, ] * steps
|
453 |
+
else:
|
454 |
+
raise ValueError("'order' must be '1' or '2' or '3'.")
|
455 |
+
if skip_type == 'logSNR':
|
456 |
+
# To reproduce the results in DPM-Solver paper
|
457 |
+
timesteps_outer = self.get_time_steps(skip_type, t_T, t_0, K, device)
|
458 |
+
else:
|
459 |
+
timesteps_outer = self.get_time_steps(skip_type, t_T, t_0, steps, device)[
|
460 |
+
torch.cumsum(torch.tensor([0, ] + orders)).to(device)]
|
461 |
+
return timesteps_outer, orders
|
462 |
+
|
463 |
+
def denoise_to_zero_fn(self, x, s):
|
464 |
+
"""
|
465 |
+
Denoise at the final step, which is equivalent to solve the ODE from lambda_s to infty by first-order discretization.
|
466 |
+
"""
|
467 |
+
return self.data_prediction_fn(x, s)
|
468 |
+
|
469 |
+
def dpm_solver_first_update(self, x, s, t, model_s=None, return_intermediate=False):
|
470 |
+
"""
|
471 |
+
DPM-Solver-1 (equivalent to DDIM) from time `s` to time `t`.
|
472 |
+
Args:
|
473 |
+
x: A pytorch tensor. The initial value at time `s`.
|
474 |
+
s: A pytorch tensor. The starting time, with the shape (x.shape[0],).
|
475 |
+
t: A pytorch tensor. The ending time, with the shape (x.shape[0],).
|
476 |
+
model_s: A pytorch tensor. The model function evaluated at time `s`.
|
477 |
+
If `model_s` is None, we evaluate the model by `x` and `s`; otherwise we directly use it.
|
478 |
+
return_intermediate: A `bool`. If true, also return the model value at time `s`.
|
479 |
+
Returns:
|
480 |
+
x_t: A pytorch tensor. The approximated solution at time `t`.
|
481 |
+
"""
|
482 |
+
ns = self.noise_schedule
|
483 |
+
dims = x.dim()
|
484 |
+
lambda_s, lambda_t = ns.marginal_lambda(s), ns.marginal_lambda(t)
|
485 |
+
h = lambda_t - lambda_s
|
486 |
+
log_alpha_s, log_alpha_t = ns.marginal_log_mean_coeff(s), ns.marginal_log_mean_coeff(t)
|
487 |
+
sigma_s, sigma_t = ns.marginal_std(s), ns.marginal_std(t)
|
488 |
+
alpha_t = torch.exp(log_alpha_t)
|
489 |
+
|
490 |
+
if self.predict_x0:
|
491 |
+
phi_1 = torch.expm1(-h)
|
492 |
+
if model_s is None:
|
493 |
+
model_s = self.model_fn(x, s)
|
494 |
+
x_t = (
|
495 |
+
expand_dims(sigma_t / sigma_s, dims) * x
|
496 |
+
- expand_dims(alpha_t * phi_1, dims) * model_s
|
497 |
+
)
|
498 |
+
if return_intermediate:
|
499 |
+
return x_t, {'model_s': model_s}
|
500 |
+
else:
|
501 |
+
return x_t
|
502 |
+
else:
|
503 |
+
phi_1 = torch.expm1(h)
|
504 |
+
if model_s is None:
|
505 |
+
model_s = self.model_fn(x, s)
|
506 |
+
x_t = (
|
507 |
+
expand_dims(torch.exp(log_alpha_t - log_alpha_s), dims) * x
|
508 |
+
- expand_dims(sigma_t * phi_1, dims) * model_s
|
509 |
+
)
|
510 |
+
if return_intermediate:
|
511 |
+
return x_t, {'model_s': model_s}
|
512 |
+
else:
|
513 |
+
return x_t
|
514 |
+
|
515 |
+
def singlestep_dpm_solver_second_update(self, x, s, t, r1=0.5, model_s=None, return_intermediate=False,
|
516 |
+
solver_type='dpm_solver'):
|
517 |
+
"""
|
518 |
+
Singlestep solver DPM-Solver-2 from time `s` to time `t`.
|
519 |
+
Args:
|
520 |
+
x: A pytorch tensor. The initial value at time `s`.
|
521 |
+
s: A pytorch tensor. The starting time, with the shape (x.shape[0],).
|
522 |
+
t: A pytorch tensor. The ending time, with the shape (x.shape[0],).
|
523 |
+
r1: A `float`. The hyperparameter of the second-order solver.
|
524 |
+
model_s: A pytorch tensor. The model function evaluated at time `s`.
|
525 |
+
If `model_s` is None, we evaluate the model by `x` and `s`; otherwise we directly use it.
|
526 |
+
return_intermediate: A `bool`. If true, also return the model value at time `s` and `s1` (the intermediate time).
|
527 |
+
solver_type: either 'dpm_solver' or 'taylor'. The type for the high-order solvers.
|
528 |
+
The type slightly impacts the performance. We recommend to use 'dpm_solver' type.
|
529 |
+
Returns:
|
530 |
+
x_t: A pytorch tensor. The approximated solution at time `t`.
|
531 |
+
"""
|
532 |
+
if solver_type not in ['dpm_solver', 'taylor']:
|
533 |
+
raise ValueError("'solver_type' must be either 'dpm_solver' or 'taylor', got {}".format(solver_type))
|
534 |
+
if r1 is None:
|
535 |
+
r1 = 0.5
|
536 |
+
ns = self.noise_schedule
|
537 |
+
dims = x.dim()
|
538 |
+
lambda_s, lambda_t = ns.marginal_lambda(s), ns.marginal_lambda(t)
|
539 |
+
h = lambda_t - lambda_s
|
540 |
+
lambda_s1 = lambda_s + r1 * h
|
541 |
+
s1 = ns.inverse_lambda(lambda_s1)
|
542 |
+
log_alpha_s, log_alpha_s1, log_alpha_t = ns.marginal_log_mean_coeff(s), ns.marginal_log_mean_coeff(
|
543 |
+
s1), ns.marginal_log_mean_coeff(t)
|
544 |
+
sigma_s, sigma_s1, sigma_t = ns.marginal_std(s), ns.marginal_std(s1), ns.marginal_std(t)
|
545 |
+
alpha_s1, alpha_t = torch.exp(log_alpha_s1), torch.exp(log_alpha_t)
|
546 |
+
|
547 |
+
if self.predict_x0:
|
548 |
+
phi_11 = torch.expm1(-r1 * h)
|
549 |
+
phi_1 = torch.expm1(-h)
|
550 |
+
|
551 |
+
if model_s is None:
|
552 |
+
model_s = self.model_fn(x, s)
|
553 |
+
x_s1 = (
|
554 |
+
expand_dims(sigma_s1 / sigma_s, dims) * x
|
555 |
+
- expand_dims(alpha_s1 * phi_11, dims) * model_s
|
556 |
+
)
|
557 |
+
model_s1 = self.model_fn(x_s1, s1)
|
558 |
+
if solver_type == 'dpm_solver':
|
559 |
+
x_t = (
|
560 |
+
expand_dims(sigma_t / sigma_s, dims) * x
|
561 |
+
- expand_dims(alpha_t * phi_1, dims) * model_s
|
562 |
+
- (0.5 / r1) * expand_dims(alpha_t * phi_1, dims) * (model_s1 - model_s)
|
563 |
+
)
|
564 |
+
elif solver_type == 'taylor':
|
565 |
+
x_t = (
|
566 |
+
expand_dims(sigma_t / sigma_s, dims) * x
|
567 |
+
- expand_dims(alpha_t * phi_1, dims) * model_s
|
568 |
+
+ (1. / r1) * expand_dims(alpha_t * ((torch.exp(-h) - 1.) / h + 1.), dims) * (
|
569 |
+
model_s1 - model_s)
|
570 |
+
)
|
571 |
+
else:
|
572 |
+
phi_11 = torch.expm1(r1 * h)
|
573 |
+
phi_1 = torch.expm1(h)
|
574 |
+
|
575 |
+
if model_s is None:
|
576 |
+
model_s = self.model_fn(x, s)
|
577 |
+
x_s1 = (
|
578 |
+
expand_dims(torch.exp(log_alpha_s1 - log_alpha_s), dims) * x
|
579 |
+
- expand_dims(sigma_s1 * phi_11, dims) * model_s
|
580 |
+
)
|
581 |
+
model_s1 = self.model_fn(x_s1, s1)
|
582 |
+
if solver_type == 'dpm_solver':
|
583 |
+
x_t = (
|
584 |
+
expand_dims(torch.exp(log_alpha_t - log_alpha_s), dims) * x
|
585 |
+
- expand_dims(sigma_t * phi_1, dims) * model_s
|
586 |
+
- (0.5 / r1) * expand_dims(sigma_t * phi_1, dims) * (model_s1 - model_s)
|
587 |
+
)
|
588 |
+
elif solver_type == 'taylor':
|
589 |
+
x_t = (
|
590 |
+
expand_dims(torch.exp(log_alpha_t - log_alpha_s), dims) * x
|
591 |
+
- expand_dims(sigma_t * phi_1, dims) * model_s
|
592 |
+
- (1. / r1) * expand_dims(sigma_t * ((torch.exp(h) - 1.) / h - 1.), dims) * (model_s1 - model_s)
|
593 |
+
)
|
594 |
+
if return_intermediate:
|
595 |
+
return x_t, {'model_s': model_s, 'model_s1': model_s1}
|
596 |
+
else:
|
597 |
+
return x_t
|
598 |
+
|
599 |
+
def singlestep_dpm_solver_third_update(self, x, s, t, r1=1. / 3., r2=2. / 3., model_s=None, model_s1=None,
|
600 |
+
return_intermediate=False, solver_type='dpm_solver'):
|
601 |
+
"""
|
602 |
+
Singlestep solver DPM-Solver-3 from time `s` to time `t`.
|
603 |
+
Args:
|
604 |
+
x: A pytorch tensor. The initial value at time `s`.
|
605 |
+
s: A pytorch tensor. The starting time, with the shape (x.shape[0],).
|
606 |
+
t: A pytorch tensor. The ending time, with the shape (x.shape[0],).
|
607 |
+
r1: A `float`. The hyperparameter of the third-order solver.
|
608 |
+
r2: A `float`. The hyperparameter of the third-order solver.
|
609 |
+
model_s: A pytorch tensor. The model function evaluated at time `s`.
|
610 |
+
If `model_s` is None, we evaluate the model by `x` and `s`; otherwise we directly use it.
|
611 |
+
model_s1: A pytorch tensor. The model function evaluated at time `s1` (the intermediate time given by `r1`).
|
612 |
+
If `model_s1` is None, we evaluate the model at `s1`; otherwise we directly use it.
|
613 |
+
return_intermediate: A `bool`. If true, also return the model value at time `s`, `s1` and `s2` (the intermediate times).
|
614 |
+
solver_type: either 'dpm_solver' or 'taylor'. The type for the high-order solvers.
|
615 |
+
The type slightly impacts the performance. We recommend to use 'dpm_solver' type.
|
616 |
+
Returns:
|
617 |
+
x_t: A pytorch tensor. The approximated solution at time `t`.
|
618 |
+
"""
|
619 |
+
if solver_type not in ['dpm_solver', 'taylor']:
|
620 |
+
raise ValueError("'solver_type' must be either 'dpm_solver' or 'taylor', got {}".format(solver_type))
|
621 |
+
if r1 is None:
|
622 |
+
r1 = 1. / 3.
|
623 |
+
if r2 is None:
|
624 |
+
r2 = 2. / 3.
|
625 |
+
ns = self.noise_schedule
|
626 |
+
dims = x.dim()
|
627 |
+
lambda_s, lambda_t = ns.marginal_lambda(s), ns.marginal_lambda(t)
|
628 |
+
h = lambda_t - lambda_s
|
629 |
+
lambda_s1 = lambda_s + r1 * h
|
630 |
+
lambda_s2 = lambda_s + r2 * h
|
631 |
+
s1 = ns.inverse_lambda(lambda_s1)
|
632 |
+
s2 = ns.inverse_lambda(lambda_s2)
|
633 |
+
log_alpha_s, log_alpha_s1, log_alpha_s2, log_alpha_t = ns.marginal_log_mean_coeff(
|
634 |
+
s), ns.marginal_log_mean_coeff(s1), ns.marginal_log_mean_coeff(s2), ns.marginal_log_mean_coeff(t)
|
635 |
+
sigma_s, sigma_s1, sigma_s2, sigma_t = ns.marginal_std(s), ns.marginal_std(s1), ns.marginal_std(
|
636 |
+
s2), ns.marginal_std(t)
|
637 |
+
alpha_s1, alpha_s2, alpha_t = torch.exp(log_alpha_s1), torch.exp(log_alpha_s2), torch.exp(log_alpha_t)
|
638 |
+
|
639 |
+
if self.predict_x0:
|
640 |
+
phi_11 = torch.expm1(-r1 * h)
|
641 |
+
phi_12 = torch.expm1(-r2 * h)
|
642 |
+
phi_1 = torch.expm1(-h)
|
643 |
+
phi_22 = torch.expm1(-r2 * h) / (r2 * h) + 1.
|
644 |
+
phi_2 = phi_1 / h + 1.
|
645 |
+
phi_3 = phi_2 / h - 0.5
|
646 |
+
|
647 |
+
if model_s is None:
|
648 |
+
model_s = self.model_fn(x, s)
|
649 |
+
if model_s1 is None:
|
650 |
+
x_s1 = (
|
651 |
+
expand_dims(sigma_s1 / sigma_s, dims) * x
|
652 |
+
- expand_dims(alpha_s1 * phi_11, dims) * model_s
|
653 |
+
)
|
654 |
+
model_s1 = self.model_fn(x_s1, s1)
|
655 |
+
x_s2 = (
|
656 |
+
expand_dims(sigma_s2 / sigma_s, dims) * x
|
657 |
+
- expand_dims(alpha_s2 * phi_12, dims) * model_s
|
658 |
+
+ r2 / r1 * expand_dims(alpha_s2 * phi_22, dims) * (model_s1 - model_s)
|
659 |
+
)
|
660 |
+
model_s2 = self.model_fn(x_s2, s2)
|
661 |
+
if solver_type == 'dpm_solver':
|
662 |
+
x_t = (
|
663 |
+
expand_dims(sigma_t / sigma_s, dims) * x
|
664 |
+
- expand_dims(alpha_t * phi_1, dims) * model_s
|
665 |
+
+ (1. / r2) * expand_dims(alpha_t * phi_2, dims) * (model_s2 - model_s)
|
666 |
+
)
|
667 |
+
elif solver_type == 'taylor':
|
668 |
+
D1_0 = (1. / r1) * (model_s1 - model_s)
|
669 |
+
D1_1 = (1. / r2) * (model_s2 - model_s)
|
670 |
+
D1 = (r2 * D1_0 - r1 * D1_1) / (r2 - r1)
|
671 |
+
D2 = 2. * (D1_1 - D1_0) / (r2 - r1)
|
672 |
+
x_t = (
|
673 |
+
expand_dims(sigma_t / sigma_s, dims) * x
|
674 |
+
- expand_dims(alpha_t * phi_1, dims) * model_s
|
675 |
+
+ expand_dims(alpha_t * phi_2, dims) * D1
|
676 |
+
- expand_dims(alpha_t * phi_3, dims) * D2
|
677 |
+
)
|
678 |
+
else:
|
679 |
+
phi_11 = torch.expm1(r1 * h)
|
680 |
+
phi_12 = torch.expm1(r2 * h)
|
681 |
+
phi_1 = torch.expm1(h)
|
682 |
+
phi_22 = torch.expm1(r2 * h) / (r2 * h) - 1.
|
683 |
+
phi_2 = phi_1 / h - 1.
|
684 |
+
phi_3 = phi_2 / h - 0.5
|
685 |
+
|
686 |
+
if model_s is None:
|
687 |
+
model_s = self.model_fn(x, s)
|
688 |
+
if model_s1 is None:
|
689 |
+
x_s1 = (
|
690 |
+
expand_dims(torch.exp(log_alpha_s1 - log_alpha_s), dims) * x
|
691 |
+
- expand_dims(sigma_s1 * phi_11, dims) * model_s
|
692 |
+
)
|
693 |
+
model_s1 = self.model_fn(x_s1, s1)
|
694 |
+
x_s2 = (
|
695 |
+
expand_dims(torch.exp(log_alpha_s2 - log_alpha_s), dims) * x
|
696 |
+
- expand_dims(sigma_s2 * phi_12, dims) * model_s
|
697 |
+
- r2 / r1 * expand_dims(sigma_s2 * phi_22, dims) * (model_s1 - model_s)
|
698 |
+
)
|
699 |
+
model_s2 = self.model_fn(x_s2, s2)
|
700 |
+
if solver_type == 'dpm_solver':
|
701 |
+
x_t = (
|
702 |
+
expand_dims(torch.exp(log_alpha_t - log_alpha_s), dims) * x
|
703 |
+
- expand_dims(sigma_t * phi_1, dims) * model_s
|
704 |
+
- (1. / r2) * expand_dims(sigma_t * phi_2, dims) * (model_s2 - model_s)
|
705 |
+
)
|
706 |
+
elif solver_type == 'taylor':
|
707 |
+
D1_0 = (1. / r1) * (model_s1 - model_s)
|
708 |
+
D1_1 = (1. / r2) * (model_s2 - model_s)
|
709 |
+
D1 = (r2 * D1_0 - r1 * D1_1) / (r2 - r1)
|
710 |
+
D2 = 2. * (D1_1 - D1_0) / (r2 - r1)
|
711 |
+
x_t = (
|
712 |
+
expand_dims(torch.exp(log_alpha_t - log_alpha_s), dims) * x
|
713 |
+
- expand_dims(sigma_t * phi_1, dims) * model_s
|
714 |
+
- expand_dims(sigma_t * phi_2, dims) * D1
|
715 |
+
- expand_dims(sigma_t * phi_3, dims) * D2
|
716 |
+
)
|
717 |
+
|
718 |
+
if return_intermediate:
|
719 |
+
return x_t, {'model_s': model_s, 'model_s1': model_s1, 'model_s2': model_s2}
|
720 |
+
else:
|
721 |
+
return x_t
|
722 |
+
|
723 |
+
def multistep_dpm_solver_second_update(self, x, model_prev_list, t_prev_list, t, solver_type="dpm_solver"):
|
724 |
+
"""
|
725 |
+
Multistep solver DPM-Solver-2 from time `t_prev_list[-1]` to time `t`.
|
726 |
+
Args:
|
727 |
+
x: A pytorch tensor. The initial value at time `s`.
|
728 |
+
model_prev_list: A list of pytorch tensor. The previous computed model values.
|
729 |
+
t_prev_list: A list of pytorch tensor. The previous times, each time has the shape (x.shape[0],)
|
730 |
+
t: A pytorch tensor. The ending time, with the shape (x.shape[0],).
|
731 |
+
solver_type: either 'dpm_solver' or 'taylor'. The type for the high-order solvers.
|
732 |
+
The type slightly impacts the performance. We recommend to use 'dpm_solver' type.
|
733 |
+
Returns:
|
734 |
+
x_t: A pytorch tensor. The approximated solution at time `t`.
|
735 |
+
"""
|
736 |
+
if solver_type not in ['dpm_solver', 'taylor']:
|
737 |
+
raise ValueError("'solver_type' must be either 'dpm_solver' or 'taylor', got {}".format(solver_type))
|
738 |
+
ns = self.noise_schedule
|
739 |
+
dims = x.dim()
|
740 |
+
model_prev_1, model_prev_0 = model_prev_list
|
741 |
+
t_prev_1, t_prev_0 = t_prev_list
|
742 |
+
lambda_prev_1, lambda_prev_0, lambda_t = ns.marginal_lambda(t_prev_1), ns.marginal_lambda(
|
743 |
+
t_prev_0), ns.marginal_lambda(t)
|
744 |
+
log_alpha_prev_0, log_alpha_t = ns.marginal_log_mean_coeff(t_prev_0), ns.marginal_log_mean_coeff(t)
|
745 |
+
sigma_prev_0, sigma_t = ns.marginal_std(t_prev_0), ns.marginal_std(t)
|
746 |
+
alpha_t = torch.exp(log_alpha_t)
|
747 |
+
|
748 |
+
h_0 = lambda_prev_0 - lambda_prev_1
|
749 |
+
h = lambda_t - lambda_prev_0
|
750 |
+
r0 = h_0 / h
|
751 |
+
D1_0 = expand_dims(1. / r0, dims) * (model_prev_0 - model_prev_1)
|
752 |
+
if self.predict_x0:
|
753 |
+
if solver_type == 'dpm_solver':
|
754 |
+
x_t = (
|
755 |
+
expand_dims(sigma_t / sigma_prev_0, dims) * x
|
756 |
+
- expand_dims(alpha_t * (torch.exp(-h) - 1.), dims) * model_prev_0
|
757 |
+
- 0.5 * expand_dims(alpha_t * (torch.exp(-h) - 1.), dims) * D1_0
|
758 |
+
)
|
759 |
+
elif solver_type == 'taylor':
|
760 |
+
x_t = (
|
761 |
+
expand_dims(sigma_t / sigma_prev_0, dims) * x
|
762 |
+
- expand_dims(alpha_t * (torch.exp(-h) - 1.), dims) * model_prev_0
|
763 |
+
+ expand_dims(alpha_t * ((torch.exp(-h) - 1.) / h + 1.), dims) * D1_0
|
764 |
+
)
|
765 |
+
else:
|
766 |
+
if solver_type == 'dpm_solver':
|
767 |
+
x_t = (
|
768 |
+
expand_dims(torch.exp(log_alpha_t - log_alpha_prev_0), dims) * x
|
769 |
+
- expand_dims(sigma_t * (torch.exp(h) - 1.), dims) * model_prev_0
|
770 |
+
- 0.5 * expand_dims(sigma_t * (torch.exp(h) - 1.), dims) * D1_0
|
771 |
+
)
|
772 |
+
elif solver_type == 'taylor':
|
773 |
+
x_t = (
|
774 |
+
expand_dims(torch.exp(log_alpha_t - log_alpha_prev_0), dims) * x
|
775 |
+
- expand_dims(sigma_t * (torch.exp(h) - 1.), dims) * model_prev_0
|
776 |
+
- expand_dims(sigma_t * ((torch.exp(h) - 1.) / h - 1.), dims) * D1_0
|
777 |
+
)
|
778 |
+
return x_t
|
779 |
+
|
780 |
+
def multistep_dpm_solver_third_update(self, x, model_prev_list, t_prev_list, t, solver_type='dpm_solver'):
|
781 |
+
"""
|
782 |
+
Multistep solver DPM-Solver-3 from time `t_prev_list[-1]` to time `t`.
|
783 |
+
Args:
|
784 |
+
x: A pytorch tensor. The initial value at time `s`.
|
785 |
+
model_prev_list: A list of pytorch tensor. The previous computed model values.
|
786 |
+
t_prev_list: A list of pytorch tensor. The previous times, each time has the shape (x.shape[0],)
|
787 |
+
t: A pytorch tensor. The ending time, with the shape (x.shape[0],).
|
788 |
+
solver_type: either 'dpm_solver' or 'taylor'. The type for the high-order solvers.
|
789 |
+
The type slightly impacts the performance. We recommend to use 'dpm_solver' type.
|
790 |
+
Returns:
|
791 |
+
x_t: A pytorch tensor. The approximated solution at time `t`.
|
792 |
+
"""
|
793 |
+
ns = self.noise_schedule
|
794 |
+
dims = x.dim()
|
795 |
+
model_prev_2, model_prev_1, model_prev_0 = model_prev_list
|
796 |
+
t_prev_2, t_prev_1, t_prev_0 = t_prev_list
|
797 |
+
lambda_prev_2, lambda_prev_1, lambda_prev_0, lambda_t = ns.marginal_lambda(t_prev_2), ns.marginal_lambda(
|
798 |
+
t_prev_1), ns.marginal_lambda(t_prev_0), ns.marginal_lambda(t)
|
799 |
+
log_alpha_prev_0, log_alpha_t = ns.marginal_log_mean_coeff(t_prev_0), ns.marginal_log_mean_coeff(t)
|
800 |
+
sigma_prev_0, sigma_t = ns.marginal_std(t_prev_0), ns.marginal_std(t)
|
801 |
+
alpha_t = torch.exp(log_alpha_t)
|
802 |
+
|
803 |
+
h_1 = lambda_prev_1 - lambda_prev_2
|
804 |
+
h_0 = lambda_prev_0 - lambda_prev_1
|
805 |
+
h = lambda_t - lambda_prev_0
|
806 |
+
r0, r1 = h_0 / h, h_1 / h
|
807 |
+
D1_0 = expand_dims(1. / r0, dims) * (model_prev_0 - model_prev_1)
|
808 |
+
D1_1 = expand_dims(1. / r1, dims) * (model_prev_1 - model_prev_2)
|
809 |
+
D1 = D1_0 + expand_dims(r0 / (r0 + r1), dims) * (D1_0 - D1_1)
|
810 |
+
D2 = expand_dims(1. / (r0 + r1), dims) * (D1_0 - D1_1)
|
811 |
+
if self.predict_x0:
|
812 |
+
x_t = (
|
813 |
+
expand_dims(sigma_t / sigma_prev_0, dims) * x
|
814 |
+
- expand_dims(alpha_t * (torch.exp(-h) - 1.), dims) * model_prev_0
|
815 |
+
+ expand_dims(alpha_t * ((torch.exp(-h) - 1.) / h + 1.), dims) * D1
|
816 |
+
- expand_dims(alpha_t * ((torch.exp(-h) - 1. + h) / h ** 2 - 0.5), dims) * D2
|
817 |
+
)
|
818 |
+
else:
|
819 |
+
x_t = (
|
820 |
+
expand_dims(torch.exp(log_alpha_t - log_alpha_prev_0), dims) * x
|
821 |
+
- expand_dims(sigma_t * (torch.exp(h) - 1.), dims) * model_prev_0
|
822 |
+
- expand_dims(sigma_t * ((torch.exp(h) - 1.) / h - 1.), dims) * D1
|
823 |
+
- expand_dims(sigma_t * ((torch.exp(h) - 1. - h) / h ** 2 - 0.5), dims) * D2
|
824 |
+
)
|
825 |
+
return x_t
|
826 |
+
|
827 |
+
def singlestep_dpm_solver_update(self, x, s, t, order, return_intermediate=False, solver_type='dpm_solver', r1=None,
|
828 |
+
r2=None):
|
829 |
+
"""
|
830 |
+
Singlestep DPM-Solver with the order `order` from time `s` to time `t`.
|
831 |
+
Args:
|
832 |
+
x: A pytorch tensor. The initial value at time `s`.
|
833 |
+
s: A pytorch tensor. The starting time, with the shape (x.shape[0],).
|
834 |
+
t: A pytorch tensor. The ending time, with the shape (x.shape[0],).
|
835 |
+
order: A `int`. The order of DPM-Solver. We only support order == 1 or 2 or 3.
|
836 |
+
return_intermediate: A `bool`. If true, also return the model value at time `s`, `s1` and `s2` (the intermediate times).
|
837 |
+
solver_type: either 'dpm_solver' or 'taylor'. The type for the high-order solvers.
|
838 |
+
The type slightly impacts the performance. We recommend to use 'dpm_solver' type.
|
839 |
+
r1: A `float`. The hyperparameter of the second-order or third-order solver.
|
840 |
+
r2: A `float`. The hyperparameter of the third-order solver.
|
841 |
+
Returns:
|
842 |
+
x_t: A pytorch tensor. The approximated solution at time `t`.
|
843 |
+
"""
|
844 |
+
if order == 1:
|
845 |
+
return self.dpm_solver_first_update(x, s, t, return_intermediate=return_intermediate)
|
846 |
+
elif order == 2:
|
847 |
+
return self.singlestep_dpm_solver_second_update(x, s, t, return_intermediate=return_intermediate,
|
848 |
+
solver_type=solver_type, r1=r1)
|
849 |
+
elif order == 3:
|
850 |
+
return self.singlestep_dpm_solver_third_update(x, s, t, return_intermediate=return_intermediate,
|
851 |
+
solver_type=solver_type, r1=r1, r2=r2)
|
852 |
+
else:
|
853 |
+
raise ValueError("Solver order must be 1 or 2 or 3, got {}".format(order))
|
854 |
+
|
855 |
+
def multistep_dpm_solver_update(self, x, model_prev_list, t_prev_list, t, order, solver_type='dpm_solver'):
|
856 |
+
"""
|
857 |
+
Multistep DPM-Solver with the order `order` from time `t_prev_list[-1]` to time `t`.
|
858 |
+
Args:
|
859 |
+
x: A pytorch tensor. The initial value at time `s`.
|
860 |
+
model_prev_list: A list of pytorch tensor. The previous computed model values.
|
861 |
+
t_prev_list: A list of pytorch tensor. The previous times, each time has the shape (x.shape[0],)
|
862 |
+
t: A pytorch tensor. The ending time, with the shape (x.shape[0],).
|
863 |
+
order: A `int`. The order of DPM-Solver. We only support order == 1 or 2 or 3.
|
864 |
+
solver_type: either 'dpm_solver' or 'taylor'. The type for the high-order solvers.
|
865 |
+
The type slightly impacts the performance. We recommend to use 'dpm_solver' type.
|
866 |
+
Returns:
|
867 |
+
x_t: A pytorch tensor. The approximated solution at time `t`.
|
868 |
+
"""
|
869 |
+
if order == 1:
|
870 |
+
return self.dpm_solver_first_update(x, t_prev_list[-1], t, model_s=model_prev_list[-1])
|
871 |
+
elif order == 2:
|
872 |
+
return self.multistep_dpm_solver_second_update(x, model_prev_list, t_prev_list, t, solver_type=solver_type)
|
873 |
+
elif order == 3:
|
874 |
+
return self.multistep_dpm_solver_third_update(x, model_prev_list, t_prev_list, t, solver_type=solver_type)
|
875 |
+
else:
|
876 |
+
raise ValueError("Solver order must be 1 or 2 or 3, got {}".format(order))
|
877 |
+
|
878 |
+
def dpm_solver_adaptive(self, x, order, t_T, t_0, h_init=0.05, atol=0.0078, rtol=0.05, theta=0.9, t_err=1e-5,
|
879 |
+
solver_type='dpm_solver'):
|
880 |
+
"""
|
881 |
+
The adaptive step size solver based on singlestep DPM-Solver.
|
882 |
+
Args:
|
883 |
+
x: A pytorch tensor. The initial value at time `t_T`.
|
884 |
+
order: A `int`. The (higher) order of the solver. We only support order == 2 or 3.
|
885 |
+
t_T: A `float`. The starting time of the sampling (default is T).
|
886 |
+
t_0: A `float`. The ending time of the sampling (default is epsilon).
|
887 |
+
h_init: A `float`. The initial step size (for logSNR).
|
888 |
+
atol: A `float`. The absolute tolerance of the solver. For image data, the default setting is 0.0078, followed [1].
|
889 |
+
rtol: A `float`. The relative tolerance of the solver. The default setting is 0.05.
|
890 |
+
theta: A `float`. The safety hyperparameter for adapting the step size. The default setting is 0.9, followed [1].
|
891 |
+
t_err: A `float`. The tolerance for the time. We solve the diffusion ODE until the absolute error between the
|
892 |
+
current time and `t_0` is less than `t_err`. The default setting is 1e-5.
|
893 |
+
solver_type: either 'dpm_solver' or 'taylor'. The type for the high-order solvers.
|
894 |
+
The type slightly impacts the performance. We recommend to use 'dpm_solver' type.
|
895 |
+
Returns:
|
896 |
+
x_0: A pytorch tensor. The approximated solution at time `t_0`.
|
897 |
+
[1] A. Jolicoeur-Martineau, K. Li, R. Piché-Taillefer, T. Kachman, and I. Mitliagkas, "Gotta go fast when generating data with score-based models," arXiv preprint arXiv:2105.14080, 2021.
|
898 |
+
"""
|
899 |
+
ns = self.noise_schedule
|
900 |
+
s = t_T * torch.ones((x.shape[0],)).to(x)
|
901 |
+
lambda_s = ns.marginal_lambda(s)
|
902 |
+
lambda_0 = ns.marginal_lambda(t_0 * torch.ones_like(s).to(x))
|
903 |
+
h = h_init * torch.ones_like(s).to(x)
|
904 |
+
x_prev = x
|
905 |
+
nfe = 0
|
906 |
+
if order == 2:
|
907 |
+
r1 = 0.5
|
908 |
+
lower_update = lambda x, s, t: self.dpm_solver_first_update(x, s, t, return_intermediate=True)
|
909 |
+
higher_update = lambda x, s, t, **kwargs: self.singlestep_dpm_solver_second_update(x, s, t, r1=r1,
|
910 |
+
solver_type=solver_type,
|
911 |
+
**kwargs)
|
912 |
+
elif order == 3:
|
913 |
+
r1, r2 = 1. / 3., 2. / 3.
|
914 |
+
lower_update = lambda x, s, t: self.singlestep_dpm_solver_second_update(x, s, t, r1=r1,
|
915 |
+
return_intermediate=True,
|
916 |
+
solver_type=solver_type)
|
917 |
+
higher_update = lambda x, s, t, **kwargs: self.singlestep_dpm_solver_third_update(x, s, t, r1=r1, r2=r2,
|
918 |
+
solver_type=solver_type,
|
919 |
+
**kwargs)
|
920 |
+
else:
|
921 |
+
raise ValueError("For adaptive step size solver, order must be 2 or 3, got {}".format(order))
|
922 |
+
while torch.abs((s - t_0)).mean() > t_err:
|
923 |
+
t = ns.inverse_lambda(lambda_s + h)
|
924 |
+
x_lower, lower_noise_kwargs = lower_update(x, s, t)
|
925 |
+
x_higher = higher_update(x, s, t, **lower_noise_kwargs)
|
926 |
+
delta = torch.max(torch.ones_like(x).to(x) * atol, rtol * torch.max(torch.abs(x_lower), torch.abs(x_prev)))
|
927 |
+
norm_fn = lambda v: torch.sqrt(torch.square(v.reshape((v.shape[0], -1))).mean(dim=-1, keepdim=True))
|
928 |
+
E = norm_fn((x_higher - x_lower) / delta).max()
|
929 |
+
if torch.all(E <= 1.):
|
930 |
+
x = x_higher
|
931 |
+
s = t
|
932 |
+
x_prev = x_lower
|
933 |
+
lambda_s = ns.marginal_lambda(s)
|
934 |
+
h = torch.min(theta * h * torch.float_power(E, -1. / order).float(), lambda_0 - lambda_s)
|
935 |
+
nfe += order
|
936 |
+
print('adaptive solver nfe', nfe)
|
937 |
+
return x
|
938 |
+
|
939 |
+
def sample(self, x, steps=20, t_start=None, t_end=None, order=3, skip_type='time_uniform',
|
940 |
+
method='singlestep', lower_order_final=True, denoise_to_zero=False, solver_type='dpm_solver',
|
941 |
+
atol=0.0078, rtol=0.05,
|
942 |
+
):
|
943 |
+
"""
|
944 |
+
Compute the sample at time `t_end` by DPM-Solver, given the initial `x` at time `t_start`.
|
945 |
+
=====================================================
|
946 |
+
We support the following algorithms for both noise prediction model and data prediction model:
|
947 |
+
- 'singlestep':
|
948 |
+
Singlestep DPM-Solver (i.e. "DPM-Solver-fast" in the paper), which combines different orders of singlestep DPM-Solver.
|
949 |
+
We combine all the singlestep solvers with order <= `order` to use up all the function evaluations (steps).
|
950 |
+
The total number of function evaluations (NFE) == `steps`.
|
951 |
+
Given a fixed NFE == `steps`, the sampling procedure is:
|
952 |
+
- If `order` == 1:
|
953 |
+
- Denote K = steps. We use K steps of DPM-Solver-1 (i.e. DDIM).
|
954 |
+
- If `order` == 2:
|
955 |
+
- Denote K = (steps // 2) + (steps % 2). We take K intermediate time steps for sampling.
|
956 |
+
- If steps % 2 == 0, we use K steps of singlestep DPM-Solver-2.
|
957 |
+
- If steps % 2 == 1, we use (K - 1) steps of singlestep DPM-Solver-2 and 1 step of DPM-Solver-1.
|
958 |
+
- If `order` == 3:
|
959 |
+
- Denote K = (steps // 3 + 1). We take K intermediate time steps for sampling.
|
960 |
+
- If steps % 3 == 0, we use (K - 2) steps of singlestep DPM-Solver-3, and 1 step of singlestep DPM-Solver-2 and 1 step of DPM-Solver-1.
|
961 |
+
- If steps % 3 == 1, we use (K - 1) steps of singlestep DPM-Solver-3 and 1 step of DPM-Solver-1.
|
962 |
+
- If steps % 3 == 2, we use (K - 1) steps of singlestep DPM-Solver-3 and 1 step of singlestep DPM-Solver-2.
|
963 |
+
- 'multistep':
|
964 |
+
Multistep DPM-Solver with the order of `order`. The total number of function evaluations (NFE) == `steps`.
|
965 |
+
We initialize the first `order` values by lower order multistep solvers.
|
966 |
+
Given a fixed NFE == `steps`, the sampling procedure is:
|
967 |
+
Denote K = steps.
|
968 |
+
- If `order` == 1:
|
969 |
+
- We use K steps of DPM-Solver-1 (i.e. DDIM).
|
970 |
+
- If `order` == 2:
|
971 |
+
- We firstly use 1 step of DPM-Solver-1, then use (K - 1) step of multistep DPM-Solver-2.
|
972 |
+
- If `order` == 3:
|
973 |
+
- We firstly use 1 step of DPM-Solver-1, then 1 step of multistep DPM-Solver-2, then (K - 2) step of multistep DPM-Solver-3.
|
974 |
+
- 'singlestep_fixed':
|
975 |
+
Fixed order singlestep DPM-Solver (i.e. DPM-Solver-1 or singlestep DPM-Solver-2 or singlestep DPM-Solver-3).
|
976 |
+
We use singlestep DPM-Solver-`order` for `order`=1 or 2 or 3, with total [`steps` // `order`] * `order` NFE.
|
977 |
+
- 'adaptive':
|
978 |
+
Adaptive step size DPM-Solver (i.e. "DPM-Solver-12" and "DPM-Solver-23" in the paper).
|
979 |
+
We ignore `steps` and use adaptive step size DPM-Solver with a higher order of `order`.
|
980 |
+
You can adjust the absolute tolerance `atol` and the relative tolerance `rtol` to balance the computatation costs
|
981 |
+
(NFE) and the sample quality.
|
982 |
+
- If `order` == 2, we use DPM-Solver-12 which combines DPM-Solver-1 and singlestep DPM-Solver-2.
|
983 |
+
- If `order` == 3, we use DPM-Solver-23 which combines singlestep DPM-Solver-2 and singlestep DPM-Solver-3.
|
984 |
+
=====================================================
|
985 |
+
Some advices for choosing the algorithm:
|
986 |
+
- For **unconditional sampling** or **guided sampling with small guidance scale** by DPMs:
|
987 |
+
Use singlestep DPM-Solver ("DPM-Solver-fast" in the paper) with `order = 3`.
|
988 |
+
e.g.
|
989 |
+
>>> dpm_solver = DPM_Solver(model_fn, noise_schedule, predict_x0=False)
|
990 |
+
>>> x_sample = dpm_solver.sample(x, steps=steps, t_start=t_start, t_end=t_end, order=3,
|
991 |
+
skip_type='time_uniform', method='singlestep')
|
992 |
+
- For **guided sampling with large guidance scale** by DPMs:
|
993 |
+
Use multistep DPM-Solver with `predict_x0 = True` and `order = 2`.
|
994 |
+
e.g.
|
995 |
+
>>> dpm_solver = DPM_Solver(model_fn, noise_schedule, predict_x0=True)
|
996 |
+
>>> x_sample = dpm_solver.sample(x, steps=steps, t_start=t_start, t_end=t_end, order=2,
|
997 |
+
skip_type='time_uniform', method='multistep')
|
998 |
+
We support three types of `skip_type`:
|
999 |
+
- 'logSNR': uniform logSNR for the time steps. **Recommended for low-resolutional images**
|
1000 |
+
- 'time_uniform': uniform time for the time steps. **Recommended for high-resolutional images**.
|
1001 |
+
- 'time_quadratic': quadratic time for the time steps.
|
1002 |
+
=====================================================
|
1003 |
+
Args:
|
1004 |
+
x: A pytorch tensor. The initial value at time `t_start`
|
1005 |
+
e.g. if `t_start` == T, then `x` is a sample from the standard normal distribution.
|
1006 |
+
steps: A `int`. The total number of function evaluations (NFE).
|
1007 |
+
t_start: A `float`. The starting time of the sampling.
|
1008 |
+
If `T` is None, we use self.noise_schedule.T (default is 1.0).
|
1009 |
+
t_end: A `float`. The ending time of the sampling.
|
1010 |
+
If `t_end` is None, we use 1. / self.noise_schedule.total_N.
|
1011 |
+
e.g. if total_N == 1000, we have `t_end` == 1e-3.
|
1012 |
+
For discrete-time DPMs:
|
1013 |
+
- We recommend `t_end` == 1. / self.noise_schedule.total_N.
|
1014 |
+
For continuous-time DPMs:
|
1015 |
+
- We recommend `t_end` == 1e-3 when `steps` <= 15; and `t_end` == 1e-4 when `steps` > 15.
|
1016 |
+
order: A `int`. The order of DPM-Solver.
|
1017 |
+
skip_type: A `str`. The type for the spacing of the time steps. 'time_uniform' or 'logSNR' or 'time_quadratic'.
|
1018 |
+
method: A `str`. The method for sampling. 'singlestep' or 'multistep' or 'singlestep_fixed' or 'adaptive'.
|
1019 |
+
denoise_to_zero: A `bool`. Whether to denoise to time 0 at the final step.
|
1020 |
+
Default is `False`. If `denoise_to_zero` is `True`, the total NFE is (`steps` + 1).
|
1021 |
+
This trick is firstly proposed by DDPM (https://arxiv.org/abs/2006.11239) and
|
1022 |
+
score_sde (https://arxiv.org/abs/2011.13456). Such trick can improve the FID
|
1023 |
+
for diffusion models sampling by diffusion SDEs for low-resolutional images
|
1024 |
+
(such as CIFAR-10). However, we observed that such trick does not matter for
|
1025 |
+
high-resolutional images. As it needs an additional NFE, we do not recommend
|
1026 |
+
it for high-resolutional images.
|
1027 |
+
lower_order_final: A `bool`. Whether to use lower order solvers at the final steps.
|
1028 |
+
Only valid for `method=multistep` and `steps < 15`. We empirically find that
|
1029 |
+
this trick is a key to stabilizing the sampling by DPM-Solver with very few steps
|
1030 |
+
(especially for steps <= 10). So we recommend to set it to be `True`.
|
1031 |
+
solver_type: A `str`. The taylor expansion type for the solver. `dpm_solver` or `taylor`. We recommend `dpm_solver`.
|
1032 |
+
atol: A `float`. The absolute tolerance of the adaptive step size solver. Valid when `method` == 'adaptive'.
|
1033 |
+
rtol: A `float`. The relative tolerance of the adaptive step size solver. Valid when `method` == 'adaptive'.
|
1034 |
+
Returns:
|
1035 |
+
x_end: A pytorch tensor. The approximated solution at time `t_end`.
|
1036 |
+
"""
|
1037 |
+
t_0 = 1. / self.noise_schedule.total_N if t_end is None else t_end
|
1038 |
+
t_T = self.noise_schedule.T if t_start is None else t_start
|
1039 |
+
device = x.device
|
1040 |
+
if method == 'adaptive':
|
1041 |
+
with torch.no_grad():
|
1042 |
+
x = self.dpm_solver_adaptive(x, order=order, t_T=t_T, t_0=t_0, atol=atol, rtol=rtol,
|
1043 |
+
solver_type=solver_type)
|
1044 |
+
elif method == 'multistep':
|
1045 |
+
assert steps >= order
|
1046 |
+
timesteps = self.get_time_steps(skip_type=skip_type, t_T=t_T, t_0=t_0, N=steps, device=device)
|
1047 |
+
assert timesteps.shape[0] - 1 == steps
|
1048 |
+
with torch.no_grad():
|
1049 |
+
vec_t = timesteps[0].expand((x.shape[0]))
|
1050 |
+
model_prev_list = [self.model_fn(x, vec_t)]
|
1051 |
+
t_prev_list = [vec_t]
|
1052 |
+
# Init the first `order` values by lower order multistep DPM-Solver.
|
1053 |
+
for init_order in tqdm(range(1, order), desc="DPM init order"):
|
1054 |
+
vec_t = timesteps[init_order].expand(x.shape[0])
|
1055 |
+
x = self.multistep_dpm_solver_update(x, model_prev_list, t_prev_list, vec_t, init_order,
|
1056 |
+
solver_type=solver_type)
|
1057 |
+
model_prev_list.append(self.model_fn(x, vec_t))
|
1058 |
+
t_prev_list.append(vec_t)
|
1059 |
+
# Compute the remaining values by `order`-th order multistep DPM-Solver.
|
1060 |
+
for step in tqdm(range(order, steps + 1), desc="DPM multistep"):
|
1061 |
+
vec_t = timesteps[step].expand(x.shape[0])
|
1062 |
+
if lower_order_final and steps < 15:
|
1063 |
+
step_order = min(order, steps + 1 - step)
|
1064 |
+
else:
|
1065 |
+
step_order = order
|
1066 |
+
x = self.multistep_dpm_solver_update(x, model_prev_list, t_prev_list, vec_t, step_order,
|
1067 |
+
solver_type=solver_type)
|
1068 |
+
for i in range(order - 1):
|
1069 |
+
t_prev_list[i] = t_prev_list[i + 1]
|
1070 |
+
model_prev_list[i] = model_prev_list[i + 1]
|
1071 |
+
t_prev_list[-1] = vec_t
|
1072 |
+
# We do not need to evaluate the final model value.
|
1073 |
+
if step < steps:
|
1074 |
+
model_prev_list[-1] = self.model_fn(x, vec_t)
|
1075 |
+
elif method in ['singlestep', 'singlestep_fixed']:
|
1076 |
+
if method == 'singlestep':
|
1077 |
+
timesteps_outer, orders = self.get_orders_and_timesteps_for_singlestep_solver(steps=steps, order=order,
|
1078 |
+
skip_type=skip_type,
|
1079 |
+
t_T=t_T, t_0=t_0,
|
1080 |
+
device=device)
|
1081 |
+
elif method == 'singlestep_fixed':
|
1082 |
+
K = steps // order
|
1083 |
+
orders = [order, ] * K
|
1084 |
+
timesteps_outer = self.get_time_steps(skip_type=skip_type, t_T=t_T, t_0=t_0, N=K, device=device)
|
1085 |
+
for i, order in enumerate(orders):
|
1086 |
+
t_T_inner, t_0_inner = timesteps_outer[i], timesteps_outer[i + 1]
|
1087 |
+
timesteps_inner = self.get_time_steps(skip_type=skip_type, t_T=t_T_inner.item(), t_0=t_0_inner.item(),
|
1088 |
+
N=order, device=device)
|
1089 |
+
lambda_inner = self.noise_schedule.marginal_lambda(timesteps_inner)
|
1090 |
+
vec_s, vec_t = t_T_inner.tile(x.shape[0]), t_0_inner.tile(x.shape[0])
|
1091 |
+
h = lambda_inner[-1] - lambda_inner[0]
|
1092 |
+
r1 = None if order <= 1 else (lambda_inner[1] - lambda_inner[0]) / h
|
1093 |
+
r2 = None if order <= 2 else (lambda_inner[2] - lambda_inner[0]) / h
|
1094 |
+
x = self.singlestep_dpm_solver_update(x, vec_s, vec_t, order, solver_type=solver_type, r1=r1, r2=r2)
|
1095 |
+
if denoise_to_zero:
|
1096 |
+
x = self.denoise_to_zero_fn(x, torch.ones((x.shape[0],)).to(device) * t_0)
|
1097 |
+
return x
|
1098 |
+
|
1099 |
+
|
1100 |
+
#############################################################
|
1101 |
+
# other utility functions
|
1102 |
+
#############################################################
|
1103 |
+
|
1104 |
+
def interpolate_fn(x, xp, yp):
|
1105 |
+
"""
|
1106 |
+
A piecewise linear function y = f(x), using xp and yp as keypoints.
|
1107 |
+
We implement f(x) in a differentiable way (i.e. applicable for autograd).
|
1108 |
+
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.)
|
1109 |
+
Args:
|
1110 |
+
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).
|
1111 |
+
xp: PyTorch tensor with shape [C, K], where K is the number of keypoints.
|
1112 |
+
yp: PyTorch tensor with shape [C, K].
|
1113 |
+
Returns:
|
1114 |
+
The function values f(x), with shape [N, C].
|
1115 |
+
"""
|
1116 |
+
N, K = x.shape[0], xp.shape[1]
|
1117 |
+
all_x = torch.cat([x.unsqueeze(2), xp.unsqueeze(0).repeat((N, 1, 1))], dim=2)
|
1118 |
+
sorted_all_x, x_indices = torch.sort(all_x, dim=2)
|
1119 |
+
x_idx = torch.argmin(x_indices, dim=2)
|
1120 |
+
cand_start_idx = x_idx - 1
|
1121 |
+
start_idx = torch.where(
|
1122 |
+
torch.eq(x_idx, 0),
|
1123 |
+
torch.tensor(1, device=x.device),
|
1124 |
+
torch.where(
|
1125 |
+
torch.eq(x_idx, K), torch.tensor(K - 2, device=x.device), cand_start_idx,
|
1126 |
+
),
|
1127 |
+
)
|
1128 |
+
end_idx = torch.where(torch.eq(start_idx, cand_start_idx), start_idx + 2, start_idx + 1)
|
1129 |
+
start_x = torch.gather(sorted_all_x, dim=2, index=start_idx.unsqueeze(2)).squeeze(2)
|
1130 |
+
end_x = torch.gather(sorted_all_x, dim=2, index=end_idx.unsqueeze(2)).squeeze(2)
|
1131 |
+
start_idx2 = torch.where(
|
1132 |
+
torch.eq(x_idx, 0),
|
1133 |
+
torch.tensor(0, device=x.device),
|
1134 |
+
torch.where(
|
1135 |
+
torch.eq(x_idx, K), torch.tensor(K - 2, device=x.device), cand_start_idx,
|
1136 |
+
),
|
1137 |
+
)
|
1138 |
+
y_positions_expanded = yp.unsqueeze(0).expand(N, -1, -1)
|
1139 |
+
start_y = torch.gather(y_positions_expanded, dim=2, index=start_idx2.unsqueeze(2)).squeeze(2)
|
1140 |
+
end_y = torch.gather(y_positions_expanded, dim=2, index=(start_idx2 + 1).unsqueeze(2)).squeeze(2)
|
1141 |
+
cand = start_y + (x - start_x) * (end_y - start_y) / (end_x - start_x)
|
1142 |
+
return cand
|
1143 |
+
|
1144 |
+
|
1145 |
+
def expand_dims(v, dims):
|
1146 |
+
"""
|
1147 |
+
Expand the tensor `v` to the dim `dims`.
|
1148 |
+
Args:
|
1149 |
+
`v`: a PyTorch tensor with shape [N].
|
1150 |
+
`dim`: a `int`.
|
1151 |
+
Returns:
|
1152 |
+
a PyTorch tensor with shape [N, 1, 1, ..., 1] and the total dimension is `dims`.
|
1153 |
+
"""
|
1154 |
+
return v[(...,) + (None,) * (dims - 1)]
|
ttts/AA_diffusion_deprecated/ldm/models/diffusion/dpm_solver/sampler.py
ADDED
@@ -0,0 +1,87 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""SAMPLING ONLY."""
|
2 |
+
import torch
|
3 |
+
|
4 |
+
from .dpm_solver import NoiseScheduleVP, model_wrapper, DPM_Solver
|
5 |
+
|
6 |
+
|
7 |
+
MODEL_TYPES = {
|
8 |
+
"eps": "noise",
|
9 |
+
"v": "v"
|
10 |
+
}
|
11 |
+
|
12 |
+
|
13 |
+
class DPMSolverSampler(object):
|
14 |
+
def __init__(self, model, **kwargs):
|
15 |
+
super().__init__()
|
16 |
+
self.model = model
|
17 |
+
to_torch = lambda x: x.clone().detach().to(torch.float32).to(model.device)
|
18 |
+
self.register_buffer('alphas_cumprod', to_torch(model.alphas_cumprod))
|
19 |
+
|
20 |
+
def register_buffer(self, name, attr):
|
21 |
+
if type(attr) == torch.Tensor:
|
22 |
+
if attr.device != torch.device("cuda"):
|
23 |
+
attr = attr.to(torch.device("cuda"))
|
24 |
+
setattr(self, name, attr)
|
25 |
+
|
26 |
+
@torch.no_grad()
|
27 |
+
def sample(self,
|
28 |
+
S,
|
29 |
+
batch_size,
|
30 |
+
shape,
|
31 |
+
conditioning=None,
|
32 |
+
callback=None,
|
33 |
+
normals_sequence=None,
|
34 |
+
img_callback=None,
|
35 |
+
quantize_x0=False,
|
36 |
+
eta=0.,
|
37 |
+
mask=None,
|
38 |
+
x0=None,
|
39 |
+
temperature=1.,
|
40 |
+
noise_dropout=0.,
|
41 |
+
score_corrector=None,
|
42 |
+
corrector_kwargs=None,
|
43 |
+
verbose=True,
|
44 |
+
x_T=None,
|
45 |
+
log_every_t=100,
|
46 |
+
unconditional_guidance_scale=1.,
|
47 |
+
unconditional_conditioning=None,
|
48 |
+
# this has to come in the same format as the conditioning, # e.g. as encoded tokens, ...
|
49 |
+
**kwargs
|
50 |
+
):
|
51 |
+
if conditioning is not None:
|
52 |
+
if isinstance(conditioning, dict):
|
53 |
+
cbs = conditioning[list(conditioning.keys())[0]].shape[0]
|
54 |
+
if cbs != batch_size:
|
55 |
+
print(f"Warning: Got {cbs} conditionings but batch-size is {batch_size}")
|
56 |
+
else:
|
57 |
+
if conditioning.shape[0] != batch_size:
|
58 |
+
print(f"Warning: Got {conditioning.shape[0]} conditionings but batch-size is {batch_size}")
|
59 |
+
|
60 |
+
# sampling
|
61 |
+
C, H, W = shape
|
62 |
+
size = (batch_size, C, H, W)
|
63 |
+
|
64 |
+
print(f'Data shape for DPM-Solver sampling is {size}, sampling steps {S}')
|
65 |
+
|
66 |
+
device = self.model.betas.device
|
67 |
+
if x_T is None:
|
68 |
+
img = torch.randn(size, device=device)
|
69 |
+
else:
|
70 |
+
img = x_T
|
71 |
+
|
72 |
+
ns = NoiseScheduleVP('discrete', alphas_cumprod=self.alphas_cumprod)
|
73 |
+
|
74 |
+
model_fn = model_wrapper(
|
75 |
+
lambda x, t, c: self.model.apply_model(x, t, c),
|
76 |
+
ns,
|
77 |
+
model_type=MODEL_TYPES[self.model.parameterization],
|
78 |
+
guidance_type="classifier-free",
|
79 |
+
condition=conditioning,
|
80 |
+
unconditional_condition=unconditional_conditioning,
|
81 |
+
guidance_scale=unconditional_guidance_scale,
|
82 |
+
)
|
83 |
+
|
84 |
+
dpm_solver = DPM_Solver(model_fn, ns, predict_x0=True, thresholding=False)
|
85 |
+
x = dpm_solver.sample(img, steps=S, skip_type="time_uniform", method="multistep", order=2, lower_order_final=True)
|
86 |
+
|
87 |
+
return x.to(device), None
|
ttts/AA_diffusion_deprecated/ldm/models/diffusion/plms.py
ADDED
@@ -0,0 +1,244 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""SAMPLING ONLY."""
|
2 |
+
|
3 |
+
import torch
|
4 |
+
import numpy as np
|
5 |
+
from tqdm import tqdm
|
6 |
+
from functools import partial
|
7 |
+
|
8 |
+
from ldm.modules.diffusionmodules.util import make_ddim_sampling_parameters, make_ddim_timesteps, noise_like
|
9 |
+
from ldm.models.diffusion.sampling_util import norm_thresholding
|
10 |
+
|
11 |
+
|
12 |
+
class PLMSSampler(object):
|
13 |
+
def __init__(self, model, schedule="linear", **kwargs):
|
14 |
+
super().__init__()
|
15 |
+
self.model = model
|
16 |
+
self.ddpm_num_timesteps = model.num_timesteps
|
17 |
+
self.schedule = schedule
|
18 |
+
|
19 |
+
def register_buffer(self, name, attr):
|
20 |
+
if type(attr) == torch.Tensor:
|
21 |
+
if attr.device != torch.device("cuda"):
|
22 |
+
attr = attr.to(torch.device("cuda"))
|
23 |
+
setattr(self, name, attr)
|
24 |
+
|
25 |
+
def make_schedule(self, ddim_num_steps, ddim_discretize="uniform", ddim_eta=0., verbose=True):
|
26 |
+
if ddim_eta != 0:
|
27 |
+
raise ValueError('ddim_eta must be 0 for PLMS')
|
28 |
+
self.ddim_timesteps = make_ddim_timesteps(ddim_discr_method=ddim_discretize, num_ddim_timesteps=ddim_num_steps,
|
29 |
+
num_ddpm_timesteps=self.ddpm_num_timesteps,verbose=verbose)
|
30 |
+
alphas_cumprod = self.model.alphas_cumprod
|
31 |
+
assert alphas_cumprod.shape[0] == self.ddpm_num_timesteps, 'alphas have to be defined for each timestep'
|
32 |
+
to_torch = lambda x: x.clone().detach().to(torch.float32).to(self.model.device)
|
33 |
+
|
34 |
+
self.register_buffer('betas', to_torch(self.model.betas))
|
35 |
+
self.register_buffer('alphas_cumprod', to_torch(alphas_cumprod))
|
36 |
+
self.register_buffer('alphas_cumprod_prev', to_torch(self.model.alphas_cumprod_prev))
|
37 |
+
|
38 |
+
# calculations for diffusion q(x_t | x_{t-1}) and others
|
39 |
+
self.register_buffer('sqrt_alphas_cumprod', to_torch(np.sqrt(alphas_cumprod.cpu())))
|
40 |
+
self.register_buffer('sqrt_one_minus_alphas_cumprod', to_torch(np.sqrt(1. - alphas_cumprod.cpu())))
|
41 |
+
self.register_buffer('log_one_minus_alphas_cumprod', to_torch(np.log(1. - alphas_cumprod.cpu())))
|
42 |
+
self.register_buffer('sqrt_recip_alphas_cumprod', to_torch(np.sqrt(1. / alphas_cumprod.cpu())))
|
43 |
+
self.register_buffer('sqrt_recipm1_alphas_cumprod', to_torch(np.sqrt(1. / alphas_cumprod.cpu() - 1)))
|
44 |
+
|
45 |
+
# ddim sampling parameters
|
46 |
+
ddim_sigmas, ddim_alphas, ddim_alphas_prev = make_ddim_sampling_parameters(alphacums=alphas_cumprod.cpu(),
|
47 |
+
ddim_timesteps=self.ddim_timesteps,
|
48 |
+
eta=ddim_eta,verbose=verbose)
|
49 |
+
self.register_buffer('ddim_sigmas', ddim_sigmas)
|
50 |
+
self.register_buffer('ddim_alphas', ddim_alphas)
|
51 |
+
self.register_buffer('ddim_alphas_prev', ddim_alphas_prev)
|
52 |
+
self.register_buffer('ddim_sqrt_one_minus_alphas', np.sqrt(1. - ddim_alphas))
|
53 |
+
sigmas_for_original_sampling_steps = ddim_eta * torch.sqrt(
|
54 |
+
(1 - self.alphas_cumprod_prev) / (1 - self.alphas_cumprod) * (
|
55 |
+
1 - self.alphas_cumprod / self.alphas_cumprod_prev))
|
56 |
+
self.register_buffer('ddim_sigmas_for_original_num_steps', sigmas_for_original_sampling_steps)
|
57 |
+
|
58 |
+
@torch.no_grad()
|
59 |
+
def sample(self,
|
60 |
+
S,
|
61 |
+
batch_size,
|
62 |
+
shape,
|
63 |
+
conditioning=None,
|
64 |
+
callback=None,
|
65 |
+
normals_sequence=None,
|
66 |
+
img_callback=None,
|
67 |
+
quantize_x0=False,
|
68 |
+
eta=0.,
|
69 |
+
mask=None,
|
70 |
+
x0=None,
|
71 |
+
temperature=1.,
|
72 |
+
noise_dropout=0.,
|
73 |
+
score_corrector=None,
|
74 |
+
corrector_kwargs=None,
|
75 |
+
verbose=True,
|
76 |
+
x_T=None,
|
77 |
+
log_every_t=100,
|
78 |
+
unconditional_guidance_scale=1.,
|
79 |
+
unconditional_conditioning=None,
|
80 |
+
# this has to come in the same format as the conditioning, # e.g. as encoded tokens, ...
|
81 |
+
dynamic_threshold=None,
|
82 |
+
**kwargs
|
83 |
+
):
|
84 |
+
if conditioning is not None:
|
85 |
+
if isinstance(conditioning, dict):
|
86 |
+
cbs = conditioning[list(conditioning.keys())[0]].shape[0]
|
87 |
+
if cbs != batch_size:
|
88 |
+
print(f"Warning: Got {cbs} conditionings but batch-size is {batch_size}")
|
89 |
+
else:
|
90 |
+
if conditioning.shape[0] != batch_size:
|
91 |
+
print(f"Warning: Got {conditioning.shape[0]} conditionings but batch-size is {batch_size}")
|
92 |
+
|
93 |
+
self.make_schedule(ddim_num_steps=S, ddim_eta=eta, verbose=verbose)
|
94 |
+
# sampling
|
95 |
+
C, H, W = shape
|
96 |
+
size = (batch_size, C, H, W)
|
97 |
+
print(f'Data shape for PLMS sampling is {size}')
|
98 |
+
|
99 |
+
samples, intermediates = self.plms_sampling(conditioning, size,
|
100 |
+
callback=callback,
|
101 |
+
img_callback=img_callback,
|
102 |
+
quantize_denoised=quantize_x0,
|
103 |
+
mask=mask, x0=x0,
|
104 |
+
ddim_use_original_steps=False,
|
105 |
+
noise_dropout=noise_dropout,
|
106 |
+
temperature=temperature,
|
107 |
+
score_corrector=score_corrector,
|
108 |
+
corrector_kwargs=corrector_kwargs,
|
109 |
+
x_T=x_T,
|
110 |
+
log_every_t=log_every_t,
|
111 |
+
unconditional_guidance_scale=unconditional_guidance_scale,
|
112 |
+
unconditional_conditioning=unconditional_conditioning,
|
113 |
+
dynamic_threshold=dynamic_threshold,
|
114 |
+
)
|
115 |
+
return samples, intermediates
|
116 |
+
|
117 |
+
@torch.no_grad()
|
118 |
+
def plms_sampling(self, cond, shape,
|
119 |
+
x_T=None, ddim_use_original_steps=False,
|
120 |
+
callback=None, timesteps=None, quantize_denoised=False,
|
121 |
+
mask=None, x0=None, img_callback=None, log_every_t=100,
|
122 |
+
temperature=1., noise_dropout=0., score_corrector=None, corrector_kwargs=None,
|
123 |
+
unconditional_guidance_scale=1., unconditional_conditioning=None,
|
124 |
+
dynamic_threshold=None):
|
125 |
+
device = self.model.betas.device
|
126 |
+
b = shape[0]
|
127 |
+
if x_T is None:
|
128 |
+
img = torch.randn(shape, device=device)
|
129 |
+
else:
|
130 |
+
img = x_T
|
131 |
+
|
132 |
+
if timesteps is None:
|
133 |
+
timesteps = self.ddpm_num_timesteps if ddim_use_original_steps else self.ddim_timesteps
|
134 |
+
elif timesteps is not None and not ddim_use_original_steps:
|
135 |
+
subset_end = int(min(timesteps / self.ddim_timesteps.shape[0], 1) * self.ddim_timesteps.shape[0]) - 1
|
136 |
+
timesteps = self.ddim_timesteps[:subset_end]
|
137 |
+
|
138 |
+
intermediates = {'x_inter': [img], 'pred_x0': [img]}
|
139 |
+
time_range = list(reversed(range(0,timesteps))) if ddim_use_original_steps else np.flip(timesteps)
|
140 |
+
total_steps = timesteps if ddim_use_original_steps else timesteps.shape[0]
|
141 |
+
print(f"Running PLMS Sampling with {total_steps} timesteps")
|
142 |
+
|
143 |
+
iterator = tqdm(time_range, desc='PLMS Sampler', total=total_steps)
|
144 |
+
old_eps = []
|
145 |
+
|
146 |
+
for i, step in enumerate(iterator):
|
147 |
+
index = total_steps - i - 1
|
148 |
+
ts = torch.full((b,), step, device=device, dtype=torch.long)
|
149 |
+
ts_next = torch.full((b,), time_range[min(i + 1, len(time_range) - 1)], device=device, dtype=torch.long)
|
150 |
+
|
151 |
+
if mask is not None:
|
152 |
+
assert x0 is not None
|
153 |
+
img_orig = self.model.q_sample(x0, ts) # TODO: deterministic forward pass?
|
154 |
+
img = img_orig * mask + (1. - mask) * img
|
155 |
+
|
156 |
+
outs = self.p_sample_plms(img, cond, ts, index=index, use_original_steps=ddim_use_original_steps,
|
157 |
+
quantize_denoised=quantize_denoised, temperature=temperature,
|
158 |
+
noise_dropout=noise_dropout, score_corrector=score_corrector,
|
159 |
+
corrector_kwargs=corrector_kwargs,
|
160 |
+
unconditional_guidance_scale=unconditional_guidance_scale,
|
161 |
+
unconditional_conditioning=unconditional_conditioning,
|
162 |
+
old_eps=old_eps, t_next=ts_next,
|
163 |
+
dynamic_threshold=dynamic_threshold)
|
164 |
+
img, pred_x0, e_t = outs
|
165 |
+
old_eps.append(e_t)
|
166 |
+
if len(old_eps) >= 4:
|
167 |
+
old_eps.pop(0)
|
168 |
+
if callback: callback(i)
|
169 |
+
if img_callback: img_callback(pred_x0, i)
|
170 |
+
|
171 |
+
if index % log_every_t == 0 or index == total_steps - 1:
|
172 |
+
intermediates['x_inter'].append(img)
|
173 |
+
intermediates['pred_x0'].append(pred_x0)
|
174 |
+
|
175 |
+
return img, intermediates
|
176 |
+
|
177 |
+
@torch.no_grad()
|
178 |
+
def p_sample_plms(self, x, c, t, index, repeat_noise=False, use_original_steps=False, quantize_denoised=False,
|
179 |
+
temperature=1., noise_dropout=0., score_corrector=None, corrector_kwargs=None,
|
180 |
+
unconditional_guidance_scale=1., unconditional_conditioning=None, old_eps=None, t_next=None,
|
181 |
+
dynamic_threshold=None):
|
182 |
+
b, *_, device = *x.shape, x.device
|
183 |
+
|
184 |
+
def get_model_output(x, t):
|
185 |
+
if unconditional_conditioning is None or unconditional_guidance_scale == 1.:
|
186 |
+
e_t = self.model.apply_model(x, t, c)
|
187 |
+
else:
|
188 |
+
x_in = torch.cat([x] * 2)
|
189 |
+
t_in = torch.cat([t] * 2)
|
190 |
+
c_in = torch.cat([unconditional_conditioning, c])
|
191 |
+
e_t_uncond, e_t = self.model.apply_model(x_in, t_in, c_in).chunk(2)
|
192 |
+
e_t = e_t_uncond + unconditional_guidance_scale * (e_t - e_t_uncond)
|
193 |
+
|
194 |
+
if score_corrector is not None:
|
195 |
+
assert self.model.parameterization == "eps"
|
196 |
+
e_t = score_corrector.modify_score(self.model, e_t, x, t, c, **corrector_kwargs)
|
197 |
+
|
198 |
+
return e_t
|
199 |
+
|
200 |
+
alphas = self.model.alphas_cumprod if use_original_steps else self.ddim_alphas
|
201 |
+
alphas_prev = self.model.alphas_cumprod_prev if use_original_steps else self.ddim_alphas_prev
|
202 |
+
sqrt_one_minus_alphas = self.model.sqrt_one_minus_alphas_cumprod if use_original_steps else self.ddim_sqrt_one_minus_alphas
|
203 |
+
sigmas = self.model.ddim_sigmas_for_original_num_steps if use_original_steps else self.ddim_sigmas
|
204 |
+
|
205 |
+
def get_x_prev_and_pred_x0(e_t, index):
|
206 |
+
# select parameters corresponding to the currently considered timestep
|
207 |
+
a_t = torch.full((b, 1, 1, 1), alphas[index], device=device)
|
208 |
+
a_prev = torch.full((b, 1, 1, 1), alphas_prev[index], device=device)
|
209 |
+
sigma_t = torch.full((b, 1, 1, 1), sigmas[index], device=device)
|
210 |
+
sqrt_one_minus_at = torch.full((b, 1, 1, 1), sqrt_one_minus_alphas[index],device=device)
|
211 |
+
|
212 |
+
# current prediction for x_0
|
213 |
+
pred_x0 = (x - sqrt_one_minus_at * e_t) / a_t.sqrt()
|
214 |
+
if quantize_denoised:
|
215 |
+
pred_x0, _, *_ = self.model.first_stage_model.quantize(pred_x0)
|
216 |
+
if dynamic_threshold is not None:
|
217 |
+
pred_x0 = norm_thresholding(pred_x0, dynamic_threshold)
|
218 |
+
# direction pointing to x_t
|
219 |
+
dir_xt = (1. - a_prev - sigma_t**2).sqrt() * e_t
|
220 |
+
noise = sigma_t * noise_like(x.shape, device, repeat_noise) * temperature
|
221 |
+
if noise_dropout > 0.:
|
222 |
+
noise = torch.nn.functional.dropout(noise, p=noise_dropout)
|
223 |
+
x_prev = a_prev.sqrt() * pred_x0 + dir_xt + noise
|
224 |
+
return x_prev, pred_x0
|
225 |
+
|
226 |
+
e_t = get_model_output(x, t)
|
227 |
+
if len(old_eps) == 0:
|
228 |
+
# Pseudo Improved Euler (2nd order)
|
229 |
+
x_prev, pred_x0 = get_x_prev_and_pred_x0(e_t, index)
|
230 |
+
e_t_next = get_model_output(x_prev, t_next)
|
231 |
+
e_t_prime = (e_t + e_t_next) / 2
|
232 |
+
elif len(old_eps) == 1:
|
233 |
+
# 2nd order Pseudo Linear Multistep (Adams-Bashforth)
|
234 |
+
e_t_prime = (3 * e_t - old_eps[-1]) / 2
|
235 |
+
elif len(old_eps) == 2:
|
236 |
+
# 3nd order Pseudo Linear Multistep (Adams-Bashforth)
|
237 |
+
e_t_prime = (23 * e_t - 16 * old_eps[-1] + 5 * old_eps[-2]) / 12
|
238 |
+
elif len(old_eps) >= 3:
|
239 |
+
# 4nd order Pseudo Linear Multistep (Adams-Bashforth)
|
240 |
+
e_t_prime = (55 * e_t - 59 * old_eps[-1] + 37 * old_eps[-2] - 9 * old_eps[-3]) / 24
|
241 |
+
|
242 |
+
x_prev, pred_x0 = get_x_prev_and_pred_x0(e_t_prime, index)
|
243 |
+
|
244 |
+
return x_prev, pred_x0, e_t
|
ttts/AA_diffusion_deprecated/ldm/models/diffusion/sampling_util.py
ADDED
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
import numpy as np
|
3 |
+
|
4 |
+
|
5 |
+
def append_dims(x, target_dims):
|
6 |
+
"""Appends dimensions to the end of a tensor until it has target_dims dimensions.
|
7 |
+
From https://github.com/crowsonkb/k-diffusion/blob/master/k_diffusion/utils.py"""
|
8 |
+
dims_to_append = target_dims - x.ndim
|
9 |
+
if dims_to_append < 0:
|
10 |
+
raise ValueError(f'input has {x.ndim} dims but target_dims is {target_dims}, which is less')
|
11 |
+
return x[(...,) + (None,) * dims_to_append]
|
12 |
+
|
13 |
+
|
14 |
+
def norm_thresholding(x0, value):
|
15 |
+
s = append_dims(x0.pow(2).flatten(1).mean(1).sqrt().clamp(min=value), x0.ndim)
|
16 |
+
return x0 * (value / s)
|
17 |
+
|
18 |
+
|
19 |
+
def spatial_norm_thresholding(x0, value):
|
20 |
+
# b c h w
|
21 |
+
s = x0.pow(2).mean(1, keepdim=True).sqrt().clamp(min=value)
|
22 |
+
return x0 * (value / s)
|
ttts/AA_diffusion_deprecated/ldm/modules/attention.py
ADDED
@@ -0,0 +1,365 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 ldm.modules.diffusionmodules.util import checkpoint
|
10 |
+
|
11 |
+
|
12 |
+
try:
|
13 |
+
import xformers
|
14 |
+
import xformers.ops
|
15 |
+
XFORMERS_IS_AVAILBLE = True
|
16 |
+
except:
|
17 |
+
XFORMERS_IS_AVAILBLE = False
|
18 |
+
|
19 |
+
# CrossAttn precision handling
|
20 |
+
import os
|
21 |
+
_ATTN_PRECISION = os.environ.get("ATTN_PRECISION", "fp32")
|
22 |
+
|
23 |
+
def exists(val):
|
24 |
+
return val is not None
|
25 |
+
|
26 |
+
|
27 |
+
def uniq(arr):
|
28 |
+
return{el: True for el in arr}.keys()
|
29 |
+
|
30 |
+
|
31 |
+
def default(val, d):
|
32 |
+
if exists(val):
|
33 |
+
return val
|
34 |
+
return d() if isfunction(d) else d
|
35 |
+
|
36 |
+
|
37 |
+
def max_neg_value(t):
|
38 |
+
return -torch.finfo(t.dtype).max
|
39 |
+
|
40 |
+
|
41 |
+
def init_(tensor):
|
42 |
+
dim = tensor.shape[-1]
|
43 |
+
std = 1 / math.sqrt(dim)
|
44 |
+
tensor.uniform_(-std, std)
|
45 |
+
return tensor
|
46 |
+
|
47 |
+
|
48 |
+
# feedforward
|
49 |
+
class GEGLU(nn.Module):
|
50 |
+
def __init__(self, dim_in, dim_out):
|
51 |
+
super().__init__()
|
52 |
+
self.proj = nn.Linear(dim_in, dim_out * 2)
|
53 |
+
|
54 |
+
def forward(self, x):
|
55 |
+
x, gate = self.proj(x).chunk(2, dim=-1)
|
56 |
+
return x * F.gelu(gate)
|
57 |
+
|
58 |
+
|
59 |
+
class FeedForward(nn.Module):
|
60 |
+
def __init__(self, dim, dim_out=None, mult=4, glu=False, dropout=0.):
|
61 |
+
super().__init__()
|
62 |
+
inner_dim = int(dim * mult)
|
63 |
+
dim_out = default(dim_out, dim)
|
64 |
+
project_in = nn.Sequential(
|
65 |
+
nn.Linear(dim, inner_dim),
|
66 |
+
nn.GELU()
|
67 |
+
) if not glu else GEGLU(dim, inner_dim)
|
68 |
+
|
69 |
+
self.net = nn.Sequential(
|
70 |
+
project_in,
|
71 |
+
nn.Dropout(dropout),
|
72 |
+
nn.Linear(inner_dim, dim_out)
|
73 |
+
)
|
74 |
+
|
75 |
+
def forward(self, x):
|
76 |
+
return self.net(x)
|
77 |
+
|
78 |
+
|
79 |
+
def zero_module(module):
|
80 |
+
"""
|
81 |
+
Zero out the parameters of a module and return it.
|
82 |
+
"""
|
83 |
+
for p in module.parameters():
|
84 |
+
p.detach().zero_()
|
85 |
+
return module
|
86 |
+
|
87 |
+
|
88 |
+
def Normalize(in_channels):
|
89 |
+
return torch.nn.GroupNorm(num_groups=32, num_channels=in_channels, eps=1e-6, affine=True)
|
90 |
+
|
91 |
+
|
92 |
+
class SpatialSelfAttention(nn.Module):
|
93 |
+
def __init__(self, in_channels):
|
94 |
+
super().__init__()
|
95 |
+
self.in_channels = in_channels
|
96 |
+
|
97 |
+
self.norm = Normalize(in_channels)
|
98 |
+
self.q = torch.nn.Conv2d(in_channels,
|
99 |
+
in_channels,
|
100 |
+
kernel_size=1,
|
101 |
+
stride=1,
|
102 |
+
padding=0)
|
103 |
+
self.k = torch.nn.Conv2d(in_channels,
|
104 |
+
in_channels,
|
105 |
+
kernel_size=1,
|
106 |
+
stride=1,
|
107 |
+
padding=0)
|
108 |
+
self.v = torch.nn.Conv2d(in_channels,
|
109 |
+
in_channels,
|
110 |
+
kernel_size=1,
|
111 |
+
stride=1,
|
112 |
+
padding=0)
|
113 |
+
self.proj_out = torch.nn.Conv2d(in_channels,
|
114 |
+
in_channels,
|
115 |
+
kernel_size=1,
|
116 |
+
stride=1,
|
117 |
+
padding=0)
|
118 |
+
|
119 |
+
def forward(self, x):
|
120 |
+
h_ = x
|
121 |
+
h_ = self.norm(h_)
|
122 |
+
q = self.q(h_)
|
123 |
+
k = self.k(h_)
|
124 |
+
v = self.v(h_)
|
125 |
+
|
126 |
+
# compute attention
|
127 |
+
b,c,h,w = q.shape
|
128 |
+
q = rearrange(q, 'b c h w -> b (h w) c')
|
129 |
+
k = rearrange(k, 'b c h w -> b c (h w)')
|
130 |
+
w_ = torch.einsum('bij,bjk->bik', q, k)
|
131 |
+
|
132 |
+
w_ = w_ * (int(c)**(-0.5))
|
133 |
+
w_ = torch.nn.functional.softmax(w_, dim=2)
|
134 |
+
|
135 |
+
# attend to values
|
136 |
+
v = rearrange(v, 'b c h w -> b c (h w)')
|
137 |
+
w_ = rearrange(w_, 'b i j -> b j i')
|
138 |
+
h_ = torch.einsum('bij,bjk->bik', v, w_)
|
139 |
+
h_ = rearrange(h_, 'b c (h w) -> b c h w', h=h)
|
140 |
+
h_ = self.proj_out(h_)
|
141 |
+
|
142 |
+
return x+h_
|
143 |
+
|
144 |
+
|
145 |
+
class CrossAttention(nn.Module):
|
146 |
+
def __init__(self, query_dim, context_dim=None, heads=8, dim_head=64, dropout=0.):
|
147 |
+
super().__init__()
|
148 |
+
inner_dim = dim_head * heads
|
149 |
+
context_dim = default(context_dim, query_dim)
|
150 |
+
|
151 |
+
self.scale = dim_head ** -0.5
|
152 |
+
self.heads = heads
|
153 |
+
|
154 |
+
self.to_q = nn.Linear(query_dim, inner_dim, bias=False)
|
155 |
+
self.to_k = nn.Linear(context_dim, inner_dim, bias=False)
|
156 |
+
self.to_v = nn.Linear(context_dim, inner_dim, bias=False)
|
157 |
+
|
158 |
+
self.to_out = nn.Sequential(
|
159 |
+
nn.Linear(inner_dim, query_dim),
|
160 |
+
nn.Dropout(dropout)
|
161 |
+
)
|
162 |
+
|
163 |
+
def forward(self, x, context=None, mask=None):
|
164 |
+
h = self.heads
|
165 |
+
|
166 |
+
q = self.to_q(x)
|
167 |
+
context = default(context, x)
|
168 |
+
k = self.to_k(context)
|
169 |
+
v = self.to_v(context)
|
170 |
+
|
171 |
+
q, k, v = map(lambda t: rearrange(t, 'b n (h d) -> (b h) n d', h=h), (q, k, v))
|
172 |
+
|
173 |
+
# force cast to fp32 to avoid overflowing
|
174 |
+
if _ATTN_PRECISION =="fp32":
|
175 |
+
with torch.autocast(enabled=False, device_type = 'cuda'):
|
176 |
+
q, k = q.float(), k.float()
|
177 |
+
sim = einsum('b i d, b j d -> b i j', q, k) * self.scale
|
178 |
+
else:
|
179 |
+
sim = einsum('b i d, b j d -> b i j', q, k) * self.scale
|
180 |
+
|
181 |
+
del q, k
|
182 |
+
|
183 |
+
if exists(mask):
|
184 |
+
mask = rearrange(mask, 'b ... -> b (...)')
|
185 |
+
max_neg_value = -torch.finfo(sim.dtype).max
|
186 |
+
mask = repeat(mask, 'b j -> (b h) () j', h=h)
|
187 |
+
sim.masked_fill_(~mask, max_neg_value)
|
188 |
+
|
189 |
+
# attention, what we cannot get enough of
|
190 |
+
sim = sim.softmax(dim=-1)
|
191 |
+
|
192 |
+
out = einsum('b i j, b j d -> b i d', sim, v)
|
193 |
+
out = rearrange(out, '(b h) n d -> b n (h d)', h=h)
|
194 |
+
return self.to_out(out)
|
195 |
+
|
196 |
+
|
197 |
+
class MemoryEfficientCrossAttention(nn.Module):
|
198 |
+
# https://github.com/MatthieuTPHR/diffusers/blob/d80b531ff8060ec1ea982b65a1b8df70f73aa67c/src/diffusers/models/attention.py#L223
|
199 |
+
def __init__(self, query_dim, context_dim=None, heads=8, dim_head=64, dropout=0.0):
|
200 |
+
super().__init__()
|
201 |
+
print(f"Setting up {self.__class__.__name__}. Query dim is {query_dim}, context_dim is {context_dim} and using "
|
202 |
+
f"{heads} heads.")
|
203 |
+
inner_dim = dim_head * heads
|
204 |
+
context_dim = default(context_dim, query_dim)
|
205 |
+
|
206 |
+
self.heads = heads
|
207 |
+
self.dim_head = dim_head
|
208 |
+
|
209 |
+
self.to_q = nn.Linear(query_dim, inner_dim, bias=False)
|
210 |
+
self.to_k = nn.Linear(context_dim, inner_dim, bias=False)
|
211 |
+
self.to_v = nn.Linear(context_dim, inner_dim, bias=False)
|
212 |
+
|
213 |
+
self.to_out = nn.Sequential(nn.Linear(inner_dim, query_dim), nn.Dropout(dropout))
|
214 |
+
self.attention_op: Optional[Any] = None
|
215 |
+
|
216 |
+
def forward(self, x, context=None, mask=None):
|
217 |
+
q = self.to_q(x)
|
218 |
+
context = default(context, x)
|
219 |
+
k = self.to_k(context)
|
220 |
+
v = self.to_v(context)
|
221 |
+
|
222 |
+
b, _, _ = q.shape
|
223 |
+
q, k, v = map(
|
224 |
+
lambda t: t.unsqueeze(3)
|
225 |
+
.reshape(b, t.shape[1], self.heads, self.dim_head)
|
226 |
+
.permute(0, 2, 1, 3)
|
227 |
+
.reshape(b * self.heads, t.shape[1], self.dim_head)
|
228 |
+
.contiguous(),
|
229 |
+
(q, k, v),
|
230 |
+
)
|
231 |
+
|
232 |
+
# actually compute the attention, what we cannot get enough of
|
233 |
+
out = xformers.ops.memory_efficient_attention(q, k, v, attn_bias=None, op=self.attention_op)
|
234 |
+
|
235 |
+
if exists(mask):
|
236 |
+
raise NotImplementedError
|
237 |
+
out = (
|
238 |
+
out.unsqueeze(0)
|
239 |
+
.reshape(b, self.heads, out.shape[1], self.dim_head)
|
240 |
+
.permute(0, 2, 1, 3)
|
241 |
+
.reshape(b, out.shape[1], self.heads * self.dim_head)
|
242 |
+
)
|
243 |
+
return self.to_out(out)
|
244 |
+
|
245 |
+
|
246 |
+
class BasicTransformerBlock(nn.Module):
|
247 |
+
ATTENTION_MODES = {
|
248 |
+
"softmax": CrossAttention, # vanilla attention
|
249 |
+
"softmax-xformers": MemoryEfficientCrossAttention
|
250 |
+
}
|
251 |
+
def __init__(self, dim, n_heads, d_head, dropout=0., context_dim=None, gated_ff=True, checkpoint=True,
|
252 |
+
disable_self_attn=False):
|
253 |
+
super().__init__()
|
254 |
+
attn_mode = "softmax-xformers" if XFORMERS_IS_AVAILBLE else "softmax"
|
255 |
+
assert attn_mode in self.ATTENTION_MODES
|
256 |
+
attn_cls = self.ATTENTION_MODES[attn_mode]
|
257 |
+
self.disable_self_attn = disable_self_attn
|
258 |
+
self.attn1 = attn_cls(query_dim=dim, heads=n_heads, dim_head=d_head, dropout=dropout,
|
259 |
+
context_dim=context_dim if self.disable_self_attn else None) # is a self-attention if not self.disable_self_attn
|
260 |
+
self.ff = FeedForward(dim, dropout=dropout, glu=gated_ff)
|
261 |
+
self.attn2 = attn_cls(query_dim=dim, context_dim=context_dim,
|
262 |
+
heads=n_heads, dim_head=d_head, dropout=dropout) # is self-attn if context is none
|
263 |
+
self.norm1 = nn.LayerNorm(dim)
|
264 |
+
self.norm2 = nn.LayerNorm(dim)
|
265 |
+
self.norm3 = nn.LayerNorm(dim)
|
266 |
+
self.checkpoint = checkpoint
|
267 |
+
|
268 |
+
def forward(self, x, context=None, refer=None):
|
269 |
+
if refer is not None:
|
270 |
+
return checkpoint(self._forward, (x, context, refer), self.parameters(), self.checkpoint)
|
271 |
+
else:
|
272 |
+
return checkpoint(self._forward, (x, context), self.parameters(), self.checkpoint)
|
273 |
+
|
274 |
+
def _forward(self, x, context=None, refer=None):
|
275 |
+
flag=0
|
276 |
+
if refer==None:
|
277 |
+
refer = x
|
278 |
+
else:
|
279 |
+
x_len = x.shape[1]
|
280 |
+
x = torch.cat([x,refer],dim=1)
|
281 |
+
flag=1
|
282 |
+
x = self.attn1(self.norm1(x), context=context if self.disable_self_attn else None) + x
|
283 |
+
if flag == 1:
|
284 |
+
x = x[:,:x_len,:]
|
285 |
+
x = self.attn2(self.norm2(x), context=context) + x
|
286 |
+
x = self.ff(self.norm3(x)) + x
|
287 |
+
if flag==1:
|
288 |
+
return x
|
289 |
+
else:
|
290 |
+
return x, refer
|
291 |
+
|
292 |
+
|
293 |
+
class SpatialTransformer(nn.Module):
|
294 |
+
"""
|
295 |
+
Transformer block for image-like data.
|
296 |
+
First, project the input (aka embedding)
|
297 |
+
and reshape to b, t, d.
|
298 |
+
Then apply standard transformer action.
|
299 |
+
Finally, reshape to image
|
300 |
+
NEW: use_linear for more efficiency instead of the 1x1 convs
|
301 |
+
"""
|
302 |
+
def __init__(self, in_channels, n_heads, d_head,
|
303 |
+
depth=1, dropout=0., context_dim=None,
|
304 |
+
disable_self_attn=False, use_linear=False,
|
305 |
+
use_checkpoint=True):
|
306 |
+
super().__init__()
|
307 |
+
if exists(context_dim) and not isinstance(context_dim, list):
|
308 |
+
context_dim = [context_dim]
|
309 |
+
self.in_channels = in_channels
|
310 |
+
inner_dim = n_heads * d_head
|
311 |
+
self.norm = Normalize(in_channels)
|
312 |
+
if not use_linear:
|
313 |
+
self.proj_in = nn.Conv1d(in_channels,
|
314 |
+
inner_dim,
|
315 |
+
kernel_size=1,
|
316 |
+
stride=1,
|
317 |
+
padding=0)
|
318 |
+
else:
|
319 |
+
self.proj_in = nn.Linear(in_channels, inner_dim)
|
320 |
+
|
321 |
+
self.transformer_blocks = nn.ModuleList(
|
322 |
+
[BasicTransformerBlock(inner_dim, n_heads, d_head, dropout=dropout, context_dim=context_dim[d],
|
323 |
+
disable_self_attn=disable_self_attn, checkpoint=use_checkpoint)
|
324 |
+
for d in range(depth)]
|
325 |
+
)
|
326 |
+
if not use_linear:
|
327 |
+
self.proj_out = zero_module(nn.Conv1d(inner_dim,
|
328 |
+
in_channels,
|
329 |
+
kernel_size=1,
|
330 |
+
stride=1,
|
331 |
+
padding=0))
|
332 |
+
else:
|
333 |
+
self.proj_out = zero_module(nn.Linear(in_channels, inner_dim))
|
334 |
+
self.use_linear = use_linear
|
335 |
+
|
336 |
+
def forward(self, x, context=None, refer=None):
|
337 |
+
# note: if no context is given, cross-attention defaults to self-attention
|
338 |
+
if not isinstance(context, list):
|
339 |
+
context = [context]
|
340 |
+
if refer is not None and not isinstance(refer, list):
|
341 |
+
refer = [refer]
|
342 |
+
b, c, t = x.shape
|
343 |
+
x_in = x
|
344 |
+
x = self.norm(x)
|
345 |
+
if not self.use_linear:
|
346 |
+
x = self.proj_in(x)
|
347 |
+
x = rearrange(x, 'b c t -> b t c').contiguous()
|
348 |
+
if self.use_linear:
|
349 |
+
x = self.proj_in(x)
|
350 |
+
for i, block in enumerate(self.transformer_blocks):
|
351 |
+
if refer is not None:
|
352 |
+
x = block(x, context=context[i], refer=refer[i])
|
353 |
+
else:
|
354 |
+
x, refer_ret = block(x, context=context[i])
|
355 |
+
|
356 |
+
if self.use_linear:
|
357 |
+
x = self.proj_out(x)
|
358 |
+
x = rearrange(x, 'b t c -> b c t', t=t).contiguous()
|
359 |
+
if not self.use_linear:
|
360 |
+
x = self.proj_out(x)
|
361 |
+
if refer is not None:
|
362 |
+
return x+x_in
|
363 |
+
else:
|
364 |
+
return x + x_in, refer_ret
|
365 |
+
|
ttts/AA_diffusion_deprecated/ldm/modules/diffusionmodules/__init__.py
ADDED
File without changes
|
ttts/AA_diffusion_deprecated/ldm/modules/diffusionmodules/model.py
ADDED
@@ -0,0 +1,852 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 ldm.modules.attention import MemoryEfficientCrossAttention
|
10 |
+
|
11 |
+
try:
|
12 |
+
import xformers
|
13 |
+
import xformers.ops
|
14 |
+
XFORMERS_IS_AVAILBLE = True
|
15 |
+
except:
|
16 |
+
XFORMERS_IS_AVAILBLE = False
|
17 |
+
print("No module 'xformers'. Proceeding without it.")
|
18 |
+
|
19 |
+
|
20 |
+
def get_timestep_embedding(timesteps, embedding_dim):
|
21 |
+
"""
|
22 |
+
This matches the implementation in Denoising Diffusion Probabilistic Models:
|
23 |
+
From Fairseq.
|
24 |
+
Build sinusoidal embeddings.
|
25 |
+
This matches the implementation in tensor2tensor, but differs slightly
|
26 |
+
from the description in Section 3.5 of "Attention Is All You Need".
|
27 |
+
"""
|
28 |
+
assert len(timesteps.shape) == 1
|
29 |
+
|
30 |
+
half_dim = embedding_dim // 2
|
31 |
+
emb = math.log(10000) / (half_dim - 1)
|
32 |
+
emb = torch.exp(torch.arange(half_dim, dtype=torch.float32) * -emb)
|
33 |
+
emb = emb.to(device=timesteps.device)
|
34 |
+
emb = timesteps.float()[:, None] * emb[None, :]
|
35 |
+
emb = torch.cat([torch.sin(emb), torch.cos(emb)], dim=1)
|
36 |
+
if embedding_dim % 2 == 1: # zero pad
|
37 |
+
emb = torch.nn.functional.pad(emb, (0,1,0,0))
|
38 |
+
return emb
|
39 |
+
|
40 |
+
|
41 |
+
def nonlinearity(x):
|
42 |
+
# swish
|
43 |
+
return x*torch.sigmoid(x)
|
44 |
+
|
45 |
+
|
46 |
+
def Normalize(in_channels, num_groups=32):
|
47 |
+
return torch.nn.GroupNorm(num_groups=num_groups, num_channels=in_channels, eps=1e-6, affine=True)
|
48 |
+
|
49 |
+
|
50 |
+
class Upsample(nn.Module):
|
51 |
+
def __init__(self, in_channels, with_conv):
|
52 |
+
super().__init__()
|
53 |
+
self.with_conv = with_conv
|
54 |
+
if self.with_conv:
|
55 |
+
self.conv = torch.nn.Conv2d(in_channels,
|
56 |
+
in_channels,
|
57 |
+
kernel_size=3,
|
58 |
+
stride=1,
|
59 |
+
padding=1)
|
60 |
+
|
61 |
+
def forward(self, x):
|
62 |
+
x = torch.nn.functional.interpolate(x, scale_factor=2.0, mode="nearest")
|
63 |
+
if self.with_conv:
|
64 |
+
x = self.conv(x)
|
65 |
+
return x
|
66 |
+
|
67 |
+
|
68 |
+
class Downsample(nn.Module):
|
69 |
+
def __init__(self, in_channels, with_conv):
|
70 |
+
super().__init__()
|
71 |
+
self.with_conv = with_conv
|
72 |
+
if self.with_conv:
|
73 |
+
# no asymmetric padding in torch conv, must do it ourselves
|
74 |
+
self.conv = torch.nn.Conv2d(in_channels,
|
75 |
+
in_channels,
|
76 |
+
kernel_size=3,
|
77 |
+
stride=2,
|
78 |
+
padding=0)
|
79 |
+
|
80 |
+
def forward(self, x):
|
81 |
+
if self.with_conv:
|
82 |
+
pad = (0,1,0,1)
|
83 |
+
x = torch.nn.functional.pad(x, pad, mode="constant", value=0)
|
84 |
+
x = self.conv(x)
|
85 |
+
else:
|
86 |
+
x = torch.nn.functional.avg_pool2d(x, kernel_size=2, stride=2)
|
87 |
+
return x
|
88 |
+
|
89 |
+
|
90 |
+
class ResnetBlock(nn.Module):
|
91 |
+
def __init__(self, *, in_channels, out_channels=None, conv_shortcut=False,
|
92 |
+
dropout, temb_channels=512):
|
93 |
+
super().__init__()
|
94 |
+
self.in_channels = in_channels
|
95 |
+
out_channels = in_channels if out_channels is None else out_channels
|
96 |
+
self.out_channels = out_channels
|
97 |
+
self.use_conv_shortcut = conv_shortcut
|
98 |
+
|
99 |
+
self.norm1 = Normalize(in_channels)
|
100 |
+
self.conv1 = torch.nn.Conv2d(in_channels,
|
101 |
+
out_channels,
|
102 |
+
kernel_size=3,
|
103 |
+
stride=1,
|
104 |
+
padding=1)
|
105 |
+
if temb_channels > 0:
|
106 |
+
self.temb_proj = torch.nn.Linear(temb_channels,
|
107 |
+
out_channels)
|
108 |
+
self.norm2 = Normalize(out_channels)
|
109 |
+
self.dropout = torch.nn.Dropout(dropout)
|
110 |
+
self.conv2 = torch.nn.Conv2d(out_channels,
|
111 |
+
out_channels,
|
112 |
+
kernel_size=3,
|
113 |
+
stride=1,
|
114 |
+
padding=1)
|
115 |
+
if self.in_channels != self.out_channels:
|
116 |
+
if self.use_conv_shortcut:
|
117 |
+
self.conv_shortcut = torch.nn.Conv2d(in_channels,
|
118 |
+
out_channels,
|
119 |
+
kernel_size=3,
|
120 |
+
stride=1,
|
121 |
+
padding=1)
|
122 |
+
else:
|
123 |
+
self.nin_shortcut = torch.nn.Conv2d(in_channels,
|
124 |
+
out_channels,
|
125 |
+
kernel_size=1,
|
126 |
+
stride=1,
|
127 |
+
padding=0)
|
128 |
+
|
129 |
+
def forward(self, x, temb):
|
130 |
+
h = x
|
131 |
+
h = self.norm1(h)
|
132 |
+
h = nonlinearity(h)
|
133 |
+
h = self.conv1(h)
|
134 |
+
|
135 |
+
if temb is not None:
|
136 |
+
h = h + self.temb_proj(nonlinearity(temb))[:,:,None,None]
|
137 |
+
|
138 |
+
h = self.norm2(h)
|
139 |
+
h = nonlinearity(h)
|
140 |
+
h = self.dropout(h)
|
141 |
+
h = self.conv2(h)
|
142 |
+
|
143 |
+
if self.in_channels != self.out_channels:
|
144 |
+
if self.use_conv_shortcut:
|
145 |
+
x = self.conv_shortcut(x)
|
146 |
+
else:
|
147 |
+
x = self.nin_shortcut(x)
|
148 |
+
|
149 |
+
return x+h
|
150 |
+
|
151 |
+
|
152 |
+
class AttnBlock(nn.Module):
|
153 |
+
def __init__(self, in_channels):
|
154 |
+
super().__init__()
|
155 |
+
self.in_channels = in_channels
|
156 |
+
|
157 |
+
self.norm = Normalize(in_channels)
|
158 |
+
self.q = torch.nn.Conv2d(in_channels,
|
159 |
+
in_channels,
|
160 |
+
kernel_size=1,
|
161 |
+
stride=1,
|
162 |
+
padding=0)
|
163 |
+
self.k = torch.nn.Conv2d(in_channels,
|
164 |
+
in_channels,
|
165 |
+
kernel_size=1,
|
166 |
+
stride=1,
|
167 |
+
padding=0)
|
168 |
+
self.v = torch.nn.Conv2d(in_channels,
|
169 |
+
in_channels,
|
170 |
+
kernel_size=1,
|
171 |
+
stride=1,
|
172 |
+
padding=0)
|
173 |
+
self.proj_out = torch.nn.Conv2d(in_channels,
|
174 |
+
in_channels,
|
175 |
+
kernel_size=1,
|
176 |
+
stride=1,
|
177 |
+
padding=0)
|
178 |
+
|
179 |
+
def forward(self, x):
|
180 |
+
h_ = x
|
181 |
+
h_ = self.norm(h_)
|
182 |
+
q = self.q(h_)
|
183 |
+
k = self.k(h_)
|
184 |
+
v = self.v(h_)
|
185 |
+
|
186 |
+
# compute attention
|
187 |
+
b,c,h,w = q.shape
|
188 |
+
q = q.reshape(b,c,h*w)
|
189 |
+
q = q.permute(0,2,1) # b,hw,c
|
190 |
+
k = k.reshape(b,c,h*w) # b,c,hw
|
191 |
+
w_ = torch.bmm(q,k) # b,hw,hw w[b,i,j]=sum_c q[b,i,c]k[b,c,j]
|
192 |
+
w_ = w_ * (int(c)**(-0.5))
|
193 |
+
w_ = torch.nn.functional.softmax(w_, dim=2)
|
194 |
+
|
195 |
+
# attend to values
|
196 |
+
v = v.reshape(b,c,h*w)
|
197 |
+
w_ = w_.permute(0,2,1) # b,hw,hw (first hw of k, second of q)
|
198 |
+
h_ = torch.bmm(v,w_) # b, c,hw (hw of q) h_[b,c,j] = sum_i v[b,c,i] w_[b,i,j]
|
199 |
+
h_ = h_.reshape(b,c,h,w)
|
200 |
+
|
201 |
+
h_ = self.proj_out(h_)
|
202 |
+
|
203 |
+
return x+h_
|
204 |
+
|
205 |
+
class MemoryEfficientAttnBlock(nn.Module):
|
206 |
+
"""
|
207 |
+
Uses xformers efficient implementation,
|
208 |
+
see https://github.com/MatthieuTPHR/diffusers/blob/d80b531ff8060ec1ea982b65a1b8df70f73aa67c/src/diffusers/models/attention.py#L223
|
209 |
+
Note: this is a single-head self-attention operation
|
210 |
+
"""
|
211 |
+
#
|
212 |
+
def __init__(self, in_channels):
|
213 |
+
super().__init__()
|
214 |
+
self.in_channels = in_channels
|
215 |
+
|
216 |
+
self.norm = Normalize(in_channels)
|
217 |
+
self.q = torch.nn.Conv2d(in_channels,
|
218 |
+
in_channels,
|
219 |
+
kernel_size=1,
|
220 |
+
stride=1,
|
221 |
+
padding=0)
|
222 |
+
self.k = torch.nn.Conv2d(in_channels,
|
223 |
+
in_channels,
|
224 |
+
kernel_size=1,
|
225 |
+
stride=1,
|
226 |
+
padding=0)
|
227 |
+
self.v = torch.nn.Conv2d(in_channels,
|
228 |
+
in_channels,
|
229 |
+
kernel_size=1,
|
230 |
+
stride=1,
|
231 |
+
padding=0)
|
232 |
+
self.proj_out = torch.nn.Conv2d(in_channels,
|
233 |
+
in_channels,
|
234 |
+
kernel_size=1,
|
235 |
+
stride=1,
|
236 |
+
padding=0)
|
237 |
+
self.attention_op: Optional[Any] = None
|
238 |
+
|
239 |
+
def forward(self, x):
|
240 |
+
h_ = x
|
241 |
+
h_ = self.norm(h_)
|
242 |
+
q = self.q(h_)
|
243 |
+
k = self.k(h_)
|
244 |
+
v = self.v(h_)
|
245 |
+
|
246 |
+
# compute attention
|
247 |
+
B, C, H, W = q.shape
|
248 |
+
q, k, v = map(lambda x: rearrange(x, 'b c h w -> b (h w) c'), (q, k, v))
|
249 |
+
|
250 |
+
q, k, v = map(
|
251 |
+
lambda t: t.unsqueeze(3)
|
252 |
+
.reshape(B, t.shape[1], 1, C)
|
253 |
+
.permute(0, 2, 1, 3)
|
254 |
+
.reshape(B * 1, t.shape[1], C)
|
255 |
+
.contiguous(),
|
256 |
+
(q, k, v),
|
257 |
+
)
|
258 |
+
out = xformers.ops.memory_efficient_attention(q, k, v, attn_bias=None, op=self.attention_op)
|
259 |
+
|
260 |
+
out = (
|
261 |
+
out.unsqueeze(0)
|
262 |
+
.reshape(B, 1, out.shape[1], C)
|
263 |
+
.permute(0, 2, 1, 3)
|
264 |
+
.reshape(B, out.shape[1], C)
|
265 |
+
)
|
266 |
+
out = rearrange(out, 'b (h w) c -> b c h w', b=B, h=H, w=W, c=C)
|
267 |
+
out = self.proj_out(out)
|
268 |
+
return x+out
|
269 |
+
|
270 |
+
|
271 |
+
class MemoryEfficientCrossAttentionWrapper(MemoryEfficientCrossAttention):
|
272 |
+
def forward(self, x, context=None, mask=None):
|
273 |
+
b, c, h, w = x.shape
|
274 |
+
x = rearrange(x, 'b c h w -> b (h w) c')
|
275 |
+
out = super().forward(x, context=context, mask=mask)
|
276 |
+
out = rearrange(out, 'b (h w) c -> b c h w', h=h, w=w, c=c)
|
277 |
+
return x + out
|
278 |
+
|
279 |
+
|
280 |
+
def make_attn(in_channels, attn_type="vanilla", attn_kwargs=None):
|
281 |
+
assert attn_type in ["vanilla", "vanilla-xformers", "memory-efficient-cross-attn", "linear", "none"], f'attn_type {attn_type} unknown'
|
282 |
+
if XFORMERS_IS_AVAILBLE and attn_type == "vanilla":
|
283 |
+
attn_type = "vanilla-xformers"
|
284 |
+
print(f"making attention of type '{attn_type}' with {in_channels} in_channels")
|
285 |
+
if attn_type == "vanilla":
|
286 |
+
assert attn_kwargs is None
|
287 |
+
return AttnBlock(in_channels)
|
288 |
+
elif attn_type == "vanilla-xformers":
|
289 |
+
print(f"building MemoryEfficientAttnBlock with {in_channels} in_channels...")
|
290 |
+
return MemoryEfficientAttnBlock(in_channels)
|
291 |
+
elif type == "memory-efficient-cross-attn":
|
292 |
+
attn_kwargs["query_dim"] = in_channels
|
293 |
+
return MemoryEfficientCrossAttentionWrapper(**attn_kwargs)
|
294 |
+
elif attn_type == "none":
|
295 |
+
return nn.Identity(in_channels)
|
296 |
+
else:
|
297 |
+
raise NotImplementedError()
|
298 |
+
|
299 |
+
|
300 |
+
class Model(nn.Module):
|
301 |
+
def __init__(self, *, ch, out_ch, ch_mult=(1,2,4,8), num_res_blocks,
|
302 |
+
attn_resolutions, dropout=0.0, resamp_with_conv=True, in_channels,
|
303 |
+
resolution, use_timestep=True, use_linear_attn=False, attn_type="vanilla"):
|
304 |
+
super().__init__()
|
305 |
+
if use_linear_attn: attn_type = "linear"
|
306 |
+
self.ch = ch
|
307 |
+
self.temb_ch = self.ch*4
|
308 |
+
self.num_resolutions = len(ch_mult)
|
309 |
+
self.num_res_blocks = num_res_blocks
|
310 |
+
self.resolution = resolution
|
311 |
+
self.in_channels = in_channels
|
312 |
+
|
313 |
+
self.use_timestep = use_timestep
|
314 |
+
if self.use_timestep:
|
315 |
+
# timestep embedding
|
316 |
+
self.temb = nn.Module()
|
317 |
+
self.temb.dense = nn.ModuleList([
|
318 |
+
torch.nn.Linear(self.ch,
|
319 |
+
self.temb_ch),
|
320 |
+
torch.nn.Linear(self.temb_ch,
|
321 |
+
self.temb_ch),
|
322 |
+
])
|
323 |
+
|
324 |
+
# downsampling
|
325 |
+
self.conv_in = torch.nn.Conv2d(in_channels,
|
326 |
+
self.ch,
|
327 |
+
kernel_size=3,
|
328 |
+
stride=1,
|
329 |
+
padding=1)
|
330 |
+
|
331 |
+
curr_res = resolution
|
332 |
+
in_ch_mult = (1,)+tuple(ch_mult)
|
333 |
+
self.down = nn.ModuleList()
|
334 |
+
for i_level in range(self.num_resolutions):
|
335 |
+
block = nn.ModuleList()
|
336 |
+
attn = nn.ModuleList()
|
337 |
+
block_in = ch*in_ch_mult[i_level]
|
338 |
+
block_out = ch*ch_mult[i_level]
|
339 |
+
for i_block in range(self.num_res_blocks):
|
340 |
+
block.append(ResnetBlock(in_channels=block_in,
|
341 |
+
out_channels=block_out,
|
342 |
+
temb_channels=self.temb_ch,
|
343 |
+
dropout=dropout))
|
344 |
+
block_in = block_out
|
345 |
+
if curr_res in attn_resolutions:
|
346 |
+
attn.append(make_attn(block_in, attn_type=attn_type))
|
347 |
+
down = nn.Module()
|
348 |
+
down.block = block
|
349 |
+
down.attn = attn
|
350 |
+
if i_level != self.num_resolutions-1:
|
351 |
+
down.downsample = Downsample(block_in, resamp_with_conv)
|
352 |
+
curr_res = curr_res // 2
|
353 |
+
self.down.append(down)
|
354 |
+
|
355 |
+
# middle
|
356 |
+
self.mid = nn.Module()
|
357 |
+
self.mid.block_1 = ResnetBlock(in_channels=block_in,
|
358 |
+
out_channels=block_in,
|
359 |
+
temb_channels=self.temb_ch,
|
360 |
+
dropout=dropout)
|
361 |
+
self.mid.attn_1 = make_attn(block_in, attn_type=attn_type)
|
362 |
+
self.mid.block_2 = ResnetBlock(in_channels=block_in,
|
363 |
+
out_channels=block_in,
|
364 |
+
temb_channels=self.temb_ch,
|
365 |
+
dropout=dropout)
|
366 |
+
|
367 |
+
# upsampling
|
368 |
+
self.up = nn.ModuleList()
|
369 |
+
for i_level in reversed(range(self.num_resolutions)):
|
370 |
+
block = nn.ModuleList()
|
371 |
+
attn = nn.ModuleList()
|
372 |
+
block_out = ch*ch_mult[i_level]
|
373 |
+
skip_in = ch*ch_mult[i_level]
|
374 |
+
for i_block in range(self.num_res_blocks+1):
|
375 |
+
if i_block == self.num_res_blocks:
|
376 |
+
skip_in = ch*in_ch_mult[i_level]
|
377 |
+
block.append(ResnetBlock(in_channels=block_in+skip_in,
|
378 |
+
out_channels=block_out,
|
379 |
+
temb_channels=self.temb_ch,
|
380 |
+
dropout=dropout))
|
381 |
+
block_in = block_out
|
382 |
+
if curr_res in attn_resolutions:
|
383 |
+
attn.append(make_attn(block_in, attn_type=attn_type))
|
384 |
+
up = nn.Module()
|
385 |
+
up.block = block
|
386 |
+
up.attn = attn
|
387 |
+
if i_level != 0:
|
388 |
+
up.upsample = Upsample(block_in, resamp_with_conv)
|
389 |
+
curr_res = curr_res * 2
|
390 |
+
self.up.insert(0, up) # prepend to get consistent order
|
391 |
+
|
392 |
+
# end
|
393 |
+
self.norm_out = Normalize(block_in)
|
394 |
+
self.conv_out = torch.nn.Conv2d(block_in,
|
395 |
+
out_ch,
|
396 |
+
kernel_size=3,
|
397 |
+
stride=1,
|
398 |
+
padding=1)
|
399 |
+
|
400 |
+
def forward(self, x, t=None, context=None):
|
401 |
+
#assert x.shape[2] == x.shape[3] == self.resolution
|
402 |
+
if context is not None:
|
403 |
+
# assume aligned context, cat along channel axis
|
404 |
+
x = torch.cat((x, context), dim=1)
|
405 |
+
if self.use_timestep:
|
406 |
+
# timestep embedding
|
407 |
+
assert t is not None
|
408 |
+
temb = get_timestep_embedding(t, self.ch)
|
409 |
+
temb = self.temb.dense[0](temb)
|
410 |
+
temb = nonlinearity(temb)
|
411 |
+
temb = self.temb.dense[1](temb)
|
412 |
+
else:
|
413 |
+
temb = None
|
414 |
+
|
415 |
+
# downsampling
|
416 |
+
hs = [self.conv_in(x)]
|
417 |
+
for i_level in range(self.num_resolutions):
|
418 |
+
for i_block in range(self.num_res_blocks):
|
419 |
+
h = self.down[i_level].block[i_block](hs[-1], temb)
|
420 |
+
if len(self.down[i_level].attn) > 0:
|
421 |
+
h = self.down[i_level].attn[i_block](h)
|
422 |
+
hs.append(h)
|
423 |
+
if i_level != self.num_resolutions-1:
|
424 |
+
hs.append(self.down[i_level].downsample(hs[-1]))
|
425 |
+
|
426 |
+
# middle
|
427 |
+
h = hs[-1]
|
428 |
+
h = self.mid.block_1(h, temb)
|
429 |
+
h = self.mid.attn_1(h)
|
430 |
+
h = self.mid.block_2(h, temb)
|
431 |
+
|
432 |
+
# upsampling
|
433 |
+
for i_level in reversed(range(self.num_resolutions)):
|
434 |
+
for i_block in range(self.num_res_blocks+1):
|
435 |
+
h = self.up[i_level].block[i_block](
|
436 |
+
torch.cat([h, hs.pop()], dim=1), temb)
|
437 |
+
if len(self.up[i_level].attn) > 0:
|
438 |
+
h = self.up[i_level].attn[i_block](h)
|
439 |
+
if i_level != 0:
|
440 |
+
h = self.up[i_level].upsample(h)
|
441 |
+
|
442 |
+
# end
|
443 |
+
h = self.norm_out(h)
|
444 |
+
h = nonlinearity(h)
|
445 |
+
h = self.conv_out(h)
|
446 |
+
return h
|
447 |
+
|
448 |
+
def get_last_layer(self):
|
449 |
+
return self.conv_out.weight
|
450 |
+
|
451 |
+
|
452 |
+
class Encoder(nn.Module):
|
453 |
+
def __init__(self, *, ch, out_ch, ch_mult=(1,2,4,8), num_res_blocks,
|
454 |
+
attn_resolutions, dropout=0.0, resamp_with_conv=True, in_channels,
|
455 |
+
resolution, z_channels, double_z=True, use_linear_attn=False, attn_type="vanilla",
|
456 |
+
**ignore_kwargs):
|
457 |
+
super().__init__()
|
458 |
+
if use_linear_attn: attn_type = "linear"
|
459 |
+
self.ch = ch
|
460 |
+
self.temb_ch = 0
|
461 |
+
self.num_resolutions = len(ch_mult)
|
462 |
+
self.num_res_blocks = num_res_blocks
|
463 |
+
self.resolution = resolution
|
464 |
+
self.in_channels = in_channels
|
465 |
+
|
466 |
+
# downsampling
|
467 |
+
self.conv_in = torch.nn.Conv2d(in_channels,
|
468 |
+
self.ch,
|
469 |
+
kernel_size=3,
|
470 |
+
stride=1,
|
471 |
+
padding=1)
|
472 |
+
|
473 |
+
curr_res = resolution
|
474 |
+
in_ch_mult = (1,)+tuple(ch_mult)
|
475 |
+
self.in_ch_mult = in_ch_mult
|
476 |
+
self.down = nn.ModuleList()
|
477 |
+
for i_level in range(self.num_resolutions):
|
478 |
+
block = nn.ModuleList()
|
479 |
+
attn = nn.ModuleList()
|
480 |
+
block_in = ch*in_ch_mult[i_level]
|
481 |
+
block_out = ch*ch_mult[i_level]
|
482 |
+
for i_block in range(self.num_res_blocks):
|
483 |
+
block.append(ResnetBlock(in_channels=block_in,
|
484 |
+
out_channels=block_out,
|
485 |
+
temb_channels=self.temb_ch,
|
486 |
+
dropout=dropout))
|
487 |
+
block_in = block_out
|
488 |
+
if curr_res in attn_resolutions:
|
489 |
+
attn.append(make_attn(block_in, attn_type=attn_type))
|
490 |
+
down = nn.Module()
|
491 |
+
down.block = block
|
492 |
+
down.attn = attn
|
493 |
+
if i_level != self.num_resolutions-1:
|
494 |
+
down.downsample = Downsample(block_in, resamp_with_conv)
|
495 |
+
curr_res = curr_res // 2
|
496 |
+
self.down.append(down)
|
497 |
+
|
498 |
+
# middle
|
499 |
+
self.mid = nn.Module()
|
500 |
+
self.mid.block_1 = ResnetBlock(in_channels=block_in,
|
501 |
+
out_channels=block_in,
|
502 |
+
temb_channels=self.temb_ch,
|
503 |
+
dropout=dropout)
|
504 |
+
self.mid.attn_1 = make_attn(block_in, attn_type=attn_type)
|
505 |
+
self.mid.block_2 = ResnetBlock(in_channels=block_in,
|
506 |
+
out_channels=block_in,
|
507 |
+
temb_channels=self.temb_ch,
|
508 |
+
dropout=dropout)
|
509 |
+
|
510 |
+
# end
|
511 |
+
self.norm_out = Normalize(block_in)
|
512 |
+
self.conv_out = torch.nn.Conv2d(block_in,
|
513 |
+
2*z_channels if double_z else z_channels,
|
514 |
+
kernel_size=3,
|
515 |
+
stride=1,
|
516 |
+
padding=1)
|
517 |
+
|
518 |
+
def forward(self, x):
|
519 |
+
# timestep embedding
|
520 |
+
temb = None
|
521 |
+
|
522 |
+
# downsampling
|
523 |
+
hs = [self.conv_in(x)]
|
524 |
+
for i_level in range(self.num_resolutions):
|
525 |
+
for i_block in range(self.num_res_blocks):
|
526 |
+
h = self.down[i_level].block[i_block](hs[-1], temb)
|
527 |
+
if len(self.down[i_level].attn) > 0:
|
528 |
+
h = self.down[i_level].attn[i_block](h)
|
529 |
+
hs.append(h)
|
530 |
+
if i_level != self.num_resolutions-1:
|
531 |
+
hs.append(self.down[i_level].downsample(hs[-1]))
|
532 |
+
|
533 |
+
# middle
|
534 |
+
h = hs[-1]
|
535 |
+
h = self.mid.block_1(h, temb)
|
536 |
+
h = self.mid.attn_1(h)
|
537 |
+
h = self.mid.block_2(h, temb)
|
538 |
+
|
539 |
+
# end
|
540 |
+
h = self.norm_out(h)
|
541 |
+
h = nonlinearity(h)
|
542 |
+
h = self.conv_out(h)
|
543 |
+
return h
|
544 |
+
|
545 |
+
|
546 |
+
class Decoder(nn.Module):
|
547 |
+
def __init__(self, *, ch, out_ch, ch_mult=(1,2,4,8), num_res_blocks,
|
548 |
+
attn_resolutions, dropout=0.0, resamp_with_conv=True, in_channels,
|
549 |
+
resolution, z_channels, give_pre_end=False, tanh_out=False, use_linear_attn=False,
|
550 |
+
attn_type="vanilla", **ignorekwargs):
|
551 |
+
super().__init__()
|
552 |
+
if use_linear_attn: attn_type = "linear"
|
553 |
+
self.ch = ch
|
554 |
+
self.temb_ch = 0
|
555 |
+
self.num_resolutions = len(ch_mult)
|
556 |
+
self.num_res_blocks = num_res_blocks
|
557 |
+
self.resolution = resolution
|
558 |
+
self.in_channels = in_channels
|
559 |
+
self.give_pre_end = give_pre_end
|
560 |
+
self.tanh_out = tanh_out
|
561 |
+
|
562 |
+
# compute in_ch_mult, block_in and curr_res at lowest res
|
563 |
+
in_ch_mult = (1,)+tuple(ch_mult)
|
564 |
+
block_in = ch*ch_mult[self.num_resolutions-1]
|
565 |
+
curr_res = resolution // 2**(self.num_resolutions-1)
|
566 |
+
self.z_shape = (1,z_channels,curr_res,curr_res)
|
567 |
+
print("Working with z of shape {} = {} dimensions.".format(
|
568 |
+
self.z_shape, np.prod(self.z_shape)))
|
569 |
+
|
570 |
+
# z to block_in
|
571 |
+
self.conv_in = torch.nn.Conv2d(z_channels,
|
572 |
+
block_in,
|
573 |
+
kernel_size=3,
|
574 |
+
stride=1,
|
575 |
+
padding=1)
|
576 |
+
|
577 |
+
# middle
|
578 |
+
self.mid = nn.Module()
|
579 |
+
self.mid.block_1 = ResnetBlock(in_channels=block_in,
|
580 |
+
out_channels=block_in,
|
581 |
+
temb_channels=self.temb_ch,
|
582 |
+
dropout=dropout)
|
583 |
+
self.mid.attn_1 = make_attn(block_in, attn_type=attn_type)
|
584 |
+
self.mid.block_2 = ResnetBlock(in_channels=block_in,
|
585 |
+
out_channels=block_in,
|
586 |
+
temb_channels=self.temb_ch,
|
587 |
+
dropout=dropout)
|
588 |
+
|
589 |
+
# upsampling
|
590 |
+
self.up = nn.ModuleList()
|
591 |
+
for i_level in reversed(range(self.num_resolutions)):
|
592 |
+
block = nn.ModuleList()
|
593 |
+
attn = nn.ModuleList()
|
594 |
+
block_out = ch*ch_mult[i_level]
|
595 |
+
for i_block in range(self.num_res_blocks+1):
|
596 |
+
block.append(ResnetBlock(in_channels=block_in,
|
597 |
+
out_channels=block_out,
|
598 |
+
temb_channels=self.temb_ch,
|
599 |
+
dropout=dropout))
|
600 |
+
block_in = block_out
|
601 |
+
if curr_res in attn_resolutions:
|
602 |
+
attn.append(make_attn(block_in, attn_type=attn_type))
|
603 |
+
up = nn.Module()
|
604 |
+
up.block = block
|
605 |
+
up.attn = attn
|
606 |
+
if i_level != 0:
|
607 |
+
up.upsample = Upsample(block_in, resamp_with_conv)
|
608 |
+
curr_res = curr_res * 2
|
609 |
+
self.up.insert(0, up) # prepend to get consistent order
|
610 |
+
|
611 |
+
# end
|
612 |
+
self.norm_out = Normalize(block_in)
|
613 |
+
self.conv_out = torch.nn.Conv2d(block_in,
|
614 |
+
out_ch,
|
615 |
+
kernel_size=3,
|
616 |
+
stride=1,
|
617 |
+
padding=1)
|
618 |
+
|
619 |
+
def forward(self, z):
|
620 |
+
#assert z.shape[1:] == self.z_shape[1:]
|
621 |
+
self.last_z_shape = z.shape
|
622 |
+
|
623 |
+
# timestep embedding
|
624 |
+
temb = None
|
625 |
+
|
626 |
+
# z to block_in
|
627 |
+
h = self.conv_in(z)
|
628 |
+
|
629 |
+
# middle
|
630 |
+
h = self.mid.block_1(h, temb)
|
631 |
+
h = self.mid.attn_1(h)
|
632 |
+
h = self.mid.block_2(h, temb)
|
633 |
+
|
634 |
+
# upsampling
|
635 |
+
for i_level in reversed(range(self.num_resolutions)):
|
636 |
+
for i_block in range(self.num_res_blocks+1):
|
637 |
+
h = self.up[i_level].block[i_block](h, temb)
|
638 |
+
if len(self.up[i_level].attn) > 0:
|
639 |
+
h = self.up[i_level].attn[i_block](h)
|
640 |
+
if i_level != 0:
|
641 |
+
h = self.up[i_level].upsample(h)
|
642 |
+
|
643 |
+
# end
|
644 |
+
if self.give_pre_end:
|
645 |
+
return h
|
646 |
+
|
647 |
+
h = self.norm_out(h)
|
648 |
+
h = nonlinearity(h)
|
649 |
+
h = self.conv_out(h)
|
650 |
+
if self.tanh_out:
|
651 |
+
h = torch.tanh(h)
|
652 |
+
return h
|
653 |
+
|
654 |
+
|
655 |
+
class SimpleDecoder(nn.Module):
|
656 |
+
def __init__(self, in_channels, out_channels, *args, **kwargs):
|
657 |
+
super().__init__()
|
658 |
+
self.model = nn.ModuleList([nn.Conv2d(in_channels, in_channels, 1),
|
659 |
+
ResnetBlock(in_channels=in_channels,
|
660 |
+
out_channels=2 * in_channels,
|
661 |
+
temb_channels=0, dropout=0.0),
|
662 |
+
ResnetBlock(in_channels=2 * in_channels,
|
663 |
+
out_channels=4 * in_channels,
|
664 |
+
temb_channels=0, dropout=0.0),
|
665 |
+
ResnetBlock(in_channels=4 * in_channels,
|
666 |
+
out_channels=2 * in_channels,
|
667 |
+
temb_channels=0, dropout=0.0),
|
668 |
+
nn.Conv2d(2*in_channels, in_channels, 1),
|
669 |
+
Upsample(in_channels, with_conv=True)])
|
670 |
+
# end
|
671 |
+
self.norm_out = Normalize(in_channels)
|
672 |
+
self.conv_out = torch.nn.Conv2d(in_channels,
|
673 |
+
out_channels,
|
674 |
+
kernel_size=3,
|
675 |
+
stride=1,
|
676 |
+
padding=1)
|
677 |
+
|
678 |
+
def forward(self, x):
|
679 |
+
for i, layer in enumerate(self.model):
|
680 |
+
if i in [1,2,3]:
|
681 |
+
x = layer(x, None)
|
682 |
+
else:
|
683 |
+
x = layer(x)
|
684 |
+
|
685 |
+
h = self.norm_out(x)
|
686 |
+
h = nonlinearity(h)
|
687 |
+
x = self.conv_out(h)
|
688 |
+
return x
|
689 |
+
|
690 |
+
|
691 |
+
class UpsampleDecoder(nn.Module):
|
692 |
+
def __init__(self, in_channels, out_channels, ch, num_res_blocks, resolution,
|
693 |
+
ch_mult=(2,2), dropout=0.0):
|
694 |
+
super().__init__()
|
695 |
+
# upsampling
|
696 |
+
self.temb_ch = 0
|
697 |
+
self.num_resolutions = len(ch_mult)
|
698 |
+
self.num_res_blocks = num_res_blocks
|
699 |
+
block_in = in_channels
|
700 |
+
curr_res = resolution // 2 ** (self.num_resolutions - 1)
|
701 |
+
self.res_blocks = nn.ModuleList()
|
702 |
+
self.upsample_blocks = nn.ModuleList()
|
703 |
+
for i_level in range(self.num_resolutions):
|
704 |
+
res_block = []
|
705 |
+
block_out = ch * ch_mult[i_level]
|
706 |
+
for i_block in range(self.num_res_blocks + 1):
|
707 |
+
res_block.append(ResnetBlock(in_channels=block_in,
|
708 |
+
out_channels=block_out,
|
709 |
+
temb_channels=self.temb_ch,
|
710 |
+
dropout=dropout))
|
711 |
+
block_in = block_out
|
712 |
+
self.res_blocks.append(nn.ModuleList(res_block))
|
713 |
+
if i_level != self.num_resolutions - 1:
|
714 |
+
self.upsample_blocks.append(Upsample(block_in, True))
|
715 |
+
curr_res = curr_res * 2
|
716 |
+
|
717 |
+
# end
|
718 |
+
self.norm_out = Normalize(block_in)
|
719 |
+
self.conv_out = torch.nn.Conv2d(block_in,
|
720 |
+
out_channels,
|
721 |
+
kernel_size=3,
|
722 |
+
stride=1,
|
723 |
+
padding=1)
|
724 |
+
|
725 |
+
def forward(self, x):
|
726 |
+
# upsampling
|
727 |
+
h = x
|
728 |
+
for k, i_level in enumerate(range(self.num_resolutions)):
|
729 |
+
for i_block in range(self.num_res_blocks + 1):
|
730 |
+
h = self.res_blocks[i_level][i_block](h, None)
|
731 |
+
if i_level != self.num_resolutions - 1:
|
732 |
+
h = self.upsample_blocks[k](h)
|
733 |
+
h = self.norm_out(h)
|
734 |
+
h = nonlinearity(h)
|
735 |
+
h = self.conv_out(h)
|
736 |
+
return h
|
737 |
+
|
738 |
+
|
739 |
+
class LatentRescaler(nn.Module):
|
740 |
+
def __init__(self, factor, in_channels, mid_channels, out_channels, depth=2):
|
741 |
+
super().__init__()
|
742 |
+
# residual block, interpolate, residual block
|
743 |
+
self.factor = factor
|
744 |
+
self.conv_in = nn.Conv2d(in_channels,
|
745 |
+
mid_channels,
|
746 |
+
kernel_size=3,
|
747 |
+
stride=1,
|
748 |
+
padding=1)
|
749 |
+
self.res_block1 = nn.ModuleList([ResnetBlock(in_channels=mid_channels,
|
750 |
+
out_channels=mid_channels,
|
751 |
+
temb_channels=0,
|
752 |
+
dropout=0.0) for _ in range(depth)])
|
753 |
+
self.attn = AttnBlock(mid_channels)
|
754 |
+
self.res_block2 = nn.ModuleList([ResnetBlock(in_channels=mid_channels,
|
755 |
+
out_channels=mid_channels,
|
756 |
+
temb_channels=0,
|
757 |
+
dropout=0.0) for _ in range(depth)])
|
758 |
+
|
759 |
+
self.conv_out = nn.Conv2d(mid_channels,
|
760 |
+
out_channels,
|
761 |
+
kernel_size=1,
|
762 |
+
)
|
763 |
+
|
764 |
+
def forward(self, x):
|
765 |
+
x = self.conv_in(x)
|
766 |
+
for block in self.res_block1:
|
767 |
+
x = block(x, None)
|
768 |
+
x = torch.nn.functional.interpolate(x, size=(int(round(x.shape[2]*self.factor)), int(round(x.shape[3]*self.factor))))
|
769 |
+
x = self.attn(x)
|
770 |
+
for block in self.res_block2:
|
771 |
+
x = block(x, None)
|
772 |
+
x = self.conv_out(x)
|
773 |
+
return x
|
774 |
+
|
775 |
+
|
776 |
+
class MergedRescaleEncoder(nn.Module):
|
777 |
+
def __init__(self, in_channels, ch, resolution, out_ch, num_res_blocks,
|
778 |
+
attn_resolutions, dropout=0.0, resamp_with_conv=True,
|
779 |
+
ch_mult=(1,2,4,8), rescale_factor=1.0, rescale_module_depth=1):
|
780 |
+
super().__init__()
|
781 |
+
intermediate_chn = ch * ch_mult[-1]
|
782 |
+
self.encoder = Encoder(in_channels=in_channels, num_res_blocks=num_res_blocks, ch=ch, ch_mult=ch_mult,
|
783 |
+
z_channels=intermediate_chn, double_z=False, resolution=resolution,
|
784 |
+
attn_resolutions=attn_resolutions, dropout=dropout, resamp_with_conv=resamp_with_conv,
|
785 |
+
out_ch=None)
|
786 |
+
self.rescaler = LatentRescaler(factor=rescale_factor, in_channels=intermediate_chn,
|
787 |
+
mid_channels=intermediate_chn, out_channels=out_ch, depth=rescale_module_depth)
|
788 |
+
|
789 |
+
def forward(self, x):
|
790 |
+
x = self.encoder(x)
|
791 |
+
x = self.rescaler(x)
|
792 |
+
return x
|
793 |
+
|
794 |
+
|
795 |
+
class MergedRescaleDecoder(nn.Module):
|
796 |
+
def __init__(self, z_channels, out_ch, resolution, num_res_blocks, attn_resolutions, ch, ch_mult=(1,2,4,8),
|
797 |
+
dropout=0.0, resamp_with_conv=True, rescale_factor=1.0, rescale_module_depth=1):
|
798 |
+
super().__init__()
|
799 |
+
tmp_chn = z_channels*ch_mult[-1]
|
800 |
+
self.decoder = Decoder(out_ch=out_ch, z_channels=tmp_chn, attn_resolutions=attn_resolutions, dropout=dropout,
|
801 |
+
resamp_with_conv=resamp_with_conv, in_channels=None, num_res_blocks=num_res_blocks,
|
802 |
+
ch_mult=ch_mult, resolution=resolution, ch=ch)
|
803 |
+
self.rescaler = LatentRescaler(factor=rescale_factor, in_channels=z_channels, mid_channels=tmp_chn,
|
804 |
+
out_channels=tmp_chn, depth=rescale_module_depth)
|
805 |
+
|
806 |
+
def forward(self, x):
|
807 |
+
x = self.rescaler(x)
|
808 |
+
x = self.decoder(x)
|
809 |
+
return x
|
810 |
+
|
811 |
+
|
812 |
+
class Upsampler(nn.Module):
|
813 |
+
def __init__(self, in_size, out_size, in_channels, out_channels, ch_mult=2):
|
814 |
+
super().__init__()
|
815 |
+
assert out_size >= in_size
|
816 |
+
num_blocks = int(np.log2(out_size//in_size))+1
|
817 |
+
factor_up = 1.+ (out_size % in_size)
|
818 |
+
print(f"Building {self.__class__.__name__} with in_size: {in_size} --> out_size {out_size} and factor {factor_up}")
|
819 |
+
self.rescaler = LatentRescaler(factor=factor_up, in_channels=in_channels, mid_channels=2*in_channels,
|
820 |
+
out_channels=in_channels)
|
821 |
+
self.decoder = Decoder(out_ch=out_channels, resolution=out_size, z_channels=in_channels, num_res_blocks=2,
|
822 |
+
attn_resolutions=[], in_channels=None, ch=in_channels,
|
823 |
+
ch_mult=[ch_mult for _ in range(num_blocks)])
|
824 |
+
|
825 |
+
def forward(self, x):
|
826 |
+
x = self.rescaler(x)
|
827 |
+
x = self.decoder(x)
|
828 |
+
return x
|
829 |
+
|
830 |
+
|
831 |
+
class Resize(nn.Module):
|
832 |
+
def __init__(self, in_channels=None, learned=False, mode="bilinear"):
|
833 |
+
super().__init__()
|
834 |
+
self.with_conv = learned
|
835 |
+
self.mode = mode
|
836 |
+
if self.with_conv:
|
837 |
+
print(f"Note: {self.__class__.__name} uses learned downsampling and will ignore the fixed {mode} mode")
|
838 |
+
raise NotImplementedError()
|
839 |
+
assert in_channels is not None
|
840 |
+
# no asymmetric padding in torch conv, must do it ourselves
|
841 |
+
self.conv = torch.nn.Conv2d(in_channels,
|
842 |
+
in_channels,
|
843 |
+
kernel_size=4,
|
844 |
+
stride=2,
|
845 |
+
padding=1)
|
846 |
+
|
847 |
+
def forward(self, x, scale_factor=1.0):
|
848 |
+
if scale_factor==1.0:
|
849 |
+
return x
|
850 |
+
else:
|
851 |
+
x = torch.nn.functional.interpolate(x, mode=self.mode, align_corners=False, scale_factor=scale_factor)
|
852 |
+
return x
|
ttts/AA_diffusion_deprecated/ldm/modules/diffusionmodules/openaimodel.py
ADDED
@@ -0,0 +1,796 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 ldm.modules.diffusionmodules.util import (
|
10 |
+
checkpoint,
|
11 |
+
conv_nd,
|
12 |
+
linear,
|
13 |
+
avg_pool_nd,
|
14 |
+
zero_module,
|
15 |
+
normalization,
|
16 |
+
timestep_embedding,
|
17 |
+
)
|
18 |
+
from ldm.modules.attention import SpatialTransformer
|
19 |
+
from ldm.util import exists
|
20 |
+
|
21 |
+
|
22 |
+
# dummy replace
|
23 |
+
def convert_module_to_f16(x):
|
24 |
+
pass
|
25 |
+
|
26 |
+
def convert_module_to_f32(x):
|
27 |
+
pass
|
28 |
+
|
29 |
+
|
30 |
+
## go
|
31 |
+
class AttentionPool2d(nn.Module):
|
32 |
+
"""
|
33 |
+
Adapted from CLIP: https://github.com/openai/CLIP/blob/main/clip/model.py
|
34 |
+
"""
|
35 |
+
|
36 |
+
def __init__(
|
37 |
+
self,
|
38 |
+
spacial_dim: int,
|
39 |
+
embed_dim: int,
|
40 |
+
num_heads_channels: int,
|
41 |
+
output_dim: int = None,
|
42 |
+
):
|
43 |
+
super().__init__()
|
44 |
+
self.positional_embedding = nn.Parameter(th.randn(embed_dim, spacial_dim ** 2 + 1) / embed_dim ** 0.5)
|
45 |
+
self.qkv_proj = conv_nd(1, embed_dim, 3 * embed_dim, 1)
|
46 |
+
self.c_proj = conv_nd(1, embed_dim, output_dim or embed_dim, 1)
|
47 |
+
self.num_heads = embed_dim // num_heads_channels
|
48 |
+
self.attention = QKVAttention(self.num_heads)
|
49 |
+
|
50 |
+
def forward(self, x):
|
51 |
+
b, c, *_spatial = x.shape
|
52 |
+
x = x.reshape(b, c, -1) # NC(HW)
|
53 |
+
x = th.cat([x.mean(dim=-1, keepdim=True), x], dim=-1) # NC(HW+1)
|
54 |
+
x = x + self.positional_embedding[None, :, :].to(x.dtype) # NC(HW+1)
|
55 |
+
x = self.qkv_proj(x)
|
56 |
+
x = self.attention(x)
|
57 |
+
x = self.c_proj(x)
|
58 |
+
return x[:, :, 0]
|
59 |
+
|
60 |
+
|
61 |
+
class TimestepBlock(nn.Module):
|
62 |
+
"""
|
63 |
+
Any module where forward() takes timestep embeddings as a second argument.
|
64 |
+
"""
|
65 |
+
|
66 |
+
@abstractmethod
|
67 |
+
def forward(self, x, emb):
|
68 |
+
"""
|
69 |
+
Apply the module to `x` given `emb` timestep embeddings.
|
70 |
+
"""
|
71 |
+
|
72 |
+
|
73 |
+
class TimestepEmbedSequential(nn.Sequential, TimestepBlock):
|
74 |
+
"""
|
75 |
+
A sequential module that passes timestep embeddings to the children that
|
76 |
+
support it as an extra input.
|
77 |
+
"""
|
78 |
+
|
79 |
+
def forward(self, x, emb=None, context=None, refers=None, return_refer=False):
|
80 |
+
refer_ret = []
|
81 |
+
i = 0
|
82 |
+
for layer in self:
|
83 |
+
if isinstance(layer, TimestepBlock):
|
84 |
+
x = layer(x, emb)
|
85 |
+
elif isinstance(layer, SpatialTransformer):
|
86 |
+
if refers==None:
|
87 |
+
x, refer = layer(x, context)
|
88 |
+
refer_ret.append(refer)
|
89 |
+
else:
|
90 |
+
x = layer(x, context, refers[i])
|
91 |
+
i+=1
|
92 |
+
else:
|
93 |
+
x = layer(x)
|
94 |
+
if return_refer==True:
|
95 |
+
return x, refer_ret
|
96 |
+
else:
|
97 |
+
return x
|
98 |
+
|
99 |
+
|
100 |
+
class Upsample(nn.Module):
|
101 |
+
"""
|
102 |
+
An upsampling 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 |
+
upsampling occurs in the inner-two dimensions.
|
107 |
+
"""
|
108 |
+
|
109 |
+
def __init__(self, channels, use_conv, dims=2, out_channels=None, padding=1):
|
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 |
+
if use_conv:
|
116 |
+
self.conv = conv_nd(dims, self.channels, self.out_channels, 3, padding=padding)
|
117 |
+
|
118 |
+
def forward(self, x):
|
119 |
+
assert x.shape[1] == self.channels
|
120 |
+
if self.dims == 3:
|
121 |
+
x = F.interpolate(
|
122 |
+
x, (x.shape[2], x.shape[3] * 2, x.shape[4] * 2), mode="nearest"
|
123 |
+
)
|
124 |
+
else:
|
125 |
+
x = F.interpolate(x, scale_factor=2, mode="nearest")
|
126 |
+
if self.use_conv:
|
127 |
+
x = self.conv(x)
|
128 |
+
return x
|
129 |
+
|
130 |
+
class TransposedUpsample(nn.Module):
|
131 |
+
'Learned 2x upsampling without padding'
|
132 |
+
def __init__(self, channels, out_channels=None, ks=5):
|
133 |
+
super().__init__()
|
134 |
+
self.channels = channels
|
135 |
+
self.out_channels = out_channels or channels
|
136 |
+
|
137 |
+
self.up = nn.ConvTranspose2d(self.channels,self.out_channels,kernel_size=ks,stride=2)
|
138 |
+
|
139 |
+
def forward(self,x):
|
140 |
+
return self.up(x)
|
141 |
+
|
142 |
+
|
143 |
+
class Downsample(nn.Module):
|
144 |
+
"""
|
145 |
+
A downsampling layer with an optional convolution.
|
146 |
+
:param channels: channels in the inputs and outputs.
|
147 |
+
:param use_conv: a bool determining if a convolution is applied.
|
148 |
+
:param dims: determines if the signal is 1D, 2D, or 3D. If 3D, then
|
149 |
+
downsampling occurs in the inner-two dimensions.
|
150 |
+
"""
|
151 |
+
|
152 |
+
def __init__(self, channels, use_conv, dims=2, out_channels=None,padding=1):
|
153 |
+
super().__init__()
|
154 |
+
self.channels = channels
|
155 |
+
self.out_channels = out_channels or channels
|
156 |
+
self.use_conv = use_conv
|
157 |
+
self.dims = dims
|
158 |
+
stride = 2 if dims != 3 else (1, 2, 2)
|
159 |
+
if use_conv:
|
160 |
+
self.op = conv_nd(
|
161 |
+
dims, self.channels, self.out_channels, 3, stride=stride, padding=padding
|
162 |
+
)
|
163 |
+
else:
|
164 |
+
assert self.channels == self.out_channels
|
165 |
+
self.op = avg_pool_nd(dims, kernel_size=stride, stride=stride)
|
166 |
+
|
167 |
+
def forward(self, x):
|
168 |
+
assert x.shape[1] == self.channels
|
169 |
+
return self.op(x)
|
170 |
+
|
171 |
+
|
172 |
+
class ResBlock(TimestepBlock):
|
173 |
+
"""
|
174 |
+
A residual block that can optionally change the number of channels.
|
175 |
+
:param channels: the number of input channels.
|
176 |
+
:param emb_channels: the number of timestep embedding channels.
|
177 |
+
:param dropout: the rate of dropout.
|
178 |
+
:param out_channels: if specified, the number of out channels.
|
179 |
+
:param use_conv: if True and out_channels is specified, use a spatial
|
180 |
+
convolution instead of a smaller 1x1 convolution to change the
|
181 |
+
channels in the skip connection.
|
182 |
+
:param dims: determines if the signal is 1D, 2D, or 3D.
|
183 |
+
:param use_checkpoint: if True, use gradient checkpointing on this module.
|
184 |
+
:param up: if True, use this block for upsampling.
|
185 |
+
:param down: if True, use this block for downsampling.
|
186 |
+
"""
|
187 |
+
|
188 |
+
def __init__(
|
189 |
+
self,
|
190 |
+
channels,
|
191 |
+
emb_channels,
|
192 |
+
dropout,
|
193 |
+
out_channels=None,
|
194 |
+
use_conv=False,
|
195 |
+
use_scale_shift_norm=False,
|
196 |
+
dims=2,
|
197 |
+
use_checkpoint=False,
|
198 |
+
up=False,
|
199 |
+
down=False,
|
200 |
+
):
|
201 |
+
super().__init__()
|
202 |
+
self.channels = channels
|
203 |
+
self.emb_channels = emb_channels
|
204 |
+
self.dropout = dropout
|
205 |
+
self.out_channels = out_channels or channels
|
206 |
+
self.use_conv = use_conv
|
207 |
+
self.use_checkpoint = use_checkpoint
|
208 |
+
self.use_scale_shift_norm = use_scale_shift_norm
|
209 |
+
|
210 |
+
self.in_layers = nn.Sequential(
|
211 |
+
normalization(channels),
|
212 |
+
nn.SiLU(),
|
213 |
+
conv_nd(dims, channels, self.out_channels, 3, padding=1),
|
214 |
+
)
|
215 |
+
|
216 |
+
self.updown = up or down
|
217 |
+
|
218 |
+
if up:
|
219 |
+
self.h_upd = Upsample(channels, False, dims)
|
220 |
+
self.x_upd = Upsample(channels, False, dims)
|
221 |
+
elif down:
|
222 |
+
self.h_upd = Downsample(channels, False, dims)
|
223 |
+
self.x_upd = Downsample(channels, False, dims)
|
224 |
+
else:
|
225 |
+
self.h_upd = self.x_upd = nn.Identity()
|
226 |
+
|
227 |
+
self.emb_layers = nn.Sequential(
|
228 |
+
nn.SiLU(),
|
229 |
+
linear(
|
230 |
+
emb_channels,
|
231 |
+
2 * self.out_channels if use_scale_shift_norm else self.out_channels,
|
232 |
+
),
|
233 |
+
)
|
234 |
+
self.out_layers = nn.Sequential(
|
235 |
+
normalization(self.out_channels),
|
236 |
+
nn.SiLU(),
|
237 |
+
nn.Dropout(p=dropout),
|
238 |
+
zero_module(
|
239 |
+
conv_nd(dims, self.out_channels, self.out_channels, 3, padding=1)
|
240 |
+
),
|
241 |
+
)
|
242 |
+
|
243 |
+
if self.out_channels == channels:
|
244 |
+
self.skip_connection = nn.Identity()
|
245 |
+
elif use_conv:
|
246 |
+
self.skip_connection = conv_nd(
|
247 |
+
dims, channels, self.out_channels, 3, padding=1
|
248 |
+
)
|
249 |
+
else:
|
250 |
+
self.skip_connection = conv_nd(dims, channels, self.out_channels, 1)
|
251 |
+
|
252 |
+
def forward(self, x, emb):
|
253 |
+
"""
|
254 |
+
Apply the block to a Tensor, conditioned on a timestep embedding.
|
255 |
+
:param x: an [N x C x ...] Tensor of features.
|
256 |
+
:param emb: an [N x emb_channels] Tensor of timestep embeddings.
|
257 |
+
:return: an [N x C x ...] Tensor of outputs.
|
258 |
+
"""
|
259 |
+
return checkpoint(
|
260 |
+
self._forward, (x, emb), self.parameters(), self.use_checkpoint
|
261 |
+
)
|
262 |
+
|
263 |
+
|
264 |
+
def _forward(self, x, emb):
|
265 |
+
if self.updown:
|
266 |
+
in_rest, in_conv = self.in_layers[:-1], self.in_layers[-1]
|
267 |
+
h = in_rest(x)
|
268 |
+
h = self.h_upd(h)
|
269 |
+
x = self.x_upd(x)
|
270 |
+
h = in_conv(h)
|
271 |
+
else:
|
272 |
+
h = self.in_layers(x)
|
273 |
+
emb_out = self.emb_layers(emb).type(h.dtype)
|
274 |
+
while len(emb_out.shape) < len(h.shape):
|
275 |
+
emb_out = emb_out[..., None]
|
276 |
+
if self.use_scale_shift_norm:
|
277 |
+
out_norm, out_rest = self.out_layers[0], self.out_layers[1:]
|
278 |
+
scale, shift = th.chunk(emb_out, 2, dim=1)
|
279 |
+
h = out_norm(h) * (1 + scale) + shift
|
280 |
+
h = out_rest(h)
|
281 |
+
else:
|
282 |
+
h = h + emb_out
|
283 |
+
h = self.out_layers(h)
|
284 |
+
return self.skip_connection(x) + h
|
285 |
+
|
286 |
+
|
287 |
+
class AttentionBlock(nn.Module):
|
288 |
+
"""
|
289 |
+
An attention block that allows spatial positions to attend to each other.
|
290 |
+
Originally ported from here, but adapted to the N-d case.
|
291 |
+
https://github.com/hojonathanho/diffusion/blob/1e0dceb3b3495bbe19116a5e1b3596cd0706c543/diffusion_tf/models/unet.py#L66.
|
292 |
+
"""
|
293 |
+
|
294 |
+
def __init__(
|
295 |
+
self,
|
296 |
+
channels,
|
297 |
+
num_heads=1,
|
298 |
+
num_head_channels=-1,
|
299 |
+
use_checkpoint=False,
|
300 |
+
use_new_attention_order=False,
|
301 |
+
):
|
302 |
+
super().__init__()
|
303 |
+
self.channels = channels
|
304 |
+
if num_head_channels == -1:
|
305 |
+
self.num_heads = num_heads
|
306 |
+
else:
|
307 |
+
assert (
|
308 |
+
channels % num_head_channels == 0
|
309 |
+
), f"q,k,v channels {channels} is not divisible by num_head_channels {num_head_channels}"
|
310 |
+
self.num_heads = channels // num_head_channels
|
311 |
+
self.use_checkpoint = use_checkpoint
|
312 |
+
self.norm = normalization(channels)
|
313 |
+
self.qkv = conv_nd(1, channels, channels * 3, 1)
|
314 |
+
if use_new_attention_order:
|
315 |
+
# split qkv before split heads
|
316 |
+
self.attention = QKVAttention(self.num_heads)
|
317 |
+
else:
|
318 |
+
# split heads before split qkv
|
319 |
+
self.attention = QKVAttentionLegacy(self.num_heads)
|
320 |
+
|
321 |
+
self.proj_out = zero_module(conv_nd(1, channels, channels, 1))
|
322 |
+
|
323 |
+
def forward(self, x):
|
324 |
+
return checkpoint(self._forward, (x,), self.parameters(), True) # TODO: check checkpoint usage, is True # TODO: fix the .half call!!!
|
325 |
+
#return pt_checkpoint(self._forward, x) # pytorch
|
326 |
+
|
327 |
+
def _forward(self, x):
|
328 |
+
b, c, *spatial = x.shape
|
329 |
+
x = x.reshape(b, c, -1)
|
330 |
+
qkv = self.qkv(self.norm(x))
|
331 |
+
h = self.attention(qkv)
|
332 |
+
h = self.proj_out(h)
|
333 |
+
return (x + h).reshape(b, c, *spatial)
|
334 |
+
|
335 |
+
|
336 |
+
def count_flops_attn(model, _x, y):
|
337 |
+
"""
|
338 |
+
A counter for the `thop` package to count the operations in an
|
339 |
+
attention operation.
|
340 |
+
Meant to be used like:
|
341 |
+
macs, params = thop.profile(
|
342 |
+
model,
|
343 |
+
inputs=(inputs, timestamps),
|
344 |
+
custom_ops={QKVAttention: QKVAttention.count_flops},
|
345 |
+
)
|
346 |
+
"""
|
347 |
+
b, c, *spatial = y[0].shape
|
348 |
+
num_spatial = int(np.prod(spatial))
|
349 |
+
# We perform two matmuls with the same number of ops.
|
350 |
+
# The first computes the weight matrix, the second computes
|
351 |
+
# the combination of the value vectors.
|
352 |
+
matmul_ops = 2 * b * (num_spatial ** 2) * c
|
353 |
+
model.total_ops += th.DoubleTensor([matmul_ops])
|
354 |
+
|
355 |
+
|
356 |
+
class QKVAttentionLegacy(nn.Module):
|
357 |
+
"""
|
358 |
+
A module which performs QKV attention. Matches legacy QKVAttention + input/ouput heads shaping
|
359 |
+
"""
|
360 |
+
|
361 |
+
def __init__(self, n_heads):
|
362 |
+
super().__init__()
|
363 |
+
self.n_heads = n_heads
|
364 |
+
|
365 |
+
def forward(self, qkv):
|
366 |
+
"""
|
367 |
+
Apply QKV attention.
|
368 |
+
:param qkv: an [N x (H * 3 * C) x T] tensor of Qs, Ks, and Vs.
|
369 |
+
:return: an [N x (H * C) x T] tensor after attention.
|
370 |
+
"""
|
371 |
+
bs, width, length = qkv.shape
|
372 |
+
assert width % (3 * self.n_heads) == 0
|
373 |
+
ch = width // (3 * self.n_heads)
|
374 |
+
q, k, v = qkv.reshape(bs * self.n_heads, ch * 3, length).split(ch, dim=1)
|
375 |
+
scale = 1 / math.sqrt(math.sqrt(ch))
|
376 |
+
weight = th.einsum(
|
377 |
+
"bct,bcs->bts", q * scale, k * scale
|
378 |
+
) # More stable with f16 than dividing afterwards
|
379 |
+
weight = th.softmax(weight.float(), dim=-1).type(weight.dtype)
|
380 |
+
a = th.einsum("bts,bcs->bct", weight, v)
|
381 |
+
return a.reshape(bs, -1, length)
|
382 |
+
|
383 |
+
@staticmethod
|
384 |
+
def count_flops(model, _x, y):
|
385 |
+
return count_flops_attn(model, _x, y)
|
386 |
+
|
387 |
+
|
388 |
+
class QKVAttention(nn.Module):
|
389 |
+
"""
|
390 |
+
A module which performs QKV attention and splits in a different order.
|
391 |
+
"""
|
392 |
+
|
393 |
+
def __init__(self, n_heads):
|
394 |
+
super().__init__()
|
395 |
+
self.n_heads = n_heads
|
396 |
+
|
397 |
+
def forward(self, qkv):
|
398 |
+
"""
|
399 |
+
Apply QKV attention.
|
400 |
+
:param qkv: an [N x (3 * H * C) x T] tensor of Qs, Ks, and Vs.
|
401 |
+
:return: an [N x (H * C) x T] tensor after attention.
|
402 |
+
"""
|
403 |
+
bs, width, length = qkv.shape
|
404 |
+
assert width % (3 * self.n_heads) == 0
|
405 |
+
ch = width // (3 * self.n_heads)
|
406 |
+
q, k, v = qkv.chunk(3, dim=1)
|
407 |
+
scale = 1 / math.sqrt(math.sqrt(ch))
|
408 |
+
weight = th.einsum(
|
409 |
+
"bct,bcs->bts",
|
410 |
+
(q * scale).view(bs * self.n_heads, ch, length),
|
411 |
+
(k * scale).view(bs * self.n_heads, ch, length),
|
412 |
+
) # More stable with f16 than dividing afterwards
|
413 |
+
weight = th.softmax(weight.float(), dim=-1).type(weight.dtype)
|
414 |
+
a = th.einsum("bts,bcs->bct", weight, v.reshape(bs * self.n_heads, ch, length))
|
415 |
+
return a.reshape(bs, -1, length)
|
416 |
+
|
417 |
+
@staticmethod
|
418 |
+
def count_flops(model, _x, y):
|
419 |
+
return count_flops_attn(model, _x, y)
|
420 |
+
|
421 |
+
|
422 |
+
class UNetModel(nn.Module):
|
423 |
+
"""
|
424 |
+
The full UNet model with attention and timestep embedding.
|
425 |
+
:param in_channels: channels in the input Tensor.
|
426 |
+
:param model_channels: base channel count for the model.
|
427 |
+
:param out_channels: channels in the output Tensor.
|
428 |
+
:param num_res_blocks: number of residual blocks per downsample.
|
429 |
+
:param attention_resolutions: a collection of downsample rates at which
|
430 |
+
attention will take place. May be a set, list, or tuple.
|
431 |
+
For example, if this contains 4, then at 4x downsampling, attention
|
432 |
+
will be used.
|
433 |
+
:param dropout: the dropout probability.
|
434 |
+
:param channel_mult: channel multiplier for each level of the UNet.
|
435 |
+
:param conv_resample: if True, use learned convolutions for upsampling and
|
436 |
+
downsampling.
|
437 |
+
:param dims: determines if the signal is 1D, 2D, or 3D.
|
438 |
+
:param num_classes: if specified (as an int), then this model will be
|
439 |
+
class-conditional with `num_classes` classes.
|
440 |
+
:param use_checkpoint: use gradient checkpointing to reduce memory usage.
|
441 |
+
:param num_heads: the number of attention heads in each attention layer.
|
442 |
+
:param num_heads_channels: if specified, ignore num_heads and instead use
|
443 |
+
a fixed channel width per attention head.
|
444 |
+
:param num_heads_upsample: works with num_heads to set a different number
|
445 |
+
of heads for upsampling. Deprecated.
|
446 |
+
:param use_scale_shift_norm: use a FiLM-like conditioning mechanism.
|
447 |
+
:param resblock_updown: use residual blocks for up/downsampling.
|
448 |
+
:param use_new_attention_order: use a different attention pattern for potentially
|
449 |
+
increased efficiency.
|
450 |
+
"""
|
451 |
+
|
452 |
+
def __init__(
|
453 |
+
self,
|
454 |
+
image_size,
|
455 |
+
in_channels,
|
456 |
+
model_channels,
|
457 |
+
out_channels,
|
458 |
+
num_res_blocks,
|
459 |
+
attention_resolutions,
|
460 |
+
dropout=0,
|
461 |
+
channel_mult=(1, 2, 4, 8),
|
462 |
+
conv_resample=True,
|
463 |
+
dims=1,
|
464 |
+
num_classes=None,
|
465 |
+
use_checkpoint=False,
|
466 |
+
use_fp16=False,
|
467 |
+
num_heads=-1,
|
468 |
+
num_head_channels=-1,
|
469 |
+
num_heads_upsample=-1,
|
470 |
+
use_scale_shift_norm=False,
|
471 |
+
resblock_updown=False,
|
472 |
+
use_new_attention_order=False,
|
473 |
+
use_spatial_transformer=False, # custom transformer support
|
474 |
+
transformer_depth=1, # custom transformer support
|
475 |
+
context_dim=None, # custom transformer support
|
476 |
+
n_embed=None, # custom support for prediction of discrete ids into codebook of first stage vq model
|
477 |
+
legacy=True,
|
478 |
+
disable_self_attentions=None,
|
479 |
+
num_attention_blocks=None,
|
480 |
+
disable_middle_self_attn=False,
|
481 |
+
use_linear_in_transformer=False,
|
482 |
+
):
|
483 |
+
super().__init__()
|
484 |
+
if use_spatial_transformer:
|
485 |
+
assert context_dim is not None, 'Fool!! You forgot to include the dimension of your cross-attention conditioning...'
|
486 |
+
|
487 |
+
if context_dim is not None:
|
488 |
+
assert use_spatial_transformer, 'Fool!! You forgot to use the spatial transformer for your cross-attention conditioning...'
|
489 |
+
from omegaconf.listconfig import ListConfig
|
490 |
+
if type(context_dim) == ListConfig:
|
491 |
+
context_dim = list(context_dim)
|
492 |
+
|
493 |
+
if num_heads_upsample == -1:
|
494 |
+
num_heads_upsample = num_heads
|
495 |
+
|
496 |
+
if num_heads == -1:
|
497 |
+
assert num_head_channels != -1, 'Either num_heads or num_head_channels has to be set'
|
498 |
+
|
499 |
+
if num_head_channels == -1:
|
500 |
+
assert num_heads != -1, 'Either num_heads or num_head_channels has to be set'
|
501 |
+
|
502 |
+
self.image_size = image_size
|
503 |
+
self.in_channels = in_channels
|
504 |
+
self.model_channels = model_channels
|
505 |
+
self.out_channels = out_channels
|
506 |
+
if isinstance(num_res_blocks, int):
|
507 |
+
self.num_res_blocks = len(channel_mult) * [num_res_blocks]
|
508 |
+
else:
|
509 |
+
if len(num_res_blocks) != len(channel_mult):
|
510 |
+
raise ValueError("provide num_res_blocks either as an int (globally constant) or "
|
511 |
+
"as a list/tuple (per-level) with the same length as channel_mult")
|
512 |
+
self.num_res_blocks = num_res_blocks
|
513 |
+
if disable_self_attentions is not None:
|
514 |
+
# should be a list of booleans, indicating whether to disable self-attention in TransformerBlocks or not
|
515 |
+
assert len(disable_self_attentions) == len(channel_mult)
|
516 |
+
if num_attention_blocks is not None:
|
517 |
+
assert len(num_attention_blocks) == len(self.num_res_blocks)
|
518 |
+
assert all(map(lambda i: self.num_res_blocks[i] >= num_attention_blocks[i], range(len(num_attention_blocks))))
|
519 |
+
print(f"Constructor of UNetModel received num_attention_blocks={num_attention_blocks}. "
|
520 |
+
f"This option has LESS priority than attention_resolutions {attention_resolutions}, "
|
521 |
+
f"i.e., in cases where num_attention_blocks[i] > 0 but 2**i not in attention_resolutions, "
|
522 |
+
f"attention will still not be set.")
|
523 |
+
|
524 |
+
self.attention_resolutions = attention_resolutions
|
525 |
+
self.dropout = dropout
|
526 |
+
self.channel_mult = channel_mult
|
527 |
+
self.conv_resample = conv_resample
|
528 |
+
self.num_classes = num_classes
|
529 |
+
self.use_checkpoint = use_checkpoint
|
530 |
+
self.dtype = th.float16 if use_fp16 else th.float32
|
531 |
+
self.num_heads = num_heads
|
532 |
+
self.num_head_channels = num_head_channels
|
533 |
+
self.num_heads_upsample = num_heads_upsample
|
534 |
+
self.predict_codebook_ids = n_embed is not None
|
535 |
+
|
536 |
+
time_embed_dim = model_channels * 4
|
537 |
+
self.time_embed = nn.Sequential(
|
538 |
+
linear(model_channels, time_embed_dim),
|
539 |
+
nn.SiLU(),
|
540 |
+
linear(time_embed_dim, time_embed_dim),
|
541 |
+
)
|
542 |
+
|
543 |
+
if self.num_classes is not None:
|
544 |
+
if isinstance(self.num_classes, int):
|
545 |
+
self.label_emb = nn.Embedding(num_classes, time_embed_dim)
|
546 |
+
elif self.num_classes == "continuous":
|
547 |
+
print("setting up linear c_adm embedding layer")
|
548 |
+
self.label_emb = nn.Linear(1, time_embed_dim)
|
549 |
+
else:
|
550 |
+
raise ValueError()
|
551 |
+
|
552 |
+
self.input_blocks = nn.ModuleList(
|
553 |
+
[
|
554 |
+
TimestepEmbedSequential(
|
555 |
+
conv_nd(dims, in_channels, model_channels, 3, padding=1)
|
556 |
+
)
|
557 |
+
]
|
558 |
+
)
|
559 |
+
self._feature_size = model_channels
|
560 |
+
input_block_chans = [model_channels]
|
561 |
+
ch = model_channels
|
562 |
+
ds = 1
|
563 |
+
for level, mult in enumerate(channel_mult):
|
564 |
+
for nr in range(self.num_res_blocks[level]):
|
565 |
+
layers = [
|
566 |
+
ResBlock(
|
567 |
+
ch,
|
568 |
+
time_embed_dim,
|
569 |
+
dropout,
|
570 |
+
out_channels=mult * model_channels,
|
571 |
+
dims=dims,
|
572 |
+
use_checkpoint=use_checkpoint,
|
573 |
+
use_scale_shift_norm=use_scale_shift_norm,
|
574 |
+
)
|
575 |
+
]
|
576 |
+
ch = mult * model_channels
|
577 |
+
if ds in attention_resolutions:
|
578 |
+
if num_head_channels == -1:
|
579 |
+
dim_head = ch // num_heads
|
580 |
+
else:
|
581 |
+
num_heads = ch // num_head_channels
|
582 |
+
dim_head = num_head_channels
|
583 |
+
if legacy:
|
584 |
+
#num_heads = 1
|
585 |
+
dim_head = ch // num_heads if use_spatial_transformer else num_head_channels
|
586 |
+
if exists(disable_self_attentions):
|
587 |
+
disabled_sa = disable_self_attentions[level]
|
588 |
+
else:
|
589 |
+
disabled_sa = False
|
590 |
+
|
591 |
+
if not exists(num_attention_blocks) or nr < num_attention_blocks[level]:
|
592 |
+
layers.append(
|
593 |
+
AttentionBlock(
|
594 |
+
ch,
|
595 |
+
use_checkpoint=use_checkpoint,
|
596 |
+
num_heads=num_heads,
|
597 |
+
num_head_channels=dim_head,
|
598 |
+
use_new_attention_order=use_new_attention_order,
|
599 |
+
) if not use_spatial_transformer else SpatialTransformer(
|
600 |
+
ch, num_heads, dim_head, depth=transformer_depth, context_dim=context_dim,
|
601 |
+
disable_self_attn=disabled_sa, use_linear=use_linear_in_transformer,
|
602 |
+
use_checkpoint=use_checkpoint
|
603 |
+
)
|
604 |
+
)
|
605 |
+
self.input_blocks.append(TimestepEmbedSequential(*layers))
|
606 |
+
self._feature_size += ch
|
607 |
+
input_block_chans.append(ch)
|
608 |
+
if level != len(channel_mult) - 1:
|
609 |
+
out_ch = ch
|
610 |
+
self.input_blocks.append(
|
611 |
+
TimestepEmbedSequential(
|
612 |
+
ResBlock(
|
613 |
+
ch,
|
614 |
+
time_embed_dim,
|
615 |
+
dropout,
|
616 |
+
out_channels=out_ch,
|
617 |
+
dims=dims,
|
618 |
+
use_checkpoint=use_checkpoint,
|
619 |
+
use_scale_shift_norm=use_scale_shift_norm,
|
620 |
+
down=True,
|
621 |
+
)
|
622 |
+
if resblock_updown
|
623 |
+
else Downsample(
|
624 |
+
ch, conv_resample, dims=dims, out_channels=out_ch
|
625 |
+
)
|
626 |
+
)
|
627 |
+
)
|
628 |
+
ch = out_ch
|
629 |
+
input_block_chans.append(ch)
|
630 |
+
ds *= 2
|
631 |
+
self._feature_size += ch
|
632 |
+
|
633 |
+
if num_head_channels == -1:
|
634 |
+
dim_head = ch // num_heads
|
635 |
+
else:
|
636 |
+
num_heads = ch // num_head_channels
|
637 |
+
dim_head = num_head_channels
|
638 |
+
if legacy:
|
639 |
+
#num_heads = 1
|
640 |
+
dim_head = ch // num_heads if use_spatial_transformer else num_head_channels
|
641 |
+
self.middle_block = TimestepEmbedSequential(
|
642 |
+
ResBlock(
|
643 |
+
ch,
|
644 |
+
time_embed_dim,
|
645 |
+
dropout,
|
646 |
+
dims=dims,
|
647 |
+
use_checkpoint=use_checkpoint,
|
648 |
+
use_scale_shift_norm=use_scale_shift_norm,
|
649 |
+
),
|
650 |
+
AttentionBlock(
|
651 |
+
ch,
|
652 |
+
use_checkpoint=use_checkpoint,
|
653 |
+
num_heads=num_heads,
|
654 |
+
num_head_channels=dim_head,
|
655 |
+
use_new_attention_order=use_new_attention_order,
|
656 |
+
) if not use_spatial_transformer else SpatialTransformer( # always uses a self-attn
|
657 |
+
ch, num_heads, dim_head, depth=transformer_depth, context_dim=context_dim,
|
658 |
+
disable_self_attn=disable_middle_self_attn, use_linear=use_linear_in_transformer,
|
659 |
+
use_checkpoint=use_checkpoint
|
660 |
+
),
|
661 |
+
ResBlock(
|
662 |
+
ch,
|
663 |
+
time_embed_dim,
|
664 |
+
dropout,
|
665 |
+
dims=dims,
|
666 |
+
use_checkpoint=use_checkpoint,
|
667 |
+
use_scale_shift_norm=use_scale_shift_norm,
|
668 |
+
),
|
669 |
+
)
|
670 |
+
self._feature_size += ch
|
671 |
+
|
672 |
+
self.output_blocks = nn.ModuleList([])
|
673 |
+
for level, mult in list(enumerate(channel_mult))[::-1]:
|
674 |
+
for i in range(self.num_res_blocks[level] + 1):
|
675 |
+
ich = input_block_chans.pop()
|
676 |
+
layers = [
|
677 |
+
ResBlock(
|
678 |
+
ch + ich,
|
679 |
+
time_embed_dim,
|
680 |
+
dropout,
|
681 |
+
out_channels=model_channels * mult,
|
682 |
+
dims=dims,
|
683 |
+
use_checkpoint=use_checkpoint,
|
684 |
+
use_scale_shift_norm=use_scale_shift_norm,
|
685 |
+
)
|
686 |
+
]
|
687 |
+
ch = model_channels * mult
|
688 |
+
if ds in attention_resolutions:
|
689 |
+
if num_head_channels == -1:
|
690 |
+
dim_head = ch // num_heads
|
691 |
+
else:
|
692 |
+
num_heads = ch // num_head_channels
|
693 |
+
dim_head = num_head_channels
|
694 |
+
if legacy:
|
695 |
+
#num_heads = 1
|
696 |
+
dim_head = ch // num_heads if use_spatial_transformer else num_head_channels
|
697 |
+
if exists(disable_self_attentions):
|
698 |
+
disabled_sa = disable_self_attentions[level]
|
699 |
+
else:
|
700 |
+
disabled_sa = False
|
701 |
+
|
702 |
+
if not exists(num_attention_blocks) or i < num_attention_blocks[level]:
|
703 |
+
layers.append(
|
704 |
+
AttentionBlock(
|
705 |
+
ch,
|
706 |
+
use_checkpoint=use_checkpoint,
|
707 |
+
num_heads=num_heads_upsample,
|
708 |
+
num_head_channels=dim_head,
|
709 |
+
use_new_attention_order=use_new_attention_order,
|
710 |
+
) if not use_spatial_transformer else SpatialTransformer(
|
711 |
+
ch, num_heads, dim_head, depth=transformer_depth, context_dim=context_dim,
|
712 |
+
disable_self_attn=disabled_sa, use_linear=use_linear_in_transformer,
|
713 |
+
use_checkpoint=use_checkpoint
|
714 |
+
)
|
715 |
+
)
|
716 |
+
if level and i == self.num_res_blocks[level]:
|
717 |
+
out_ch = ch
|
718 |
+
layers.append(
|
719 |
+
ResBlock(
|
720 |
+
ch,
|
721 |
+
time_embed_dim,
|
722 |
+
dropout,
|
723 |
+
out_channels=out_ch,
|
724 |
+
dims=dims,
|
725 |
+
use_checkpoint=use_checkpoint,
|
726 |
+
use_scale_shift_norm=use_scale_shift_norm,
|
727 |
+
up=True,
|
728 |
+
)
|
729 |
+
if resblock_updown
|
730 |
+
else Upsample(ch, conv_resample, dims=dims, out_channels=out_ch)
|
731 |
+
)
|
732 |
+
ds //= 2
|
733 |
+
self.output_blocks.append(TimestepEmbedSequential(*layers))
|
734 |
+
self._feature_size += ch
|
735 |
+
|
736 |
+
self.out = nn.Sequential(
|
737 |
+
normalization(ch),
|
738 |
+
nn.SiLU(),
|
739 |
+
zero_module(conv_nd(dims, model_channels, out_channels, 3, padding=1)),
|
740 |
+
)
|
741 |
+
if self.predict_codebook_ids:
|
742 |
+
self.id_predictor = nn.Sequential(
|
743 |
+
normalization(ch),
|
744 |
+
conv_nd(dims, model_channels, n_embed, 1),
|
745 |
+
#nn.LogSoftmax(dim=1) # change to cross_entropy and produce non-normalized logits
|
746 |
+
)
|
747 |
+
|
748 |
+
def convert_to_fp16(self):
|
749 |
+
"""
|
750 |
+
Convert the torso of the model to float16.
|
751 |
+
"""
|
752 |
+
self.input_blocks.apply(convert_module_to_f16)
|
753 |
+
self.middle_block.apply(convert_module_to_f16)
|
754 |
+
self.output_blocks.apply(convert_module_to_f16)
|
755 |
+
|
756 |
+
def convert_to_fp32(self):
|
757 |
+
"""
|
758 |
+
Convert the torso of the model to float32.
|
759 |
+
"""
|
760 |
+
self.input_blocks.apply(convert_module_to_f32)
|
761 |
+
self.middle_block.apply(convert_module_to_f32)
|
762 |
+
self.output_blocks.apply(convert_module_to_f32)
|
763 |
+
|
764 |
+
def forward(self, x, timesteps=None, context=None, y=None,**kwargs):
|
765 |
+
"""
|
766 |
+
Apply the model to an input batch.
|
767 |
+
:param x: an [N x C x ...] Tensor of inputs.
|
768 |
+
:param timesteps: a 1-D batch of timesteps.
|
769 |
+
:param context: conditioning plugged in via crossattn
|
770 |
+
:param y: an [N] Tensor of labels, if class-conditional.
|
771 |
+
:return: an [N x C x ...] Tensor of outputs.
|
772 |
+
"""
|
773 |
+
assert (y is not None) == (
|
774 |
+
self.num_classes is not None
|
775 |
+
), "must specify y if and only if the model is class-conditional"
|
776 |
+
hs = []
|
777 |
+
t_emb = timestep_embedding(timesteps, self.model_channels, repeat_only=False)
|
778 |
+
emb = self.time_embed(t_emb)
|
779 |
+
|
780 |
+
if self.num_classes is not None:
|
781 |
+
assert y.shape[0] == x.shape[0]
|
782 |
+
emb = emb + self.label_emb(y)
|
783 |
+
|
784 |
+
h = x.type(self.dtype)
|
785 |
+
for module in self.input_blocks:
|
786 |
+
h = module(h, emb, context)
|
787 |
+
hs.append(h)
|
788 |
+
h = self.middle_block(h, emb, context)
|
789 |
+
for module in self.output_blocks:
|
790 |
+
h = th.cat([h, hs.pop()], dim=1)
|
791 |
+
h = module(h, emb, context)
|
792 |
+
h = h.type(x.dtype)
|
793 |
+
if self.predict_codebook_ids:
|
794 |
+
return self.id_predictor(h)
|
795 |
+
else:
|
796 |
+
return self.out(h)
|
ttts/AA_diffusion_deprecated/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 ldm.modules.diffusionmodules.util import extract_into_tensor, make_beta_schedule
|
7 |
+
from 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 |
+
|
ttts/AA_diffusion_deprecated/ldm/modules/diffusionmodules/util.py
ADDED
@@ -0,0 +1,275 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 ldm.util import instantiate_from_config
|
19 |
+
|
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 == "sqrt_linear":
|
38 |
+
betas = torch.linspace(linear_start, linear_end, n_timestep, dtype=torch.float64)
|
39 |
+
elif schedule == "sqrt":
|
40 |
+
betas = torch.linspace(linear_start, linear_end, n_timestep, dtype=torch.float64) ** 0.5
|
41 |
+
else:
|
42 |
+
raise ValueError(f"schedule '{schedule}' unknown.")
|
43 |
+
return betas.numpy()
|
44 |
+
|
45 |
+
|
46 |
+
def make_ddim_timesteps(ddim_discr_method, num_ddim_timesteps, num_ddpm_timesteps, verbose=True):
|
47 |
+
if ddim_discr_method == 'uniform':
|
48 |
+
c = num_ddpm_timesteps // num_ddim_timesteps
|
49 |
+
ddim_timesteps = np.asarray(list(range(0, num_ddpm_timesteps, c)))
|
50 |
+
elif ddim_discr_method == 'quad':
|
51 |
+
ddim_timesteps = ((np.linspace(0, np.sqrt(num_ddpm_timesteps * .8), num_ddim_timesteps)) ** 2).astype(int)
|
52 |
+
else:
|
53 |
+
raise NotImplementedError(f'There is no ddim discretization method called "{ddim_discr_method}"')
|
54 |
+
|
55 |
+
# assert ddim_timesteps.shape[0] == num_ddim_timesteps
|
56 |
+
# add one to get the final alpha values right (the ones from first scale to data during sampling)
|
57 |
+
steps_out = ddim_timesteps + 1
|
58 |
+
if verbose:
|
59 |
+
print(f'Selected timesteps for ddim sampler: {steps_out}')
|
60 |
+
return steps_out
|
61 |
+
|
62 |
+
|
63 |
+
def make_ddim_sampling_parameters(alphacums, ddim_timesteps, eta, verbose=True):
|
64 |
+
# select alphas for computing the variance schedule
|
65 |
+
alphas = alphacums[ddim_timesteps]
|
66 |
+
alphas_prev = np.asarray([alphacums[0]] + alphacums[ddim_timesteps[:-1]].tolist())
|
67 |
+
|
68 |
+
# according the the formula provided in https://arxiv.org/abs/2010.02502
|
69 |
+
sigmas = eta * np.sqrt((1 - alphas_prev) / (1 - alphas) * (1 - alphas / alphas_prev))
|
70 |
+
if verbose:
|
71 |
+
print(f'Selected alphas for ddim sampler: a_t: {alphas}; a_(t-1): {alphas_prev}')
|
72 |
+
print(f'For the chosen value of eta, which is {eta}, '
|
73 |
+
f'this results in the following sigma_t schedule for ddim sampler {sigmas}')
|
74 |
+
return sigmas, alphas, alphas_prev
|
75 |
+
|
76 |
+
|
77 |
+
def betas_for_alpha_bar(num_diffusion_timesteps, alpha_bar, max_beta=0.999):
|
78 |
+
"""
|
79 |
+
Create a beta schedule that discretizes the given alpha_t_bar function,
|
80 |
+
which defines the cumulative product of (1-beta) over time from t = [0,1].
|
81 |
+
:param num_diffusion_timesteps: the number of betas to produce.
|
82 |
+
:param alpha_bar: a lambda that takes an argument t from 0 to 1 and
|
83 |
+
produces the cumulative product of (1-beta) up to that
|
84 |
+
part of the diffusion process.
|
85 |
+
:param max_beta: the maximum beta to use; use values lower than 1 to
|
86 |
+
prevent singularities.
|
87 |
+
"""
|
88 |
+
betas = []
|
89 |
+
for i in range(num_diffusion_timesteps):
|
90 |
+
t1 = i / num_diffusion_timesteps
|
91 |
+
t2 = (i + 1) / num_diffusion_timesteps
|
92 |
+
betas.append(min(1 - alpha_bar(t2) / alpha_bar(t1), max_beta))
|
93 |
+
return np.array(betas)
|
94 |
+
|
95 |
+
|
96 |
+
def extract_into_tensor(a, t, x_shape):
|
97 |
+
b, *_ = t.shape
|
98 |
+
out = a.gather(-1, t)
|
99 |
+
return out.reshape(b, *((1,) * (len(x_shape) - 1)))
|
100 |
+
|
101 |
+
|
102 |
+
def checkpoint(func, inputs, params, flag):
|
103 |
+
"""
|
104 |
+
Evaluate a function without caching intermediate activations, allowing for
|
105 |
+
reduced memory at the expense of extra compute in the backward pass.
|
106 |
+
:param func: the function to evaluate.
|
107 |
+
:param inputs: the argument sequence to pass to `func`.
|
108 |
+
:param params: a sequence of parameters `func` depends on but does not
|
109 |
+
explicitly take as arguments.
|
110 |
+
:param flag: if False, disable gradient checkpointing.
|
111 |
+
"""
|
112 |
+
if flag:
|
113 |
+
args = tuple(inputs) + tuple(params)
|
114 |
+
# print(func)
|
115 |
+
return CheckpointFunction.apply(func, len(inputs), *args)
|
116 |
+
else:
|
117 |
+
return func(*inputs)
|
118 |
+
|
119 |
+
|
120 |
+
class CheckpointFunction(torch.autograd.Function):
|
121 |
+
@staticmethod
|
122 |
+
def forward(ctx, run_function, length, *args):
|
123 |
+
ctx.run_function = run_function
|
124 |
+
ctx.input_tensors = list(args[:length])
|
125 |
+
ctx.input_params = list(args[length:])
|
126 |
+
ctx.gpu_autocast_kwargs = {"enabled": torch.is_autocast_enabled(),
|
127 |
+
"dtype": torch.get_autocast_gpu_dtype(),
|
128 |
+
"cache_enabled": torch.is_autocast_cache_enabled()}
|
129 |
+
with torch.no_grad():
|
130 |
+
output_tensors = ctx.run_function(*ctx.input_tensors)
|
131 |
+
return output_tensors
|
132 |
+
|
133 |
+
@staticmethod
|
134 |
+
def backward(ctx, *output_grads):
|
135 |
+
for x in ctx.input_tensors:
|
136 |
+
if x == None:
|
137 |
+
print(ctx.run_function)
|
138 |
+
print(ctx.input_tensors)
|
139 |
+
ctx.input_tensors = [x.detach().requires_grad_(True) for x in ctx.input_tensors]
|
140 |
+
with torch.enable_grad(), \
|
141 |
+
torch.cuda.amp.autocast(**ctx.gpu_autocast_kwargs):
|
142 |
+
# Fixes a bug where the first op in run_function modifies the
|
143 |
+
# Tensor storage in place, which is not allowed for detach()'d
|
144 |
+
# Tensors.
|
145 |
+
shallow_copies = [x.view_as(x) for x in ctx.input_tensors]
|
146 |
+
output_tensors = ctx.run_function(*shallow_copies)
|
147 |
+
input_grads = torch.autograd.grad(
|
148 |
+
output_tensors,
|
149 |
+
ctx.input_tensors + ctx.input_params,
|
150 |
+
output_grads,
|
151 |
+
allow_unused=True,
|
152 |
+
)
|
153 |
+
del ctx.input_tensors
|
154 |
+
del ctx.input_params
|
155 |
+
del output_tensors
|
156 |
+
return (None, None) + input_grads
|
157 |
+
|
158 |
+
|
159 |
+
def timestep_embedding(timesteps, dim, max_period=10000, repeat_only=False):
|
160 |
+
"""
|
161 |
+
Create sinusoidal timestep embeddings.
|
162 |
+
:param timesteps: a 1-D Tensor of N indices, one per batch element.
|
163 |
+
These may be fractional.
|
164 |
+
:param dim: the dimension of the output.
|
165 |
+
:param max_period: controls the minimum frequency of the embeddings.
|
166 |
+
:return: an [N x dim] Tensor of positional embeddings.
|
167 |
+
"""
|
168 |
+
if not repeat_only:
|
169 |
+
half = dim // 2
|
170 |
+
freqs = torch.exp(
|
171 |
+
-math.log(max_period) * torch.arange(start=0, end=half, dtype=torch.float32) / half
|
172 |
+
).to(device=timesteps.device)
|
173 |
+
args = timesteps[:, None].float() * freqs[None]
|
174 |
+
embedding = torch.cat([torch.cos(args), torch.sin(args)], dim=-1)
|
175 |
+
if dim % 2:
|
176 |
+
embedding = torch.cat([embedding, torch.zeros_like(embedding[:, :1])], dim=-1)
|
177 |
+
else:
|
178 |
+
embedding = repeat(timesteps, 'b -> b d', d=dim)
|
179 |
+
return embedding
|
180 |
+
|
181 |
+
|
182 |
+
def zero_module(module):
|
183 |
+
"""
|
184 |
+
Zero out the parameters of a module and return it.
|
185 |
+
"""
|
186 |
+
for p in module.parameters():
|
187 |
+
p.detach().zero_()
|
188 |
+
return module
|
189 |
+
|
190 |
+
|
191 |
+
def scale_module(module, scale):
|
192 |
+
"""
|
193 |
+
Scale the parameters of a module and return it.
|
194 |
+
"""
|
195 |
+
for p in module.parameters():
|
196 |
+
p.detach().mul_(scale)
|
197 |
+
return module
|
198 |
+
|
199 |
+
|
200 |
+
def mean_flat(tensor):
|
201 |
+
"""
|
202 |
+
Take the mean over all non-batch dimensions.
|
203 |
+
"""
|
204 |
+
return tensor.mean(dim=list(range(1, len(tensor.shape))))
|
205 |
+
|
206 |
+
|
207 |
+
def normalization(channels):
|
208 |
+
"""
|
209 |
+
Make a standard normalization layer.
|
210 |
+
:param channels: number of input channels.
|
211 |
+
:return: an nn.Module for normalization.
|
212 |
+
"""
|
213 |
+
return GroupNorm32(32, channels)
|
214 |
+
|
215 |
+
|
216 |
+
# PyTorch 1.7 has SiLU, but we support PyTorch 1.5.
|
217 |
+
class SiLU(nn.Module):
|
218 |
+
def forward(self, x):
|
219 |
+
return x * torch.sigmoid(x)
|
220 |
+
|
221 |
+
|
222 |
+
class GroupNorm32(nn.GroupNorm):
|
223 |
+
def forward(self, x):
|
224 |
+
return super().forward(x.float()).type(x.dtype)
|
225 |
+
|
226 |
+
def conv_nd(dims, *args, **kwargs):
|
227 |
+
"""
|
228 |
+
Create a 1D, 2D, or 3D convolution module.
|
229 |
+
"""
|
230 |
+
if dims == 1:
|
231 |
+
return nn.Conv1d(*args, **kwargs)
|
232 |
+
elif dims == 2:
|
233 |
+
return nn.Conv2d(*args, **kwargs)
|
234 |
+
elif dims == 3:
|
235 |
+
return nn.Conv3d(*args, **kwargs)
|
236 |
+
raise ValueError(f"unsupported dimensions: {dims}")
|
237 |
+
|
238 |
+
|
239 |
+
def linear(*args, **kwargs):
|
240 |
+
"""
|
241 |
+
Create a linear module.
|
242 |
+
"""
|
243 |
+
return nn.Linear(*args, **kwargs)
|
244 |
+
|
245 |
+
|
246 |
+
def avg_pool_nd(dims, *args, **kwargs):
|
247 |
+
"""
|
248 |
+
Create a 1D, 2D, or 3D average pooling module.
|
249 |
+
"""
|
250 |
+
if dims == 1:
|
251 |
+
return nn.AvgPool1d(*args, **kwargs)
|
252 |
+
elif dims == 2:
|
253 |
+
return nn.AvgPool2d(*args, **kwargs)
|
254 |
+
elif dims == 3:
|
255 |
+
return nn.AvgPool3d(*args, **kwargs)
|
256 |
+
raise ValueError(f"unsupported dimensions: {dims}")
|
257 |
+
|
258 |
+
|
259 |
+
class HybridConditioner(nn.Module):
|
260 |
+
|
261 |
+
def __init__(self, c_concat_config, c_crossattn_config):
|
262 |
+
super().__init__()
|
263 |
+
self.concat_conditioner = instantiate_from_config(c_concat_config)
|
264 |
+
self.crossattn_conditioner = instantiate_from_config(c_crossattn_config)
|
265 |
+
|
266 |
+
def forward(self, c_concat, c_crossattn):
|
267 |
+
c_concat = self.concat_conditioner(c_concat)
|
268 |
+
c_crossattn = self.crossattn_conditioner(c_crossattn)
|
269 |
+
return {'c_concat': [c_concat], 'c_crossattn': [c_crossattn]}
|
270 |
+
|
271 |
+
|
272 |
+
def noise_like(shape, device, repeat=False):
|
273 |
+
repeat_noise = lambda: torch.randn((1, *shape[1:]), device=device).repeat(shape[0], *((1,) * (len(shape) - 1)))
|
274 |
+
noise = lambda: torch.randn(shape, device=device)
|
275 |
+
return repeat_noise() if repeat else noise()
|
ttts/AA_diffusion_deprecated/ldm/modules/distributions/__init__.py
ADDED
File without changes
|
ttts/AA_diffusion_deprecated/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 |
+
)
|
ttts/AA_diffusion_deprecated/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)
|
ttts/AA_diffusion_deprecated/ldm/modules/encoders/__init__.py
ADDED
File without changes
|
ttts/AA_diffusion_deprecated/ldm/modules/encoders/modules.py
ADDED
@@ -0,0 +1,213 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
import torch.nn as nn
|
3 |
+
from torch.utils.checkpoint import checkpoint
|
4 |
+
|
5 |
+
from transformers import T5Tokenizer, T5EncoderModel, CLIPTokenizer, CLIPTextModel
|
6 |
+
|
7 |
+
import open_clip
|
8 |
+
from ldm.util import default, count_params
|
9 |
+
|
10 |
+
|
11 |
+
class AbstractEncoder(nn.Module):
|
12 |
+
def __init__(self):
|
13 |
+
super().__init__()
|
14 |
+
|
15 |
+
def encode(self, *args, **kwargs):
|
16 |
+
raise NotImplementedError
|
17 |
+
|
18 |
+
|
19 |
+
class IdentityEncoder(AbstractEncoder):
|
20 |
+
|
21 |
+
def encode(self, x):
|
22 |
+
return x
|
23 |
+
|
24 |
+
|
25 |
+
class ClassEmbedder(nn.Module):
|
26 |
+
def __init__(self, embed_dim, n_classes=1000, key='class', ucg_rate=0.1):
|
27 |
+
super().__init__()
|
28 |
+
self.key = key
|
29 |
+
self.embedding = nn.Embedding(n_classes, embed_dim)
|
30 |
+
self.n_classes = n_classes
|
31 |
+
self.ucg_rate = ucg_rate
|
32 |
+
|
33 |
+
def forward(self, batch, key=None, disable_dropout=False):
|
34 |
+
if key is None:
|
35 |
+
key = self.key
|
36 |
+
# this is for use in crossattn
|
37 |
+
c = batch[key][:, None]
|
38 |
+
if self.ucg_rate > 0. and not disable_dropout:
|
39 |
+
mask = 1. - torch.bernoulli(torch.ones_like(c) * self.ucg_rate)
|
40 |
+
c = mask * c + (1-mask) * torch.ones_like(c)*(self.n_classes-1)
|
41 |
+
c = c.long()
|
42 |
+
c = self.embedding(c)
|
43 |
+
return c
|
44 |
+
|
45 |
+
def get_unconditional_conditioning(self, bs, device="cuda"):
|
46 |
+
uc_class = self.n_classes - 1 # 1000 classes --> 0 ... 999, one extra class for ucg (class 1000)
|
47 |
+
uc = torch.ones((bs,), device=device) * uc_class
|
48 |
+
uc = {self.key: uc}
|
49 |
+
return uc
|
50 |
+
|
51 |
+
|
52 |
+
def disabled_train(self, mode=True):
|
53 |
+
"""Overwrite model.train with this function to make sure train/eval mode
|
54 |
+
does not change anymore."""
|
55 |
+
return self
|
56 |
+
|
57 |
+
|
58 |
+
class FrozenT5Embedder(AbstractEncoder):
|
59 |
+
"""Uses the T5 transformer encoder for text"""
|
60 |
+
def __init__(self, version="google/t5-v1_1-large", device="cuda", max_length=77, freeze=True): # others are google/t5-v1_1-xl and google/t5-v1_1-xxl
|
61 |
+
super().__init__()
|
62 |
+
self.tokenizer = T5Tokenizer.from_pretrained(version)
|
63 |
+
self.transformer = T5EncoderModel.from_pretrained(version)
|
64 |
+
self.device = device
|
65 |
+
self.max_length = max_length # TODO: typical value?
|
66 |
+
if freeze:
|
67 |
+
self.freeze()
|
68 |
+
|
69 |
+
def freeze(self):
|
70 |
+
self.transformer = self.transformer.eval()
|
71 |
+
#self.train = disabled_train
|
72 |
+
for param in self.parameters():
|
73 |
+
param.requires_grad = False
|
74 |
+
|
75 |
+
def forward(self, text):
|
76 |
+
batch_encoding = self.tokenizer(text, truncation=True, max_length=self.max_length, return_length=True,
|
77 |
+
return_overflowing_tokens=False, padding="max_length", return_tensors="pt")
|
78 |
+
tokens = batch_encoding["input_ids"].to(self.device)
|
79 |
+
outputs = self.transformer(input_ids=tokens)
|
80 |
+
|
81 |
+
z = outputs.last_hidden_state
|
82 |
+
return z
|
83 |
+
|
84 |
+
def encode(self, text):
|
85 |
+
return self(text)
|
86 |
+
|
87 |
+
|
88 |
+
class FrozenCLIPEmbedder(AbstractEncoder):
|
89 |
+
"""Uses the CLIP transformer encoder for text (from huggingface)"""
|
90 |
+
LAYERS = [
|
91 |
+
"last",
|
92 |
+
"pooled",
|
93 |
+
"hidden"
|
94 |
+
]
|
95 |
+
def __init__(self, version="openai/clip-vit-large-patch14", device="cuda", max_length=77,
|
96 |
+
freeze=True, layer="last", layer_idx=None): # clip-vit-base-patch32
|
97 |
+
super().__init__()
|
98 |
+
assert layer in self.LAYERS
|
99 |
+
self.tokenizer = CLIPTokenizer.from_pretrained(version)
|
100 |
+
self.transformer = CLIPTextModel.from_pretrained(version)
|
101 |
+
self.device = device
|
102 |
+
self.max_length = max_length
|
103 |
+
if freeze:
|
104 |
+
self.freeze()
|
105 |
+
self.layer = layer
|
106 |
+
self.layer_idx = layer_idx
|
107 |
+
if layer == "hidden":
|
108 |
+
assert layer_idx is not None
|
109 |
+
assert 0 <= abs(layer_idx) <= 12
|
110 |
+
|
111 |
+
def freeze(self):
|
112 |
+
self.transformer = self.transformer.eval()
|
113 |
+
#self.train = disabled_train
|
114 |
+
for param in self.parameters():
|
115 |
+
param.requires_grad = False
|
116 |
+
|
117 |
+
def forward(self, text):
|
118 |
+
batch_encoding = self.tokenizer(text, truncation=True, max_length=self.max_length, return_length=True,
|
119 |
+
return_overflowing_tokens=False, padding="max_length", return_tensors="pt")
|
120 |
+
tokens = batch_encoding["input_ids"].to(self.device)
|
121 |
+
outputs = self.transformer(input_ids=tokens, output_hidden_states=self.layer=="hidden")
|
122 |
+
if self.layer == "last":
|
123 |
+
z = outputs.last_hidden_state
|
124 |
+
elif self.layer == "pooled":
|
125 |
+
z = outputs.pooler_output[:, None, :]
|
126 |
+
else:
|
127 |
+
z = outputs.hidden_states[self.layer_idx]
|
128 |
+
return z
|
129 |
+
|
130 |
+
def encode(self, text):
|
131 |
+
return self(text)
|
132 |
+
|
133 |
+
|
134 |
+
class FrozenOpenCLIPEmbedder(AbstractEncoder):
|
135 |
+
"""
|
136 |
+
Uses the OpenCLIP transformer encoder for text
|
137 |
+
"""
|
138 |
+
LAYERS = [
|
139 |
+
#"pooled",
|
140 |
+
"last",
|
141 |
+
"penultimate"
|
142 |
+
]
|
143 |
+
def __init__(self, arch="ViT-H-14", version="laion2b_s32b_b79k", device="cuda", max_length=77,
|
144 |
+
freeze=True, layer="last"):
|
145 |
+
super().__init__()
|
146 |
+
assert layer in self.LAYERS
|
147 |
+
model, _, _ = open_clip.create_model_and_transforms(arch, device=torch.device('cpu'), pretrained=version)
|
148 |
+
del model.visual
|
149 |
+
self.model = model
|
150 |
+
|
151 |
+
self.device = device
|
152 |
+
self.max_length = max_length
|
153 |
+
if freeze:
|
154 |
+
self.freeze()
|
155 |
+
self.layer = layer
|
156 |
+
if self.layer == "last":
|
157 |
+
self.layer_idx = 0
|
158 |
+
elif self.layer == "penultimate":
|
159 |
+
self.layer_idx = 1
|
160 |
+
else:
|
161 |
+
raise NotImplementedError()
|
162 |
+
|
163 |
+
def freeze(self):
|
164 |
+
self.model = self.model.eval()
|
165 |
+
for param in self.parameters():
|
166 |
+
param.requires_grad = False
|
167 |
+
|
168 |
+
def forward(self, text):
|
169 |
+
tokens = open_clip.tokenize(text)
|
170 |
+
z = self.encode_with_transformer(tokens.to(self.device))
|
171 |
+
return z
|
172 |
+
|
173 |
+
def encode_with_transformer(self, text):
|
174 |
+
x = self.model.token_embedding(text) # [batch_size, n_ctx, d_model]
|
175 |
+
x = x + self.model.positional_embedding
|
176 |
+
x = x.permute(1, 0, 2) # NLD -> LND
|
177 |
+
x = self.text_transformer_forward(x, attn_mask=self.model.attn_mask)
|
178 |
+
x = x.permute(1, 0, 2) # LND -> NLD
|
179 |
+
x = self.model.ln_final(x)
|
180 |
+
return x
|
181 |
+
|
182 |
+
def text_transformer_forward(self, x: torch.Tensor, attn_mask = None):
|
183 |
+
for i, r in enumerate(self.model.transformer.resblocks):
|
184 |
+
if i == len(self.model.transformer.resblocks) - self.layer_idx:
|
185 |
+
break
|
186 |
+
if self.model.transformer.grad_checkpointing and not torch.jit.is_scripting():
|
187 |
+
x = checkpoint(r, x, attn_mask)
|
188 |
+
else:
|
189 |
+
x = r(x, attn_mask=attn_mask)
|
190 |
+
return x
|
191 |
+
|
192 |
+
def encode(self, text):
|
193 |
+
return self(text)
|
194 |
+
|
195 |
+
|
196 |
+
class FrozenCLIPT5Encoder(AbstractEncoder):
|
197 |
+
def __init__(self, clip_version="openai/clip-vit-large-patch14", t5_version="google/t5-v1_1-xl", device="cuda",
|
198 |
+
clip_max_length=77, t5_max_length=77):
|
199 |
+
super().__init__()
|
200 |
+
self.clip_encoder = FrozenCLIPEmbedder(clip_version, device, max_length=clip_max_length)
|
201 |
+
self.t5_encoder = FrozenT5Embedder(t5_version, device, max_length=t5_max_length)
|
202 |
+
print(f"{self.clip_encoder.__class__.__name__} has {count_params(self.clip_encoder)*1.e-6:.2f} M parameters, "
|
203 |
+
f"{self.t5_encoder.__class__.__name__} comes with {count_params(self.t5_encoder)*1.e-6:.2f} M params.")
|
204 |
+
|
205 |
+
def encode(self, text):
|
206 |
+
return self(text)
|
207 |
+
|
208 |
+
def forward(self, text):
|
209 |
+
clip_z = self.clip_encoder.encode(text)
|
210 |
+
t5_z = self.t5_encoder.encode(text)
|
211 |
+
return [clip_z, t5_z]
|
212 |
+
|
213 |
+
|
ttts/AA_diffusion_deprecated/ldm/modules/image_degradation/__init__.py
ADDED
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
1 |
+
from ldm.modules.image_degradation.bsrgan import degradation_bsrgan_variant as degradation_fn_bsr
|
2 |
+
from ldm.modules.image_degradation.bsrgan_light import degradation_bsrgan_variant as degradation_fn_bsr_light
|
ttts/AA_diffusion_deprecated/ldm/modules/image_degradation/bsrgan.py
ADDED
@@ -0,0 +1,730 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# -*- coding: utf-8 -*-
|
2 |
+
"""
|
3 |
+
# --------------------------------------------
|
4 |
+
# Super-Resolution
|
5 |
+
# --------------------------------------------
|
6 |
+
#
|
7 |
+
# Kai Zhang (cskaizhang@gmail.com)
|
8 |
+
# https://github.com/cszn
|
9 |
+
# From 2019/03--2021/08
|
10 |
+
# --------------------------------------------
|
11 |
+
"""
|
12 |
+
|
13 |
+
import numpy as np
|
14 |
+
import cv2
|
15 |
+
import torch
|
16 |
+
|
17 |
+
from functools import partial
|
18 |
+
import random
|
19 |
+
from scipy import ndimage
|
20 |
+
import scipy
|
21 |
+
import scipy.stats as ss
|
22 |
+
from scipy.interpolate import interp2d
|
23 |
+
from scipy.linalg import orth
|
24 |
+
import albumentations
|
25 |
+
|
26 |
+
import ldm.modules.image_degradation.utils_image as util
|
27 |
+
|
28 |
+
|
29 |
+
def modcrop_np(img, sf):
|
30 |
+
'''
|
31 |
+
Args:
|
32 |
+
img: numpy image, WxH or WxHxC
|
33 |
+
sf: scale factor
|
34 |
+
Return:
|
35 |
+
cropped image
|
36 |
+
'''
|
37 |
+
w, h = img.shape[:2]
|
38 |
+
im = np.copy(img)
|
39 |
+
return im[:w - w % sf, :h - h % sf, ...]
|
40 |
+
|
41 |
+
|
42 |
+
"""
|
43 |
+
# --------------------------------------------
|
44 |
+
# anisotropic Gaussian kernels
|
45 |
+
# --------------------------------------------
|
46 |
+
"""
|
47 |
+
|
48 |
+
|
49 |
+
def analytic_kernel(k):
|
50 |
+
"""Calculate the X4 kernel from the X2 kernel (for proof see appendix in paper)"""
|
51 |
+
k_size = k.shape[0]
|
52 |
+
# Calculate the big kernels size
|
53 |
+
big_k = np.zeros((3 * k_size - 2, 3 * k_size - 2))
|
54 |
+
# Loop over the small kernel to fill the big one
|
55 |
+
for r in range(k_size):
|
56 |
+
for c in range(k_size):
|
57 |
+
big_k[2 * r:2 * r + k_size, 2 * c:2 * c + k_size] += k[r, c] * k
|
58 |
+
# Crop the edges of the big kernel to ignore very small values and increase run time of SR
|
59 |
+
crop = k_size // 2
|
60 |
+
cropped_big_k = big_k[crop:-crop, crop:-crop]
|
61 |
+
# Normalize to 1
|
62 |
+
return cropped_big_k / cropped_big_k.sum()
|
63 |
+
|
64 |
+
|
65 |
+
def anisotropic_Gaussian(ksize=15, theta=np.pi, l1=6, l2=6):
|
66 |
+
""" generate an anisotropic Gaussian kernel
|
67 |
+
Args:
|
68 |
+
ksize : e.g., 15, kernel size
|
69 |
+
theta : [0, pi], rotation angle range
|
70 |
+
l1 : [0.1,50], scaling of eigenvalues
|
71 |
+
l2 : [0.1,l1], scaling of eigenvalues
|
72 |
+
If l1 = l2, will get an isotropic Gaussian kernel.
|
73 |
+
Returns:
|
74 |
+
k : kernel
|
75 |
+
"""
|
76 |
+
|
77 |
+
v = np.dot(np.array([[np.cos(theta), -np.sin(theta)], [np.sin(theta), np.cos(theta)]]), np.array([1., 0.]))
|
78 |
+
V = np.array([[v[0], v[1]], [v[1], -v[0]]])
|
79 |
+
D = np.array([[l1, 0], [0, l2]])
|
80 |
+
Sigma = np.dot(np.dot(V, D), np.linalg.inv(V))
|
81 |
+
k = gm_blur_kernel(mean=[0, 0], cov=Sigma, size=ksize)
|
82 |
+
|
83 |
+
return k
|
84 |
+
|
85 |
+
|
86 |
+
def gm_blur_kernel(mean, cov, size=15):
|
87 |
+
center = size / 2.0 + 0.5
|
88 |
+
k = np.zeros([size, size])
|
89 |
+
for y in range(size):
|
90 |
+
for x in range(size):
|
91 |
+
cy = y - center + 1
|
92 |
+
cx = x - center + 1
|
93 |
+
k[y, x] = ss.multivariate_normal.pdf([cx, cy], mean=mean, cov=cov)
|
94 |
+
|
95 |
+
k = k / np.sum(k)
|
96 |
+
return k
|
97 |
+
|
98 |
+
|
99 |
+
def shift_pixel(x, sf, upper_left=True):
|
100 |
+
"""shift pixel for super-resolution with different scale factors
|
101 |
+
Args:
|
102 |
+
x: WxHxC or WxH
|
103 |
+
sf: scale factor
|
104 |
+
upper_left: shift direction
|
105 |
+
"""
|
106 |
+
h, w = x.shape[:2]
|
107 |
+
shift = (sf - 1) * 0.5
|
108 |
+
xv, yv = np.arange(0, w, 1.0), np.arange(0, h, 1.0)
|
109 |
+
if upper_left:
|
110 |
+
x1 = xv + shift
|
111 |
+
y1 = yv + shift
|
112 |
+
else:
|
113 |
+
x1 = xv - shift
|
114 |
+
y1 = yv - shift
|
115 |
+
|
116 |
+
x1 = np.clip(x1, 0, w - 1)
|
117 |
+
y1 = np.clip(y1, 0, h - 1)
|
118 |
+
|
119 |
+
if x.ndim == 2:
|
120 |
+
x = interp2d(xv, yv, x)(x1, y1)
|
121 |
+
if x.ndim == 3:
|
122 |
+
for i in range(x.shape[-1]):
|
123 |
+
x[:, :, i] = interp2d(xv, yv, x[:, :, i])(x1, y1)
|
124 |
+
|
125 |
+
return x
|
126 |
+
|
127 |
+
|
128 |
+
def blur(x, k):
|
129 |
+
'''
|
130 |
+
x: image, NxcxHxW
|
131 |
+
k: kernel, Nx1xhxw
|
132 |
+
'''
|
133 |
+
n, c = x.shape[:2]
|
134 |
+
p1, p2 = (k.shape[-2] - 1) // 2, (k.shape[-1] - 1) // 2
|
135 |
+
x = torch.nn.functional.pad(x, pad=(p1, p2, p1, p2), mode='replicate')
|
136 |
+
k = k.repeat(1, c, 1, 1)
|
137 |
+
k = k.view(-1, 1, k.shape[2], k.shape[3])
|
138 |
+
x = x.view(1, -1, x.shape[2], x.shape[3])
|
139 |
+
x = torch.nn.functional.conv2d(x, k, bias=None, stride=1, padding=0, groups=n * c)
|
140 |
+
x = x.view(n, c, x.shape[2], x.shape[3])
|
141 |
+
|
142 |
+
return x
|
143 |
+
|
144 |
+
|
145 |
+
def gen_kernel(k_size=np.array([15, 15]), scale_factor=np.array([4, 4]), min_var=0.6, max_var=10., noise_level=0):
|
146 |
+
""""
|
147 |
+
# modified version of https://github.com/assafshocher/BlindSR_dataset_generator
|
148 |
+
# Kai Zhang
|
149 |
+
# min_var = 0.175 * sf # variance of the gaussian kernel will be sampled between min_var and max_var
|
150 |
+
# max_var = 2.5 * sf
|
151 |
+
"""
|
152 |
+
# Set random eigen-vals (lambdas) and angle (theta) for COV matrix
|
153 |
+
lambda_1 = min_var + np.random.rand() * (max_var - min_var)
|
154 |
+
lambda_2 = min_var + np.random.rand() * (max_var - min_var)
|
155 |
+
theta = np.random.rand() * np.pi # random theta
|
156 |
+
noise = -noise_level + np.random.rand(*k_size) * noise_level * 2
|
157 |
+
|
158 |
+
# Set COV matrix using Lambdas and Theta
|
159 |
+
LAMBDA = np.diag([lambda_1, lambda_2])
|
160 |
+
Q = np.array([[np.cos(theta), -np.sin(theta)],
|
161 |
+
[np.sin(theta), np.cos(theta)]])
|
162 |
+
SIGMA = Q @ LAMBDA @ Q.T
|
163 |
+
INV_SIGMA = np.linalg.inv(SIGMA)[None, None, :, :]
|
164 |
+
|
165 |
+
# Set expectation position (shifting kernel for aligned image)
|
166 |
+
MU = k_size // 2 - 0.5 * (scale_factor - 1) # - 0.5 * (scale_factor - k_size % 2)
|
167 |
+
MU = MU[None, None, :, None]
|
168 |
+
|
169 |
+
# Create meshgrid for Gaussian
|
170 |
+
[X, Y] = np.meshgrid(range(k_size[0]), range(k_size[1]))
|
171 |
+
Z = np.stack([X, Y], 2)[:, :, :, None]
|
172 |
+
|
173 |
+
# Calcualte Gaussian for every pixel of the kernel
|
174 |
+
ZZ = Z - MU
|
175 |
+
ZZ_t = ZZ.transpose(0, 1, 3, 2)
|
176 |
+
raw_kernel = np.exp(-0.5 * np.squeeze(ZZ_t @ INV_SIGMA @ ZZ)) * (1 + noise)
|
177 |
+
|
178 |
+
# shift the kernel so it will be centered
|
179 |
+
# raw_kernel_centered = kernel_shift(raw_kernel, scale_factor)
|
180 |
+
|
181 |
+
# Normalize the kernel and return
|
182 |
+
# kernel = raw_kernel_centered / np.sum(raw_kernel_centered)
|
183 |
+
kernel = raw_kernel / np.sum(raw_kernel)
|
184 |
+
return kernel
|
185 |
+
|
186 |
+
|
187 |
+
def fspecial_gaussian(hsize, sigma):
|
188 |
+
hsize = [hsize, hsize]
|
189 |
+
siz = [(hsize[0] - 1.0) / 2.0, (hsize[1] - 1.0) / 2.0]
|
190 |
+
std = sigma
|
191 |
+
[x, y] = np.meshgrid(np.arange(-siz[1], siz[1] + 1), np.arange(-siz[0], siz[0] + 1))
|
192 |
+
arg = -(x * x + y * y) / (2 * std * std)
|
193 |
+
h = np.exp(arg)
|
194 |
+
h[h < scipy.finfo(float).eps * h.max()] = 0
|
195 |
+
sumh = h.sum()
|
196 |
+
if sumh != 0:
|
197 |
+
h = h / sumh
|
198 |
+
return h
|
199 |
+
|
200 |
+
|
201 |
+
def fspecial_laplacian(alpha):
|
202 |
+
alpha = max([0, min([alpha, 1])])
|
203 |
+
h1 = alpha / (alpha + 1)
|
204 |
+
h2 = (1 - alpha) / (alpha + 1)
|
205 |
+
h = [[h1, h2, h1], [h2, -4 / (alpha + 1), h2], [h1, h2, h1]]
|
206 |
+
h = np.array(h)
|
207 |
+
return h
|
208 |
+
|
209 |
+
|
210 |
+
def fspecial(filter_type, *args, **kwargs):
|
211 |
+
'''
|
212 |
+
python code from:
|
213 |
+
https://github.com/ronaldosena/imagens-medicas-2/blob/40171a6c259edec7827a6693a93955de2bd39e76/Aulas/aula_2_-_uniform_filter/matlab_fspecial.py
|
214 |
+
'''
|
215 |
+
if filter_type == 'gaussian':
|
216 |
+
return fspecial_gaussian(*args, **kwargs)
|
217 |
+
if filter_type == 'laplacian':
|
218 |
+
return fspecial_laplacian(*args, **kwargs)
|
219 |
+
|
220 |
+
|
221 |
+
"""
|
222 |
+
# --------------------------------------------
|
223 |
+
# degradation models
|
224 |
+
# --------------------------------------------
|
225 |
+
"""
|
226 |
+
|
227 |
+
|
228 |
+
def bicubic_degradation(x, sf=3):
|
229 |
+
'''
|
230 |
+
Args:
|
231 |
+
x: HxWxC image, [0, 1]
|
232 |
+
sf: down-scale factor
|
233 |
+
Return:
|
234 |
+
bicubicly downsampled LR image
|
235 |
+
'''
|
236 |
+
x = util.imresize_np(x, scale=1 / sf)
|
237 |
+
return x
|
238 |
+
|
239 |
+
|
240 |
+
def srmd_degradation(x, k, sf=3):
|
241 |
+
''' blur + bicubic downsampling
|
242 |
+
Args:
|
243 |
+
x: HxWxC image, [0, 1]
|
244 |
+
k: hxw, double
|
245 |
+
sf: down-scale factor
|
246 |
+
Return:
|
247 |
+
downsampled LR image
|
248 |
+
Reference:
|
249 |
+
@inproceedings{zhang2018learning,
|
250 |
+
title={Learning a single convolutional super-resolution network for multiple degradations},
|
251 |
+
author={Zhang, Kai and Zuo, Wangmeng and Zhang, Lei},
|
252 |
+
booktitle={IEEE Conference on Computer Vision and Pattern Recognition},
|
253 |
+
pages={3262--3271},
|
254 |
+
year={2018}
|
255 |
+
}
|
256 |
+
'''
|
257 |
+
x = ndimage.filters.convolve(x, np.expand_dims(k, axis=2), mode='wrap') # 'nearest' | 'mirror'
|
258 |
+
x = bicubic_degradation(x, sf=sf)
|
259 |
+
return x
|
260 |
+
|
261 |
+
|
262 |
+
def dpsr_degradation(x, k, sf=3):
|
263 |
+
''' bicubic downsampling + blur
|
264 |
+
Args:
|
265 |
+
x: HxWxC image, [0, 1]
|
266 |
+
k: hxw, double
|
267 |
+
sf: down-scale factor
|
268 |
+
Return:
|
269 |
+
downsampled LR image
|
270 |
+
Reference:
|
271 |
+
@inproceedings{zhang2019deep,
|
272 |
+
title={Deep Plug-and-Play Super-Resolution for Arbitrary Blur Kernels},
|
273 |
+
author={Zhang, Kai and Zuo, Wangmeng and Zhang, Lei},
|
274 |
+
booktitle={IEEE Conference on Computer Vision and Pattern Recognition},
|
275 |
+
pages={1671--1681},
|
276 |
+
year={2019}
|
277 |
+
}
|
278 |
+
'''
|
279 |
+
x = bicubic_degradation(x, sf=sf)
|
280 |
+
x = ndimage.filters.convolve(x, np.expand_dims(k, axis=2), mode='wrap')
|
281 |
+
return x
|
282 |
+
|
283 |
+
|
284 |
+
def classical_degradation(x, k, sf=3):
|
285 |
+
''' blur + downsampling
|
286 |
+
Args:
|
287 |
+
x: HxWxC image, [0, 1]/[0, 255]
|
288 |
+
k: hxw, double
|
289 |
+
sf: down-scale factor
|
290 |
+
Return:
|
291 |
+
downsampled LR image
|
292 |
+
'''
|
293 |
+
x = ndimage.filters.convolve(x, np.expand_dims(k, axis=2), mode='wrap')
|
294 |
+
# x = filters.correlate(x, np.expand_dims(np.flip(k), axis=2))
|
295 |
+
st = 0
|
296 |
+
return x[st::sf, st::sf, ...]
|
297 |
+
|
298 |
+
|
299 |
+
def add_sharpening(img, weight=0.5, radius=50, threshold=10):
|
300 |
+
"""USM sharpening. borrowed from real-ESRGAN
|
301 |
+
Input image: I; Blurry image: B.
|
302 |
+
1. K = I + weight * (I - B)
|
303 |
+
2. Mask = 1 if abs(I - B) > threshold, else: 0
|
304 |
+
3. Blur mask:
|
305 |
+
4. Out = Mask * K + (1 - Mask) * I
|
306 |
+
Args:
|
307 |
+
img (Numpy array): Input image, HWC, BGR; float32, [0, 1].
|
308 |
+
weight (float): Sharp weight. Default: 1.
|
309 |
+
radius (float): Kernel size of Gaussian blur. Default: 50.
|
310 |
+
threshold (int):
|
311 |
+
"""
|
312 |
+
if radius % 2 == 0:
|
313 |
+
radius += 1
|
314 |
+
blur = cv2.GaussianBlur(img, (radius, radius), 0)
|
315 |
+
residual = img - blur
|
316 |
+
mask = np.abs(residual) * 255 > threshold
|
317 |
+
mask = mask.astype('float32')
|
318 |
+
soft_mask = cv2.GaussianBlur(mask, (radius, radius), 0)
|
319 |
+
|
320 |
+
K = img + weight * residual
|
321 |
+
K = np.clip(K, 0, 1)
|
322 |
+
return soft_mask * K + (1 - soft_mask) * img
|
323 |
+
|
324 |
+
|
325 |
+
def add_blur(img, sf=4):
|
326 |
+
wd2 = 4.0 + sf
|
327 |
+
wd = 2.0 + 0.2 * sf
|
328 |
+
if random.random() < 0.5:
|
329 |
+
l1 = wd2 * random.random()
|
330 |
+
l2 = wd2 * random.random()
|
331 |
+
k = anisotropic_Gaussian(ksize=2 * random.randint(2, 11) + 3, theta=random.random() * np.pi, l1=l1, l2=l2)
|
332 |
+
else:
|
333 |
+
k = fspecial('gaussian', 2 * random.randint(2, 11) + 3, wd * random.random())
|
334 |
+
img = ndimage.filters.convolve(img, np.expand_dims(k, axis=2), mode='mirror')
|
335 |
+
|
336 |
+
return img
|
337 |
+
|
338 |
+
|
339 |
+
def add_resize(img, sf=4):
|
340 |
+
rnum = np.random.rand()
|
341 |
+
if rnum > 0.8: # up
|
342 |
+
sf1 = random.uniform(1, 2)
|
343 |
+
elif rnum < 0.7: # down
|
344 |
+
sf1 = random.uniform(0.5 / sf, 1)
|
345 |
+
else:
|
346 |
+
sf1 = 1.0
|
347 |
+
img = cv2.resize(img, (int(sf1 * img.shape[1]), int(sf1 * img.shape[0])), interpolation=random.choice([1, 2, 3]))
|
348 |
+
img = np.clip(img, 0.0, 1.0)
|
349 |
+
|
350 |
+
return img
|
351 |
+
|
352 |
+
|
353 |
+
# def add_Gaussian_noise(img, noise_level1=2, noise_level2=25):
|
354 |
+
# noise_level = random.randint(noise_level1, noise_level2)
|
355 |
+
# rnum = np.random.rand()
|
356 |
+
# if rnum > 0.6: # add color Gaussian noise
|
357 |
+
# img += np.random.normal(0, noise_level / 255.0, img.shape).astype(np.float32)
|
358 |
+
# elif rnum < 0.4: # add grayscale Gaussian noise
|
359 |
+
# img += np.random.normal(0, noise_level / 255.0, (*img.shape[:2], 1)).astype(np.float32)
|
360 |
+
# else: # add noise
|
361 |
+
# L = noise_level2 / 255.
|
362 |
+
# D = np.diag(np.random.rand(3))
|
363 |
+
# U = orth(np.random.rand(3, 3))
|
364 |
+
# conv = np.dot(np.dot(np.transpose(U), D), U)
|
365 |
+
# img += np.random.multivariate_normal([0, 0, 0], np.abs(L ** 2 * conv), img.shape[:2]).astype(np.float32)
|
366 |
+
# img = np.clip(img, 0.0, 1.0)
|
367 |
+
# return img
|
368 |
+
|
369 |
+
def add_Gaussian_noise(img, noise_level1=2, noise_level2=25):
|
370 |
+
noise_level = random.randint(noise_level1, noise_level2)
|
371 |
+
rnum = np.random.rand()
|
372 |
+
if rnum > 0.6: # add color Gaussian noise
|
373 |
+
img = img + np.random.normal(0, noise_level / 255.0, img.shape).astype(np.float32)
|
374 |
+
elif rnum < 0.4: # add grayscale Gaussian noise
|
375 |
+
img = img + np.random.normal(0, noise_level / 255.0, (*img.shape[:2], 1)).astype(np.float32)
|
376 |
+
else: # add noise
|
377 |
+
L = noise_level2 / 255.
|
378 |
+
D = np.diag(np.random.rand(3))
|
379 |
+
U = orth(np.random.rand(3, 3))
|
380 |
+
conv = np.dot(np.dot(np.transpose(U), D), U)
|
381 |
+
img = img + np.random.multivariate_normal([0, 0, 0], np.abs(L ** 2 * conv), img.shape[:2]).astype(np.float32)
|
382 |
+
img = np.clip(img, 0.0, 1.0)
|
383 |
+
return img
|
384 |
+
|
385 |
+
|
386 |
+
def add_speckle_noise(img, noise_level1=2, noise_level2=25):
|
387 |
+
noise_level = random.randint(noise_level1, noise_level2)
|
388 |
+
img = np.clip(img, 0.0, 1.0)
|
389 |
+
rnum = random.random()
|
390 |
+
if rnum > 0.6:
|
391 |
+
img += img * np.random.normal(0, noise_level / 255.0, img.shape).astype(np.float32)
|
392 |
+
elif rnum < 0.4:
|
393 |
+
img += img * np.random.normal(0, noise_level / 255.0, (*img.shape[:2], 1)).astype(np.float32)
|
394 |
+
else:
|
395 |
+
L = noise_level2 / 255.
|
396 |
+
D = np.diag(np.random.rand(3))
|
397 |
+
U = orth(np.random.rand(3, 3))
|
398 |
+
conv = np.dot(np.dot(np.transpose(U), D), U)
|
399 |
+
img += img * np.random.multivariate_normal([0, 0, 0], np.abs(L ** 2 * conv), img.shape[:2]).astype(np.float32)
|
400 |
+
img = np.clip(img, 0.0, 1.0)
|
401 |
+
return img
|
402 |
+
|
403 |
+
|
404 |
+
def add_Poisson_noise(img):
|
405 |
+
img = np.clip((img * 255.0).round(), 0, 255) / 255.
|
406 |
+
vals = 10 ** (2 * random.random() + 2.0) # [2, 4]
|
407 |
+
if random.random() < 0.5:
|
408 |
+
img = np.random.poisson(img * vals).astype(np.float32) / vals
|
409 |
+
else:
|
410 |
+
img_gray = np.dot(img[..., :3], [0.299, 0.587, 0.114])
|
411 |
+
img_gray = np.clip((img_gray * 255.0).round(), 0, 255) / 255.
|
412 |
+
noise_gray = np.random.poisson(img_gray * vals).astype(np.float32) / vals - img_gray
|
413 |
+
img += noise_gray[:, :, np.newaxis]
|
414 |
+
img = np.clip(img, 0.0, 1.0)
|
415 |
+
return img
|
416 |
+
|
417 |
+
|
418 |
+
def add_JPEG_noise(img):
|
419 |
+
quality_factor = random.randint(30, 95)
|
420 |
+
img = cv2.cvtColor(util.single2uint(img), cv2.COLOR_RGB2BGR)
|
421 |
+
result, encimg = cv2.imencode('.jpg', img, [int(cv2.IMWRITE_JPEG_QUALITY), quality_factor])
|
422 |
+
img = cv2.imdecode(encimg, 1)
|
423 |
+
img = cv2.cvtColor(util.uint2single(img), cv2.COLOR_BGR2RGB)
|
424 |
+
return img
|
425 |
+
|
426 |
+
|
427 |
+
def random_crop(lq, hq, sf=4, lq_patchsize=64):
|
428 |
+
h, w = lq.shape[:2]
|
429 |
+
rnd_h = random.randint(0, h - lq_patchsize)
|
430 |
+
rnd_w = random.randint(0, w - lq_patchsize)
|
431 |
+
lq = lq[rnd_h:rnd_h + lq_patchsize, rnd_w:rnd_w + lq_patchsize, :]
|
432 |
+
|
433 |
+
rnd_h_H, rnd_w_H = int(rnd_h * sf), int(rnd_w * sf)
|
434 |
+
hq = hq[rnd_h_H:rnd_h_H + lq_patchsize * sf, rnd_w_H:rnd_w_H + lq_patchsize * sf, :]
|
435 |
+
return lq, hq
|
436 |
+
|
437 |
+
|
438 |
+
def degradation_bsrgan(img, sf=4, lq_patchsize=72, isp_model=None):
|
439 |
+
"""
|
440 |
+
This is the degradation model of BSRGAN from the paper
|
441 |
+
"Designing a Practical Degradation Model for Deep Blind Image Super-Resolution"
|
442 |
+
----------
|
443 |
+
img: HXWXC, [0, 1], its size should be large than (lq_patchsizexsf)x(lq_patchsizexsf)
|
444 |
+
sf: scale factor
|
445 |
+
isp_model: camera ISP model
|
446 |
+
Returns
|
447 |
+
-------
|
448 |
+
img: low-quality patch, size: lq_patchsizeXlq_patchsizeXC, range: [0, 1]
|
449 |
+
hq: corresponding high-quality patch, size: (lq_patchsizexsf)X(lq_patchsizexsf)XC, range: [0, 1]
|
450 |
+
"""
|
451 |
+
isp_prob, jpeg_prob, scale2_prob = 0.25, 0.9, 0.25
|
452 |
+
sf_ori = sf
|
453 |
+
|
454 |
+
h1, w1 = img.shape[:2]
|
455 |
+
img = img.copy()[:w1 - w1 % sf, :h1 - h1 % sf, ...] # mod crop
|
456 |
+
h, w = img.shape[:2]
|
457 |
+
|
458 |
+
if h < lq_patchsize * sf or w < lq_patchsize * sf:
|
459 |
+
raise ValueError(f'img size ({h1}X{w1}) is too small!')
|
460 |
+
|
461 |
+
hq = img.copy()
|
462 |
+
|
463 |
+
if sf == 4 and random.random() < scale2_prob: # downsample1
|
464 |
+
if np.random.rand() < 0.5:
|
465 |
+
img = cv2.resize(img, (int(1 / 2 * img.shape[1]), int(1 / 2 * img.shape[0])),
|
466 |
+
interpolation=random.choice([1, 2, 3]))
|
467 |
+
else:
|
468 |
+
img = util.imresize_np(img, 1 / 2, True)
|
469 |
+
img = np.clip(img, 0.0, 1.0)
|
470 |
+
sf = 2
|
471 |
+
|
472 |
+
shuffle_order = random.sample(range(7), 7)
|
473 |
+
idx1, idx2 = shuffle_order.index(2), shuffle_order.index(3)
|
474 |
+
if idx1 > idx2: # keep downsample3 last
|
475 |
+
shuffle_order[idx1], shuffle_order[idx2] = shuffle_order[idx2], shuffle_order[idx1]
|
476 |
+
|
477 |
+
for i in shuffle_order:
|
478 |
+
|
479 |
+
if i == 0:
|
480 |
+
img = add_blur(img, sf=sf)
|
481 |
+
|
482 |
+
elif i == 1:
|
483 |
+
img = add_blur(img, sf=sf)
|
484 |
+
|
485 |
+
elif i == 2:
|
486 |
+
a, b = img.shape[1], img.shape[0]
|
487 |
+
# downsample2
|
488 |
+
if random.random() < 0.75:
|
489 |
+
sf1 = random.uniform(1, 2 * sf)
|
490 |
+
img = cv2.resize(img, (int(1 / sf1 * img.shape[1]), int(1 / sf1 * img.shape[0])),
|
491 |
+
interpolation=random.choice([1, 2, 3]))
|
492 |
+
else:
|
493 |
+
k = fspecial('gaussian', 25, random.uniform(0.1, 0.6 * sf))
|
494 |
+
k_shifted = shift_pixel(k, sf)
|
495 |
+
k_shifted = k_shifted / k_shifted.sum() # blur with shifted kernel
|
496 |
+
img = ndimage.filters.convolve(img, np.expand_dims(k_shifted, axis=2), mode='mirror')
|
497 |
+
img = img[0::sf, 0::sf, ...] # nearest downsampling
|
498 |
+
img = np.clip(img, 0.0, 1.0)
|
499 |
+
|
500 |
+
elif i == 3:
|
501 |
+
# downsample3
|
502 |
+
img = cv2.resize(img, (int(1 / sf * a), int(1 / sf * b)), interpolation=random.choice([1, 2, 3]))
|
503 |
+
img = np.clip(img, 0.0, 1.0)
|
504 |
+
|
505 |
+
elif i == 4:
|
506 |
+
# add Gaussian noise
|
507 |
+
img = add_Gaussian_noise(img, noise_level1=2, noise_level2=25)
|
508 |
+
|
509 |
+
elif i == 5:
|
510 |
+
# add JPEG noise
|
511 |
+
if random.random() < jpeg_prob:
|
512 |
+
img = add_JPEG_noise(img)
|
513 |
+
|
514 |
+
elif i == 6:
|
515 |
+
# add processed camera sensor noise
|
516 |
+
if random.random() < isp_prob and isp_model is not None:
|
517 |
+
with torch.no_grad():
|
518 |
+
img, hq = isp_model.forward(img.copy(), hq)
|
519 |
+
|
520 |
+
# add final JPEG compression noise
|
521 |
+
img = add_JPEG_noise(img)
|
522 |
+
|
523 |
+
# random crop
|
524 |
+
img, hq = random_crop(img, hq, sf_ori, lq_patchsize)
|
525 |
+
|
526 |
+
return img, hq
|
527 |
+
|
528 |
+
|
529 |
+
# todo no isp_model?
|
530 |
+
def degradation_bsrgan_variant(image, sf=4, isp_model=None):
|
531 |
+
"""
|
532 |
+
This is the degradation model of BSRGAN from the paper
|
533 |
+
"Designing a Practical Degradation Model for Deep Blind Image Super-Resolution"
|
534 |
+
----------
|
535 |
+
sf: scale factor
|
536 |
+
isp_model: camera ISP model
|
537 |
+
Returns
|
538 |
+
-------
|
539 |
+
img: low-quality patch, size: lq_patchsizeXlq_patchsizeXC, range: [0, 1]
|
540 |
+
hq: corresponding high-quality patch, size: (lq_patchsizexsf)X(lq_patchsizexsf)XC, range: [0, 1]
|
541 |
+
"""
|
542 |
+
image = util.uint2single(image)
|
543 |
+
isp_prob, jpeg_prob, scale2_prob = 0.25, 0.9, 0.25
|
544 |
+
sf_ori = sf
|
545 |
+
|
546 |
+
h1, w1 = image.shape[:2]
|
547 |
+
image = image.copy()[:w1 - w1 % sf, :h1 - h1 % sf, ...] # mod crop
|
548 |
+
h, w = image.shape[:2]
|
549 |
+
|
550 |
+
hq = image.copy()
|
551 |
+
|
552 |
+
if sf == 4 and random.random() < scale2_prob: # downsample1
|
553 |
+
if np.random.rand() < 0.5:
|
554 |
+
image = cv2.resize(image, (int(1 / 2 * image.shape[1]), int(1 / 2 * image.shape[0])),
|
555 |
+
interpolation=random.choice([1, 2, 3]))
|
556 |
+
else:
|
557 |
+
image = util.imresize_np(image, 1 / 2, True)
|
558 |
+
image = np.clip(image, 0.0, 1.0)
|
559 |
+
sf = 2
|
560 |
+
|
561 |
+
shuffle_order = random.sample(range(7), 7)
|
562 |
+
idx1, idx2 = shuffle_order.index(2), shuffle_order.index(3)
|
563 |
+
if idx1 > idx2: # keep downsample3 last
|
564 |
+
shuffle_order[idx1], shuffle_order[idx2] = shuffle_order[idx2], shuffle_order[idx1]
|
565 |
+
|
566 |
+
for i in shuffle_order:
|
567 |
+
|
568 |
+
if i == 0:
|
569 |
+
image = add_blur(image, sf=sf)
|
570 |
+
|
571 |
+
elif i == 1:
|
572 |
+
image = add_blur(image, sf=sf)
|
573 |
+
|
574 |
+
elif i == 2:
|
575 |
+
a, b = image.shape[1], image.shape[0]
|
576 |
+
# downsample2
|
577 |
+
if random.random() < 0.75:
|
578 |
+
sf1 = random.uniform(1, 2 * sf)
|
579 |
+
image = cv2.resize(image, (int(1 / sf1 * image.shape[1]), int(1 / sf1 * image.shape[0])),
|
580 |
+
interpolation=random.choice([1, 2, 3]))
|
581 |
+
else:
|
582 |
+
k = fspecial('gaussian', 25, random.uniform(0.1, 0.6 * sf))
|
583 |
+
k_shifted = shift_pixel(k, sf)
|
584 |
+
k_shifted = k_shifted / k_shifted.sum() # blur with shifted kernel
|
585 |
+
image = ndimage.filters.convolve(image, np.expand_dims(k_shifted, axis=2), mode='mirror')
|
586 |
+
image = image[0::sf, 0::sf, ...] # nearest downsampling
|
587 |
+
image = np.clip(image, 0.0, 1.0)
|
588 |
+
|
589 |
+
elif i == 3:
|
590 |
+
# downsample3
|
591 |
+
image = cv2.resize(image, (int(1 / sf * a), int(1 / sf * b)), interpolation=random.choice([1, 2, 3]))
|
592 |
+
image = np.clip(image, 0.0, 1.0)
|
593 |
+
|
594 |
+
elif i == 4:
|
595 |
+
# add Gaussian noise
|
596 |
+
image = add_Gaussian_noise(image, noise_level1=2, noise_level2=25)
|
597 |
+
|
598 |
+
elif i == 5:
|
599 |
+
# add JPEG noise
|
600 |
+
if random.random() < jpeg_prob:
|
601 |
+
image = add_JPEG_noise(image)
|
602 |
+
|
603 |
+
# elif i == 6:
|
604 |
+
# # add processed camera sensor noise
|
605 |
+
# if random.random() < isp_prob and isp_model is not None:
|
606 |
+
# with torch.no_grad():
|
607 |
+
# img, hq = isp_model.forward(img.copy(), hq)
|
608 |
+
|
609 |
+
# add final JPEG compression noise
|
610 |
+
image = add_JPEG_noise(image)
|
611 |
+
image = util.single2uint(image)
|
612 |
+
example = {"image":image}
|
613 |
+
return example
|
614 |
+
|
615 |
+
|
616 |
+
# TODO incase there is a pickle error one needs to replace a += x with a = a + x in add_speckle_noise etc...
|
617 |
+
def degradation_bsrgan_plus(img, sf=4, shuffle_prob=0.5, use_sharp=True, lq_patchsize=64, isp_model=None):
|
618 |
+
"""
|
619 |
+
This is an extended degradation model by combining
|
620 |
+
the degradation models of BSRGAN and Real-ESRGAN
|
621 |
+
----------
|
622 |
+
img: HXWXC, [0, 1], its size should be large than (lq_patchsizexsf)x(lq_patchsizexsf)
|
623 |
+
sf: scale factor
|
624 |
+
use_shuffle: the degradation shuffle
|
625 |
+
use_sharp: sharpening the img
|
626 |
+
Returns
|
627 |
+
-------
|
628 |
+
img: low-quality patch, size: lq_patchsizeXlq_patchsizeXC, range: [0, 1]
|
629 |
+
hq: corresponding high-quality patch, size: (lq_patchsizexsf)X(lq_patchsizexsf)XC, range: [0, 1]
|
630 |
+
"""
|
631 |
+
|
632 |
+
h1, w1 = img.shape[:2]
|
633 |
+
img = img.copy()[:w1 - w1 % sf, :h1 - h1 % sf, ...] # mod crop
|
634 |
+
h, w = img.shape[:2]
|
635 |
+
|
636 |
+
if h < lq_patchsize * sf or w < lq_patchsize * sf:
|
637 |
+
raise ValueError(f'img size ({h1}X{w1}) is too small!')
|
638 |
+
|
639 |
+
if use_sharp:
|
640 |
+
img = add_sharpening(img)
|
641 |
+
hq = img.copy()
|
642 |
+
|
643 |
+
if random.random() < shuffle_prob:
|
644 |
+
shuffle_order = random.sample(range(13), 13)
|
645 |
+
else:
|
646 |
+
shuffle_order = list(range(13))
|
647 |
+
# local shuffle for noise, JPEG is always the last one
|
648 |
+
shuffle_order[2:6] = random.sample(shuffle_order[2:6], len(range(2, 6)))
|
649 |
+
shuffle_order[9:13] = random.sample(shuffle_order[9:13], len(range(9, 13)))
|
650 |
+
|
651 |
+
poisson_prob, speckle_prob, isp_prob = 0.1, 0.1, 0.1
|
652 |
+
|
653 |
+
for i in shuffle_order:
|
654 |
+
if i == 0:
|
655 |
+
img = add_blur(img, sf=sf)
|
656 |
+
elif i == 1:
|
657 |
+
img = add_resize(img, sf=sf)
|
658 |
+
elif i == 2:
|
659 |
+
img = add_Gaussian_noise(img, noise_level1=2, noise_level2=25)
|
660 |
+
elif i == 3:
|
661 |
+
if random.random() < poisson_prob:
|
662 |
+
img = add_Poisson_noise(img)
|
663 |
+
elif i == 4:
|
664 |
+
if random.random() < speckle_prob:
|
665 |
+
img = add_speckle_noise(img)
|
666 |
+
elif i == 5:
|
667 |
+
if random.random() < isp_prob and isp_model is not None:
|
668 |
+
with torch.no_grad():
|
669 |
+
img, hq = isp_model.forward(img.copy(), hq)
|
670 |
+
elif i == 6:
|
671 |
+
img = add_JPEG_noise(img)
|
672 |
+
elif i == 7:
|
673 |
+
img = add_blur(img, sf=sf)
|
674 |
+
elif i == 8:
|
675 |
+
img = add_resize(img, sf=sf)
|
676 |
+
elif i == 9:
|
677 |
+
img = add_Gaussian_noise(img, noise_level1=2, noise_level2=25)
|
678 |
+
elif i == 10:
|
679 |
+
if random.random() < poisson_prob:
|
680 |
+
img = add_Poisson_noise(img)
|
681 |
+
elif i == 11:
|
682 |
+
if random.random() < speckle_prob:
|
683 |
+
img = add_speckle_noise(img)
|
684 |
+
elif i == 12:
|
685 |
+
if random.random() < isp_prob and isp_model is not None:
|
686 |
+
with torch.no_grad():
|
687 |
+
img, hq = isp_model.forward(img.copy(), hq)
|
688 |
+
else:
|
689 |
+
print('check the shuffle!')
|
690 |
+
|
691 |
+
# resize to desired size
|
692 |
+
img = cv2.resize(img, (int(1 / sf * hq.shape[1]), int(1 / sf * hq.shape[0])),
|
693 |
+
interpolation=random.choice([1, 2, 3]))
|
694 |
+
|
695 |
+
# add final JPEG compression noise
|
696 |
+
img = add_JPEG_noise(img)
|
697 |
+
|
698 |
+
# random crop
|
699 |
+
img, hq = random_crop(img, hq, sf, lq_patchsize)
|
700 |
+
|
701 |
+
return img, hq
|
702 |
+
|
703 |
+
|
704 |
+
if __name__ == '__main__':
|
705 |
+
print("hey")
|
706 |
+
img = util.imread_uint('utils/test.png', 3)
|
707 |
+
print(img)
|
708 |
+
img = util.uint2single(img)
|
709 |
+
print(img)
|
710 |
+
img = img[:448, :448]
|
711 |
+
h = img.shape[0] // 4
|
712 |
+
print("resizing to", h)
|
713 |
+
sf = 4
|
714 |
+
deg_fn = partial(degradation_bsrgan_variant, sf=sf)
|
715 |
+
for i in range(20):
|
716 |
+
print(i)
|
717 |
+
img_lq = deg_fn(img)
|
718 |
+
print(img_lq)
|
719 |
+
img_lq_bicubic = albumentations.SmallestMaxSize(max_size=h, interpolation=cv2.INTER_CUBIC)(image=img)["image"]
|
720 |
+
print(img_lq.shape)
|
721 |
+
print("bicubic", img_lq_bicubic.shape)
|
722 |
+
print(img_hq.shape)
|
723 |
+
lq_nearest = cv2.resize(util.single2uint(img_lq), (int(sf * img_lq.shape[1]), int(sf * img_lq.shape[0])),
|
724 |
+
interpolation=0)
|
725 |
+
lq_bicubic_nearest = cv2.resize(util.single2uint(img_lq_bicubic), (int(sf * img_lq.shape[1]), int(sf * img_lq.shape[0])),
|
726 |
+
interpolation=0)
|
727 |
+
img_concat = np.concatenate([lq_bicubic_nearest, lq_nearest, util.single2uint(img_hq)], axis=1)
|
728 |
+
util.imsave(img_concat, str(i) + '.png')
|
729 |
+
|
730 |
+
|
ttts/AA_diffusion_deprecated/ldm/modules/image_degradation/bsrgan_light.py
ADDED
@@ -0,0 +1,651 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# -*- coding: utf-8 -*-
|
2 |
+
import numpy as np
|
3 |
+
import cv2
|
4 |
+
import torch
|
5 |
+
|
6 |
+
from functools import partial
|
7 |
+
import random
|
8 |
+
from scipy import ndimage
|
9 |
+
import scipy
|
10 |
+
import scipy.stats as ss
|
11 |
+
from scipy.interpolate import interp2d
|
12 |
+
from scipy.linalg import orth
|
13 |
+
import albumentations
|
14 |
+
|
15 |
+
import ldm.modules.image_degradation.utils_image as util
|
16 |
+
|
17 |
+
"""
|
18 |
+
# --------------------------------------------
|
19 |
+
# Super-Resolution
|
20 |
+
# --------------------------------------------
|
21 |
+
#
|
22 |
+
# Kai Zhang (cskaizhang@gmail.com)
|
23 |
+
# https://github.com/cszn
|
24 |
+
# From 2019/03--2021/08
|
25 |
+
# --------------------------------------------
|
26 |
+
"""
|
27 |
+
|
28 |
+
def modcrop_np(img, sf):
|
29 |
+
'''
|
30 |
+
Args:
|
31 |
+
img: numpy image, WxH or WxHxC
|
32 |
+
sf: scale factor
|
33 |
+
Return:
|
34 |
+
cropped image
|
35 |
+
'''
|
36 |
+
w, h = img.shape[:2]
|
37 |
+
im = np.copy(img)
|
38 |
+
return im[:w - w % sf, :h - h % sf, ...]
|
39 |
+
|
40 |
+
|
41 |
+
"""
|
42 |
+
# --------------------------------------------
|
43 |
+
# anisotropic Gaussian kernels
|
44 |
+
# --------------------------------------------
|
45 |
+
"""
|
46 |
+
|
47 |
+
|
48 |
+
def analytic_kernel(k):
|
49 |
+
"""Calculate the X4 kernel from the X2 kernel (for proof see appendix in paper)"""
|
50 |
+
k_size = k.shape[0]
|
51 |
+
# Calculate the big kernels size
|
52 |
+
big_k = np.zeros((3 * k_size - 2, 3 * k_size - 2))
|
53 |
+
# Loop over the small kernel to fill the big one
|
54 |
+
for r in range(k_size):
|
55 |
+
for c in range(k_size):
|
56 |
+
big_k[2 * r:2 * r + k_size, 2 * c:2 * c + k_size] += k[r, c] * k
|
57 |
+
# Crop the edges of the big kernel to ignore very small values and increase run time of SR
|
58 |
+
crop = k_size // 2
|
59 |
+
cropped_big_k = big_k[crop:-crop, crop:-crop]
|
60 |
+
# Normalize to 1
|
61 |
+
return cropped_big_k / cropped_big_k.sum()
|
62 |
+
|
63 |
+
|
64 |
+
def anisotropic_Gaussian(ksize=15, theta=np.pi, l1=6, l2=6):
|
65 |
+
""" generate an anisotropic Gaussian kernel
|
66 |
+
Args:
|
67 |
+
ksize : e.g., 15, kernel size
|
68 |
+
theta : [0, pi], rotation angle range
|
69 |
+
l1 : [0.1,50], scaling of eigenvalues
|
70 |
+
l2 : [0.1,l1], scaling of eigenvalues
|
71 |
+
If l1 = l2, will get an isotropic Gaussian kernel.
|
72 |
+
Returns:
|
73 |
+
k : kernel
|
74 |
+
"""
|
75 |
+
|
76 |
+
v = np.dot(np.array([[np.cos(theta), -np.sin(theta)], [np.sin(theta), np.cos(theta)]]), np.array([1., 0.]))
|
77 |
+
V = np.array([[v[0], v[1]], [v[1], -v[0]]])
|
78 |
+
D = np.array([[l1, 0], [0, l2]])
|
79 |
+
Sigma = np.dot(np.dot(V, D), np.linalg.inv(V))
|
80 |
+
k = gm_blur_kernel(mean=[0, 0], cov=Sigma, size=ksize)
|
81 |
+
|
82 |
+
return k
|
83 |
+
|
84 |
+
|
85 |
+
def gm_blur_kernel(mean, cov, size=15):
|
86 |
+
center = size / 2.0 + 0.5
|
87 |
+
k = np.zeros([size, size])
|
88 |
+
for y in range(size):
|
89 |
+
for x in range(size):
|
90 |
+
cy = y - center + 1
|
91 |
+
cx = x - center + 1
|
92 |
+
k[y, x] = ss.multivariate_normal.pdf([cx, cy], mean=mean, cov=cov)
|
93 |
+
|
94 |
+
k = k / np.sum(k)
|
95 |
+
return k
|
96 |
+
|
97 |
+
|
98 |
+
def shift_pixel(x, sf, upper_left=True):
|
99 |
+
"""shift pixel for super-resolution with different scale factors
|
100 |
+
Args:
|
101 |
+
x: WxHxC or WxH
|
102 |
+
sf: scale factor
|
103 |
+
upper_left: shift direction
|
104 |
+
"""
|
105 |
+
h, w = x.shape[:2]
|
106 |
+
shift = (sf - 1) * 0.5
|
107 |
+
xv, yv = np.arange(0, w, 1.0), np.arange(0, h, 1.0)
|
108 |
+
if upper_left:
|
109 |
+
x1 = xv + shift
|
110 |
+
y1 = yv + shift
|
111 |
+
else:
|
112 |
+
x1 = xv - shift
|
113 |
+
y1 = yv - shift
|
114 |
+
|
115 |
+
x1 = np.clip(x1, 0, w - 1)
|
116 |
+
y1 = np.clip(y1, 0, h - 1)
|
117 |
+
|
118 |
+
if x.ndim == 2:
|
119 |
+
x = interp2d(xv, yv, x)(x1, y1)
|
120 |
+
if x.ndim == 3:
|
121 |
+
for i in range(x.shape[-1]):
|
122 |
+
x[:, :, i] = interp2d(xv, yv, x[:, :, i])(x1, y1)
|
123 |
+
|
124 |
+
return x
|
125 |
+
|
126 |
+
|
127 |
+
def blur(x, k):
|
128 |
+
'''
|
129 |
+
x: image, NxcxHxW
|
130 |
+
k: kernel, Nx1xhxw
|
131 |
+
'''
|
132 |
+
n, c = x.shape[:2]
|
133 |
+
p1, p2 = (k.shape[-2] - 1) // 2, (k.shape[-1] - 1) // 2
|
134 |
+
x = torch.nn.functional.pad(x, pad=(p1, p2, p1, p2), mode='replicate')
|
135 |
+
k = k.repeat(1, c, 1, 1)
|
136 |
+
k = k.view(-1, 1, k.shape[2], k.shape[3])
|
137 |
+
x = x.view(1, -1, x.shape[2], x.shape[3])
|
138 |
+
x = torch.nn.functional.conv2d(x, k, bias=None, stride=1, padding=0, groups=n * c)
|
139 |
+
x = x.view(n, c, x.shape[2], x.shape[3])
|
140 |
+
|
141 |
+
return x
|
142 |
+
|
143 |
+
|
144 |
+
def gen_kernel(k_size=np.array([15, 15]), scale_factor=np.array([4, 4]), min_var=0.6, max_var=10., noise_level=0):
|
145 |
+
""""
|
146 |
+
# modified version of https://github.com/assafshocher/BlindSR_dataset_generator
|
147 |
+
# Kai Zhang
|
148 |
+
# min_var = 0.175 * sf # variance of the gaussian kernel will be sampled between min_var and max_var
|
149 |
+
# max_var = 2.5 * sf
|
150 |
+
"""
|
151 |
+
# Set random eigen-vals (lambdas) and angle (theta) for COV matrix
|
152 |
+
lambda_1 = min_var + np.random.rand() * (max_var - min_var)
|
153 |
+
lambda_2 = min_var + np.random.rand() * (max_var - min_var)
|
154 |
+
theta = np.random.rand() * np.pi # random theta
|
155 |
+
noise = -noise_level + np.random.rand(*k_size) * noise_level * 2
|
156 |
+
|
157 |
+
# Set COV matrix using Lambdas and Theta
|
158 |
+
LAMBDA = np.diag([lambda_1, lambda_2])
|
159 |
+
Q = np.array([[np.cos(theta), -np.sin(theta)],
|
160 |
+
[np.sin(theta), np.cos(theta)]])
|
161 |
+
SIGMA = Q @ LAMBDA @ Q.T
|
162 |
+
INV_SIGMA = np.linalg.inv(SIGMA)[None, None, :, :]
|
163 |
+
|
164 |
+
# Set expectation position (shifting kernel for aligned image)
|
165 |
+
MU = k_size // 2 - 0.5 * (scale_factor - 1) # - 0.5 * (scale_factor - k_size % 2)
|
166 |
+
MU = MU[None, None, :, None]
|
167 |
+
|
168 |
+
# Create meshgrid for Gaussian
|
169 |
+
[X, Y] = np.meshgrid(range(k_size[0]), range(k_size[1]))
|
170 |
+
Z = np.stack([X, Y], 2)[:, :, :, None]
|
171 |
+
|
172 |
+
# Calcualte Gaussian for every pixel of the kernel
|
173 |
+
ZZ = Z - MU
|
174 |
+
ZZ_t = ZZ.transpose(0, 1, 3, 2)
|
175 |
+
raw_kernel = np.exp(-0.5 * np.squeeze(ZZ_t @ INV_SIGMA @ ZZ)) * (1 + noise)
|
176 |
+
|
177 |
+
# shift the kernel so it will be centered
|
178 |
+
# raw_kernel_centered = kernel_shift(raw_kernel, scale_factor)
|
179 |
+
|
180 |
+
# Normalize the kernel and return
|
181 |
+
# kernel = raw_kernel_centered / np.sum(raw_kernel_centered)
|
182 |
+
kernel = raw_kernel / np.sum(raw_kernel)
|
183 |
+
return kernel
|
184 |
+
|
185 |
+
|
186 |
+
def fspecial_gaussian(hsize, sigma):
|
187 |
+
hsize = [hsize, hsize]
|
188 |
+
siz = [(hsize[0] - 1.0) / 2.0, (hsize[1] - 1.0) / 2.0]
|
189 |
+
std = sigma
|
190 |
+
[x, y] = np.meshgrid(np.arange(-siz[1], siz[1] + 1), np.arange(-siz[0], siz[0] + 1))
|
191 |
+
arg = -(x * x + y * y) / (2 * std * std)
|
192 |
+
h = np.exp(arg)
|
193 |
+
h[h < scipy.finfo(float).eps * h.max()] = 0
|
194 |
+
sumh = h.sum()
|
195 |
+
if sumh != 0:
|
196 |
+
h = h / sumh
|
197 |
+
return h
|
198 |
+
|
199 |
+
|
200 |
+
def fspecial_laplacian(alpha):
|
201 |
+
alpha = max([0, min([alpha, 1])])
|
202 |
+
h1 = alpha / (alpha + 1)
|
203 |
+
h2 = (1 - alpha) / (alpha + 1)
|
204 |
+
h = [[h1, h2, h1], [h2, -4 / (alpha + 1), h2], [h1, h2, h1]]
|
205 |
+
h = np.array(h)
|
206 |
+
return h
|
207 |
+
|
208 |
+
|
209 |
+
def fspecial(filter_type, *args, **kwargs):
|
210 |
+
'''
|
211 |
+
python code from:
|
212 |
+
https://github.com/ronaldosena/imagens-medicas-2/blob/40171a6c259edec7827a6693a93955de2bd39e76/Aulas/aula_2_-_uniform_filter/matlab_fspecial.py
|
213 |
+
'''
|
214 |
+
if filter_type == 'gaussian':
|
215 |
+
return fspecial_gaussian(*args, **kwargs)
|
216 |
+
if filter_type == 'laplacian':
|
217 |
+
return fspecial_laplacian(*args, **kwargs)
|
218 |
+
|
219 |
+
|
220 |
+
"""
|
221 |
+
# --------------------------------------------
|
222 |
+
# degradation models
|
223 |
+
# --------------------------------------------
|
224 |
+
"""
|
225 |
+
|
226 |
+
|
227 |
+
def bicubic_degradation(x, sf=3):
|
228 |
+
'''
|
229 |
+
Args:
|
230 |
+
x: HxWxC image, [0, 1]
|
231 |
+
sf: down-scale factor
|
232 |
+
Return:
|
233 |
+
bicubicly downsampled LR image
|
234 |
+
'''
|
235 |
+
x = util.imresize_np(x, scale=1 / sf)
|
236 |
+
return x
|
237 |
+
|
238 |
+
|
239 |
+
def srmd_degradation(x, k, sf=3):
|
240 |
+
''' blur + bicubic downsampling
|
241 |
+
Args:
|
242 |
+
x: HxWxC image, [0, 1]
|
243 |
+
k: hxw, double
|
244 |
+
sf: down-scale factor
|
245 |
+
Return:
|
246 |
+
downsampled LR image
|
247 |
+
Reference:
|
248 |
+
@inproceedings{zhang2018learning,
|
249 |
+
title={Learning a single convolutional super-resolution network for multiple degradations},
|
250 |
+
author={Zhang, Kai and Zuo, Wangmeng and Zhang, Lei},
|
251 |
+
booktitle={IEEE Conference on Computer Vision and Pattern Recognition},
|
252 |
+
pages={3262--3271},
|
253 |
+
year={2018}
|
254 |
+
}
|
255 |
+
'''
|
256 |
+
x = ndimage.convolve(x, np.expand_dims(k, axis=2), mode='wrap') # 'nearest' | 'mirror'
|
257 |
+
x = bicubic_degradation(x, sf=sf)
|
258 |
+
return x
|
259 |
+
|
260 |
+
|
261 |
+
def dpsr_degradation(x, k, sf=3):
|
262 |
+
''' bicubic downsampling + blur
|
263 |
+
Args:
|
264 |
+
x: HxWxC image, [0, 1]
|
265 |
+
k: hxw, double
|
266 |
+
sf: down-scale factor
|
267 |
+
Return:
|
268 |
+
downsampled LR image
|
269 |
+
Reference:
|
270 |
+
@inproceedings{zhang2019deep,
|
271 |
+
title={Deep Plug-and-Play Super-Resolution for Arbitrary Blur Kernels},
|
272 |
+
author={Zhang, Kai and Zuo, Wangmeng and Zhang, Lei},
|
273 |
+
booktitle={IEEE Conference on Computer Vision and Pattern Recognition},
|
274 |
+
pages={1671--1681},
|
275 |
+
year={2019}
|
276 |
+
}
|
277 |
+
'''
|
278 |
+
x = bicubic_degradation(x, sf=sf)
|
279 |
+
x = ndimage.convolve(x, np.expand_dims(k, axis=2), mode='wrap')
|
280 |
+
return x
|
281 |
+
|
282 |
+
|
283 |
+
def classical_degradation(x, k, sf=3):
|
284 |
+
''' blur + downsampling
|
285 |
+
Args:
|
286 |
+
x: HxWxC image, [0, 1]/[0, 255]
|
287 |
+
k: hxw, double
|
288 |
+
sf: down-scale factor
|
289 |
+
Return:
|
290 |
+
downsampled LR image
|
291 |
+
'''
|
292 |
+
x = ndimage.convolve(x, np.expand_dims(k, axis=2), mode='wrap')
|
293 |
+
# x = filters.correlate(x, np.expand_dims(np.flip(k), axis=2))
|
294 |
+
st = 0
|
295 |
+
return x[st::sf, st::sf, ...]
|
296 |
+
|
297 |
+
|
298 |
+
def add_sharpening(img, weight=0.5, radius=50, threshold=10):
|
299 |
+
"""USM sharpening. borrowed from real-ESRGAN
|
300 |
+
Input image: I; Blurry image: B.
|
301 |
+
1. K = I + weight * (I - B)
|
302 |
+
2. Mask = 1 if abs(I - B) > threshold, else: 0
|
303 |
+
3. Blur mask:
|
304 |
+
4. Out = Mask * K + (1 - Mask) * I
|
305 |
+
Args:
|
306 |
+
img (Numpy array): Input image, HWC, BGR; float32, [0, 1].
|
307 |
+
weight (float): Sharp weight. Default: 1.
|
308 |
+
radius (float): Kernel size of Gaussian blur. Default: 50.
|
309 |
+
threshold (int):
|
310 |
+
"""
|
311 |
+
if radius % 2 == 0:
|
312 |
+
radius += 1
|
313 |
+
blur = cv2.GaussianBlur(img, (radius, radius), 0)
|
314 |
+
residual = img - blur
|
315 |
+
mask = np.abs(residual) * 255 > threshold
|
316 |
+
mask = mask.astype('float32')
|
317 |
+
soft_mask = cv2.GaussianBlur(mask, (radius, radius), 0)
|
318 |
+
|
319 |
+
K = img + weight * residual
|
320 |
+
K = np.clip(K, 0, 1)
|
321 |
+
return soft_mask * K + (1 - soft_mask) * img
|
322 |
+
|
323 |
+
|
324 |
+
def add_blur(img, sf=4):
|
325 |
+
wd2 = 4.0 + sf
|
326 |
+
wd = 2.0 + 0.2 * sf
|
327 |
+
|
328 |
+
wd2 = wd2/4
|
329 |
+
wd = wd/4
|
330 |
+
|
331 |
+
if random.random() < 0.5:
|
332 |
+
l1 = wd2 * random.random()
|
333 |
+
l2 = wd2 * random.random()
|
334 |
+
k = anisotropic_Gaussian(ksize=random.randint(2, 11) + 3, theta=random.random() * np.pi, l1=l1, l2=l2)
|
335 |
+
else:
|
336 |
+
k = fspecial('gaussian', random.randint(2, 4) + 3, wd * random.random())
|
337 |
+
img = ndimage.convolve(img, np.expand_dims(k, axis=2), mode='mirror')
|
338 |
+
|
339 |
+
return img
|
340 |
+
|
341 |
+
|
342 |
+
def add_resize(img, sf=4):
|
343 |
+
rnum = np.random.rand()
|
344 |
+
if rnum > 0.8: # up
|
345 |
+
sf1 = random.uniform(1, 2)
|
346 |
+
elif rnum < 0.7: # down
|
347 |
+
sf1 = random.uniform(0.5 / sf, 1)
|
348 |
+
else:
|
349 |
+
sf1 = 1.0
|
350 |
+
img = cv2.resize(img, (int(sf1 * img.shape[1]), int(sf1 * img.shape[0])), interpolation=random.choice([1, 2, 3]))
|
351 |
+
img = np.clip(img, 0.0, 1.0)
|
352 |
+
|
353 |
+
return img
|
354 |
+
|
355 |
+
|
356 |
+
# def add_Gaussian_noise(img, noise_level1=2, noise_level2=25):
|
357 |
+
# noise_level = random.randint(noise_level1, noise_level2)
|
358 |
+
# rnum = np.random.rand()
|
359 |
+
# if rnum > 0.6: # add color Gaussian noise
|
360 |
+
# img += np.random.normal(0, noise_level / 255.0, img.shape).astype(np.float32)
|
361 |
+
# elif rnum < 0.4: # add grayscale Gaussian noise
|
362 |
+
# img += np.random.normal(0, noise_level / 255.0, (*img.shape[:2], 1)).astype(np.float32)
|
363 |
+
# else: # add noise
|
364 |
+
# L = noise_level2 / 255.
|
365 |
+
# D = np.diag(np.random.rand(3))
|
366 |
+
# U = orth(np.random.rand(3, 3))
|
367 |
+
# conv = np.dot(np.dot(np.transpose(U), D), U)
|
368 |
+
# img += np.random.multivariate_normal([0, 0, 0], np.abs(L ** 2 * conv), img.shape[:2]).astype(np.float32)
|
369 |
+
# img = np.clip(img, 0.0, 1.0)
|
370 |
+
# return img
|
371 |
+
|
372 |
+
def add_Gaussian_noise(img, noise_level1=2, noise_level2=25):
|
373 |
+
noise_level = random.randint(noise_level1, noise_level2)
|
374 |
+
rnum = np.random.rand()
|
375 |
+
if rnum > 0.6: # add color Gaussian noise
|
376 |
+
img = img + np.random.normal(0, noise_level / 255.0, img.shape).astype(np.float32)
|
377 |
+
elif rnum < 0.4: # add grayscale Gaussian noise
|
378 |
+
img = img + np.random.normal(0, noise_level / 255.0, (*img.shape[:2], 1)).astype(np.float32)
|
379 |
+
else: # add noise
|
380 |
+
L = noise_level2 / 255.
|
381 |
+
D = np.diag(np.random.rand(3))
|
382 |
+
U = orth(np.random.rand(3, 3))
|
383 |
+
conv = np.dot(np.dot(np.transpose(U), D), U)
|
384 |
+
img = img + np.random.multivariate_normal([0, 0, 0], np.abs(L ** 2 * conv), img.shape[:2]).astype(np.float32)
|
385 |
+
img = np.clip(img, 0.0, 1.0)
|
386 |
+
return img
|
387 |
+
|
388 |
+
|
389 |
+
def add_speckle_noise(img, noise_level1=2, noise_level2=25):
|
390 |
+
noise_level = random.randint(noise_level1, noise_level2)
|
391 |
+
img = np.clip(img, 0.0, 1.0)
|
392 |
+
rnum = random.random()
|
393 |
+
if rnum > 0.6:
|
394 |
+
img += img * np.random.normal(0, noise_level / 255.0, img.shape).astype(np.float32)
|
395 |
+
elif rnum < 0.4:
|
396 |
+
img += img * np.random.normal(0, noise_level / 255.0, (*img.shape[:2], 1)).astype(np.float32)
|
397 |
+
else:
|
398 |
+
L = noise_level2 / 255.
|
399 |
+
D = np.diag(np.random.rand(3))
|
400 |
+
U = orth(np.random.rand(3, 3))
|
401 |
+
conv = np.dot(np.dot(np.transpose(U), D), U)
|
402 |
+
img += img * np.random.multivariate_normal([0, 0, 0], np.abs(L ** 2 * conv), img.shape[:2]).astype(np.float32)
|
403 |
+
img = np.clip(img, 0.0, 1.0)
|
404 |
+
return img
|
405 |
+
|
406 |
+
|
407 |
+
def add_Poisson_noise(img):
|
408 |
+
img = np.clip((img * 255.0).round(), 0, 255) / 255.
|
409 |
+
vals = 10 ** (2 * random.random() + 2.0) # [2, 4]
|
410 |
+
if random.random() < 0.5:
|
411 |
+
img = np.random.poisson(img * vals).astype(np.float32) / vals
|
412 |
+
else:
|
413 |
+
img_gray = np.dot(img[..., :3], [0.299, 0.587, 0.114])
|
414 |
+
img_gray = np.clip((img_gray * 255.0).round(), 0, 255) / 255.
|
415 |
+
noise_gray = np.random.poisson(img_gray * vals).astype(np.float32) / vals - img_gray
|
416 |
+
img += noise_gray[:, :, np.newaxis]
|
417 |
+
img = np.clip(img, 0.0, 1.0)
|
418 |
+
return img
|
419 |
+
|
420 |
+
|
421 |
+
def add_JPEG_noise(img):
|
422 |
+
quality_factor = random.randint(80, 95)
|
423 |
+
img = cv2.cvtColor(util.single2uint(img), cv2.COLOR_RGB2BGR)
|
424 |
+
result, encimg = cv2.imencode('.jpg', img, [int(cv2.IMWRITE_JPEG_QUALITY), quality_factor])
|
425 |
+
img = cv2.imdecode(encimg, 1)
|
426 |
+
img = cv2.cvtColor(util.uint2single(img), cv2.COLOR_BGR2RGB)
|
427 |
+
return img
|
428 |
+
|
429 |
+
|
430 |
+
def random_crop(lq, hq, sf=4, lq_patchsize=64):
|
431 |
+
h, w = lq.shape[:2]
|
432 |
+
rnd_h = random.randint(0, h - lq_patchsize)
|
433 |
+
rnd_w = random.randint(0, w - lq_patchsize)
|
434 |
+
lq = lq[rnd_h:rnd_h + lq_patchsize, rnd_w:rnd_w + lq_patchsize, :]
|
435 |
+
|
436 |
+
rnd_h_H, rnd_w_H = int(rnd_h * sf), int(rnd_w * sf)
|
437 |
+
hq = hq[rnd_h_H:rnd_h_H + lq_patchsize * sf, rnd_w_H:rnd_w_H + lq_patchsize * sf, :]
|
438 |
+
return lq, hq
|
439 |
+
|
440 |
+
|
441 |
+
def degradation_bsrgan(img, sf=4, lq_patchsize=72, isp_model=None):
|
442 |
+
"""
|
443 |
+
This is the degradation model of BSRGAN from the paper
|
444 |
+
"Designing a Practical Degradation Model for Deep Blind Image Super-Resolution"
|
445 |
+
----------
|
446 |
+
img: HXWXC, [0, 1], its size should be large than (lq_patchsizexsf)x(lq_patchsizexsf)
|
447 |
+
sf: scale factor
|
448 |
+
isp_model: camera ISP model
|
449 |
+
Returns
|
450 |
+
-------
|
451 |
+
img: low-quality patch, size: lq_patchsizeXlq_patchsizeXC, range: [0, 1]
|
452 |
+
hq: corresponding high-quality patch, size: (lq_patchsizexsf)X(lq_patchsizexsf)XC, range: [0, 1]
|
453 |
+
"""
|
454 |
+
isp_prob, jpeg_prob, scale2_prob = 0.25, 0.9, 0.25
|
455 |
+
sf_ori = sf
|
456 |
+
|
457 |
+
h1, w1 = img.shape[:2]
|
458 |
+
img = img.copy()[:w1 - w1 % sf, :h1 - h1 % sf, ...] # mod crop
|
459 |
+
h, w = img.shape[:2]
|
460 |
+
|
461 |
+
if h < lq_patchsize * sf or w < lq_patchsize * sf:
|
462 |
+
raise ValueError(f'img size ({h1}X{w1}) is too small!')
|
463 |
+
|
464 |
+
hq = img.copy()
|
465 |
+
|
466 |
+
if sf == 4 and random.random() < scale2_prob: # downsample1
|
467 |
+
if np.random.rand() < 0.5:
|
468 |
+
img = cv2.resize(img, (int(1 / 2 * img.shape[1]), int(1 / 2 * img.shape[0])),
|
469 |
+
interpolation=random.choice([1, 2, 3]))
|
470 |
+
else:
|
471 |
+
img = util.imresize_np(img, 1 / 2, True)
|
472 |
+
img = np.clip(img, 0.0, 1.0)
|
473 |
+
sf = 2
|
474 |
+
|
475 |
+
shuffle_order = random.sample(range(7), 7)
|
476 |
+
idx1, idx2 = shuffle_order.index(2), shuffle_order.index(3)
|
477 |
+
if idx1 > idx2: # keep downsample3 last
|
478 |
+
shuffle_order[idx1], shuffle_order[idx2] = shuffle_order[idx2], shuffle_order[idx1]
|
479 |
+
|
480 |
+
for i in shuffle_order:
|
481 |
+
|
482 |
+
if i == 0:
|
483 |
+
img = add_blur(img, sf=sf)
|
484 |
+
|
485 |
+
elif i == 1:
|
486 |
+
img = add_blur(img, sf=sf)
|
487 |
+
|
488 |
+
elif i == 2:
|
489 |
+
a, b = img.shape[1], img.shape[0]
|
490 |
+
# downsample2
|
491 |
+
if random.random() < 0.75:
|
492 |
+
sf1 = random.uniform(1, 2 * sf)
|
493 |
+
img = cv2.resize(img, (int(1 / sf1 * img.shape[1]), int(1 / sf1 * img.shape[0])),
|
494 |
+
interpolation=random.choice([1, 2, 3]))
|
495 |
+
else:
|
496 |
+
k = fspecial('gaussian', 25, random.uniform(0.1, 0.6 * sf))
|
497 |
+
k_shifted = shift_pixel(k, sf)
|
498 |
+
k_shifted = k_shifted / k_shifted.sum() # blur with shifted kernel
|
499 |
+
img = ndimage.convolve(img, np.expand_dims(k_shifted, axis=2), mode='mirror')
|
500 |
+
img = img[0::sf, 0::sf, ...] # nearest downsampling
|
501 |
+
img = np.clip(img, 0.0, 1.0)
|
502 |
+
|
503 |
+
elif i == 3:
|
504 |
+
# downsample3
|
505 |
+
img = cv2.resize(img, (int(1 / sf * a), int(1 / sf * b)), interpolation=random.choice([1, 2, 3]))
|
506 |
+
img = np.clip(img, 0.0, 1.0)
|
507 |
+
|
508 |
+
elif i == 4:
|
509 |
+
# add Gaussian noise
|
510 |
+
img = add_Gaussian_noise(img, noise_level1=2, noise_level2=8)
|
511 |
+
|
512 |
+
elif i == 5:
|
513 |
+
# add JPEG noise
|
514 |
+
if random.random() < jpeg_prob:
|
515 |
+
img = add_JPEG_noise(img)
|
516 |
+
|
517 |
+
elif i == 6:
|
518 |
+
# add processed camera sensor noise
|
519 |
+
if random.random() < isp_prob and isp_model is not None:
|
520 |
+
with torch.no_grad():
|
521 |
+
img, hq = isp_model.forward(img.copy(), hq)
|
522 |
+
|
523 |
+
# add final JPEG compression noise
|
524 |
+
img = add_JPEG_noise(img)
|
525 |
+
|
526 |
+
# random crop
|
527 |
+
img, hq = random_crop(img, hq, sf_ori, lq_patchsize)
|
528 |
+
|
529 |
+
return img, hq
|
530 |
+
|
531 |
+
|
532 |
+
# todo no isp_model?
|
533 |
+
def degradation_bsrgan_variant(image, sf=4, isp_model=None, up=False):
|
534 |
+
"""
|
535 |
+
This is the degradation model of BSRGAN from the paper
|
536 |
+
"Designing a Practical Degradation Model for Deep Blind Image Super-Resolution"
|
537 |
+
----------
|
538 |
+
sf: scale factor
|
539 |
+
isp_model: camera ISP model
|
540 |
+
Returns
|
541 |
+
-------
|
542 |
+
img: low-quality patch, size: lq_patchsizeXlq_patchsizeXC, range: [0, 1]
|
543 |
+
hq: corresponding high-quality patch, size: (lq_patchsizexsf)X(lq_patchsizexsf)XC, range: [0, 1]
|
544 |
+
"""
|
545 |
+
image = util.uint2single(image)
|
546 |
+
isp_prob, jpeg_prob, scale2_prob = 0.25, 0.9, 0.25
|
547 |
+
sf_ori = sf
|
548 |
+
|
549 |
+
h1, w1 = image.shape[:2]
|
550 |
+
image = image.copy()[:w1 - w1 % sf, :h1 - h1 % sf, ...] # mod crop
|
551 |
+
h, w = image.shape[:2]
|
552 |
+
|
553 |
+
hq = image.copy()
|
554 |
+
|
555 |
+
if sf == 4 and random.random() < scale2_prob: # downsample1
|
556 |
+
if np.random.rand() < 0.5:
|
557 |
+
image = cv2.resize(image, (int(1 / 2 * image.shape[1]), int(1 / 2 * image.shape[0])),
|
558 |
+
interpolation=random.choice([1, 2, 3]))
|
559 |
+
else:
|
560 |
+
image = util.imresize_np(image, 1 / 2, True)
|
561 |
+
image = np.clip(image, 0.0, 1.0)
|
562 |
+
sf = 2
|
563 |
+
|
564 |
+
shuffle_order = random.sample(range(7), 7)
|
565 |
+
idx1, idx2 = shuffle_order.index(2), shuffle_order.index(3)
|
566 |
+
if idx1 > idx2: # keep downsample3 last
|
567 |
+
shuffle_order[idx1], shuffle_order[idx2] = shuffle_order[idx2], shuffle_order[idx1]
|
568 |
+
|
569 |
+
for i in shuffle_order:
|
570 |
+
|
571 |
+
if i == 0:
|
572 |
+
image = add_blur(image, sf=sf)
|
573 |
+
|
574 |
+
# elif i == 1:
|
575 |
+
# image = add_blur(image, sf=sf)
|
576 |
+
|
577 |
+
if i == 0:
|
578 |
+
pass
|
579 |
+
|
580 |
+
elif i == 2:
|
581 |
+
a, b = image.shape[1], image.shape[0]
|
582 |
+
# downsample2
|
583 |
+
if random.random() < 0.8:
|
584 |
+
sf1 = random.uniform(1, 2 * sf)
|
585 |
+
image = cv2.resize(image, (int(1 / sf1 * image.shape[1]), int(1 / sf1 * image.shape[0])),
|
586 |
+
interpolation=random.choice([1, 2, 3]))
|
587 |
+
else:
|
588 |
+
k = fspecial('gaussian', 25, random.uniform(0.1, 0.6 * sf))
|
589 |
+
k_shifted = shift_pixel(k, sf)
|
590 |
+
k_shifted = k_shifted / k_shifted.sum() # blur with shifted kernel
|
591 |
+
image = ndimage.convolve(image, np.expand_dims(k_shifted, axis=2), mode='mirror')
|
592 |
+
image = image[0::sf, 0::sf, ...] # nearest downsampling
|
593 |
+
|
594 |
+
image = np.clip(image, 0.0, 1.0)
|
595 |
+
|
596 |
+
elif i == 3:
|
597 |
+
# downsample3
|
598 |
+
image = cv2.resize(image, (int(1 / sf * a), int(1 / sf * b)), interpolation=random.choice([1, 2, 3]))
|
599 |
+
image = np.clip(image, 0.0, 1.0)
|
600 |
+
|
601 |
+
elif i == 4:
|
602 |
+
# add Gaussian noise
|
603 |
+
image = add_Gaussian_noise(image, noise_level1=1, noise_level2=2)
|
604 |
+
|
605 |
+
elif i == 5:
|
606 |
+
# add JPEG noise
|
607 |
+
if random.random() < jpeg_prob:
|
608 |
+
image = add_JPEG_noise(image)
|
609 |
+
#
|
610 |
+
# elif i == 6:
|
611 |
+
# # add processed camera sensor noise
|
612 |
+
# if random.random() < isp_prob and isp_model is not None:
|
613 |
+
# with torch.no_grad():
|
614 |
+
# img, hq = isp_model.forward(img.copy(), hq)
|
615 |
+
|
616 |
+
# add final JPEG compression noise
|
617 |
+
image = add_JPEG_noise(image)
|
618 |
+
image = util.single2uint(image)
|
619 |
+
if up:
|
620 |
+
image = cv2.resize(image, (w1, h1), interpolation=cv2.INTER_CUBIC) # todo: random, as above? want to condition on it then
|
621 |
+
example = {"image": image}
|
622 |
+
return example
|
623 |
+
|
624 |
+
|
625 |
+
|
626 |
+
|
627 |
+
if __name__ == '__main__':
|
628 |
+
print("hey")
|
629 |
+
img = util.imread_uint('utils/test.png', 3)
|
630 |
+
img = img[:448, :448]
|
631 |
+
h = img.shape[0] // 4
|
632 |
+
print("resizing to", h)
|
633 |
+
sf = 4
|
634 |
+
deg_fn = partial(degradation_bsrgan_variant, sf=sf)
|
635 |
+
for i in range(20):
|
636 |
+
print(i)
|
637 |
+
img_hq = img
|
638 |
+
img_lq = deg_fn(img)["image"]
|
639 |
+
img_hq, img_lq = util.uint2single(img_hq), util.uint2single(img_lq)
|
640 |
+
print(img_lq)
|
641 |
+
img_lq_bicubic = albumentations.SmallestMaxSize(max_size=h, interpolation=cv2.INTER_CUBIC)(image=img_hq)["image"]
|
642 |
+
print(img_lq.shape)
|
643 |
+
print("bicubic", img_lq_bicubic.shape)
|
644 |
+
print(img_hq.shape)
|
645 |
+
lq_nearest = cv2.resize(util.single2uint(img_lq), (int(sf * img_lq.shape[1]), int(sf * img_lq.shape[0])),
|
646 |
+
interpolation=0)
|
647 |
+
lq_bicubic_nearest = cv2.resize(util.single2uint(img_lq_bicubic),
|
648 |
+
(int(sf * img_lq.shape[1]), int(sf * img_lq.shape[0])),
|
649 |
+
interpolation=0)
|
650 |
+
img_concat = np.concatenate([lq_bicubic_nearest, lq_nearest, util.single2uint(img_hq)], axis=1)
|
651 |
+
util.imsave(img_concat, str(i) + '.png')
|