Spaces:
Runtime error
Runtime error
updaate mdt demo
Browse files- LICENSE.txt +400 -0
- README.md +7 -6
- app.py +191 -0
- diffusion/__init__.py +46 -0
- diffusion/diffusion_utils.py +88 -0
- diffusion/gaussian_diffusion.py +873 -0
- diffusion/respace.py +129 -0
- diffusion/timestep_sampler.py +150 -0
- gradio_cached_examples/25/Generated Images/3098beb2-718a-4d20-a8c4-350e6f4d706f/captions.json +1 -0
- gradio_cached_examples/25/Generated Images/3098beb2-718a-4d20-a8c4-350e6f4d706f/imagehtt65eku.png +0 -0
- gradio_cached_examples/25/Generated Images/3f1d5e43-5a07-402b-b062-045a55ee88ad/captions.json +1 -0
- gradio_cached_examples/25/Generated Images/3f1d5e43-5a07-402b-b062-045a55ee88ad/imagejpi4i9g_.png +0 -0
- gradio_cached_examples/25/Generated Images/46fdfba3-f8cc-49df-9f23-140a8a2488af/captions.json +1 -0
- gradio_cached_examples/25/Generated Images/46fdfba3-f8cc-49df-9f23-140a8a2488af/imageeuen5ewd.png +0 -0
- gradio_cached_examples/25/Generated Images/5bcc42d0-0401-45a6-b061-dabb7badf1a6/captions.json +1 -0
- gradio_cached_examples/25/Generated Images/5bcc42d0-0401-45a6-b061-dabb7badf1a6/imageb3nfp28a.png +0 -0
- gradio_cached_examples/25/Generated Images/5e8ec3cf-77eb-4a14-b9a3-c2f99f52398b/captions.json +1 -0
- gradio_cached_examples/25/Generated Images/5e8ec3cf-77eb-4a14-b9a3-c2f99f52398b/imageglbae_fo.png +0 -0
- gradio_cached_examples/25/log.csv +6 -0
- imagenet_class_data.py +1003 -0
- models.py +611 -0
- requirements.txt +8 -0
LICENSE.txt
ADDED
@@ -0,0 +1,400 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
|
2 |
+
Attribution-NonCommercial 4.0 International
|
3 |
+
|
4 |
+
=======================================================================
|
5 |
+
|
6 |
+
Creative Commons Corporation ("Creative Commons") is not a law firm and
|
7 |
+
does not provide legal services or legal advice. Distribution of
|
8 |
+
Creative Commons public licenses does not create a lawyer-client or
|
9 |
+
other relationship. Creative Commons makes its licenses and related
|
10 |
+
information available on an "as-is" basis. Creative Commons gives no
|
11 |
+
warranties regarding its licenses, any material licensed under their
|
12 |
+
terms and conditions, or any related information. Creative Commons
|
13 |
+
disclaims all liability for damages resulting from their use to the
|
14 |
+
fullest extent possible.
|
15 |
+
|
16 |
+
Using Creative Commons Public Licenses
|
17 |
+
|
18 |
+
Creative Commons public licenses provide a standard set of terms and
|
19 |
+
conditions that creators and other rights holders may use to share
|
20 |
+
original works of authorship and other material subject to copyright
|
21 |
+
and certain other rights specified in the public license below. The
|
22 |
+
following considerations are for informational purposes only, are not
|
23 |
+
exhaustive, and do not form part of our licenses.
|
24 |
+
|
25 |
+
Considerations for licensors: Our public licenses are
|
26 |
+
intended for use by those authorized to give the public
|
27 |
+
permission to use material in ways otherwise restricted by
|
28 |
+
copyright and certain other rights. Our licenses are
|
29 |
+
irrevocable. Licensors should read and understand the terms
|
30 |
+
and conditions of the license they choose before applying it.
|
31 |
+
Licensors should also secure all rights necessary before
|
32 |
+
applying our licenses so that the public can reuse the
|
33 |
+
material as expected. Licensors should clearly mark any
|
34 |
+
material not subject to the license. This includes other CC-
|
35 |
+
licensed material, or material used under an exception or
|
36 |
+
limitation to copyright. More considerations for licensors:
|
37 |
+
wiki.creativecommons.org/Considerations_for_licensors
|
38 |
+
|
39 |
+
Considerations for the public: By using one of our public
|
40 |
+
licenses, a licensor grants the public permission to use the
|
41 |
+
licensed material under specified terms and conditions. If
|
42 |
+
the licensor's permission is not necessary for any reason--for
|
43 |
+
example, because of any applicable exception or limitation to
|
44 |
+
copyright--then that use is not regulated by the license. Our
|
45 |
+
licenses grant only permissions under copyright and certain
|
46 |
+
other rights that a licensor has authority to grant. Use of
|
47 |
+
the licensed material may still be restricted for other
|
48 |
+
reasons, including because others have copyright or other
|
49 |
+
rights in the material. A licensor may make special requests,
|
50 |
+
such as asking that all changes be marked or described.
|
51 |
+
Although not required by our licenses, you are encouraged to
|
52 |
+
respect those requests where reasonable. More_considerations
|
53 |
+
for the public:
|
54 |
+
wiki.creativecommons.org/Considerations_for_licensees
|
55 |
+
|
56 |
+
=======================================================================
|
57 |
+
|
58 |
+
Creative Commons Attribution-NonCommercial 4.0 International Public
|
59 |
+
License
|
60 |
+
|
61 |
+
By exercising the Licensed Rights (defined below), You accept and agree
|
62 |
+
to be bound by the terms and conditions of this Creative Commons
|
63 |
+
Attribution-NonCommercial 4.0 International Public License ("Public
|
64 |
+
License"). To the extent this Public License may be interpreted as a
|
65 |
+
contract, You are granted the Licensed Rights in consideration of Your
|
66 |
+
acceptance of these terms and conditions, and the Licensor grants You
|
67 |
+
such rights in consideration of benefits the Licensor receives from
|
68 |
+
making the Licensed Material available under these terms and
|
69 |
+
conditions.
|
70 |
+
|
71 |
+
Section 1 -- Definitions.
|
72 |
+
|
73 |
+
a. Adapted Material means material subject to Copyright and Similar
|
74 |
+
Rights that is derived from or based upon the Licensed Material
|
75 |
+
and in which the Licensed Material is translated, altered,
|
76 |
+
arranged, transformed, or otherwise modified in a manner requiring
|
77 |
+
permission under the Copyright and Similar Rights held by the
|
78 |
+
Licensor. For purposes of this Public License, where the Licensed
|
79 |
+
Material is a musical work, performance, or sound recording,
|
80 |
+
Adapted Material is always produced where the Licensed Material is
|
81 |
+
synched in timed relation with a moving image.
|
82 |
+
|
83 |
+
b. Adapter's License means the license You apply to Your Copyright
|
84 |
+
and Similar Rights in Your contributions to Adapted Material in
|
85 |
+
accordance with the terms and conditions of this Public License.
|
86 |
+
|
87 |
+
c. Copyright and Similar Rights means copyright and/or similar rights
|
88 |
+
closely related to copyright including, without limitation,
|
89 |
+
performance, broadcast, sound recording, and Sui Generis Database
|
90 |
+
Rights, without regard to how the rights are labeled or
|
91 |
+
categorized. For purposes of this Public License, the rights
|
92 |
+
specified in Section 2(b)(1)-(2) are not Copyright and Similar
|
93 |
+
Rights.
|
94 |
+
d. Effective Technological Measures means those measures that, in the
|
95 |
+
absence of proper authority, may not be circumvented under laws
|
96 |
+
fulfilling obligations under Article 11 of the WIPO Copyright
|
97 |
+
Treaty adopted on December 20, 1996, and/or similar international
|
98 |
+
agreements.
|
99 |
+
|
100 |
+
e. Exceptions and Limitations means fair use, fair dealing, and/or
|
101 |
+
any other exception or limitation to Copyright and Similar Rights
|
102 |
+
that applies to Your use of the Licensed Material.
|
103 |
+
|
104 |
+
f. Licensed Material means the artistic or literary work, database,
|
105 |
+
or other material to which the Licensor applied this Public
|
106 |
+
License.
|
107 |
+
|
108 |
+
g. Licensed Rights means the rights granted to You subject to the
|
109 |
+
terms and conditions of this Public License, which are limited to
|
110 |
+
all Copyright and Similar Rights that apply to Your use of the
|
111 |
+
Licensed Material and that the Licensor has authority to license.
|
112 |
+
|
113 |
+
h. Licensor means the individual(s) or entity(ies) granting rights
|
114 |
+
under this Public License.
|
115 |
+
|
116 |
+
i. NonCommercial means not primarily intended for or directed towards
|
117 |
+
commercial advantage or monetary compensation. For purposes of
|
118 |
+
this Public License, the exchange of the Licensed Material for
|
119 |
+
other material subject to Copyright and Similar Rights by digital
|
120 |
+
file-sharing or similar means is NonCommercial provided there is
|
121 |
+
no payment of monetary compensation in connection with the
|
122 |
+
exchange.
|
123 |
+
|
124 |
+
j. Share means to provide material to the public by any means or
|
125 |
+
process that requires permission under the Licensed Rights, such
|
126 |
+
as reproduction, public display, public performance, distribution,
|
127 |
+
dissemination, communication, or importation, and to make material
|
128 |
+
available to the public including in ways that members of the
|
129 |
+
public may access the material from a place and at a time
|
130 |
+
individually chosen by them.
|
131 |
+
|
132 |
+
k. Sui Generis Database Rights means rights other than copyright
|
133 |
+
resulting from Directive 96/9/EC of the European Parliament and of
|
134 |
+
the Council of 11 March 1996 on the legal protection of databases,
|
135 |
+
as amended and/or succeeded, as well as other essentially
|
136 |
+
equivalent rights anywhere in the world.
|
137 |
+
|
138 |
+
l. You means the individual or entity exercising the Licensed Rights
|
139 |
+
under this Public License. Your has a corresponding meaning.
|
140 |
+
|
141 |
+
Section 2 -- Scope.
|
142 |
+
|
143 |
+
a. License grant.
|
144 |
+
|
145 |
+
1. Subject to the terms and conditions of this Public License,
|
146 |
+
the Licensor hereby grants You a worldwide, royalty-free,
|
147 |
+
non-sublicensable, non-exclusive, irrevocable license to
|
148 |
+
exercise the Licensed Rights in the Licensed Material to:
|
149 |
+
|
150 |
+
a. reproduce and Share the Licensed Material, in whole or
|
151 |
+
in part, for NonCommercial purposes only; and
|
152 |
+
|
153 |
+
b. produce, reproduce, and Share Adapted Material for
|
154 |
+
NonCommercial purposes only.
|
155 |
+
|
156 |
+
2. Exceptions and Limitations. For the avoidance of doubt, where
|
157 |
+
Exceptions and Limitations apply to Your use, this Public
|
158 |
+
License does not apply, and You do not need to comply with
|
159 |
+
its terms and conditions.
|
160 |
+
|
161 |
+
3. Term. The term of this Public License is specified in Section
|
162 |
+
6(a).
|
163 |
+
|
164 |
+
4. Media and formats; technical modifications allowed. The
|
165 |
+
Licensor authorizes You to exercise the Licensed Rights in
|
166 |
+
all media and formats whether now known or hereafter created,
|
167 |
+
and to make technical modifications necessary to do so. The
|
168 |
+
Licensor waives and/or agrees not to assert any right or
|
169 |
+
authority to forbid You from making technical modifications
|
170 |
+
necessary to exercise the Licensed Rights, including
|
171 |
+
technical modifications necessary to circumvent Effective
|
172 |
+
Technological Measures. For purposes of this Public License,
|
173 |
+
simply making modifications authorized by this Section 2(a)
|
174 |
+
(4) never produces Adapted Material.
|
175 |
+
|
176 |
+
5. Downstream recipients.
|
177 |
+
|
178 |
+
a. Offer from the Licensor -- Licensed Material. Every
|
179 |
+
recipient of the Licensed Material automatically
|
180 |
+
receives an offer from the Licensor to exercise the
|
181 |
+
Licensed Rights under the terms and conditions of this
|
182 |
+
Public License.
|
183 |
+
|
184 |
+
b. No downstream restrictions. You may not offer or impose
|
185 |
+
any additional or different terms or conditions on, or
|
186 |
+
apply any Effective Technological Measures to, the
|
187 |
+
Licensed Material if doing so restricts exercise of the
|
188 |
+
Licensed Rights by any recipient of the Licensed
|
189 |
+
Material.
|
190 |
+
|
191 |
+
6. No endorsement. Nothing in this Public License constitutes or
|
192 |
+
may be construed as permission to assert or imply that You
|
193 |
+
are, or that Your use of the Licensed Material is, connected
|
194 |
+
with, or sponsored, endorsed, or granted official status by,
|
195 |
+
the Licensor or others designated to receive attribution as
|
196 |
+
provided in Section 3(a)(1)(A)(i).
|
197 |
+
|
198 |
+
b. Other rights.
|
199 |
+
|
200 |
+
1. Moral rights, such as the right of integrity, are not
|
201 |
+
licensed under this Public License, nor are publicity,
|
202 |
+
privacy, and/or other similar personality rights; however, to
|
203 |
+
the extent possible, the Licensor waives and/or agrees not to
|
204 |
+
assert any such rights held by the Licensor to the limited
|
205 |
+
extent necessary to allow You to exercise the Licensed
|
206 |
+
Rights, but not otherwise.
|
207 |
+
|
208 |
+
2. Patent and trademark rights are not licensed under this
|
209 |
+
Public License.
|
210 |
+
|
211 |
+
3. To the extent possible, the Licensor waives any right to
|
212 |
+
collect royalties from You for the exercise of the Licensed
|
213 |
+
Rights, whether directly or through a collecting society
|
214 |
+
under any voluntary or waivable statutory or compulsory
|
215 |
+
licensing scheme. In all other cases the Licensor expressly
|
216 |
+
reserves any right to collect such royalties, including when
|
217 |
+
the Licensed Material is used other than for NonCommercial
|
218 |
+
purposes.
|
219 |
+
|
220 |
+
Section 3 -- License Conditions.
|
221 |
+
|
222 |
+
Your exercise of the Licensed Rights is expressly made subject to the
|
223 |
+
following conditions.
|
224 |
+
|
225 |
+
a. Attribution.
|
226 |
+
|
227 |
+
1. If You Share the Licensed Material (including in modified
|
228 |
+
form), You must:
|
229 |
+
|
230 |
+
a. retain the following if it is supplied by the Licensor
|
231 |
+
with the Licensed Material:
|
232 |
+
|
233 |
+
i. identification of the creator(s) of the Licensed
|
234 |
+
Material and any others designated to receive
|
235 |
+
attribution, in any reasonable manner requested by
|
236 |
+
the Licensor (including by pseudonym if
|
237 |
+
designated);
|
238 |
+
|
239 |
+
ii. a copyright notice;
|
240 |
+
|
241 |
+
iii. a notice that refers to this Public License;
|
242 |
+
|
243 |
+
iv. a notice that refers to the disclaimer of
|
244 |
+
warranties;
|
245 |
+
|
246 |
+
v. a URI or hyperlink to the Licensed Material to the
|
247 |
+
extent reasonably practicable;
|
248 |
+
|
249 |
+
b. indicate if You modified the Licensed Material and
|
250 |
+
retain an indication of any previous modifications; and
|
251 |
+
|
252 |
+
c. indicate the Licensed Material is licensed under this
|
253 |
+
Public License, and include the text of, or the URI or
|
254 |
+
hyperlink to, this Public License.
|
255 |
+
|
256 |
+
2. You may satisfy the conditions in Section 3(a)(1) in any
|
257 |
+
reasonable manner based on the medium, means, and context in
|
258 |
+
which You Share the Licensed Material. For example, it may be
|
259 |
+
reasonable to satisfy the conditions by providing a URI or
|
260 |
+
hyperlink to a resource that includes the required
|
261 |
+
information.
|
262 |
+
|
263 |
+
3. If requested by the Licensor, You must remove any of the
|
264 |
+
information required by Section 3(a)(1)(A) to the extent
|
265 |
+
reasonably practicable.
|
266 |
+
|
267 |
+
4. If You Share Adapted Material You produce, the Adapter's
|
268 |
+
License You apply must not prevent recipients of the Adapted
|
269 |
+
Material from complying with this Public License.
|
270 |
+
|
271 |
+
Section 4 -- Sui Generis Database Rights.
|
272 |
+
|
273 |
+
Where the Licensed Rights include Sui Generis Database Rights that
|
274 |
+
apply to Your use of the Licensed Material:
|
275 |
+
|
276 |
+
a. for the avoidance of doubt, Section 2(a)(1) grants You the right
|
277 |
+
to extract, reuse, reproduce, and Share all or a substantial
|
278 |
+
portion of the contents of the database for NonCommercial purposes
|
279 |
+
only;
|
280 |
+
|
281 |
+
b. if You include all or a substantial portion of the database
|
282 |
+
contents in a database in which You have Sui Generis Database
|
283 |
+
Rights, then the database in which You have Sui Generis Database
|
284 |
+
Rights (but not its individual contents) is Adapted Material; and
|
285 |
+
|
286 |
+
c. You must comply with the conditions in Section 3(a) if You Share
|
287 |
+
all or a substantial portion of the contents of the database.
|
288 |
+
|
289 |
+
For the avoidance of doubt, this Section 4 supplements and does not
|
290 |
+
replace Your obligations under this Public License where the Licensed
|
291 |
+
Rights include other Copyright and Similar Rights.
|
292 |
+
|
293 |
+
Section 5 -- Disclaimer of Warranties and Limitation of Liability.
|
294 |
+
|
295 |
+
a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE
|
296 |
+
EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS
|
297 |
+
AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF
|
298 |
+
ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS,
|
299 |
+
IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION,
|
300 |
+
WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR
|
301 |
+
PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS,
|
302 |
+
ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT
|
303 |
+
KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT
|
304 |
+
ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU.
|
305 |
+
|
306 |
+
b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE
|
307 |
+
TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION,
|
308 |
+
NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT,
|
309 |
+
INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES,
|
310 |
+
COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR
|
311 |
+
USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN
|
312 |
+
ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR
|
313 |
+
DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR
|
314 |
+
IN PART, THIS LIMITATION MAY NOT APPLY TO YOU.
|
315 |
+
|
316 |
+
c. The disclaimer of warranties and limitation of liability provided
|
317 |
+
above shall be interpreted in a manner that, to the extent
|
318 |
+
possible, most closely approximates an absolute disclaimer and
|
319 |
+
waiver of all liability.
|
320 |
+
|
321 |
+
Section 6 -- Term and Termination.
|
322 |
+
|
323 |
+
a. This Public License applies for the term of the Copyright and
|
324 |
+
Similar Rights licensed here. However, if You fail to comply with
|
325 |
+
this Public License, then Your rights under this Public License
|
326 |
+
terminate automatically.
|
327 |
+
|
328 |
+
b. Where Your right to use the Licensed Material has terminated under
|
329 |
+
Section 6(a), it reinstates:
|
330 |
+
|
331 |
+
1. automatically as of the date the violation is cured, provided
|
332 |
+
it is cured within 30 days of Your discovery of the
|
333 |
+
violation; or
|
334 |
+
|
335 |
+
2. upon express reinstatement by the Licensor.
|
336 |
+
|
337 |
+
For the avoidance of doubt, this Section 6(b) does not affect any
|
338 |
+
right the Licensor may have to seek remedies for Your violations
|
339 |
+
of this Public License.
|
340 |
+
|
341 |
+
c. For the avoidance of doubt, the Licensor may also offer the
|
342 |
+
Licensed Material under separate terms or conditions or stop
|
343 |
+
distributing the Licensed Material at any time; however, doing so
|
344 |
+
will not terminate this Public License.
|
345 |
+
|
346 |
+
d. Sections 1, 5, 6, 7, and 8 survive termination of this Public
|
347 |
+
License.
|
348 |
+
|
349 |
+
Section 7 -- Other Terms and Conditions.
|
350 |
+
|
351 |
+
a. The Licensor shall not be bound by any additional or different
|
352 |
+
terms or conditions communicated by You unless expressly agreed.
|
353 |
+
|
354 |
+
b. Any arrangements, understandings, or agreements regarding the
|
355 |
+
Licensed Material not stated herein are separate from and
|
356 |
+
independent of the terms and conditions of this Public License.
|
357 |
+
|
358 |
+
Section 8 -- Interpretation.
|
359 |
+
|
360 |
+
a. For the avoidance of doubt, this Public License does not, and
|
361 |
+
shall not be interpreted to, reduce, limit, restrict, or impose
|
362 |
+
conditions on any use of the Licensed Material that could lawfully
|
363 |
+
be made without permission under this Public License.
|
364 |
+
|
365 |
+
b. To the extent possible, if any provision of this Public License is
|
366 |
+
deemed unenforceable, it shall be automatically reformed to the
|
367 |
+
minimum extent necessary to make it enforceable. If the provision
|
368 |
+
cannot be reformed, it shall be severed from this Public License
|
369 |
+
without affecting the enforceability of the remaining terms and
|
370 |
+
conditions.
|
371 |
+
|
372 |
+
c. No term or condition of this Public License will be waived and no
|
373 |
+
failure to comply consented to unless expressly agreed to by the
|
374 |
+
Licensor.
|
375 |
+
|
376 |
+
d. Nothing in this Public License constitutes or may be interpreted
|
377 |
+
as a limitation upon, or waiver of, any privileges and immunities
|
378 |
+
that apply to the Licensor or You, including from the legal
|
379 |
+
processes of any jurisdiction or authority.
|
380 |
+
|
381 |
+
=======================================================================
|
382 |
+
|
383 |
+
Creative Commons is not a party to its public
|
384 |
+
licenses. Notwithstanding, Creative Commons may elect to apply one of
|
385 |
+
its public licenses to material it publishes and in those instances
|
386 |
+
will be considered the “Licensor.” The text of the Creative Commons
|
387 |
+
public licenses is dedicated to the public domain under the CC0 Public
|
388 |
+
Domain Dedication. Except for the limited purpose of indicating that
|
389 |
+
material is shared under a Creative Commons public license or as
|
390 |
+
otherwise permitted by the Creative Commons policies published at
|
391 |
+
creativecommons.org/policies, Creative Commons does not authorize the
|
392 |
+
use of the trademark "Creative Commons" or any other trademark or logo
|
393 |
+
of Creative Commons without its prior written consent including,
|
394 |
+
without limitation, in connection with any unauthorized modifications
|
395 |
+
to any of its public licenses or any other arrangements,
|
396 |
+
understandings, or agreements concerning use of licensed material. For
|
397 |
+
the avoidance of doubt, this paragraph does not form part of the
|
398 |
+
public licenses.
|
399 |
+
|
400 |
+
Creative Commons may be contacted at creativecommons.org.
|
README.md
CHANGED
@@ -1,12 +1,13 @@
|
|
1 |
---
|
2 |
-
title: MDT
|
3 |
-
emoji:
|
4 |
-
colorFrom:
|
5 |
-
colorTo:
|
6 |
sdk: gradio
|
7 |
-
sdk_version: 3.
|
8 |
app_file: app.py
|
9 |
pinned: false
|
|
|
10 |
---
|
11 |
|
12 |
-
|
|
|
1 |
---
|
2 |
+
title: Masked Diffusion Transformers (MDT)
|
3 |
+
emoji: 🌗
|
4 |
+
colorFrom: yellow
|
5 |
+
colorTo: green
|
6 |
sdk: gradio
|
7 |
+
sdk_version: 3.6
|
8 |
app_file: app.py
|
9 |
pinned: false
|
10 |
+
license: cc-by-nc-4.0
|
11 |
---
|
12 |
|
13 |
+
The code is based on the [DiT DEMO](https://huggingface.co/spaces/wpeebles/DiT), thanks!
|
app.py
ADDED
@@ -0,0 +1,191 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
from torchvision.utils import make_grid
|
3 |
+
import math
|
4 |
+
from PIL import Image
|
5 |
+
from diffusion import create_diffusion
|
6 |
+
from diffusers.models import AutoencoderKL
|
7 |
+
import gradio as gr
|
8 |
+
from imagenet_class_data import IMAGENET_1K_CLASSES
|
9 |
+
from models import MDT_XL_2
|
10 |
+
import os
|
11 |
+
from huggingface_hub import snapshot_download
|
12 |
+
|
13 |
+
|
14 |
+
def load_model(image_size=256):
|
15 |
+
assert image_size in [256]
|
16 |
+
latent_size = image_size // 8
|
17 |
+
model = MDT_XL_2(input_size=latent_size, decode_layer=2).to(device)
|
18 |
+
|
19 |
+
models_path = snapshot_download("shgao/MDT-XL2")
|
20 |
+
ckpt_model_path = os.path.join(models_path, "mdt_xl2_v1_ckpt.pt")
|
21 |
+
state_dict = torch.load(
|
22 |
+
ckpt_model_path, map_location=lambda storage, loc: storage)
|
23 |
+
model.load_state_dict(state_dict)
|
24 |
+
model.eval()
|
25 |
+
return model
|
26 |
+
|
27 |
+
|
28 |
+
torch.set_grad_enabled(False)
|
29 |
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
30 |
+
model = load_model(image_size=256)
|
31 |
+
vae = AutoencoderKL.from_pretrained("stabilityai/sd-vae-ft-mse").to(device)
|
32 |
+
current_image_size = 256
|
33 |
+
current_vae_model = "stabilityai/sd-vae-ft-mse"
|
34 |
+
|
35 |
+
|
36 |
+
def generate(image_size, vae_model, class_label, cfg_scale, pow_scale, num_sampling_steps, seed):
|
37 |
+
n = 1
|
38 |
+
image_size = int(image_size.split("x")[0])
|
39 |
+
global current_image_size
|
40 |
+
if image_size != current_image_size:
|
41 |
+
global model
|
42 |
+
model = model.to("cpu")
|
43 |
+
del model
|
44 |
+
if device == "cuda":
|
45 |
+
torch.cuda.empty_cache()
|
46 |
+
model = load_model(image_size=image_size)
|
47 |
+
current_image_size = image_size
|
48 |
+
|
49 |
+
global current_vae_model
|
50 |
+
if vae_model != current_vae_model:
|
51 |
+
global vae
|
52 |
+
if device == "cuda":
|
53 |
+
vae.to("cpu")
|
54 |
+
del vae
|
55 |
+
vae = AutoencoderKL.from_pretrained(vae_model).to(device)
|
56 |
+
|
57 |
+
# Seed PyTorch:
|
58 |
+
torch.manual_seed(seed)
|
59 |
+
|
60 |
+
# Setup diffusion
|
61 |
+
diffusion = create_diffusion(str(num_sampling_steps))
|
62 |
+
|
63 |
+
# Create sampling noise:
|
64 |
+
latent_size = image_size // 8
|
65 |
+
z = torch.randn(n, 4, latent_size, latent_size, device=device)
|
66 |
+
y = torch.tensor([class_label] * n, device=device)
|
67 |
+
|
68 |
+
# Setup classifier-free guidance:
|
69 |
+
z = torch.cat([z, z], 0)
|
70 |
+
y_null = torch.tensor([1000] * n, device=device)
|
71 |
+
y = torch.cat([y, y_null], 0)
|
72 |
+
model_kwargs = dict(y=y, cfg_scale=cfg_scale, scale_pow=pow_scale)
|
73 |
+
|
74 |
+
# Sample images:
|
75 |
+
samples = diffusion.p_sample_loop(
|
76 |
+
model.forward_with_cfg, z.shape, z, clip_denoised=False, model_kwargs=model_kwargs, progress=True, device=device
|
77 |
+
)
|
78 |
+
samples, _ = samples.chunk(2, dim=0) # Remove null class samples
|
79 |
+
samples = vae.decode(samples / 0.18215).sample
|
80 |
+
|
81 |
+
# Convert to PIL.Image format:
|
82 |
+
samples = samples.mul(127.5).add_(128.0).clamp_(
|
83 |
+
0, 255).permute(0, 2, 3, 1).to("cpu", torch.uint8).numpy()
|
84 |
+
samples = [Image.fromarray(sample) for sample in samples]
|
85 |
+
return samples
|
86 |
+
|
87 |
+
|
88 |
+
description = '''This is a demo of our MDT image generation models. MDT is a class-conditional model trained on ImageNet-1K.'''
|
89 |
+
duplicate = '''Skip the queue by duplicating this space and upgrading to GPU in settings
|
90 |
+
<a href="https://huggingface.co/spaces/wpeebles/DiT?duplicate=true"><img src="https://bit.ly/3gLdBN6" alt="Duplicate Space"></a>'''
|
91 |
+
|
92 |
+
more_info = '''
|
93 |
+
# Masked Diffusion Transformer
|
94 |
+
|
95 |
+
[](https://paperswithcode.com/sota/image-generation-on-imagenet-256x256?p=masked-diffusion-transformer-is-a-strong)
|
96 |
+
|
97 |
+
The official codebase for [Masked Diffusion Transformer is a Strong Image Synthesizer](https://arxiv.org/abs/2303.14389).
|
98 |
+
|
99 |
+
## Introduction
|
100 |
+
|
101 |
+
Despite its success in image synthesis, we observe that diffusion probabilistic models (DPMs) often lack contextual reasoning ability to learn the relations among object parts in an image, leading to a slow learning process.
|
102 |
+
|
103 |
+
To solve this issue, we propose a Masked Diffusion Transformer (MDT) that introduces a mask latent modeling scheme to explicitly enhance the DPMs’ ability of contextual relation learning among object semantic parts in an image. During training, MDT operates on the latent space to mask certain tokens. Then, an asymmetric masking diffusion transformer is designed to predict masked tokens from unmasked ones while maintaining the diffusion generation process. Our MDT can reconstruct the full information of an image from its incomplete contextual input, thus enabling it to learn the associated relations among image tokens.
|
104 |
+
|
105 |
+
Experimental results show that MDT achieves superior image synthesis performance, e.g. a new SoTA FID score on the ImageNet dataset, and has about 3× faster learning speed than the previous SoTA DiT.
|
106 |
+
|
107 |
+
|
108 |
+
|
109 |
+
## Citation
|
110 |
+
|
111 |
+
```
|
112 |
+
@misc{gao2023masked,
|
113 |
+
title={Masked Diffusion Transformer is a Strong Image Synthesizer},
|
114 |
+
author={Shanghua Gao and Pan Zhou and Ming-Ming Cheng and Shuicheng Yan},
|
115 |
+
year={2023},
|
116 |
+
eprint={2303.14389},
|
117 |
+
archivePrefix={arXiv},
|
118 |
+
primaryClass={cs.CV}
|
119 |
+
}
|
120 |
+
```
|
121 |
+
|
122 |
+
## Acknowledgement
|
123 |
+
|
124 |
+
This demo is built based on the [DiT](https://github.com/facebookresearch/dit). Thanks!
|
125 |
+
|
126 |
+
'''
|
127 |
+
|
128 |
+
project_links = '''
|
129 |
+
<p style="text-align: center">
|
130 |
+
<a href="https://arxiv.org/abs/2303.14389">Paper</a> ·
|
131 |
+
<a href="https://github.com/sail-sg/MDT">GitHub</a></p>'''
|
132 |
+
|
133 |
+
examples = [
|
134 |
+
["256x256", "stabilityai/sd-vae-ft-mse",
|
135 |
+
"Welsh springer spaniel", 5.0, 0.01, 300, 30, 3000],
|
136 |
+
["256x256", "stabilityai/sd-vae-ft-mse",
|
137 |
+
"golden retriever", 5.0, 0.01, 300, 30, 3000],
|
138 |
+
["256x256", "stabilityai/sd-vae-ft-mse",
|
139 |
+
"sulphur-crested cockatoo, Kakatoe galerita, Cacatua galerita", 5.0, 0.01, 300, 30, 1],
|
140 |
+
["256x256", "stabilityai/sd-vae-ft-mse",
|
141 |
+
"cheeseburger", 5.0, 0.01, 300, 30, 2],
|
142 |
+
["256x256", "stabilityai/sd-vae-ft-mse", "macaw", 5.0, 0.01, 300, 30, 1],
|
143 |
+
]
|
144 |
+
|
145 |
+
with gr.Blocks() as demo:
|
146 |
+
gr.Markdown(
|
147 |
+
"<h1 style='text-align: center'>Masked Diffusion Transformer (MDT)</h1>")
|
148 |
+
gr.Markdown(project_links)
|
149 |
+
gr.Markdown(description)
|
150 |
+
gr.Markdown(duplicate)
|
151 |
+
|
152 |
+
with gr.Tabs():
|
153 |
+
with gr.TabItem('Generate'):
|
154 |
+
with gr.Row():
|
155 |
+
with gr.Column():
|
156 |
+
with gr.Row():
|
157 |
+
image_size = gr.inputs.Radio(
|
158 |
+
choices=["256x256"], default="256x256", label='DiT Model Resolution')
|
159 |
+
vae_model = gr.inputs.Radio(choices=["stabilityai/sd-vae-ft-mse", "stabilityai/sd-vae-ft-ema"],
|
160 |
+
default="stabilityai/sd-vae-ft-mse", label='VAE Decoder')
|
161 |
+
with gr.Row():
|
162 |
+
i1k_class = gr.inputs.Dropdown(
|
163 |
+
list(IMAGENET_1K_CLASSES.values()),
|
164 |
+
default='Welsh springer spaniel',
|
165 |
+
type="index", label='ImageNet-1K Class'
|
166 |
+
)
|
167 |
+
cfg_scale = gr.inputs.Slider(
|
168 |
+
minimum=0, maximum=25, step=0.1, default=5.0, label='Classifier-free Guidance Scale')
|
169 |
+
pow_scale = gr.inputs.Slider(
|
170 |
+
minimum=0, maximum=25, step=0.1, default=0.01, label='Classifier-free Guidance Weight Scaling')
|
171 |
+
steps = gr.inputs.Slider(
|
172 |
+
minimum=4, maximum=1000, step=1, default=300, label='Sampling Steps')
|
173 |
+
n = gr.inputs.Slider(
|
174 |
+
minimum=1, maximum=16, step=1, default=1, label='Number of Samples')
|
175 |
+
seed = gr.inputs.Number(default=30, label='Seed')
|
176 |
+
button = gr.Button("Generate", variant="primary")
|
177 |
+
with gr.Column():
|
178 |
+
output = gr.Gallery(label='Generated Images').style(
|
179 |
+
grid=[2], height="auto")
|
180 |
+
button.click(generate, inputs=[
|
181 |
+
image_size, vae_model, i1k_class, cfg_scale, pow_scale, steps, seed], outputs=[output])
|
182 |
+
with gr.Row():
|
183 |
+
ex = gr.Examples(examples=examples, fn=generate,
|
184 |
+
inputs=[image_size, vae_model, i1k_class,
|
185 |
+
cfg_scale, pow_scale, steps, seed],
|
186 |
+
outputs=[output],
|
187 |
+
cache_examples=True)
|
188 |
+
gr.Markdown(more_info)
|
189 |
+
|
190 |
+
demo.queue()
|
191 |
+
demo.launch()
|
diffusion/__init__.py
ADDED
@@ -0,0 +1,46 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Modified from OpenAI's diffusion repos
|
2 |
+
# GLIDE: https://github.com/openai/glide-text2im/blob/main/glide_text2im/gaussian_diffusion.py
|
3 |
+
# ADM: https://github.com/openai/guided-diffusion/blob/main/guided_diffusion
|
4 |
+
# IDDPM: https://github.com/openai/improved-diffusion/blob/main/improved_diffusion/gaussian_diffusion.py
|
5 |
+
|
6 |
+
from . import gaussian_diffusion as gd
|
7 |
+
from .respace import SpacedDiffusion, space_timesteps
|
8 |
+
|
9 |
+
|
10 |
+
def create_diffusion(
|
11 |
+
timestep_respacing,
|
12 |
+
noise_schedule="linear",
|
13 |
+
use_kl=False,
|
14 |
+
sigma_small=False,
|
15 |
+
predict_xstart=False,
|
16 |
+
learn_sigma=True,
|
17 |
+
rescale_learned_sigmas=False,
|
18 |
+
diffusion_steps=1000
|
19 |
+
):
|
20 |
+
betas = gd.get_named_beta_schedule(noise_schedule, diffusion_steps)
|
21 |
+
if use_kl:
|
22 |
+
loss_type = gd.LossType.RESCALED_KL
|
23 |
+
elif rescale_learned_sigmas:
|
24 |
+
loss_type = gd.LossType.RESCALED_MSE
|
25 |
+
else:
|
26 |
+
loss_type = gd.LossType.MSE
|
27 |
+
if timestep_respacing is None or timestep_respacing == "":
|
28 |
+
timestep_respacing = [diffusion_steps]
|
29 |
+
return SpacedDiffusion(
|
30 |
+
use_timesteps=space_timesteps(diffusion_steps, timestep_respacing),
|
31 |
+
betas=betas,
|
32 |
+
model_mean_type=(
|
33 |
+
gd.ModelMeanType.EPSILON if not predict_xstart else gd.ModelMeanType.START_X
|
34 |
+
),
|
35 |
+
model_var_type=(
|
36 |
+
(
|
37 |
+
gd.ModelVarType.FIXED_LARGE
|
38 |
+
if not sigma_small
|
39 |
+
else gd.ModelVarType.FIXED_SMALL
|
40 |
+
)
|
41 |
+
if not learn_sigma
|
42 |
+
else gd.ModelVarType.LEARNED_RANGE
|
43 |
+
),
|
44 |
+
loss_type=loss_type
|
45 |
+
# rescale_timesteps=rescale_timesteps,
|
46 |
+
)
|
diffusion/diffusion_utils.py
ADDED
@@ -0,0 +1,88 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Modified from OpenAI's diffusion repos
|
2 |
+
# GLIDE: https://github.com/openai/glide-text2im/blob/main/glide_text2im/gaussian_diffusion.py
|
3 |
+
# ADM: https://github.com/openai/guided-diffusion/blob/main/guided_diffusion
|
4 |
+
# IDDPM: https://github.com/openai/improved-diffusion/blob/main/improved_diffusion/gaussian_diffusion.py
|
5 |
+
|
6 |
+
import torch as th
|
7 |
+
import numpy as np
|
8 |
+
|
9 |
+
|
10 |
+
def normal_kl(mean1, logvar1, mean2, logvar2):
|
11 |
+
"""
|
12 |
+
Compute the KL divergence between two gaussians.
|
13 |
+
Shapes are automatically broadcasted, so batches can be compared to
|
14 |
+
scalars, among other use cases.
|
15 |
+
"""
|
16 |
+
tensor = None
|
17 |
+
for obj in (mean1, logvar1, mean2, logvar2):
|
18 |
+
if isinstance(obj, th.Tensor):
|
19 |
+
tensor = obj
|
20 |
+
break
|
21 |
+
assert tensor is not None, "at least one argument must be a Tensor"
|
22 |
+
|
23 |
+
# Force variances to be Tensors. Broadcasting helps convert scalars to
|
24 |
+
# Tensors, but it does not work for th.exp().
|
25 |
+
logvar1, logvar2 = [
|
26 |
+
x if isinstance(x, th.Tensor) else th.tensor(x).to(tensor)
|
27 |
+
for x in (logvar1, logvar2)
|
28 |
+
]
|
29 |
+
|
30 |
+
return 0.5 * (
|
31 |
+
-1.0
|
32 |
+
+ logvar2
|
33 |
+
- logvar1
|
34 |
+
+ th.exp(logvar1 - logvar2)
|
35 |
+
+ ((mean1 - mean2) ** 2) * th.exp(-logvar2)
|
36 |
+
)
|
37 |
+
|
38 |
+
|
39 |
+
def approx_standard_normal_cdf(x):
|
40 |
+
"""
|
41 |
+
A fast approximation of the cumulative distribution function of the
|
42 |
+
standard normal.
|
43 |
+
"""
|
44 |
+
return 0.5 * (1.0 + th.tanh(np.sqrt(2.0 / np.pi) * (x + 0.044715 * th.pow(x, 3))))
|
45 |
+
|
46 |
+
|
47 |
+
def continuous_gaussian_log_likelihood(x, *, means, log_scales):
|
48 |
+
"""
|
49 |
+
Compute the log-likelihood of a continuous Gaussian distribution.
|
50 |
+
:param x: the targets
|
51 |
+
:param means: the Gaussian mean Tensor.
|
52 |
+
:param log_scales: the Gaussian log stddev Tensor.
|
53 |
+
:return: a tensor like x of log probabilities (in nats).
|
54 |
+
"""
|
55 |
+
centered_x = x - means
|
56 |
+
inv_stdv = th.exp(-log_scales)
|
57 |
+
normalized_x = centered_x * inv_stdv
|
58 |
+
log_probs = th.distributions.Normal(th.zeros_like(x), th.ones_like(x)).log_prob(normalized_x)
|
59 |
+
return log_probs
|
60 |
+
|
61 |
+
|
62 |
+
def discretized_gaussian_log_likelihood(x, *, means, log_scales):
|
63 |
+
"""
|
64 |
+
Compute the log-likelihood of a Gaussian distribution discretizing to a
|
65 |
+
given image.
|
66 |
+
:param x: the target images. It is assumed that this was uint8 values,
|
67 |
+
rescaled to the range [-1, 1].
|
68 |
+
:param means: the Gaussian mean Tensor.
|
69 |
+
:param log_scales: the Gaussian log stddev Tensor.
|
70 |
+
:return: a tensor like x of log probabilities (in nats).
|
71 |
+
"""
|
72 |
+
assert x.shape == means.shape == log_scales.shape
|
73 |
+
centered_x = x - means
|
74 |
+
inv_stdv = th.exp(-log_scales)
|
75 |
+
plus_in = inv_stdv * (centered_x + 1.0 / 255.0)
|
76 |
+
cdf_plus = approx_standard_normal_cdf(plus_in)
|
77 |
+
min_in = inv_stdv * (centered_x - 1.0 / 255.0)
|
78 |
+
cdf_min = approx_standard_normal_cdf(min_in)
|
79 |
+
log_cdf_plus = th.log(cdf_plus.clamp(min=1e-12))
|
80 |
+
log_one_minus_cdf_min = th.log((1.0 - cdf_min).clamp(min=1e-12))
|
81 |
+
cdf_delta = cdf_plus - cdf_min
|
82 |
+
log_probs = th.where(
|
83 |
+
x < -0.999,
|
84 |
+
log_cdf_plus,
|
85 |
+
th.where(x > 0.999, log_one_minus_cdf_min, th.log(cdf_delta.clamp(min=1e-12))),
|
86 |
+
)
|
87 |
+
assert log_probs.shape == x.shape
|
88 |
+
return log_probs
|
diffusion/gaussian_diffusion.py
ADDED
@@ -0,0 +1,873 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Modified from OpenAI's diffusion repos
|
2 |
+
# GLIDE: https://github.com/openai/glide-text2im/blob/main/glide_text2im/gaussian_diffusion.py
|
3 |
+
# ADM: https://github.com/openai/guided-diffusion/blob/main/guided_diffusion
|
4 |
+
# IDDPM: https://github.com/openai/improved-diffusion/blob/main/improved_diffusion/gaussian_diffusion.py
|
5 |
+
|
6 |
+
|
7 |
+
import math
|
8 |
+
|
9 |
+
import numpy as np
|
10 |
+
import torch as th
|
11 |
+
import enum
|
12 |
+
|
13 |
+
from .diffusion_utils import discretized_gaussian_log_likelihood, normal_kl
|
14 |
+
|
15 |
+
|
16 |
+
def mean_flat(tensor):
|
17 |
+
"""
|
18 |
+
Take the mean over all non-batch dimensions.
|
19 |
+
"""
|
20 |
+
return tensor.mean(dim=list(range(1, len(tensor.shape))))
|
21 |
+
|
22 |
+
|
23 |
+
class ModelMeanType(enum.Enum):
|
24 |
+
"""
|
25 |
+
Which type of output the model predicts.
|
26 |
+
"""
|
27 |
+
|
28 |
+
PREVIOUS_X = enum.auto() # the model predicts x_{t-1}
|
29 |
+
START_X = enum.auto() # the model predicts x_0
|
30 |
+
EPSILON = enum.auto() # the model predicts epsilon
|
31 |
+
|
32 |
+
|
33 |
+
class ModelVarType(enum.Enum):
|
34 |
+
"""
|
35 |
+
What is used as the model's output variance.
|
36 |
+
The LEARNED_RANGE option has been added to allow the model to predict
|
37 |
+
values between FIXED_SMALL and FIXED_LARGE, making its job easier.
|
38 |
+
"""
|
39 |
+
|
40 |
+
LEARNED = enum.auto()
|
41 |
+
FIXED_SMALL = enum.auto()
|
42 |
+
FIXED_LARGE = enum.auto()
|
43 |
+
LEARNED_RANGE = enum.auto()
|
44 |
+
|
45 |
+
|
46 |
+
class LossType(enum.Enum):
|
47 |
+
MSE = enum.auto() # use raw MSE loss (and KL when learning variances)
|
48 |
+
RESCALED_MSE = (
|
49 |
+
enum.auto()
|
50 |
+
) # use raw MSE loss (with RESCALED_KL when learning variances)
|
51 |
+
KL = enum.auto() # use the variational lower-bound
|
52 |
+
RESCALED_KL = enum.auto() # like KL, but rescale to estimate the full VLB
|
53 |
+
|
54 |
+
def is_vb(self):
|
55 |
+
return self == LossType.KL or self == LossType.RESCALED_KL
|
56 |
+
|
57 |
+
|
58 |
+
def _warmup_beta(beta_start, beta_end, num_diffusion_timesteps, warmup_frac):
|
59 |
+
betas = beta_end * np.ones(num_diffusion_timesteps, dtype=np.float64)
|
60 |
+
warmup_time = int(num_diffusion_timesteps * warmup_frac)
|
61 |
+
betas[:warmup_time] = np.linspace(beta_start, beta_end, warmup_time, dtype=np.float64)
|
62 |
+
return betas
|
63 |
+
|
64 |
+
|
65 |
+
def get_beta_schedule(beta_schedule, *, beta_start, beta_end, num_diffusion_timesteps):
|
66 |
+
"""
|
67 |
+
This is the deprecated API for creating beta schedules.
|
68 |
+
See get_named_beta_schedule() for the new library of schedules.
|
69 |
+
"""
|
70 |
+
if beta_schedule == "quad":
|
71 |
+
betas = (
|
72 |
+
np.linspace(
|
73 |
+
beta_start ** 0.5,
|
74 |
+
beta_end ** 0.5,
|
75 |
+
num_diffusion_timesteps,
|
76 |
+
dtype=np.float64,
|
77 |
+
)
|
78 |
+
** 2
|
79 |
+
)
|
80 |
+
elif beta_schedule == "linear":
|
81 |
+
betas = np.linspace(beta_start, beta_end, num_diffusion_timesteps, dtype=np.float64)
|
82 |
+
elif beta_schedule == "warmup10":
|
83 |
+
betas = _warmup_beta(beta_start, beta_end, num_diffusion_timesteps, 0.1)
|
84 |
+
elif beta_schedule == "warmup50":
|
85 |
+
betas = _warmup_beta(beta_start, beta_end, num_diffusion_timesteps, 0.5)
|
86 |
+
elif beta_schedule == "const":
|
87 |
+
betas = beta_end * np.ones(num_diffusion_timesteps, dtype=np.float64)
|
88 |
+
elif beta_schedule == "jsd": # 1/T, 1/(T-1), 1/(T-2), ..., 1
|
89 |
+
betas = 1.0 / np.linspace(
|
90 |
+
num_diffusion_timesteps, 1, num_diffusion_timesteps, dtype=np.float64
|
91 |
+
)
|
92 |
+
else:
|
93 |
+
raise NotImplementedError(beta_schedule)
|
94 |
+
assert betas.shape == (num_diffusion_timesteps,)
|
95 |
+
return betas
|
96 |
+
|
97 |
+
|
98 |
+
def get_named_beta_schedule(schedule_name, num_diffusion_timesteps):
|
99 |
+
"""
|
100 |
+
Get a pre-defined beta schedule for the given name.
|
101 |
+
The beta schedule library consists of beta schedules which remain similar
|
102 |
+
in the limit of num_diffusion_timesteps.
|
103 |
+
Beta schedules may be added, but should not be removed or changed once
|
104 |
+
they are committed to maintain backwards compatibility.
|
105 |
+
"""
|
106 |
+
if schedule_name == "linear":
|
107 |
+
# Linear schedule from Ho et al, extended to work for any number of
|
108 |
+
# diffusion steps.
|
109 |
+
scale = 1000 / num_diffusion_timesteps
|
110 |
+
return get_beta_schedule(
|
111 |
+
"linear",
|
112 |
+
beta_start=scale * 0.0001,
|
113 |
+
beta_end=scale * 0.02,
|
114 |
+
num_diffusion_timesteps=num_diffusion_timesteps,
|
115 |
+
)
|
116 |
+
elif schedule_name == "squaredcos_cap_v2":
|
117 |
+
return betas_for_alpha_bar(
|
118 |
+
num_diffusion_timesteps,
|
119 |
+
lambda t: math.cos((t + 0.008) / 1.008 * math.pi / 2) ** 2,
|
120 |
+
)
|
121 |
+
else:
|
122 |
+
raise NotImplementedError(f"unknown beta schedule: {schedule_name}")
|
123 |
+
|
124 |
+
|
125 |
+
def betas_for_alpha_bar(num_diffusion_timesteps, alpha_bar, max_beta=0.999):
|
126 |
+
"""
|
127 |
+
Create a beta schedule that discretizes the given alpha_t_bar function,
|
128 |
+
which defines the cumulative product of (1-beta) over time from t = [0,1].
|
129 |
+
:param num_diffusion_timesteps: the number of betas to produce.
|
130 |
+
:param alpha_bar: a lambda that takes an argument t from 0 to 1 and
|
131 |
+
produces the cumulative product of (1-beta) up to that
|
132 |
+
part of the diffusion process.
|
133 |
+
:param max_beta: the maximum beta to use; use values lower than 1 to
|
134 |
+
prevent singularities.
|
135 |
+
"""
|
136 |
+
betas = []
|
137 |
+
for i in range(num_diffusion_timesteps):
|
138 |
+
t1 = i / num_diffusion_timesteps
|
139 |
+
t2 = (i + 1) / num_diffusion_timesteps
|
140 |
+
betas.append(min(1 - alpha_bar(t2) / alpha_bar(t1), max_beta))
|
141 |
+
return np.array(betas)
|
142 |
+
|
143 |
+
|
144 |
+
class GaussianDiffusion:
|
145 |
+
"""
|
146 |
+
Utilities for training and sampling diffusion models.
|
147 |
+
Original ported from this codebase:
|
148 |
+
https://github.com/hojonathanho/diffusion/blob/1e0dceb3b3495bbe19116a5e1b3596cd0706c543/diffusion_tf/diffusion_utils_2.py#L42
|
149 |
+
:param betas: a 1-D numpy array of betas for each diffusion timestep,
|
150 |
+
starting at T and going to 1.
|
151 |
+
"""
|
152 |
+
|
153 |
+
def __init__(
|
154 |
+
self,
|
155 |
+
*,
|
156 |
+
betas,
|
157 |
+
model_mean_type,
|
158 |
+
model_var_type,
|
159 |
+
loss_type
|
160 |
+
):
|
161 |
+
|
162 |
+
self.model_mean_type = model_mean_type
|
163 |
+
self.model_var_type = model_var_type
|
164 |
+
self.loss_type = loss_type
|
165 |
+
|
166 |
+
# Use float64 for accuracy.
|
167 |
+
betas = np.array(betas, dtype=np.float64)
|
168 |
+
self.betas = betas
|
169 |
+
assert len(betas.shape) == 1, "betas must be 1-D"
|
170 |
+
assert (betas > 0).all() and (betas <= 1).all()
|
171 |
+
|
172 |
+
self.num_timesteps = int(betas.shape[0])
|
173 |
+
|
174 |
+
alphas = 1.0 - betas
|
175 |
+
self.alphas_cumprod = np.cumprod(alphas, axis=0)
|
176 |
+
self.alphas_cumprod_prev = np.append(1.0, self.alphas_cumprod[:-1])
|
177 |
+
self.alphas_cumprod_next = np.append(self.alphas_cumprod[1:], 0.0)
|
178 |
+
assert self.alphas_cumprod_prev.shape == (self.num_timesteps,)
|
179 |
+
|
180 |
+
# calculations for diffusion q(x_t | x_{t-1}) and others
|
181 |
+
self.sqrt_alphas_cumprod = np.sqrt(self.alphas_cumprod)
|
182 |
+
self.sqrt_one_minus_alphas_cumprod = np.sqrt(1.0 - self.alphas_cumprod)
|
183 |
+
self.log_one_minus_alphas_cumprod = np.log(1.0 - self.alphas_cumprod)
|
184 |
+
self.sqrt_recip_alphas_cumprod = np.sqrt(1.0 / self.alphas_cumprod)
|
185 |
+
self.sqrt_recipm1_alphas_cumprod = np.sqrt(1.0 / self.alphas_cumprod - 1)
|
186 |
+
|
187 |
+
# calculations for posterior q(x_{t-1} | x_t, x_0)
|
188 |
+
self.posterior_variance = (
|
189 |
+
betas * (1.0 - self.alphas_cumprod_prev) / (1.0 - self.alphas_cumprod)
|
190 |
+
)
|
191 |
+
# below: log calculation clipped because the posterior variance is 0 at the beginning of the diffusion chain
|
192 |
+
self.posterior_log_variance_clipped = np.log(
|
193 |
+
np.append(self.posterior_variance[1], self.posterior_variance[1:])
|
194 |
+
) if len(self.posterior_variance) > 1 else np.array([])
|
195 |
+
|
196 |
+
self.posterior_mean_coef1 = (
|
197 |
+
betas * np.sqrt(self.alphas_cumprod_prev) / (1.0 - self.alphas_cumprod)
|
198 |
+
)
|
199 |
+
self.posterior_mean_coef2 = (
|
200 |
+
(1.0 - self.alphas_cumprod_prev) * np.sqrt(alphas) / (1.0 - self.alphas_cumprod)
|
201 |
+
)
|
202 |
+
|
203 |
+
def q_mean_variance(self, x_start, t):
|
204 |
+
"""
|
205 |
+
Get the distribution q(x_t | x_0).
|
206 |
+
:param x_start: the [N x C x ...] tensor of noiseless inputs.
|
207 |
+
:param t: the number of diffusion steps (minus 1). Here, 0 means one step.
|
208 |
+
:return: A tuple (mean, variance, log_variance), all of x_start's shape.
|
209 |
+
"""
|
210 |
+
mean = _extract_into_tensor(self.sqrt_alphas_cumprod, t, x_start.shape) * x_start
|
211 |
+
variance = _extract_into_tensor(1.0 - self.alphas_cumprod, t, x_start.shape)
|
212 |
+
log_variance = _extract_into_tensor(self.log_one_minus_alphas_cumprod, t, x_start.shape)
|
213 |
+
return mean, variance, log_variance
|
214 |
+
|
215 |
+
def q_sample(self, x_start, t, noise=None):
|
216 |
+
"""
|
217 |
+
Diffuse the data for a given number of diffusion steps.
|
218 |
+
In other words, sample from q(x_t | x_0).
|
219 |
+
:param x_start: the initial data batch.
|
220 |
+
:param t: the number of diffusion steps (minus 1). Here, 0 means one step.
|
221 |
+
:param noise: if specified, the split-out normal noise.
|
222 |
+
:return: A noisy version of x_start.
|
223 |
+
"""
|
224 |
+
if noise is None:
|
225 |
+
noise = th.randn_like(x_start)
|
226 |
+
assert noise.shape == x_start.shape
|
227 |
+
return (
|
228 |
+
_extract_into_tensor(self.sqrt_alphas_cumprod, t, x_start.shape) * x_start
|
229 |
+
+ _extract_into_tensor(self.sqrt_one_minus_alphas_cumprod, t, x_start.shape) * noise
|
230 |
+
)
|
231 |
+
|
232 |
+
def q_posterior_mean_variance(self, x_start, x_t, t):
|
233 |
+
"""
|
234 |
+
Compute the mean and variance of the diffusion posterior:
|
235 |
+
q(x_{t-1} | x_t, x_0)
|
236 |
+
"""
|
237 |
+
assert x_start.shape == x_t.shape
|
238 |
+
posterior_mean = (
|
239 |
+
_extract_into_tensor(self.posterior_mean_coef1, t, x_t.shape) * x_start
|
240 |
+
+ _extract_into_tensor(self.posterior_mean_coef2, t, x_t.shape) * x_t
|
241 |
+
)
|
242 |
+
posterior_variance = _extract_into_tensor(self.posterior_variance, t, x_t.shape)
|
243 |
+
posterior_log_variance_clipped = _extract_into_tensor(
|
244 |
+
self.posterior_log_variance_clipped, t, x_t.shape
|
245 |
+
)
|
246 |
+
assert (
|
247 |
+
posterior_mean.shape[0]
|
248 |
+
== posterior_variance.shape[0]
|
249 |
+
== posterior_log_variance_clipped.shape[0]
|
250 |
+
== x_start.shape[0]
|
251 |
+
)
|
252 |
+
return posterior_mean, posterior_variance, posterior_log_variance_clipped
|
253 |
+
|
254 |
+
def p_mean_variance(self, model, x, t, clip_denoised=True, denoised_fn=None, model_kwargs=None):
|
255 |
+
"""
|
256 |
+
Apply the model to get p(x_{t-1} | x_t), as well as a prediction of
|
257 |
+
the initial x, x_0.
|
258 |
+
:param model: the model, which takes a signal and a batch of timesteps
|
259 |
+
as input.
|
260 |
+
:param x: the [N x C x ...] tensor at time t.
|
261 |
+
:param t: a 1-D Tensor of timesteps.
|
262 |
+
:param clip_denoised: if True, clip the denoised signal into [-1, 1].
|
263 |
+
:param denoised_fn: if not None, a function which applies to the
|
264 |
+
x_start prediction before it is used to sample. Applies before
|
265 |
+
clip_denoised.
|
266 |
+
:param model_kwargs: if not None, a dict of extra keyword arguments to
|
267 |
+
pass to the model. This can be used for conditioning.
|
268 |
+
:return: a dict with the following keys:
|
269 |
+
- 'mean': the model mean output.
|
270 |
+
- 'variance': the model variance output.
|
271 |
+
- 'log_variance': the log of 'variance'.
|
272 |
+
- 'pred_xstart': the prediction for x_0.
|
273 |
+
"""
|
274 |
+
if model_kwargs is None:
|
275 |
+
model_kwargs = {}
|
276 |
+
|
277 |
+
B, C = x.shape[:2]
|
278 |
+
assert t.shape == (B,)
|
279 |
+
model_output = model(x, t, **model_kwargs)
|
280 |
+
if isinstance(model_output, tuple):
|
281 |
+
model_output, extra = model_output
|
282 |
+
else:
|
283 |
+
extra = None
|
284 |
+
|
285 |
+
if self.model_var_type in [ModelVarType.LEARNED, ModelVarType.LEARNED_RANGE]:
|
286 |
+
assert model_output.shape == (B, C * 2, *x.shape[2:])
|
287 |
+
model_output, model_var_values = th.split(model_output, C, dim=1)
|
288 |
+
min_log = _extract_into_tensor(self.posterior_log_variance_clipped, t, x.shape)
|
289 |
+
max_log = _extract_into_tensor(np.log(self.betas), t, x.shape)
|
290 |
+
# The model_var_values is [-1, 1] for [min_var, max_var].
|
291 |
+
frac = (model_var_values + 1) / 2
|
292 |
+
model_log_variance = frac * max_log + (1 - frac) * min_log
|
293 |
+
model_variance = th.exp(model_log_variance)
|
294 |
+
else:
|
295 |
+
model_variance, model_log_variance = {
|
296 |
+
# for fixedlarge, we set the initial (log-)variance like so
|
297 |
+
# to get a better decoder log likelihood.
|
298 |
+
ModelVarType.FIXED_LARGE: (
|
299 |
+
np.append(self.posterior_variance[1], self.betas[1:]),
|
300 |
+
np.log(np.append(self.posterior_variance[1], self.betas[1:])),
|
301 |
+
),
|
302 |
+
ModelVarType.FIXED_SMALL: (
|
303 |
+
self.posterior_variance,
|
304 |
+
self.posterior_log_variance_clipped,
|
305 |
+
),
|
306 |
+
}[self.model_var_type]
|
307 |
+
model_variance = _extract_into_tensor(model_variance, t, x.shape)
|
308 |
+
model_log_variance = _extract_into_tensor(model_log_variance, t, x.shape)
|
309 |
+
|
310 |
+
def process_xstart(x):
|
311 |
+
if denoised_fn is not None:
|
312 |
+
x = denoised_fn(x)
|
313 |
+
if clip_denoised:
|
314 |
+
return x.clamp(-1, 1)
|
315 |
+
return x
|
316 |
+
|
317 |
+
if self.model_mean_type == ModelMeanType.START_X:
|
318 |
+
pred_xstart = process_xstart(model_output)
|
319 |
+
else:
|
320 |
+
pred_xstart = process_xstart(
|
321 |
+
self._predict_xstart_from_eps(x_t=x, t=t, eps=model_output)
|
322 |
+
)
|
323 |
+
model_mean, _, _ = self.q_posterior_mean_variance(x_start=pred_xstart, x_t=x, t=t)
|
324 |
+
|
325 |
+
assert model_mean.shape == model_log_variance.shape == pred_xstart.shape == x.shape
|
326 |
+
return {
|
327 |
+
"mean": model_mean,
|
328 |
+
"variance": model_variance,
|
329 |
+
"log_variance": model_log_variance,
|
330 |
+
"pred_xstart": pred_xstart,
|
331 |
+
"extra": extra,
|
332 |
+
}
|
333 |
+
|
334 |
+
def _predict_xstart_from_eps(self, x_t, t, eps):
|
335 |
+
assert x_t.shape == eps.shape
|
336 |
+
return (
|
337 |
+
_extract_into_tensor(self.sqrt_recip_alphas_cumprod, t, x_t.shape) * x_t
|
338 |
+
- _extract_into_tensor(self.sqrt_recipm1_alphas_cumprod, t, x_t.shape) * eps
|
339 |
+
)
|
340 |
+
|
341 |
+
def _predict_eps_from_xstart(self, x_t, t, pred_xstart):
|
342 |
+
return (
|
343 |
+
_extract_into_tensor(self.sqrt_recip_alphas_cumprod, t, x_t.shape) * x_t - pred_xstart
|
344 |
+
) / _extract_into_tensor(self.sqrt_recipm1_alphas_cumprod, t, x_t.shape)
|
345 |
+
|
346 |
+
def condition_mean(self, cond_fn, p_mean_var, x, t, model_kwargs=None):
|
347 |
+
"""
|
348 |
+
Compute the mean for the previous step, given a function cond_fn that
|
349 |
+
computes the gradient of a conditional log probability with respect to
|
350 |
+
x. In particular, cond_fn computes grad(log(p(y|x))), and we want to
|
351 |
+
condition on y.
|
352 |
+
This uses the conditioning strategy from Sohl-Dickstein et al. (2015).
|
353 |
+
"""
|
354 |
+
gradient = cond_fn(x, t, **model_kwargs)
|
355 |
+
new_mean = p_mean_var["mean"].float() + p_mean_var["variance"] * gradient.float()
|
356 |
+
return new_mean
|
357 |
+
|
358 |
+
def condition_score(self, cond_fn, p_mean_var, x, t, model_kwargs=None):
|
359 |
+
"""
|
360 |
+
Compute what the p_mean_variance output would have been, should the
|
361 |
+
model's score function be conditioned by cond_fn.
|
362 |
+
See condition_mean() for details on cond_fn.
|
363 |
+
Unlike condition_mean(), this instead uses the conditioning strategy
|
364 |
+
from Song et al (2020).
|
365 |
+
"""
|
366 |
+
alpha_bar = _extract_into_tensor(self.alphas_cumprod, t, x.shape)
|
367 |
+
|
368 |
+
eps = self._predict_eps_from_xstart(x, t, p_mean_var["pred_xstart"])
|
369 |
+
eps = eps - (1 - alpha_bar).sqrt() * cond_fn(x, t, **model_kwargs)
|
370 |
+
|
371 |
+
out = p_mean_var.copy()
|
372 |
+
out["pred_xstart"] = self._predict_xstart_from_eps(x, t, eps)
|
373 |
+
out["mean"], _, _ = self.q_posterior_mean_variance(x_start=out["pred_xstart"], x_t=x, t=t)
|
374 |
+
return out
|
375 |
+
|
376 |
+
def p_sample(
|
377 |
+
self,
|
378 |
+
model,
|
379 |
+
x,
|
380 |
+
t,
|
381 |
+
clip_denoised=True,
|
382 |
+
denoised_fn=None,
|
383 |
+
cond_fn=None,
|
384 |
+
model_kwargs=None,
|
385 |
+
):
|
386 |
+
"""
|
387 |
+
Sample x_{t-1} from the model at the given timestep.
|
388 |
+
:param model: the model to sample from.
|
389 |
+
:param x: the current tensor at x_{t-1}.
|
390 |
+
:param t: the value of t, starting at 0 for the first diffusion step.
|
391 |
+
:param clip_denoised: if True, clip the x_start prediction to [-1, 1].
|
392 |
+
:param denoised_fn: if not None, a function which applies to the
|
393 |
+
x_start prediction before it is used to sample.
|
394 |
+
:param cond_fn: if not None, this is a gradient function that acts
|
395 |
+
similarly to the model.
|
396 |
+
:param model_kwargs: if not None, a dict of extra keyword arguments to
|
397 |
+
pass to the model. This can be used for conditioning.
|
398 |
+
:return: a dict containing the following keys:
|
399 |
+
- 'sample': a random sample from the model.
|
400 |
+
- 'pred_xstart': a prediction of x_0.
|
401 |
+
"""
|
402 |
+
out = self.p_mean_variance(
|
403 |
+
model,
|
404 |
+
x,
|
405 |
+
t,
|
406 |
+
clip_denoised=clip_denoised,
|
407 |
+
denoised_fn=denoised_fn,
|
408 |
+
model_kwargs=model_kwargs,
|
409 |
+
)
|
410 |
+
noise = th.randn_like(x)
|
411 |
+
nonzero_mask = (
|
412 |
+
(t != 0).float().view(-1, *([1] * (len(x.shape) - 1)))
|
413 |
+
) # no noise when t == 0
|
414 |
+
if cond_fn is not None:
|
415 |
+
out["mean"] = self.condition_mean(cond_fn, out, x, t, model_kwargs=model_kwargs)
|
416 |
+
sample = out["mean"] + nonzero_mask * th.exp(0.5 * out["log_variance"]) * noise
|
417 |
+
return {"sample": sample, "pred_xstart": out["pred_xstart"]}
|
418 |
+
|
419 |
+
def p_sample_loop(
|
420 |
+
self,
|
421 |
+
model,
|
422 |
+
shape,
|
423 |
+
noise=None,
|
424 |
+
clip_denoised=True,
|
425 |
+
denoised_fn=None,
|
426 |
+
cond_fn=None,
|
427 |
+
model_kwargs=None,
|
428 |
+
device=None,
|
429 |
+
progress=False,
|
430 |
+
):
|
431 |
+
"""
|
432 |
+
Generate samples from the model.
|
433 |
+
:param model: the model module.
|
434 |
+
:param shape: the shape of the samples, (N, C, H, W).
|
435 |
+
:param noise: if specified, the noise from the encoder to sample.
|
436 |
+
Should be of the same shape as `shape`.
|
437 |
+
:param clip_denoised: if True, clip x_start predictions to [-1, 1].
|
438 |
+
:param denoised_fn: if not None, a function which applies to the
|
439 |
+
x_start prediction before it is used to sample.
|
440 |
+
:param cond_fn: if not None, this is a gradient function that acts
|
441 |
+
similarly to the model.
|
442 |
+
:param model_kwargs: if not None, a dict of extra keyword arguments to
|
443 |
+
pass to the model. This can be used for conditioning.
|
444 |
+
:param device: if specified, the device to create the samples on.
|
445 |
+
If not specified, use a model parameter's device.
|
446 |
+
:param progress: if True, show a tqdm progress bar.
|
447 |
+
:return: a non-differentiable batch of samples.
|
448 |
+
"""
|
449 |
+
final = None
|
450 |
+
for sample in self.p_sample_loop_progressive(
|
451 |
+
model,
|
452 |
+
shape,
|
453 |
+
noise=noise,
|
454 |
+
clip_denoised=clip_denoised,
|
455 |
+
denoised_fn=denoised_fn,
|
456 |
+
cond_fn=cond_fn,
|
457 |
+
model_kwargs=model_kwargs,
|
458 |
+
device=device,
|
459 |
+
progress=progress,
|
460 |
+
):
|
461 |
+
final = sample
|
462 |
+
return final["sample"]
|
463 |
+
|
464 |
+
def p_sample_loop_progressive(
|
465 |
+
self,
|
466 |
+
model,
|
467 |
+
shape,
|
468 |
+
noise=None,
|
469 |
+
clip_denoised=True,
|
470 |
+
denoised_fn=None,
|
471 |
+
cond_fn=None,
|
472 |
+
model_kwargs=None,
|
473 |
+
device=None,
|
474 |
+
progress=False,
|
475 |
+
):
|
476 |
+
"""
|
477 |
+
Generate samples from the model and yield intermediate samples from
|
478 |
+
each timestep of diffusion.
|
479 |
+
Arguments are the same as p_sample_loop().
|
480 |
+
Returns a generator over dicts, where each dict is the return value of
|
481 |
+
p_sample().
|
482 |
+
"""
|
483 |
+
if device is None:
|
484 |
+
device = next(model.parameters()).device
|
485 |
+
assert isinstance(shape, (tuple, list))
|
486 |
+
if noise is not None:
|
487 |
+
img = noise
|
488 |
+
else:
|
489 |
+
img = th.randn(*shape, device=device)
|
490 |
+
indices = list(range(self.num_timesteps))[::-1]
|
491 |
+
|
492 |
+
if progress:
|
493 |
+
# Lazy import so that we don't depend on tqdm.
|
494 |
+
from tqdm.auto import tqdm
|
495 |
+
|
496 |
+
indices = tqdm(indices)
|
497 |
+
|
498 |
+
for i in indices:
|
499 |
+
t = th.tensor([i] * shape[0], device=device)
|
500 |
+
with th.no_grad():
|
501 |
+
out = self.p_sample(
|
502 |
+
model,
|
503 |
+
img,
|
504 |
+
t,
|
505 |
+
clip_denoised=clip_denoised,
|
506 |
+
denoised_fn=denoised_fn,
|
507 |
+
cond_fn=cond_fn,
|
508 |
+
model_kwargs=model_kwargs,
|
509 |
+
)
|
510 |
+
yield out
|
511 |
+
img = out["sample"]
|
512 |
+
|
513 |
+
def ddim_sample(
|
514 |
+
self,
|
515 |
+
model,
|
516 |
+
x,
|
517 |
+
t,
|
518 |
+
clip_denoised=True,
|
519 |
+
denoised_fn=None,
|
520 |
+
cond_fn=None,
|
521 |
+
model_kwargs=None,
|
522 |
+
eta=0.0,
|
523 |
+
):
|
524 |
+
"""
|
525 |
+
Sample x_{t-1} from the model using DDIM.
|
526 |
+
Same usage as p_sample().
|
527 |
+
"""
|
528 |
+
out = self.p_mean_variance(
|
529 |
+
model,
|
530 |
+
x,
|
531 |
+
t,
|
532 |
+
clip_denoised=clip_denoised,
|
533 |
+
denoised_fn=denoised_fn,
|
534 |
+
model_kwargs=model_kwargs,
|
535 |
+
)
|
536 |
+
if cond_fn is not None:
|
537 |
+
out = self.condition_score(cond_fn, out, x, t, model_kwargs=model_kwargs)
|
538 |
+
|
539 |
+
# Usually our model outputs epsilon, but we re-derive it
|
540 |
+
# in case we used x_start or x_prev prediction.
|
541 |
+
eps = self._predict_eps_from_xstart(x, t, out["pred_xstart"])
|
542 |
+
|
543 |
+
alpha_bar = _extract_into_tensor(self.alphas_cumprod, t, x.shape)
|
544 |
+
alpha_bar_prev = _extract_into_tensor(self.alphas_cumprod_prev, t, x.shape)
|
545 |
+
sigma = (
|
546 |
+
eta
|
547 |
+
* th.sqrt((1 - alpha_bar_prev) / (1 - alpha_bar))
|
548 |
+
* th.sqrt(1 - alpha_bar / alpha_bar_prev)
|
549 |
+
)
|
550 |
+
# Equation 12.
|
551 |
+
noise = th.randn_like(x)
|
552 |
+
mean_pred = (
|
553 |
+
out["pred_xstart"] * th.sqrt(alpha_bar_prev)
|
554 |
+
+ th.sqrt(1 - alpha_bar_prev - sigma ** 2) * eps
|
555 |
+
)
|
556 |
+
nonzero_mask = (
|
557 |
+
(t != 0).float().view(-1, *([1] * (len(x.shape) - 1)))
|
558 |
+
) # no noise when t == 0
|
559 |
+
sample = mean_pred + nonzero_mask * sigma * noise
|
560 |
+
return {"sample": sample, "pred_xstart": out["pred_xstart"]}
|
561 |
+
|
562 |
+
def ddim_reverse_sample(
|
563 |
+
self,
|
564 |
+
model,
|
565 |
+
x,
|
566 |
+
t,
|
567 |
+
clip_denoised=True,
|
568 |
+
denoised_fn=None,
|
569 |
+
cond_fn=None,
|
570 |
+
model_kwargs=None,
|
571 |
+
eta=0.0,
|
572 |
+
):
|
573 |
+
"""
|
574 |
+
Sample x_{t+1} from the model using DDIM reverse ODE.
|
575 |
+
"""
|
576 |
+
assert eta == 0.0, "Reverse ODE only for deterministic path"
|
577 |
+
out = self.p_mean_variance(
|
578 |
+
model,
|
579 |
+
x,
|
580 |
+
t,
|
581 |
+
clip_denoised=clip_denoised,
|
582 |
+
denoised_fn=denoised_fn,
|
583 |
+
model_kwargs=model_kwargs,
|
584 |
+
)
|
585 |
+
if cond_fn is not None:
|
586 |
+
out = self.condition_score(cond_fn, out, x, t, model_kwargs=model_kwargs)
|
587 |
+
# Usually our model outputs epsilon, but we re-derive it
|
588 |
+
# in case we used x_start or x_prev prediction.
|
589 |
+
eps = (
|
590 |
+
_extract_into_tensor(self.sqrt_recip_alphas_cumprod, t, x.shape) * x
|
591 |
+
- out["pred_xstart"]
|
592 |
+
) / _extract_into_tensor(self.sqrt_recipm1_alphas_cumprod, t, x.shape)
|
593 |
+
alpha_bar_next = _extract_into_tensor(self.alphas_cumprod_next, t, x.shape)
|
594 |
+
|
595 |
+
# Equation 12. reversed
|
596 |
+
mean_pred = out["pred_xstart"] * th.sqrt(alpha_bar_next) + th.sqrt(1 - alpha_bar_next) * eps
|
597 |
+
|
598 |
+
return {"sample": mean_pred, "pred_xstart": out["pred_xstart"]}
|
599 |
+
|
600 |
+
def ddim_sample_loop(
|
601 |
+
self,
|
602 |
+
model,
|
603 |
+
shape,
|
604 |
+
noise=None,
|
605 |
+
clip_denoised=True,
|
606 |
+
denoised_fn=None,
|
607 |
+
cond_fn=None,
|
608 |
+
model_kwargs=None,
|
609 |
+
device=None,
|
610 |
+
progress=False,
|
611 |
+
eta=0.0,
|
612 |
+
):
|
613 |
+
"""
|
614 |
+
Generate samples from the model using DDIM.
|
615 |
+
Same usage as p_sample_loop().
|
616 |
+
"""
|
617 |
+
final = None
|
618 |
+
for sample in self.ddim_sample_loop_progressive(
|
619 |
+
model,
|
620 |
+
shape,
|
621 |
+
noise=noise,
|
622 |
+
clip_denoised=clip_denoised,
|
623 |
+
denoised_fn=denoised_fn,
|
624 |
+
cond_fn=cond_fn,
|
625 |
+
model_kwargs=model_kwargs,
|
626 |
+
device=device,
|
627 |
+
progress=progress,
|
628 |
+
eta=eta,
|
629 |
+
):
|
630 |
+
final = sample
|
631 |
+
return final["sample"]
|
632 |
+
|
633 |
+
def ddim_sample_loop_progressive(
|
634 |
+
self,
|
635 |
+
model,
|
636 |
+
shape,
|
637 |
+
noise=None,
|
638 |
+
clip_denoised=True,
|
639 |
+
denoised_fn=None,
|
640 |
+
cond_fn=None,
|
641 |
+
model_kwargs=None,
|
642 |
+
device=None,
|
643 |
+
progress=False,
|
644 |
+
eta=0.0,
|
645 |
+
):
|
646 |
+
"""
|
647 |
+
Use DDIM to sample from the model and yield intermediate samples from
|
648 |
+
each timestep of DDIM.
|
649 |
+
Same usage as p_sample_loop_progressive().
|
650 |
+
"""
|
651 |
+
if device is None:
|
652 |
+
device = next(model.parameters()).device
|
653 |
+
assert isinstance(shape, (tuple, list))
|
654 |
+
if noise is not None:
|
655 |
+
img = noise
|
656 |
+
else:
|
657 |
+
img = th.randn(*shape, device=device)
|
658 |
+
indices = list(range(self.num_timesteps))[::-1]
|
659 |
+
|
660 |
+
if progress:
|
661 |
+
# Lazy import so that we don't depend on tqdm.
|
662 |
+
from tqdm.auto import tqdm
|
663 |
+
|
664 |
+
indices = tqdm(indices)
|
665 |
+
|
666 |
+
for i in indices:
|
667 |
+
t = th.tensor([i] * shape[0], device=device)
|
668 |
+
with th.no_grad():
|
669 |
+
out = self.ddim_sample(
|
670 |
+
model,
|
671 |
+
img,
|
672 |
+
t,
|
673 |
+
clip_denoised=clip_denoised,
|
674 |
+
denoised_fn=denoised_fn,
|
675 |
+
cond_fn=cond_fn,
|
676 |
+
model_kwargs=model_kwargs,
|
677 |
+
eta=eta,
|
678 |
+
)
|
679 |
+
yield out
|
680 |
+
img = out["sample"]
|
681 |
+
|
682 |
+
def _vb_terms_bpd(
|
683 |
+
self, model, x_start, x_t, t, clip_denoised=True, model_kwargs=None
|
684 |
+
):
|
685 |
+
"""
|
686 |
+
Get a term for the variational lower-bound.
|
687 |
+
The resulting units are bits (rather than nats, as one might expect).
|
688 |
+
This allows for comparison to other papers.
|
689 |
+
:return: a dict with the following keys:
|
690 |
+
- 'output': a shape [N] tensor of NLLs or KLs.
|
691 |
+
- 'pred_xstart': the x_0 predictions.
|
692 |
+
"""
|
693 |
+
true_mean, _, true_log_variance_clipped = self.q_posterior_mean_variance(
|
694 |
+
x_start=x_start, x_t=x_t, t=t
|
695 |
+
)
|
696 |
+
out = self.p_mean_variance(
|
697 |
+
model, x_t, t, clip_denoised=clip_denoised, model_kwargs=model_kwargs
|
698 |
+
)
|
699 |
+
kl = normal_kl(
|
700 |
+
true_mean, true_log_variance_clipped, out["mean"], out["log_variance"]
|
701 |
+
)
|
702 |
+
kl = mean_flat(kl) / np.log(2.0)
|
703 |
+
|
704 |
+
decoder_nll = -discretized_gaussian_log_likelihood(
|
705 |
+
x_start, means=out["mean"], log_scales=0.5 * out["log_variance"]
|
706 |
+
)
|
707 |
+
assert decoder_nll.shape == x_start.shape
|
708 |
+
decoder_nll = mean_flat(decoder_nll) / np.log(2.0)
|
709 |
+
|
710 |
+
# At the first timestep return the decoder NLL,
|
711 |
+
# otherwise return KL(q(x_{t-1}|x_t,x_0) || p(x_{t-1}|x_t))
|
712 |
+
output = th.where((t == 0), decoder_nll, kl)
|
713 |
+
return {"output": output, "pred_xstart": out["pred_xstart"]}
|
714 |
+
|
715 |
+
def training_losses(self, model, x_start, t, model_kwargs=None, noise=None):
|
716 |
+
"""
|
717 |
+
Compute training losses for a single timestep.
|
718 |
+
:param model: the model to evaluate loss on.
|
719 |
+
:param x_start: the [N x C x ...] tensor of inputs.
|
720 |
+
:param t: a batch of timestep indices.
|
721 |
+
:param model_kwargs: if not None, a dict of extra keyword arguments to
|
722 |
+
pass to the model. This can be used for conditioning.
|
723 |
+
:param noise: if specified, the specific Gaussian noise to try to remove.
|
724 |
+
:return: a dict with the key "loss" containing a tensor of shape [N].
|
725 |
+
Some mean or variance settings may also have other keys.
|
726 |
+
"""
|
727 |
+
if model_kwargs is None:
|
728 |
+
model_kwargs = {}
|
729 |
+
if noise is None:
|
730 |
+
noise = th.randn_like(x_start)
|
731 |
+
x_t = self.q_sample(x_start, t, noise=noise)
|
732 |
+
|
733 |
+
terms = {}
|
734 |
+
|
735 |
+
if self.loss_type == LossType.KL or self.loss_type == LossType.RESCALED_KL:
|
736 |
+
terms["loss"] = self._vb_terms_bpd(
|
737 |
+
model=model,
|
738 |
+
x_start=x_start,
|
739 |
+
x_t=x_t,
|
740 |
+
t=t,
|
741 |
+
clip_denoised=False,
|
742 |
+
model_kwargs=model_kwargs,
|
743 |
+
)["output"]
|
744 |
+
if self.loss_type == LossType.RESCALED_KL:
|
745 |
+
terms["loss"] *= self.num_timesteps
|
746 |
+
elif self.loss_type == LossType.MSE or self.loss_type == LossType.RESCALED_MSE:
|
747 |
+
model_output = model(x_t, t, **model_kwargs)
|
748 |
+
|
749 |
+
if self.model_var_type in [
|
750 |
+
ModelVarType.LEARNED,
|
751 |
+
ModelVarType.LEARNED_RANGE,
|
752 |
+
]:
|
753 |
+
B, C = x_t.shape[:2]
|
754 |
+
assert model_output.shape == (B, C * 2, *x_t.shape[2:])
|
755 |
+
model_output, model_var_values = th.split(model_output, C, dim=1)
|
756 |
+
# Learn the variance using the variational bound, but don't let
|
757 |
+
# it affect our mean prediction.
|
758 |
+
frozen_out = th.cat([model_output.detach(), model_var_values], dim=1)
|
759 |
+
terms["vb"] = self._vb_terms_bpd(
|
760 |
+
model=lambda *args, r=frozen_out: r,
|
761 |
+
x_start=x_start,
|
762 |
+
x_t=x_t,
|
763 |
+
t=t,
|
764 |
+
clip_denoised=False,
|
765 |
+
)["output"]
|
766 |
+
if self.loss_type == LossType.RESCALED_MSE:
|
767 |
+
# Divide by 1000 for equivalence with initial implementation.
|
768 |
+
# Without a factor of 1/1000, the VB term hurts the MSE term.
|
769 |
+
terms["vb"] *= self.num_timesteps / 1000.0
|
770 |
+
|
771 |
+
target = {
|
772 |
+
ModelMeanType.PREVIOUS_X: self.q_posterior_mean_variance(
|
773 |
+
x_start=x_start, x_t=x_t, t=t
|
774 |
+
)[0],
|
775 |
+
ModelMeanType.START_X: x_start,
|
776 |
+
ModelMeanType.EPSILON: noise,
|
777 |
+
}[self.model_mean_type]
|
778 |
+
assert model_output.shape == target.shape == x_start.shape
|
779 |
+
terms["mse"] = mean_flat((target - model_output) ** 2)
|
780 |
+
if "vb" in terms:
|
781 |
+
terms["loss"] = terms["mse"] + terms["vb"]
|
782 |
+
else:
|
783 |
+
terms["loss"] = terms["mse"]
|
784 |
+
else:
|
785 |
+
raise NotImplementedError(self.loss_type)
|
786 |
+
|
787 |
+
return terms
|
788 |
+
|
789 |
+
def _prior_bpd(self, x_start):
|
790 |
+
"""
|
791 |
+
Get the prior KL term for the variational lower-bound, measured in
|
792 |
+
bits-per-dim.
|
793 |
+
This term can't be optimized, as it only depends on the encoder.
|
794 |
+
:param x_start: the [N x C x ...] tensor of inputs.
|
795 |
+
:return: a batch of [N] KL values (in bits), one per batch element.
|
796 |
+
"""
|
797 |
+
batch_size = x_start.shape[0]
|
798 |
+
t = th.tensor([self.num_timesteps - 1] * batch_size, device=x_start.device)
|
799 |
+
qt_mean, _, qt_log_variance = self.q_mean_variance(x_start, t)
|
800 |
+
kl_prior = normal_kl(
|
801 |
+
mean1=qt_mean, logvar1=qt_log_variance, mean2=0.0, logvar2=0.0
|
802 |
+
)
|
803 |
+
return mean_flat(kl_prior) / np.log(2.0)
|
804 |
+
|
805 |
+
def calc_bpd_loop(self, model, x_start, clip_denoised=True, model_kwargs=None):
|
806 |
+
"""
|
807 |
+
Compute the entire variational lower-bound, measured in bits-per-dim,
|
808 |
+
as well as other related quantities.
|
809 |
+
:param model: the model to evaluate loss on.
|
810 |
+
:param x_start: the [N x C x ...] tensor of inputs.
|
811 |
+
:param clip_denoised: if True, clip denoised samples.
|
812 |
+
:param model_kwargs: if not None, a dict of extra keyword arguments to
|
813 |
+
pass to the model. This can be used for conditioning.
|
814 |
+
:return: a dict containing the following keys:
|
815 |
+
- total_bpd: the total variational lower-bound, per batch element.
|
816 |
+
- prior_bpd: the prior term in the lower-bound.
|
817 |
+
- vb: an [N x T] tensor of terms in the lower-bound.
|
818 |
+
- xstart_mse: an [N x T] tensor of x_0 MSEs for each timestep.
|
819 |
+
- mse: an [N x T] tensor of epsilon MSEs for each timestep.
|
820 |
+
"""
|
821 |
+
device = x_start.device
|
822 |
+
batch_size = x_start.shape[0]
|
823 |
+
|
824 |
+
vb = []
|
825 |
+
xstart_mse = []
|
826 |
+
mse = []
|
827 |
+
for t in list(range(self.num_timesteps))[::-1]:
|
828 |
+
t_batch = th.tensor([t] * batch_size, device=device)
|
829 |
+
noise = th.randn_like(x_start)
|
830 |
+
x_t = self.q_sample(x_start=x_start, t=t_batch, noise=noise)
|
831 |
+
# Calculate VLB term at the current timestep
|
832 |
+
with th.no_grad():
|
833 |
+
out = self._vb_terms_bpd(
|
834 |
+
model,
|
835 |
+
x_start=x_start,
|
836 |
+
x_t=x_t,
|
837 |
+
t=t_batch,
|
838 |
+
clip_denoised=clip_denoised,
|
839 |
+
model_kwargs=model_kwargs,
|
840 |
+
)
|
841 |
+
vb.append(out["output"])
|
842 |
+
xstart_mse.append(mean_flat((out["pred_xstart"] - x_start) ** 2))
|
843 |
+
eps = self._predict_eps_from_xstart(x_t, t_batch, out["pred_xstart"])
|
844 |
+
mse.append(mean_flat((eps - noise) ** 2))
|
845 |
+
|
846 |
+
vb = th.stack(vb, dim=1)
|
847 |
+
xstart_mse = th.stack(xstart_mse, dim=1)
|
848 |
+
mse = th.stack(mse, dim=1)
|
849 |
+
|
850 |
+
prior_bpd = self._prior_bpd(x_start)
|
851 |
+
total_bpd = vb.sum(dim=1) + prior_bpd
|
852 |
+
return {
|
853 |
+
"total_bpd": total_bpd,
|
854 |
+
"prior_bpd": prior_bpd,
|
855 |
+
"vb": vb,
|
856 |
+
"xstart_mse": xstart_mse,
|
857 |
+
"mse": mse,
|
858 |
+
}
|
859 |
+
|
860 |
+
|
861 |
+
def _extract_into_tensor(arr, timesteps, broadcast_shape):
|
862 |
+
"""
|
863 |
+
Extract values from a 1-D numpy array for a batch of indices.
|
864 |
+
:param arr: the 1-D numpy array.
|
865 |
+
:param timesteps: a tensor of indices into the array to extract.
|
866 |
+
:param broadcast_shape: a larger shape of K dimensions with the batch
|
867 |
+
dimension equal to the length of timesteps.
|
868 |
+
:return: a tensor of shape [batch_size, 1, ...] where the shape has K dims.
|
869 |
+
"""
|
870 |
+
res = th.from_numpy(arr).to(device=timesteps.device)[timesteps].float()
|
871 |
+
while len(res.shape) < len(broadcast_shape):
|
872 |
+
res = res[..., None]
|
873 |
+
return res + th.zeros(broadcast_shape, device=timesteps.device)
|
diffusion/respace.py
ADDED
@@ -0,0 +1,129 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Modified from OpenAI's diffusion repos
|
2 |
+
# GLIDE: https://github.com/openai/glide-text2im/blob/main/glide_text2im/gaussian_diffusion.py
|
3 |
+
# ADM: https://github.com/openai/guided-diffusion/blob/main/guided_diffusion
|
4 |
+
# IDDPM: https://github.com/openai/improved-diffusion/blob/main/improved_diffusion/gaussian_diffusion.py
|
5 |
+
|
6 |
+
import numpy as np
|
7 |
+
import torch as th
|
8 |
+
|
9 |
+
from .gaussian_diffusion import GaussianDiffusion
|
10 |
+
|
11 |
+
|
12 |
+
def space_timesteps(num_timesteps, section_counts):
|
13 |
+
"""
|
14 |
+
Create a list of timesteps to use from an original diffusion process,
|
15 |
+
given the number of timesteps we want to take from equally-sized portions
|
16 |
+
of the original process.
|
17 |
+
For example, if there's 300 timesteps and the section counts are [10,15,20]
|
18 |
+
then the first 100 timesteps are strided to be 10 timesteps, the second 100
|
19 |
+
are strided to be 15 timesteps, and the final 100 are strided to be 20.
|
20 |
+
If the stride is a string starting with "ddim", then the fixed striding
|
21 |
+
from the DDIM paper is used, and only one section is allowed.
|
22 |
+
:param num_timesteps: the number of diffusion steps in the original
|
23 |
+
process to divide up.
|
24 |
+
:param section_counts: either a list of numbers, or a string containing
|
25 |
+
comma-separated numbers, indicating the step count
|
26 |
+
per section. As a special case, use "ddimN" where N
|
27 |
+
is a number of steps to use the striding from the
|
28 |
+
DDIM paper.
|
29 |
+
:return: a set of diffusion steps from the original process to use.
|
30 |
+
"""
|
31 |
+
if isinstance(section_counts, str):
|
32 |
+
if section_counts.startswith("ddim"):
|
33 |
+
desired_count = int(section_counts[len("ddim") :])
|
34 |
+
for i in range(1, num_timesteps):
|
35 |
+
if len(range(0, num_timesteps, i)) == desired_count:
|
36 |
+
return set(range(0, num_timesteps, i))
|
37 |
+
raise ValueError(
|
38 |
+
f"cannot create exactly {num_timesteps} steps with an integer stride"
|
39 |
+
)
|
40 |
+
section_counts = [int(x) for x in section_counts.split(",")]
|
41 |
+
size_per = num_timesteps // len(section_counts)
|
42 |
+
extra = num_timesteps % len(section_counts)
|
43 |
+
start_idx = 0
|
44 |
+
all_steps = []
|
45 |
+
for i, section_count in enumerate(section_counts):
|
46 |
+
size = size_per + (1 if i < extra else 0)
|
47 |
+
if size < section_count:
|
48 |
+
raise ValueError(
|
49 |
+
f"cannot divide section of {size} steps into {section_count}"
|
50 |
+
)
|
51 |
+
if section_count <= 1:
|
52 |
+
frac_stride = 1
|
53 |
+
else:
|
54 |
+
frac_stride = (size - 1) / (section_count - 1)
|
55 |
+
cur_idx = 0.0
|
56 |
+
taken_steps = []
|
57 |
+
for _ in range(section_count):
|
58 |
+
taken_steps.append(start_idx + round(cur_idx))
|
59 |
+
cur_idx += frac_stride
|
60 |
+
all_steps += taken_steps
|
61 |
+
start_idx += size
|
62 |
+
return set(all_steps)
|
63 |
+
|
64 |
+
|
65 |
+
class SpacedDiffusion(GaussianDiffusion):
|
66 |
+
"""
|
67 |
+
A diffusion process which can skip steps in a base diffusion process.
|
68 |
+
:param use_timesteps: a collection (sequence or set) of timesteps from the
|
69 |
+
original diffusion process to retain.
|
70 |
+
:param kwargs: the kwargs to create the base diffusion process.
|
71 |
+
"""
|
72 |
+
|
73 |
+
def __init__(self, use_timesteps, **kwargs):
|
74 |
+
self.use_timesteps = set(use_timesteps)
|
75 |
+
self.timestep_map = []
|
76 |
+
self.original_num_steps = len(kwargs["betas"])
|
77 |
+
|
78 |
+
base_diffusion = GaussianDiffusion(**kwargs) # pylint: disable=missing-kwoa
|
79 |
+
last_alpha_cumprod = 1.0
|
80 |
+
new_betas = []
|
81 |
+
for i, alpha_cumprod in enumerate(base_diffusion.alphas_cumprod):
|
82 |
+
if i in self.use_timesteps:
|
83 |
+
new_betas.append(1 - alpha_cumprod / last_alpha_cumprod)
|
84 |
+
last_alpha_cumprod = alpha_cumprod
|
85 |
+
self.timestep_map.append(i)
|
86 |
+
kwargs["betas"] = np.array(new_betas)
|
87 |
+
super().__init__(**kwargs)
|
88 |
+
|
89 |
+
def p_mean_variance(
|
90 |
+
self, model, *args, **kwargs
|
91 |
+
): # pylint: disable=signature-differs
|
92 |
+
return super().p_mean_variance(self._wrap_model(model), *args, **kwargs)
|
93 |
+
|
94 |
+
def training_losses(
|
95 |
+
self, model, *args, **kwargs
|
96 |
+
): # pylint: disable=signature-differs
|
97 |
+
return super().training_losses(self._wrap_model(model), *args, **kwargs)
|
98 |
+
|
99 |
+
def condition_mean(self, cond_fn, *args, **kwargs):
|
100 |
+
return super().condition_mean(self._wrap_model(cond_fn), *args, **kwargs)
|
101 |
+
|
102 |
+
def condition_score(self, cond_fn, *args, **kwargs):
|
103 |
+
return super().condition_score(self._wrap_model(cond_fn), *args, **kwargs)
|
104 |
+
|
105 |
+
def _wrap_model(self, model):
|
106 |
+
if isinstance(model, _WrappedModel):
|
107 |
+
return model
|
108 |
+
return _WrappedModel(
|
109 |
+
model, self.timestep_map, self.original_num_steps
|
110 |
+
)
|
111 |
+
|
112 |
+
def _scale_timesteps(self, t):
|
113 |
+
# Scaling is done by the wrapped model.
|
114 |
+
return t
|
115 |
+
|
116 |
+
|
117 |
+
class _WrappedModel:
|
118 |
+
def __init__(self, model, timestep_map, original_num_steps):
|
119 |
+
self.model = model
|
120 |
+
self.timestep_map = timestep_map
|
121 |
+
# self.rescale_timesteps = rescale_timesteps
|
122 |
+
self.original_num_steps = original_num_steps
|
123 |
+
|
124 |
+
def __call__(self, x, ts, **kwargs):
|
125 |
+
map_tensor = th.tensor(self.timestep_map, device=ts.device, dtype=ts.dtype)
|
126 |
+
new_ts = map_tensor[ts]
|
127 |
+
# if self.rescale_timesteps:
|
128 |
+
# new_ts = new_ts.float() * (1000.0 / self.original_num_steps)
|
129 |
+
return self.model(x, new_ts, **kwargs)
|
diffusion/timestep_sampler.py
ADDED
@@ -0,0 +1,150 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Modified from OpenAI's diffusion repos
|
2 |
+
# GLIDE: https://github.com/openai/glide-text2im/blob/main/glide_text2im/gaussian_diffusion.py
|
3 |
+
# ADM: https://github.com/openai/guided-diffusion/blob/main/guided_diffusion
|
4 |
+
# IDDPM: https://github.com/openai/improved-diffusion/blob/main/improved_diffusion/gaussian_diffusion.py
|
5 |
+
|
6 |
+
from abc import ABC, abstractmethod
|
7 |
+
|
8 |
+
import numpy as np
|
9 |
+
import torch as th
|
10 |
+
import torch.distributed as dist
|
11 |
+
|
12 |
+
|
13 |
+
def create_named_schedule_sampler(name, diffusion):
|
14 |
+
"""
|
15 |
+
Create a ScheduleSampler from a library of pre-defined samplers.
|
16 |
+
:param name: the name of the sampler.
|
17 |
+
:param diffusion: the diffusion object to sample for.
|
18 |
+
"""
|
19 |
+
if name == "uniform":
|
20 |
+
return UniformSampler(diffusion)
|
21 |
+
elif name == "loss-second-moment":
|
22 |
+
return LossSecondMomentResampler(diffusion)
|
23 |
+
else:
|
24 |
+
raise NotImplementedError(f"unknown schedule sampler: {name}")
|
25 |
+
|
26 |
+
|
27 |
+
class ScheduleSampler(ABC):
|
28 |
+
"""
|
29 |
+
A distribution over timesteps in the diffusion process, intended to reduce
|
30 |
+
variance of the objective.
|
31 |
+
By default, samplers perform unbiased importance sampling, in which the
|
32 |
+
objective's mean is unchanged.
|
33 |
+
However, subclasses may override sample() to change how the resampled
|
34 |
+
terms are reweighted, allowing for actual changes in the objective.
|
35 |
+
"""
|
36 |
+
|
37 |
+
@abstractmethod
|
38 |
+
def weights(self):
|
39 |
+
"""
|
40 |
+
Get a numpy array of weights, one per diffusion step.
|
41 |
+
The weights needn't be normalized, but must be positive.
|
42 |
+
"""
|
43 |
+
|
44 |
+
def sample(self, batch_size, device):
|
45 |
+
"""
|
46 |
+
Importance-sample timesteps for a batch.
|
47 |
+
:param batch_size: the number of timesteps.
|
48 |
+
:param device: the torch device to save to.
|
49 |
+
:return: a tuple (timesteps, weights):
|
50 |
+
- timesteps: a tensor of timestep indices.
|
51 |
+
- weights: a tensor of weights to scale the resulting losses.
|
52 |
+
"""
|
53 |
+
w = self.weights()
|
54 |
+
p = w / np.sum(w)
|
55 |
+
indices_np = np.random.choice(len(p), size=(batch_size,), p=p)
|
56 |
+
indices = th.from_numpy(indices_np).long().to(device)
|
57 |
+
weights_np = 1 / (len(p) * p[indices_np])
|
58 |
+
weights = th.from_numpy(weights_np).float().to(device)
|
59 |
+
return indices, weights
|
60 |
+
|
61 |
+
|
62 |
+
class UniformSampler(ScheduleSampler):
|
63 |
+
def __init__(self, diffusion):
|
64 |
+
self.diffusion = diffusion
|
65 |
+
self._weights = np.ones([diffusion.num_timesteps])
|
66 |
+
|
67 |
+
def weights(self):
|
68 |
+
return self._weights
|
69 |
+
|
70 |
+
|
71 |
+
class LossAwareSampler(ScheduleSampler):
|
72 |
+
def update_with_local_losses(self, local_ts, local_losses):
|
73 |
+
"""
|
74 |
+
Update the reweighting using losses from a model.
|
75 |
+
Call this method from each rank with a batch of timesteps and the
|
76 |
+
corresponding losses for each of those timesteps.
|
77 |
+
This method will perform synchronization to make sure all of the ranks
|
78 |
+
maintain the exact same reweighting.
|
79 |
+
:param local_ts: an integer Tensor of timesteps.
|
80 |
+
:param local_losses: a 1D Tensor of losses.
|
81 |
+
"""
|
82 |
+
batch_sizes = [
|
83 |
+
th.tensor([0], dtype=th.int32, device=local_ts.device)
|
84 |
+
for _ in range(dist.get_world_size())
|
85 |
+
]
|
86 |
+
dist.all_gather(
|
87 |
+
batch_sizes,
|
88 |
+
th.tensor([len(local_ts)], dtype=th.int32, device=local_ts.device),
|
89 |
+
)
|
90 |
+
|
91 |
+
# Pad all_gather batches to be the maximum batch size.
|
92 |
+
batch_sizes = [x.item() for x in batch_sizes]
|
93 |
+
max_bs = max(batch_sizes)
|
94 |
+
|
95 |
+
timestep_batches = [th.zeros(max_bs).to(local_ts) for bs in batch_sizes]
|
96 |
+
loss_batches = [th.zeros(max_bs).to(local_losses) for bs in batch_sizes]
|
97 |
+
dist.all_gather(timestep_batches, local_ts)
|
98 |
+
dist.all_gather(loss_batches, local_losses)
|
99 |
+
timesteps = [
|
100 |
+
x.item() for y, bs in zip(timestep_batches, batch_sizes) for x in y[:bs]
|
101 |
+
]
|
102 |
+
losses = [x.item() for y, bs in zip(loss_batches, batch_sizes) for x in y[:bs]]
|
103 |
+
self.update_with_all_losses(timesteps, losses)
|
104 |
+
|
105 |
+
@abstractmethod
|
106 |
+
def update_with_all_losses(self, ts, losses):
|
107 |
+
"""
|
108 |
+
Update the reweighting using losses from a model.
|
109 |
+
Sub-classes should override this method to update the reweighting
|
110 |
+
using losses from the model.
|
111 |
+
This method directly updates the reweighting without synchronizing
|
112 |
+
between workers. It is called by update_with_local_losses from all
|
113 |
+
ranks with identical arguments. Thus, it should have deterministic
|
114 |
+
behavior to maintain state across workers.
|
115 |
+
:param ts: a list of int timesteps.
|
116 |
+
:param losses: a list of float losses, one per timestep.
|
117 |
+
"""
|
118 |
+
|
119 |
+
|
120 |
+
class LossSecondMomentResampler(LossAwareSampler):
|
121 |
+
def __init__(self, diffusion, history_per_term=10, uniform_prob=0.001):
|
122 |
+
self.diffusion = diffusion
|
123 |
+
self.history_per_term = history_per_term
|
124 |
+
self.uniform_prob = uniform_prob
|
125 |
+
self._loss_history = np.zeros(
|
126 |
+
[diffusion.num_timesteps, history_per_term], dtype=np.float64
|
127 |
+
)
|
128 |
+
self._loss_counts = np.zeros([diffusion.num_timesteps], dtype=np.int)
|
129 |
+
|
130 |
+
def weights(self):
|
131 |
+
if not self._warmed_up():
|
132 |
+
return np.ones([self.diffusion.num_timesteps], dtype=np.float64)
|
133 |
+
weights = np.sqrt(np.mean(self._loss_history ** 2, axis=-1))
|
134 |
+
weights /= np.sum(weights)
|
135 |
+
weights *= 1 - self.uniform_prob
|
136 |
+
weights += self.uniform_prob / len(weights)
|
137 |
+
return weights
|
138 |
+
|
139 |
+
def update_with_all_losses(self, ts, losses):
|
140 |
+
for t, loss in zip(ts, losses):
|
141 |
+
if self._loss_counts[t] == self.history_per_term:
|
142 |
+
# Shift out the oldest loss term.
|
143 |
+
self._loss_history[t, :-1] = self._loss_history[t, 1:]
|
144 |
+
self._loss_history[t, -1] = loss
|
145 |
+
else:
|
146 |
+
self._loss_history[t, self._loss_counts[t]] = loss
|
147 |
+
self._loss_counts[t] += 1
|
148 |
+
|
149 |
+
def _warmed_up(self):
|
150 |
+
return (self._loss_counts == self.history_per_term).all()
|
gradio_cached_examples/25/Generated Images/3098beb2-718a-4d20-a8c4-350e6f4d706f/captions.json
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
{"/code/code/MDT_demo/gradio_cached_examples/25/Generated Images/3098beb2-718a-4d20-a8c4-350e6f4d706f/imagehtt65eku.png": null}
|
gradio_cached_examples/25/Generated Images/3098beb2-718a-4d20-a8c4-350e6f4d706f/imagehtt65eku.png
ADDED
![]() |
gradio_cached_examples/25/Generated Images/3f1d5e43-5a07-402b-b062-045a55ee88ad/captions.json
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
{"/code/code/MDT_demo/gradio_cached_examples/25/Generated Images/3f1d5e43-5a07-402b-b062-045a55ee88ad/imagejpi4i9g_.png": null}
|
gradio_cached_examples/25/Generated Images/3f1d5e43-5a07-402b-b062-045a55ee88ad/imagejpi4i9g_.png
ADDED
![]() |
gradio_cached_examples/25/Generated Images/46fdfba3-f8cc-49df-9f23-140a8a2488af/captions.json
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
{"/code/code/MDT_demo/gradio_cached_examples/25/Generated Images/46fdfba3-f8cc-49df-9f23-140a8a2488af/imageeuen5ewd.png": null}
|
gradio_cached_examples/25/Generated Images/46fdfba3-f8cc-49df-9f23-140a8a2488af/imageeuen5ewd.png
ADDED
![]() |
gradio_cached_examples/25/Generated Images/5bcc42d0-0401-45a6-b061-dabb7badf1a6/captions.json
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
{"/code/code/MDT_demo/gradio_cached_examples/25/Generated Images/5bcc42d0-0401-45a6-b061-dabb7badf1a6/imageb3nfp28a.png": null}
|
gradio_cached_examples/25/Generated Images/5bcc42d0-0401-45a6-b061-dabb7badf1a6/imageb3nfp28a.png
ADDED
![]() |
gradio_cached_examples/25/Generated Images/5e8ec3cf-77eb-4a14-b9a3-c2f99f52398b/captions.json
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
{"/code/code/MDT_demo/gradio_cached_examples/25/Generated Images/5e8ec3cf-77eb-4a14-b9a3-c2f99f52398b/imageglbae_fo.png": null}
|
gradio_cached_examples/25/Generated Images/5e8ec3cf-77eb-4a14-b9a3-c2f99f52398b/imageglbae_fo.png
ADDED
![]() |
gradio_cached_examples/25/log.csv
ADDED
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
Generated Images,flag,username,timestamp
|
2 |
+
/code/code/MDT_demo/gradio_cached_examples/25/Generated Images/46fdfba3-f8cc-49df-9f23-140a8a2488af,,,2023-06-05 12:07:03.450003
|
3 |
+
/code/code/MDT_demo/gradio_cached_examples/25/Generated Images/3f1d5e43-5a07-402b-b062-045a55ee88ad,,,2023-06-05 12:07:10.597645
|
4 |
+
/code/code/MDT_demo/gradio_cached_examples/25/Generated Images/5e8ec3cf-77eb-4a14-b9a3-c2f99f52398b,,,2023-06-05 12:07:17.710111
|
5 |
+
/code/code/MDT_demo/gradio_cached_examples/25/Generated Images/3098beb2-718a-4d20-a8c4-350e6f4d706f,,,2023-06-05 12:07:24.838688
|
6 |
+
/code/code/MDT_demo/gradio_cached_examples/25/Generated Images/5bcc42d0-0401-45a6-b061-dabb7badf1a6,,,2023-06-05 12:07:31.961238
|
imagenet_class_data.py
ADDED
@@ -0,0 +1,1003 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# https://gist.githubusercontent.com/yrevar/942d3a0ac09ec9e5eb3a/raw/238f720ff059c1f82f368259d1ca4ffa5dd8f9f5/imagenet1000_clsidx_to_labels.txt
|
2 |
+
|
3 |
+
IMAGENET_1K_CLASSES = \
|
4 |
+
{0: 'tench, Tinca tinca',
|
5 |
+
1: 'goldfish, Carassius auratus',
|
6 |
+
2: 'great white shark, white shark, man-eater, man-eating shark, Carcharodon carcharias',
|
7 |
+
3: 'tiger shark, Galeocerdo cuvieri',
|
8 |
+
4: 'hammerhead, hammerhead shark',
|
9 |
+
5: 'electric ray, crampfish, numbfish, torpedo',
|
10 |
+
6: 'stingray',
|
11 |
+
7: 'cock',
|
12 |
+
8: 'hen',
|
13 |
+
9: 'ostrich, Struthio camelus',
|
14 |
+
10: 'brambling, Fringilla montifringilla',
|
15 |
+
11: 'goldfinch, Carduelis carduelis',
|
16 |
+
12: 'house finch, linnet, Carpodacus mexicanus',
|
17 |
+
13: 'junco, snowbird',
|
18 |
+
14: 'indigo bunting, indigo finch, indigo bird, Passerina cyanea',
|
19 |
+
15: 'robin, American robin, Turdus migratorius',
|
20 |
+
16: 'bulbul',
|
21 |
+
17: 'jay',
|
22 |
+
18: 'magpie',
|
23 |
+
19: 'chickadee',
|
24 |
+
20: 'water ouzel, dipper',
|
25 |
+
21: 'kite',
|
26 |
+
22: 'bald eagle, American eagle, Haliaeetus leucocephalus',
|
27 |
+
23: 'vulture',
|
28 |
+
24: 'great grey owl, great gray owl, Strix nebulosa',
|
29 |
+
25: 'European fire salamander, Salamandra salamandra',
|
30 |
+
26: 'common newt, Triturus vulgaris',
|
31 |
+
27: 'eft',
|
32 |
+
28: 'spotted salamander, Ambystoma maculatum',
|
33 |
+
29: 'axolotl, mud puppy, Ambystoma mexicanum',
|
34 |
+
30: 'bullfrog, Rana catesbeiana',
|
35 |
+
31: 'tree frog, tree-frog',
|
36 |
+
32: 'tailed frog, bell toad, ribbed toad, tailed toad, Ascaphus trui',
|
37 |
+
33: 'loggerhead, loggerhead turtle, Caretta caretta',
|
38 |
+
34: 'leatherback turtle, leatherback, leathery turtle, Dermochelys coriacea',
|
39 |
+
35: 'mud turtle',
|
40 |
+
36: 'terrapin',
|
41 |
+
37: 'box turtle, box tortoise',
|
42 |
+
38: 'banded gecko',
|
43 |
+
39: 'common iguana, iguana, Iguana iguana',
|
44 |
+
40: 'American chameleon, anole, Anolis carolinensis',
|
45 |
+
41: 'whiptail, whiptail lizard',
|
46 |
+
42: 'agama',
|
47 |
+
43: 'frilled lizard, Chlamydosaurus kingi',
|
48 |
+
44: 'alligator lizard',
|
49 |
+
45: 'Gila monster, Heloderma suspectum',
|
50 |
+
46: 'green lizard, Lacerta viridis',
|
51 |
+
47: 'African chameleon, Chamaeleo chamaeleon',
|
52 |
+
48: 'Komodo dragon, Komodo lizard, dragon lizard, giant lizard, Varanus komodoensis',
|
53 |
+
49: 'African crocodile, Nile crocodile, Crocodylus niloticus',
|
54 |
+
50: 'American alligator, Alligator mississipiensis',
|
55 |
+
51: 'triceratops',
|
56 |
+
52: 'thunder snake, worm snake, Carphophis amoenus',
|
57 |
+
53: 'ringneck snake, ring-necked snake, ring snake',
|
58 |
+
54: 'hognose snake, puff adder, sand viper',
|
59 |
+
55: 'green snake, grass snake',
|
60 |
+
56: 'king snake, kingsnake',
|
61 |
+
57: 'garter snake, grass snake',
|
62 |
+
58: 'water snake',
|
63 |
+
59: 'vine snake',
|
64 |
+
60: 'night snake, Hypsiglena torquata',
|
65 |
+
61: 'boa constrictor, Constrictor constrictor',
|
66 |
+
62: 'rock python, rock snake, Python sebae',
|
67 |
+
63: 'Indian cobra, Naja naja',
|
68 |
+
64: 'green mamba',
|
69 |
+
65: 'sea snake',
|
70 |
+
66: 'horned viper, cerastes, sand viper, horned asp, Cerastes cornutus',
|
71 |
+
67: 'diamondback, diamondback rattlesnake, Crotalus adamanteus',
|
72 |
+
68: 'sidewinder, horned rattlesnake, Crotalus cerastes',
|
73 |
+
69: 'trilobite',
|
74 |
+
70: 'harvestman, daddy longlegs, Phalangium opilio',
|
75 |
+
71: 'scorpion',
|
76 |
+
72: 'black and gold garden spider, Argiope aurantia',
|
77 |
+
73: 'barn spider, Araneus cavaticus',
|
78 |
+
74: 'garden spider, Aranea diademata',
|
79 |
+
75: 'black widow, Latrodectus mactans',
|
80 |
+
76: 'tarantula',
|
81 |
+
77: 'wolf spider, hunting spider',
|
82 |
+
78: 'tick',
|
83 |
+
79: 'centipede',
|
84 |
+
80: 'black grouse',
|
85 |
+
81: 'ptarmigan',
|
86 |
+
82: 'ruffed grouse, partridge, Bonasa umbellus',
|
87 |
+
83: 'prairie chicken, prairie grouse, prairie fowl',
|
88 |
+
84: 'peacock',
|
89 |
+
85: 'quail',
|
90 |
+
86: 'partridge',
|
91 |
+
87: 'African grey, African gray, Psittacus erithacus',
|
92 |
+
88: 'macaw',
|
93 |
+
89: 'sulphur-crested cockatoo, Kakatoe galerita, Cacatua galerita',
|
94 |
+
90: 'lorikeet',
|
95 |
+
91: 'coucal',
|
96 |
+
92: 'bee eater',
|
97 |
+
93: 'hornbill',
|
98 |
+
94: 'hummingbird',
|
99 |
+
95: 'jacamar',
|
100 |
+
96: 'toucan',
|
101 |
+
97: 'drake',
|
102 |
+
98: 'red-breasted merganser, Mergus serrator',
|
103 |
+
99: 'goose',
|
104 |
+
100: 'black swan, Cygnus atratus',
|
105 |
+
101: 'tusker',
|
106 |
+
102: 'echidna, spiny anteater, anteater',
|
107 |
+
103: 'platypus, duckbill, duckbilled platypus, duck-billed platypus, Ornithorhynchus anatinus',
|
108 |
+
104: 'wallaby, brush kangaroo',
|
109 |
+
105: 'koala, koala bear, kangaroo bear, native bear, Phascolarctos cinereus',
|
110 |
+
106: 'wombat',
|
111 |
+
107: 'jellyfish',
|
112 |
+
108: 'sea anemone, anemone',
|
113 |
+
109: 'brain coral',
|
114 |
+
110: 'flatworm, platyhelminth',
|
115 |
+
111: 'nematode, nematode worm, roundworm',
|
116 |
+
112: 'conch',
|
117 |
+
113: 'snail',
|
118 |
+
114: 'slug',
|
119 |
+
115: 'sea slug, nudibranch',
|
120 |
+
116: 'chiton, coat-of-mail shell, sea cradle, polyplacophore',
|
121 |
+
117: 'chambered nautilus, pearly nautilus, nautilus',
|
122 |
+
118: 'Dungeness crab, Cancer magister',
|
123 |
+
119: 'rock crab, Cancer irroratus',
|
124 |
+
120: 'fiddler crab',
|
125 |
+
121: 'king crab, Alaska crab, Alaskan king crab, Alaska king crab, Paralithodes camtschatica',
|
126 |
+
122: 'American lobster, Northern lobster, Maine lobster, Homarus americanus',
|
127 |
+
123: 'spiny lobster, langouste, rock lobster, crawfish, crayfish, sea crawfish',
|
128 |
+
124: 'crayfish, crawfish, crawdad, crawdaddy',
|
129 |
+
125: 'hermit crab',
|
130 |
+
126: 'isopod',
|
131 |
+
127: 'white stork, Ciconia ciconia',
|
132 |
+
128: 'black stork, Ciconia nigra',
|
133 |
+
129: 'spoonbill',
|
134 |
+
130: 'flamingo',
|
135 |
+
131: 'little blue heron, Egretta caerulea',
|
136 |
+
132: 'American egret, great white heron, Egretta albus',
|
137 |
+
133: 'bittern',
|
138 |
+
134: 'crane',
|
139 |
+
135: 'limpkin, Aramus pictus',
|
140 |
+
136: 'European gallinule, Porphyrio porphyrio',
|
141 |
+
137: 'American coot, marsh hen, mud hen, water hen, Fulica americana',
|
142 |
+
138: 'bustard',
|
143 |
+
139: 'ruddy turnstone, Arenaria interpres',
|
144 |
+
140: 'red-backed sandpiper, dunlin, Erolia alpina',
|
145 |
+
141: 'redshank, Tringa totanus',
|
146 |
+
142: 'dowitcher',
|
147 |
+
143: 'oystercatcher, oyster catcher',
|
148 |
+
144: 'pelican',
|
149 |
+
145: 'king penguin, Aptenodytes patagonica',
|
150 |
+
146: 'albatross, mollymawk',
|
151 |
+
147: 'grey whale, gray whale, devilfish, Eschrichtius gibbosus, Eschrichtius robustus',
|
152 |
+
148: 'killer whale, killer, orca, grampus, sea wolf, Orcinus orca',
|
153 |
+
149: 'dugong, Dugong dugon',
|
154 |
+
150: 'sea lion',
|
155 |
+
151: 'Chihuahua',
|
156 |
+
152: 'Japanese spaniel',
|
157 |
+
153: 'Maltese dog, Maltese terrier, Maltese',
|
158 |
+
154: 'Pekinese, Pekingese, Peke',
|
159 |
+
155: 'Shih-Tzu',
|
160 |
+
156: 'Blenheim spaniel',
|
161 |
+
157: 'papillon',
|
162 |
+
158: 'toy terrier',
|
163 |
+
159: 'Rhodesian ridgeback',
|
164 |
+
160: 'Afghan hound, Afghan',
|
165 |
+
161: 'basset, basset hound',
|
166 |
+
162: 'beagle',
|
167 |
+
163: 'bloodhound, sleuthhound',
|
168 |
+
164: 'bluetick',
|
169 |
+
165: 'black-and-tan coonhound',
|
170 |
+
166: 'Walker hound, Walker foxhound',
|
171 |
+
167: 'English foxhound',
|
172 |
+
168: 'redbone',
|
173 |
+
169: 'borzoi, Russian wolfhound',
|
174 |
+
170: 'Irish wolfhound',
|
175 |
+
171: 'Italian greyhound',
|
176 |
+
172: 'whippet',
|
177 |
+
173: 'Ibizan hound, Ibizan Podenco',
|
178 |
+
174: 'Norwegian elkhound, elkhound',
|
179 |
+
175: 'otterhound, otter hound',
|
180 |
+
176: 'Saluki, gazelle hound',
|
181 |
+
177: 'Scottish deerhound, deerhound',
|
182 |
+
178: 'Weimaraner',
|
183 |
+
179: 'Staffordshire bullterrier, Staffordshire bull terrier',
|
184 |
+
180: 'American Staffordshire terrier, Staffordshire terrier, American pit bull terrier, pit bull terrier',
|
185 |
+
181: 'Bedlington terrier',
|
186 |
+
182: 'Border terrier',
|
187 |
+
183: 'Kerry blue terrier',
|
188 |
+
184: 'Irish terrier',
|
189 |
+
185: 'Norfolk terrier',
|
190 |
+
186: 'Norwich terrier',
|
191 |
+
187: 'Yorkshire terrier',
|
192 |
+
188: 'wire-haired fox terrier',
|
193 |
+
189: 'Lakeland terrier',
|
194 |
+
190: 'Sealyham terrier, Sealyham',
|
195 |
+
191: 'Airedale, Airedale terrier',
|
196 |
+
192: 'cairn, cairn terrier',
|
197 |
+
193: 'Australian terrier',
|
198 |
+
194: 'Dandie Dinmont, Dandie Dinmont terrier',
|
199 |
+
195: 'Boston bull, Boston terrier',
|
200 |
+
196: 'miniature schnauzer',
|
201 |
+
197: 'giant schnauzer',
|
202 |
+
198: 'standard schnauzer',
|
203 |
+
199: 'Scotch terrier, Scottish terrier, Scottie',
|
204 |
+
200: 'Tibetan terrier, chrysanthemum dog',
|
205 |
+
201: 'silky terrier, Sydney silky',
|
206 |
+
202: 'soft-coated wheaten terrier',
|
207 |
+
203: 'West Highland white terrier',
|
208 |
+
204: 'Lhasa, Lhasa apso',
|
209 |
+
205: 'flat-coated retriever',
|
210 |
+
206: 'curly-coated retriever',
|
211 |
+
207: 'golden retriever',
|
212 |
+
208: 'Labrador retriever',
|
213 |
+
209: 'Chesapeake Bay retriever',
|
214 |
+
210: 'German short-haired pointer',
|
215 |
+
211: 'vizsla, Hungarian pointer',
|
216 |
+
212: 'English setter',
|
217 |
+
213: 'Irish setter, red setter',
|
218 |
+
214: 'Gordon setter',
|
219 |
+
215: 'Brittany spaniel',
|
220 |
+
216: 'clumber, clumber spaniel',
|
221 |
+
217: 'English springer, English springer spaniel',
|
222 |
+
218: 'Welsh springer spaniel',
|
223 |
+
219: 'cocker spaniel, English cocker spaniel, cocker',
|
224 |
+
220: 'Sussex spaniel',
|
225 |
+
221: 'Irish water spaniel',
|
226 |
+
222: 'kuvasz',
|
227 |
+
223: 'schipperke',
|
228 |
+
224: 'groenendael',
|
229 |
+
225: 'malinois',
|
230 |
+
226: 'briard',
|
231 |
+
227: 'kelpie',
|
232 |
+
228: 'komondor',
|
233 |
+
229: 'Old English sheepdog, bobtail',
|
234 |
+
230: 'Shetland sheepdog, Shetland sheep dog, Shetland',
|
235 |
+
231: 'collie',
|
236 |
+
232: 'Border collie',
|
237 |
+
233: 'Bouvier des Flandres, Bouviers des Flandres',
|
238 |
+
234: 'Rottweiler',
|
239 |
+
235: 'German shepherd, German shepherd dog, German police dog, alsatian',
|
240 |
+
236: 'Doberman, Doberman pinscher',
|
241 |
+
237: 'miniature pinscher',
|
242 |
+
238: 'Greater Swiss Mountain dog',
|
243 |
+
239: 'Bernese mountain dog',
|
244 |
+
240: 'Appenzeller',
|
245 |
+
241: 'EntleBucher',
|
246 |
+
242: 'boxer',
|
247 |
+
243: 'bull mastiff',
|
248 |
+
244: 'Tibetan mastiff',
|
249 |
+
245: 'French bulldog',
|
250 |
+
246: 'Great Dane',
|
251 |
+
247: 'Saint Bernard, St Bernard',
|
252 |
+
248: 'Eskimo dog, husky',
|
253 |
+
249: 'malamute, malemute, Alaskan malamute',
|
254 |
+
250: 'Siberian husky',
|
255 |
+
251: 'dalmatian, coach dog, carriage dog',
|
256 |
+
252: 'affenpinscher, monkey pinscher, monkey dog',
|
257 |
+
253: 'basenji',
|
258 |
+
254: 'pug, pug-dog',
|
259 |
+
255: 'Leonberg',
|
260 |
+
256: 'Newfoundland, Newfoundland dog',
|
261 |
+
257: 'Great Pyrenees',
|
262 |
+
258: 'Samoyed, Samoyede',
|
263 |
+
259: 'Pomeranian',
|
264 |
+
260: 'chow, chow chow',
|
265 |
+
261: 'keeshond',
|
266 |
+
262: 'Brabancon griffon',
|
267 |
+
263: 'Pembroke, Pembroke Welsh corgi',
|
268 |
+
264: 'Cardigan, Cardigan Welsh corgi',
|
269 |
+
265: 'toy poodle',
|
270 |
+
266: 'miniature poodle',
|
271 |
+
267: 'standard poodle',
|
272 |
+
268: 'Mexican hairless',
|
273 |
+
269: 'timber wolf, grey wolf, gray wolf, Canis lupus',
|
274 |
+
270: 'white wolf, Arctic wolf, Canis lupus tundrarum',
|
275 |
+
271: 'red wolf, maned wolf, Canis rufus, Canis niger',
|
276 |
+
272: 'coyote, prairie wolf, brush wolf, Canis latrans',
|
277 |
+
273: 'dingo, warrigal, warragal, Canis dingo',
|
278 |
+
274: 'dhole, Cuon alpinus',
|
279 |
+
275: 'African hunting dog, hyena dog, Cape hunting dog, Lycaon pictus',
|
280 |
+
276: 'hyena, hyaena',
|
281 |
+
277: 'red fox, Vulpes vulpes',
|
282 |
+
278: 'kit fox, Vulpes macrotis',
|
283 |
+
279: 'Arctic fox, white fox, Alopex lagopus',
|
284 |
+
280: 'grey fox, gray fox, Urocyon cinereoargenteus',
|
285 |
+
281: 'tabby, tabby cat',
|
286 |
+
282: 'tiger cat',
|
287 |
+
283: 'Persian cat',
|
288 |
+
284: 'Siamese cat, Siamese',
|
289 |
+
285: 'Egyptian cat',
|
290 |
+
286: 'cougar, puma, catamount, mountain lion, painter, panther, Felis concolor',
|
291 |
+
287: 'lynx, catamount',
|
292 |
+
288: 'leopard, Panthera pardus',
|
293 |
+
289: 'snow leopard, ounce, Panthera uncia',
|
294 |
+
290: 'jaguar, panther, Panthera onca, Felis onca',
|
295 |
+
291: 'lion, king of beasts, Panthera leo',
|
296 |
+
292: 'tiger, Panthera tigris',
|
297 |
+
293: 'cheetah, chetah, Acinonyx jubatus',
|
298 |
+
294: 'brown bear, bruin, Ursus arctos',
|
299 |
+
295: 'American black bear, black bear, Ursus americanus, Euarctos americanus',
|
300 |
+
296: 'ice bear, polar bear, Ursus Maritimus, Thalarctos maritimus',
|
301 |
+
297: 'sloth bear, Melursus ursinus, Ursus ursinus',
|
302 |
+
298: 'mongoose',
|
303 |
+
299: 'meerkat, mierkat',
|
304 |
+
300: 'tiger beetle',
|
305 |
+
301: 'ladybug, ladybeetle, lady beetle, ladybird, ladybird beetle',
|
306 |
+
302: 'ground beetle, carabid beetle',
|
307 |
+
303: 'long-horned beetle, longicorn, longicorn beetle',
|
308 |
+
304: 'leaf beetle, chrysomelid',
|
309 |
+
305: 'dung beetle',
|
310 |
+
306: 'rhinoceros beetle',
|
311 |
+
307: 'weevil',
|
312 |
+
308: 'fly',
|
313 |
+
309: 'bee',
|
314 |
+
310: 'ant, emmet, pismire',
|
315 |
+
311: 'grasshopper, hopper',
|
316 |
+
312: 'cricket',
|
317 |
+
313: 'walking stick, walkingstick, stick insect',
|
318 |
+
314: 'cockroach, roach',
|
319 |
+
315: 'mantis, mantid',
|
320 |
+
316: 'cicada, cicala',
|
321 |
+
317: 'leafhopper',
|
322 |
+
318: 'lacewing, lacewing fly',
|
323 |
+
319: "dragonfly, darning needle, devil's darning needle, sewing needle, snake feeder, snake doctor, mosquito hawk, skeeter hawk",
|
324 |
+
320: 'damselfly',
|
325 |
+
321: 'admiral',
|
326 |
+
322: 'ringlet, ringlet butterfly',
|
327 |
+
323: 'monarch, monarch butterfly, milkweed butterfly, Danaus plexippus',
|
328 |
+
324: 'cabbage butterfly',
|
329 |
+
325: 'sulphur butterfly, sulfur butterfly',
|
330 |
+
326: 'lycaenid, lycaenid butterfly',
|
331 |
+
327: 'starfish, sea star',
|
332 |
+
328: 'sea urchin',
|
333 |
+
329: 'sea cucumber, holothurian',
|
334 |
+
330: 'wood rabbit, cottontail, cottontail rabbit',
|
335 |
+
331: 'hare',
|
336 |
+
332: 'Angora, Angora rabbit',
|
337 |
+
333: 'hamster',
|
338 |
+
334: 'porcupine, hedgehog',
|
339 |
+
335: 'fox squirrel, eastern fox squirrel, Sciurus niger',
|
340 |
+
336: 'marmot',
|
341 |
+
337: 'beaver',
|
342 |
+
338: 'guinea pig, Cavia cobaya',
|
343 |
+
339: 'sorrel',
|
344 |
+
340: 'zebra',
|
345 |
+
341: 'hog, pig, grunter, squealer, Sus scrofa',
|
346 |
+
342: 'wild boar, boar, Sus scrofa',
|
347 |
+
343: 'warthog',
|
348 |
+
344: 'hippopotamus, hippo, river horse, Hippopotamus amphibius',
|
349 |
+
345: 'ox',
|
350 |
+
346: 'water buffalo, water ox, Asiatic buffalo, Bubalus bubalis',
|
351 |
+
347: 'bison',
|
352 |
+
348: 'ram, tup',
|
353 |
+
349: 'bighorn, bighorn sheep, cimarron, Rocky Mountain bighorn, Rocky Mountain sheep, Ovis canadensis',
|
354 |
+
350: 'ibex, Capra ibex',
|
355 |
+
351: 'hartebeest',
|
356 |
+
352: 'impala, Aepyceros melampus',
|
357 |
+
353: 'gazelle',
|
358 |
+
354: 'Arabian camel, dromedary, Camelus dromedarius',
|
359 |
+
355: 'llama',
|
360 |
+
356: 'weasel',
|
361 |
+
357: 'mink',
|
362 |
+
358: 'polecat, fitch, foulmart, foumart, Mustela putorius',
|
363 |
+
359: 'black-footed ferret, ferret, Mustela nigripes',
|
364 |
+
360: 'otter',
|
365 |
+
361: 'skunk, polecat, wood pussy',
|
366 |
+
362: 'badger',
|
367 |
+
363: 'armadillo',
|
368 |
+
364: 'three-toed sloth, ai, Bradypus tridactylus',
|
369 |
+
365: 'orangutan, orang, orangutang, Pongo pygmaeus',
|
370 |
+
366: 'gorilla, Gorilla gorilla',
|
371 |
+
367: 'chimpanzee, chimp, Pan troglodytes',
|
372 |
+
368: 'gibbon, Hylobates lar',
|
373 |
+
369: 'siamang, Hylobates syndactylus, Symphalangus syndactylus',
|
374 |
+
370: 'guenon, guenon monkey',
|
375 |
+
371: 'patas, hussar monkey, Erythrocebus patas',
|
376 |
+
372: 'baboon',
|
377 |
+
373: 'macaque',
|
378 |
+
374: 'langur',
|
379 |
+
375: 'colobus, colobus monkey',
|
380 |
+
376: 'proboscis monkey, Nasalis larvatus',
|
381 |
+
377: 'marmoset',
|
382 |
+
378: 'capuchin, ringtail, Cebus capucinus',
|
383 |
+
379: 'howler monkey, howler',
|
384 |
+
380: 'titi, titi monkey',
|
385 |
+
381: 'spider monkey, Ateles geoffroyi',
|
386 |
+
382: 'squirrel monkey, Saimiri sciureus',
|
387 |
+
383: 'Madagascar cat, ring-tailed lemur, Lemur catta',
|
388 |
+
384: 'indri, indris, Indri indri, Indri brevicaudatus',
|
389 |
+
385: 'Indian elephant, Elephas maximus',
|
390 |
+
386: 'African elephant, Loxodonta africana',
|
391 |
+
387: 'lesser panda, red panda, panda, bear cat, cat bear, Ailurus fulgens',
|
392 |
+
388: 'giant panda, panda, panda bear, coon bear, Ailuropoda melanoleuca',
|
393 |
+
389: 'barracouta, snoek',
|
394 |
+
390: 'eel',
|
395 |
+
391: 'coho, cohoe, coho salmon, blue jack, silver salmon, Oncorhynchus kisutch',
|
396 |
+
392: 'rock beauty, Holocanthus tricolor',
|
397 |
+
393: 'anemone fish',
|
398 |
+
394: 'sturgeon',
|
399 |
+
395: 'gar, garfish, garpike, billfish, Lepisosteus osseus',
|
400 |
+
396: 'lionfish',
|
401 |
+
397: 'puffer, pufferfish, blowfish, globefish',
|
402 |
+
398: 'abacus',
|
403 |
+
399: 'abaya',
|
404 |
+
400: "academic gown, academic robe, judge's robe",
|
405 |
+
401: 'accordion, piano accordion, squeeze box',
|
406 |
+
402: 'acoustic guitar',
|
407 |
+
403: 'aircraft carrier, carrier, flattop, attack aircraft carrier',
|
408 |
+
404: 'airliner',
|
409 |
+
405: 'airship, dirigible',
|
410 |
+
406: 'altar',
|
411 |
+
407: 'ambulance',
|
412 |
+
408: 'amphibian, amphibious vehicle',
|
413 |
+
409: 'analog clock',
|
414 |
+
410: 'apiary, bee house',
|
415 |
+
411: 'apron',
|
416 |
+
412: 'ashcan, trash can, garbage can, wastebin, ash bin, ash-bin, ashbin, dustbin, trash barrel, trash bin',
|
417 |
+
413: 'assault rifle, assault gun',
|
418 |
+
414: 'backpack, back pack, knapsack, packsack, rucksack, haversack',
|
419 |
+
415: 'bakery, bakeshop, bakehouse',
|
420 |
+
416: 'balance beam, beam',
|
421 |
+
417: 'balloon',
|
422 |
+
418: 'ballpoint, ballpoint pen, ballpen, Biro',
|
423 |
+
419: 'Band Aid',
|
424 |
+
420: 'banjo',
|
425 |
+
421: 'bannister, banister, balustrade, balusters, handrail',
|
426 |
+
422: 'barbell',
|
427 |
+
423: 'barber chair',
|
428 |
+
424: 'barbershop',
|
429 |
+
425: 'barn',
|
430 |
+
426: 'barometer',
|
431 |
+
427: 'barrel, cask',
|
432 |
+
428: 'barrow, garden cart, lawn cart, wheelbarrow',
|
433 |
+
429: 'baseball',
|
434 |
+
430: 'basketball',
|
435 |
+
431: 'bassinet',
|
436 |
+
432: 'bassoon',
|
437 |
+
433: 'bathing cap, swimming cap',
|
438 |
+
434: 'bath towel',
|
439 |
+
435: 'bathtub, bathing tub, bath, tub',
|
440 |
+
436: 'beach wagon, station wagon, wagon, estate car, beach waggon, station waggon, waggon',
|
441 |
+
437: 'beacon, lighthouse, beacon light, pharos',
|
442 |
+
438: 'beaker',
|
443 |
+
439: 'bearskin, busby, shako',
|
444 |
+
440: 'beer bottle',
|
445 |
+
441: 'beer glass',
|
446 |
+
442: 'bell cote, bell cot',
|
447 |
+
443: 'bib',
|
448 |
+
444: 'bicycle-built-for-two, tandem bicycle, tandem',
|
449 |
+
445: 'bikini, two-piece',
|
450 |
+
446: 'binder, ring-binder',
|
451 |
+
447: 'binoculars, field glasses, opera glasses',
|
452 |
+
448: 'birdhouse',
|
453 |
+
449: 'boathouse',
|
454 |
+
450: 'bobsled, bobsleigh, bob',
|
455 |
+
451: 'bolo tie, bolo, bola tie, bola',
|
456 |
+
452: 'bonnet, poke bonnet',
|
457 |
+
453: 'bookcase',
|
458 |
+
454: 'bookshop, bookstore, bookstall',
|
459 |
+
455: 'bottlecap',
|
460 |
+
456: 'bow',
|
461 |
+
457: 'bow tie, bow-tie, bowtie',
|
462 |
+
458: 'brass, memorial tablet, plaque',
|
463 |
+
459: 'brassiere, bra, bandeau',
|
464 |
+
460: 'breakwater, groin, groyne, mole, bulwark, seawall, jetty',
|
465 |
+
461: 'breastplate, aegis, egis',
|
466 |
+
462: 'broom',
|
467 |
+
463: 'bucket, pail',
|
468 |
+
464: 'buckle',
|
469 |
+
465: 'bulletproof vest',
|
470 |
+
466: 'bullet train, bullet',
|
471 |
+
467: 'butcher shop, meat market',
|
472 |
+
468: 'cab, hack, taxi, taxicab',
|
473 |
+
469: 'caldron, cauldron',
|
474 |
+
470: 'candle, taper, wax light',
|
475 |
+
471: 'cannon',
|
476 |
+
472: 'canoe',
|
477 |
+
473: 'can opener, tin opener',
|
478 |
+
474: 'cardigan',
|
479 |
+
475: 'car mirror',
|
480 |
+
476: 'carousel, carrousel, merry-go-round, roundabout, whirligig',
|
481 |
+
477: "carpenter's kit, tool kit",
|
482 |
+
478: 'carton',
|
483 |
+
479: 'car wheel',
|
484 |
+
480: 'cash machine, cash dispenser, automated teller machine, automatic teller machine, automated teller, automatic teller, ATM',
|
485 |
+
481: 'cassette',
|
486 |
+
482: 'cassette player',
|
487 |
+
483: 'castle',
|
488 |
+
484: 'catamaran',
|
489 |
+
485: 'CD player',
|
490 |
+
486: 'cello, violoncello',
|
491 |
+
487: 'cellular telephone, cellular phone, cellphone, cell, mobile phone',
|
492 |
+
488: 'chain',
|
493 |
+
489: 'chainlink fence',
|
494 |
+
490: 'chain mail, ring mail, mail, chain armor, chain armour, ring armor, ring armour',
|
495 |
+
491: 'chain saw, chainsaw',
|
496 |
+
492: 'chest',
|
497 |
+
493: 'chiffonier, commode',
|
498 |
+
494: 'chime, bell, gong',
|
499 |
+
495: 'china cabinet, china closet',
|
500 |
+
496: 'Christmas stocking',
|
501 |
+
497: 'church, church building',
|
502 |
+
498: 'cinema, movie theater, movie theatre, movie house, picture palace',
|
503 |
+
499: 'cleaver, meat cleaver, chopper',
|
504 |
+
500: 'cliff dwelling',
|
505 |
+
501: 'cloak',
|
506 |
+
502: 'clog, geta, patten, sabot',
|
507 |
+
503: 'cocktail shaker',
|
508 |
+
504: 'coffee mug',
|
509 |
+
505: 'coffeepot',
|
510 |
+
506: 'coil, spiral, volute, whorl, helix',
|
511 |
+
507: 'combination lock',
|
512 |
+
508: 'computer keyboard, keypad',
|
513 |
+
509: 'confectionery, confectionary, candy store',
|
514 |
+
510: 'container ship, containership, container vessel',
|
515 |
+
511: 'convertible',
|
516 |
+
512: 'corkscrew, bottle screw',
|
517 |
+
513: 'cornet, horn, trumpet, trump',
|
518 |
+
514: 'cowboy boot',
|
519 |
+
515: 'cowboy hat, ten-gallon hat',
|
520 |
+
516: 'cradle',
|
521 |
+
517: 'crane',
|
522 |
+
518: 'crash helmet',
|
523 |
+
519: 'crate',
|
524 |
+
520: 'crib, cot',
|
525 |
+
521: 'Crock Pot',
|
526 |
+
522: 'croquet ball',
|
527 |
+
523: 'crutch',
|
528 |
+
524: 'cuirass',
|
529 |
+
525: 'dam, dike, dyke',
|
530 |
+
526: 'desk',
|
531 |
+
527: 'desktop computer',
|
532 |
+
528: 'dial telephone, dial phone',
|
533 |
+
529: 'diaper, nappy, napkin',
|
534 |
+
530: 'digital clock',
|
535 |
+
531: 'digital watch',
|
536 |
+
532: 'dining table, board',
|
537 |
+
533: 'dishrag, dishcloth',
|
538 |
+
534: 'dishwasher, dish washer, dishwashing machine',
|
539 |
+
535: 'disk brake, disc brake',
|
540 |
+
536: 'dock, dockage, docking facility',
|
541 |
+
537: 'dogsled, dog sled, dog sleigh',
|
542 |
+
538: 'dome',
|
543 |
+
539: 'doormat, welcome mat',
|
544 |
+
540: 'drilling platform, offshore rig',
|
545 |
+
541: 'drum, membranophone, tympan',
|
546 |
+
542: 'drumstick',
|
547 |
+
543: 'dumbbell',
|
548 |
+
544: 'Dutch oven',
|
549 |
+
545: 'electric fan, blower',
|
550 |
+
546: 'electric guitar',
|
551 |
+
547: 'electric locomotive',
|
552 |
+
548: 'entertainment center',
|
553 |
+
549: 'envelope',
|
554 |
+
550: 'espresso maker',
|
555 |
+
551: 'face powder',
|
556 |
+
552: 'feather boa, boa',
|
557 |
+
553: 'file, file cabinet, filing cabinet',
|
558 |
+
554: 'fireboat',
|
559 |
+
555: 'fire engine, fire truck',
|
560 |
+
556: 'fire screen, fireguard',
|
561 |
+
557: 'flagpole, flagstaff',
|
562 |
+
558: 'flute, transverse flute',
|
563 |
+
559: 'folding chair',
|
564 |
+
560: 'football helmet',
|
565 |
+
561: 'forklift',
|
566 |
+
562: 'fountain',
|
567 |
+
563: 'fountain pen',
|
568 |
+
564: 'four-poster',
|
569 |
+
565: 'freight car',
|
570 |
+
566: 'French horn, horn',
|
571 |
+
567: 'frying pan, frypan, skillet',
|
572 |
+
568: 'fur coat',
|
573 |
+
569: 'garbage truck, dustcart',
|
574 |
+
570: 'gasmask, respirator, gas helmet',
|
575 |
+
571: 'gas pump, gasoline pump, petrol pump, island dispenser',
|
576 |
+
572: 'goblet',
|
577 |
+
573: 'go-kart',
|
578 |
+
574: 'golf ball',
|
579 |
+
575: 'golfcart, golf cart',
|
580 |
+
576: 'gondola',
|
581 |
+
577: 'gong, tam-tam',
|
582 |
+
578: 'gown',
|
583 |
+
579: 'grand piano, grand',
|
584 |
+
580: 'greenhouse, nursery, glasshouse',
|
585 |
+
581: 'grille, radiator grille',
|
586 |
+
582: 'grocery store, grocery, food market, market',
|
587 |
+
583: 'guillotine',
|
588 |
+
584: 'hair slide',
|
589 |
+
585: 'hair spray',
|
590 |
+
586: 'half track',
|
591 |
+
587: 'hammer',
|
592 |
+
588: 'hamper',
|
593 |
+
589: 'hand blower, blow dryer, blow drier, hair dryer, hair drier',
|
594 |
+
590: 'hand-held computer, hand-held microcomputer',
|
595 |
+
591: 'handkerchief, hankie, hanky, hankey',
|
596 |
+
592: 'hard disc, hard disk, fixed disk',
|
597 |
+
593: 'harmonica, mouth organ, harp, mouth harp',
|
598 |
+
594: 'harp',
|
599 |
+
595: 'harvester, reaper',
|
600 |
+
596: 'hatchet',
|
601 |
+
597: 'holster',
|
602 |
+
598: 'home theater, home theatre',
|
603 |
+
599: 'honeycomb',
|
604 |
+
600: 'hook, claw',
|
605 |
+
601: 'hoopskirt, crinoline',
|
606 |
+
602: 'horizontal bar, high bar',
|
607 |
+
603: 'horse cart, horse-cart',
|
608 |
+
604: 'hourglass',
|
609 |
+
605: 'iPod',
|
610 |
+
606: 'iron, smoothing iron',
|
611 |
+
607: "jack-o'-lantern",
|
612 |
+
608: 'jean, blue jean, denim',
|
613 |
+
609: 'jeep, landrover',
|
614 |
+
610: 'jersey, T-shirt, tee shirt',
|
615 |
+
611: 'jigsaw puzzle',
|
616 |
+
612: 'jinrikisha, ricksha, rickshaw',
|
617 |
+
613: 'joystick',
|
618 |
+
614: 'kimono',
|
619 |
+
615: 'knee pad',
|
620 |
+
616: 'knot',
|
621 |
+
617: 'lab coat, laboratory coat',
|
622 |
+
618: 'ladle',
|
623 |
+
619: 'lampshade, lamp shade',
|
624 |
+
620: 'laptop, laptop computer',
|
625 |
+
621: 'lawn mower, mower',
|
626 |
+
622: 'lens cap, lens cover',
|
627 |
+
623: 'letter opener, paper knife, paperknife',
|
628 |
+
624: 'library',
|
629 |
+
625: 'lifeboat',
|
630 |
+
626: 'lighter, light, igniter, ignitor',
|
631 |
+
627: 'limousine, limo',
|
632 |
+
628: 'liner, ocean liner',
|
633 |
+
629: 'lipstick, lip rouge',
|
634 |
+
630: 'Loafer',
|
635 |
+
631: 'lotion',
|
636 |
+
632: 'loudspeaker, speaker, speaker unit, loudspeaker system, speaker system',
|
637 |
+
633: "loupe, jeweler's loupe",
|
638 |
+
634: 'lumbermill, sawmill',
|
639 |
+
635: 'magnetic compass',
|
640 |
+
636: 'mailbag, postbag',
|
641 |
+
637: 'mailbox, letter box',
|
642 |
+
638: 'maillot',
|
643 |
+
639: 'maillot, tank suit',
|
644 |
+
640: 'manhole cover',
|
645 |
+
641: 'maraca',
|
646 |
+
642: 'marimba, xylophone',
|
647 |
+
643: 'mask',
|
648 |
+
644: 'matchstick',
|
649 |
+
645: 'maypole',
|
650 |
+
646: 'maze, labyrinth',
|
651 |
+
647: 'measuring cup',
|
652 |
+
648: 'medicine chest, medicine cabinet',
|
653 |
+
649: 'megalith, megalithic structure',
|
654 |
+
650: 'microphone, mike',
|
655 |
+
651: 'microwave, microwave oven',
|
656 |
+
652: 'military uniform',
|
657 |
+
653: 'milk can',
|
658 |
+
654: 'minibus',
|
659 |
+
655: 'miniskirt, mini',
|
660 |
+
656: 'minivan',
|
661 |
+
657: 'missile',
|
662 |
+
658: 'mitten',
|
663 |
+
659: 'mixing bowl',
|
664 |
+
660: 'mobile home, manufactured home',
|
665 |
+
661: 'Model T',
|
666 |
+
662: 'modem',
|
667 |
+
663: 'monastery',
|
668 |
+
664: 'monitor',
|
669 |
+
665: 'moped',
|
670 |
+
666: 'mortar',
|
671 |
+
667: 'mortarboard',
|
672 |
+
668: 'mosque',
|
673 |
+
669: 'mosquito net',
|
674 |
+
670: 'motor scooter, scooter',
|
675 |
+
671: 'mountain bike, all-terrain bike, off-roader',
|
676 |
+
672: 'mountain tent',
|
677 |
+
673: 'mouse, computer mouse',
|
678 |
+
674: 'mousetrap',
|
679 |
+
675: 'moving van',
|
680 |
+
676: 'muzzle',
|
681 |
+
677: 'nail',
|
682 |
+
678: 'neck brace',
|
683 |
+
679: 'necklace',
|
684 |
+
680: 'nipple',
|
685 |
+
681: 'notebook, notebook computer',
|
686 |
+
682: 'obelisk',
|
687 |
+
683: 'oboe, hautboy, hautbois',
|
688 |
+
684: 'ocarina, sweet potato',
|
689 |
+
685: 'odometer, hodometer, mileometer, milometer',
|
690 |
+
686: 'oil filter',
|
691 |
+
687: 'organ, pipe organ',
|
692 |
+
688: 'oscilloscope, scope, cathode-ray oscilloscope, CRO',
|
693 |
+
689: 'overskirt',
|
694 |
+
690: 'oxcart',
|
695 |
+
691: 'oxygen mask',
|
696 |
+
692: 'packet',
|
697 |
+
693: 'paddle, boat paddle',
|
698 |
+
694: 'paddlewheel, paddle wheel',
|
699 |
+
695: 'padlock',
|
700 |
+
696: 'paintbrush',
|
701 |
+
697: "pajama, pyjama, pj's, jammies",
|
702 |
+
698: 'palace',
|
703 |
+
699: 'panpipe, pandean pipe, syrinx',
|
704 |
+
700: 'paper towel',
|
705 |
+
701: 'parachute, chute',
|
706 |
+
702: 'parallel bars, bars',
|
707 |
+
703: 'park bench',
|
708 |
+
704: 'parking meter',
|
709 |
+
705: 'passenger car, coach, carriage',
|
710 |
+
706: 'patio, terrace',
|
711 |
+
707: 'pay-phone, pay-station',
|
712 |
+
708: 'pedestal, plinth, footstall',
|
713 |
+
709: 'pencil box, pencil case',
|
714 |
+
710: 'pencil sharpener',
|
715 |
+
711: 'perfume, essence',
|
716 |
+
712: 'Petri dish',
|
717 |
+
713: 'photocopier',
|
718 |
+
714: 'pick, plectrum, plectron',
|
719 |
+
715: 'pickelhaube',
|
720 |
+
716: 'picket fence, paling',
|
721 |
+
717: 'pickup, pickup truck',
|
722 |
+
718: 'pier',
|
723 |
+
719: 'piggy bank, penny bank',
|
724 |
+
720: 'pill bottle',
|
725 |
+
721: 'pillow',
|
726 |
+
722: 'ping-pong ball',
|
727 |
+
723: 'pinwheel',
|
728 |
+
724: 'pirate, pirate ship',
|
729 |
+
725: 'pitcher, ewer',
|
730 |
+
726: "plane, carpenter's plane, woodworking plane",
|
731 |
+
727: 'planetarium',
|
732 |
+
728: 'plastic bag',
|
733 |
+
729: 'plate rack',
|
734 |
+
730: 'plow, plough',
|
735 |
+
731: "plunger, plumber's helper",
|
736 |
+
732: 'Polaroid camera, Polaroid Land camera',
|
737 |
+
733: 'pole',
|
738 |
+
734: 'police van, police wagon, paddy wagon, patrol wagon, wagon, black Maria',
|
739 |
+
735: 'poncho',
|
740 |
+
736: 'pool table, billiard table, snooker table',
|
741 |
+
737: 'pop bottle, soda bottle',
|
742 |
+
738: 'pot, flowerpot',
|
743 |
+
739: "potter's wheel",
|
744 |
+
740: 'power drill',
|
745 |
+
741: 'prayer rug, prayer mat',
|
746 |
+
742: 'printer',
|
747 |
+
743: 'prison, prison house',
|
748 |
+
744: 'projectile, missile',
|
749 |
+
745: 'projector',
|
750 |
+
746: 'puck, hockey puck',
|
751 |
+
747: 'punching bag, punch bag, punching ball, punchball',
|
752 |
+
748: 'purse',
|
753 |
+
749: 'quill, quill pen',
|
754 |
+
750: 'quilt, comforter, comfort, puff',
|
755 |
+
751: 'racer, race car, racing car',
|
756 |
+
752: 'racket, racquet',
|
757 |
+
753: 'radiator',
|
758 |
+
754: 'radio, wireless',
|
759 |
+
755: 'radio telescope, radio reflector',
|
760 |
+
756: 'rain barrel',
|
761 |
+
757: 'recreational vehicle, RV, R.V.',
|
762 |
+
758: 'reel',
|
763 |
+
759: 'reflex camera',
|
764 |
+
760: 'refrigerator, icebox',
|
765 |
+
761: 'remote control, remote',
|
766 |
+
762: 'restaurant, eating house, eating place, eatery',
|
767 |
+
763: 'revolver, six-gun, six-shooter',
|
768 |
+
764: 'rifle',
|
769 |
+
765: 'rocking chair, rocker',
|
770 |
+
766: 'rotisserie',
|
771 |
+
767: 'rubber eraser, rubber, pencil eraser',
|
772 |
+
768: 'rugby ball',
|
773 |
+
769: 'rule, ruler',
|
774 |
+
770: 'running shoe',
|
775 |
+
771: 'safe',
|
776 |
+
772: 'safety pin',
|
777 |
+
773: 'saltshaker, salt shaker',
|
778 |
+
774: 'sandal',
|
779 |
+
775: 'sarong',
|
780 |
+
776: 'sax, saxophone',
|
781 |
+
777: 'scabbard',
|
782 |
+
778: 'scale, weighing machine',
|
783 |
+
779: 'school bus',
|
784 |
+
780: 'schooner',
|
785 |
+
781: 'scoreboard',
|
786 |
+
782: 'screen, CRT screen',
|
787 |
+
783: 'screw',
|
788 |
+
784: 'screwdriver',
|
789 |
+
785: 'seat belt, seatbelt',
|
790 |
+
786: 'sewing machine',
|
791 |
+
787: 'shield, buckler',
|
792 |
+
788: 'shoe shop, shoe-shop, shoe store',
|
793 |
+
789: 'shoji',
|
794 |
+
790: 'shopping basket',
|
795 |
+
791: 'shopping cart',
|
796 |
+
792: 'shovel',
|
797 |
+
793: 'shower cap',
|
798 |
+
794: 'shower curtain',
|
799 |
+
795: 'ski',
|
800 |
+
796: 'ski mask',
|
801 |
+
797: 'sleeping bag',
|
802 |
+
798: 'slide rule, slipstick',
|
803 |
+
799: 'sliding door',
|
804 |
+
800: 'slot, one-armed bandit',
|
805 |
+
801: 'snorkel',
|
806 |
+
802: 'snowmobile',
|
807 |
+
803: 'snowplow, snowplough',
|
808 |
+
804: 'soap dispenser',
|
809 |
+
805: 'soccer ball',
|
810 |
+
806: 'sock',
|
811 |
+
807: 'solar dish, solar collector, solar furnace',
|
812 |
+
808: 'sombrero',
|
813 |
+
809: 'soup bowl',
|
814 |
+
810: 'space bar',
|
815 |
+
811: 'space heater',
|
816 |
+
812: 'space shuttle',
|
817 |
+
813: 'spatula',
|
818 |
+
814: 'speedboat',
|
819 |
+
815: "spider web, spider's web",
|
820 |
+
816: 'spindle',
|
821 |
+
817: 'sports car, sport car',
|
822 |
+
818: 'spotlight, spot',
|
823 |
+
819: 'stage',
|
824 |
+
820: 'steam locomotive',
|
825 |
+
821: 'steel arch bridge',
|
826 |
+
822: 'steel drum',
|
827 |
+
823: 'stethoscope',
|
828 |
+
824: 'stole',
|
829 |
+
825: 'stone wall',
|
830 |
+
826: 'stopwatch, stop watch',
|
831 |
+
827: 'stove',
|
832 |
+
828: 'strainer',
|
833 |
+
829: 'streetcar, tram, tramcar, trolley, trolley car',
|
834 |
+
830: 'stretcher',
|
835 |
+
831: 'studio couch, day bed',
|
836 |
+
832: 'stupa, tope',
|
837 |
+
833: 'submarine, pigboat, sub, U-boat',
|
838 |
+
834: 'suit, suit of clothes',
|
839 |
+
835: 'sundial',
|
840 |
+
836: 'sunglass',
|
841 |
+
837: 'sunglasses, dark glasses, shades',
|
842 |
+
838: 'sunscreen, sunblock, sun blocker',
|
843 |
+
839: 'suspension bridge',
|
844 |
+
840: 'swab, swob, mop',
|
845 |
+
841: 'sweatshirt',
|
846 |
+
842: 'swimming trunks, bathing trunks',
|
847 |
+
843: 'swing',
|
848 |
+
844: 'switch, electric switch, electrical switch',
|
849 |
+
845: 'syringe',
|
850 |
+
846: 'table lamp',
|
851 |
+
847: 'tank, army tank, armored combat vehicle, armoured combat vehicle',
|
852 |
+
848: 'tape player',
|
853 |
+
849: 'teapot',
|
854 |
+
850: 'teddy, teddy bear',
|
855 |
+
851: 'television, television system',
|
856 |
+
852: 'tennis ball',
|
857 |
+
853: 'thatch, thatched roof',
|
858 |
+
854: 'theater curtain, theatre curtain',
|
859 |
+
855: 'thimble',
|
860 |
+
856: 'thresher, thrasher, threshing machine',
|
861 |
+
857: 'throne',
|
862 |
+
858: 'tile roof',
|
863 |
+
859: 'toaster',
|
864 |
+
860: 'tobacco shop, tobacconist shop, tobacconist',
|
865 |
+
861: 'toilet seat',
|
866 |
+
862: 'torch',
|
867 |
+
863: 'totem pole',
|
868 |
+
864: 'tow truck, tow car, wrecker',
|
869 |
+
865: 'toyshop',
|
870 |
+
866: 'tractor',
|
871 |
+
867: 'trailer truck, tractor trailer, trucking rig, rig, articulated lorry, semi',
|
872 |
+
868: 'tray',
|
873 |
+
869: 'trench coat',
|
874 |
+
870: 'tricycle, trike, velocipede',
|
875 |
+
871: 'trimaran',
|
876 |
+
872: 'tripod',
|
877 |
+
873: 'triumphal arch',
|
878 |
+
874: 'trolleybus, trolley coach, trackless trolley',
|
879 |
+
875: 'trombone',
|
880 |
+
876: 'tub, vat',
|
881 |
+
877: 'turnstile',
|
882 |
+
878: 'typewriter keyboard',
|
883 |
+
879: 'umbrella',
|
884 |
+
880: 'unicycle, monocycle',
|
885 |
+
881: 'upright, upright piano',
|
886 |
+
882: 'vacuum, vacuum cleaner',
|
887 |
+
883: 'vase',
|
888 |
+
884: 'vault',
|
889 |
+
885: 'velvet',
|
890 |
+
886: 'vending machine',
|
891 |
+
887: 'vestment',
|
892 |
+
888: 'viaduct',
|
893 |
+
889: 'violin, fiddle',
|
894 |
+
890: 'volleyball',
|
895 |
+
891: 'waffle iron',
|
896 |
+
892: 'wall clock',
|
897 |
+
893: 'wallet, billfold, notecase, pocketbook',
|
898 |
+
894: 'wardrobe, closet, press',
|
899 |
+
895: 'warplane, military plane',
|
900 |
+
896: 'washbasin, handbasin, washbowl, lavabo, wash-hand basin',
|
901 |
+
897: 'washer, automatic washer, washing machine',
|
902 |
+
898: 'water bottle',
|
903 |
+
899: 'water jug',
|
904 |
+
900: 'water tower',
|
905 |
+
901: 'whiskey jug',
|
906 |
+
902: 'whistle',
|
907 |
+
903: 'wig',
|
908 |
+
904: 'window screen',
|
909 |
+
905: 'window shade',
|
910 |
+
906: 'Windsor tie',
|
911 |
+
907: 'wine bottle',
|
912 |
+
908: 'wing',
|
913 |
+
909: 'wok',
|
914 |
+
910: 'wooden spoon',
|
915 |
+
911: 'wool, woolen, woollen',
|
916 |
+
912: 'worm fence, snake fence, snake-rail fence, Virginia fence',
|
917 |
+
913: 'wreck',
|
918 |
+
914: 'yawl',
|
919 |
+
915: 'yurt',
|
920 |
+
916: 'web site, website, internet site, site',
|
921 |
+
917: 'comic book',
|
922 |
+
918: 'crossword puzzle, crossword',
|
923 |
+
919: 'street sign',
|
924 |
+
920: 'traffic light, traffic signal, stoplight',
|
925 |
+
921: 'book jacket, dust cover, dust jacket, dust wrapper',
|
926 |
+
922: 'menu',
|
927 |
+
923: 'plate',
|
928 |
+
924: 'guacamole',
|
929 |
+
925: 'consomme',
|
930 |
+
926: 'hot pot, hotpot',
|
931 |
+
927: 'trifle',
|
932 |
+
928: 'ice cream, icecream',
|
933 |
+
929: 'ice lolly, lolly, lollipop, popsicle',
|
934 |
+
930: 'French loaf',
|
935 |
+
931: 'bagel, beigel',
|
936 |
+
932: 'pretzel',
|
937 |
+
933: 'cheeseburger',
|
938 |
+
934: 'hotdog, hot dog, red hot',
|
939 |
+
935: 'mashed potato',
|
940 |
+
936: 'head cabbage',
|
941 |
+
937: 'broccoli',
|
942 |
+
938: 'cauliflower',
|
943 |
+
939: 'zucchini, courgette',
|
944 |
+
940: 'spaghetti squash',
|
945 |
+
941: 'acorn squash',
|
946 |
+
942: 'butternut squash',
|
947 |
+
943: 'cucumber, cuke',
|
948 |
+
944: 'artichoke, globe artichoke',
|
949 |
+
945: 'bell pepper',
|
950 |
+
946: 'cardoon',
|
951 |
+
947: 'mushroom',
|
952 |
+
948: 'Granny Smith',
|
953 |
+
949: 'strawberry',
|
954 |
+
950: 'orange',
|
955 |
+
951: 'lemon',
|
956 |
+
952: 'fig',
|
957 |
+
953: 'pineapple, ananas',
|
958 |
+
954: 'banana',
|
959 |
+
955: 'jackfruit, jak, jack',
|
960 |
+
956: 'custard apple',
|
961 |
+
957: 'pomegranate',
|
962 |
+
958: 'hay',
|
963 |
+
959: 'carbonara',
|
964 |
+
960: 'chocolate sauce, chocolate syrup',
|
965 |
+
961: 'dough',
|
966 |
+
962: 'meat loaf, meatloaf',
|
967 |
+
963: 'pizza, pizza pie',
|
968 |
+
964: 'potpie',
|
969 |
+
965: 'burrito',
|
970 |
+
966: 'red wine',
|
971 |
+
967: 'espresso',
|
972 |
+
968: 'cup',
|
973 |
+
969: 'eggnog',
|
974 |
+
970: 'alp',
|
975 |
+
971: 'bubble',
|
976 |
+
972: 'cliff, drop, drop-off',
|
977 |
+
973: 'coral reef',
|
978 |
+
974: 'geyser',
|
979 |
+
975: 'lakeside, lakeshore',
|
980 |
+
976: 'promontory, headland, head, foreland',
|
981 |
+
977: 'sandbar, sand bar',
|
982 |
+
978: 'seashore, coast, seacoast, sea-coast',
|
983 |
+
979: 'valley, vale',
|
984 |
+
980: 'volcano',
|
985 |
+
981: 'ballplayer, baseball player',
|
986 |
+
982: 'groom, bridegroom',
|
987 |
+
983: 'scuba diver',
|
988 |
+
984: 'rapeseed',
|
989 |
+
985: 'daisy',
|
990 |
+
986: "yellow lady's slipper, yellow lady-slipper, Cypripedium calceolus, Cypripedium parviflorum",
|
991 |
+
987: 'corn',
|
992 |
+
988: 'acorn',
|
993 |
+
989: 'hip, rose hip, rosehip',
|
994 |
+
990: 'buckeye, horse chestnut, conker',
|
995 |
+
991: 'coral fungus',
|
996 |
+
992: 'agaric',
|
997 |
+
993: 'gyromitra',
|
998 |
+
994: 'stinkhorn, carrion fungus',
|
999 |
+
995: 'earthstar',
|
1000 |
+
996: 'hen-of-the-woods, hen of the woods, Polyporus frondosus, Grifola frondosa',
|
1001 |
+
997: 'bolete',
|
1002 |
+
998: 'ear, spike, capitulum',
|
1003 |
+
999: 'toilet tissue, toilet paper, bathroom tissue'}
|
models.py
ADDED
@@ -0,0 +1,611 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
+
# References:
|
8 |
+
# GLIDE: https://github.com/openai/glide-text2im
|
9 |
+
# MAE: https://github.com/facebookresearch/mae/blob/main/models_mae.py
|
10 |
+
# --------------------------------------------------------
|
11 |
+
|
12 |
+
import torch
|
13 |
+
import torch.nn as nn
|
14 |
+
import numpy as np
|
15 |
+
import math
|
16 |
+
from timm.models.vision_transformer import PatchEmbed, Mlp
|
17 |
+
from timm.models.layers import trunc_normal_
|
18 |
+
import math
|
19 |
+
|
20 |
+
|
21 |
+
def modulate(x, shift, scale):
|
22 |
+
return x * (1 + scale.unsqueeze(1)) + shift.unsqueeze(1)
|
23 |
+
|
24 |
+
|
25 |
+
class Attention(nn.Module):
|
26 |
+
def __init__(self, dim, num_heads=8, qkv_bias=False, qk_scale=None, attn_drop=0., proj_drop=0., num_patches=None):
|
27 |
+
super().__init__()
|
28 |
+
self.num_heads = num_heads
|
29 |
+
head_dim = dim // num_heads
|
30 |
+
# NOTE scale factor was wrong in my original version, can set manually to be compat with prev weights
|
31 |
+
self.scale = qk_scale or head_dim ** -0.5
|
32 |
+
|
33 |
+
self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias)
|
34 |
+
self.attn_drop = nn.Dropout(attn_drop)
|
35 |
+
self.proj = nn.Linear(dim, dim)
|
36 |
+
self.proj_drop = nn.Dropout(proj_drop)
|
37 |
+
self.rel_pos_bias = RelativePositionBias(
|
38 |
+
window_size=[int(num_patches**0.5), int(num_patches**0.5)], num_heads=num_heads)
|
39 |
+
|
40 |
+
def get_masked_rel_bias(self, B, ids_keep):
|
41 |
+
# get masked rel_pos_bias
|
42 |
+
rel_pos_bias = self.rel_pos_bias()
|
43 |
+
rel_pos_bias = rel_pos_bias.unsqueeze(dim=0).repeat(B, 1, 1, 1)
|
44 |
+
|
45 |
+
rel_pos_bias_masked = torch.gather(
|
46 |
+
rel_pos_bias, dim=2, index=ids_keep.unsqueeze(dim=1).unsqueeze(dim=-1).repeat(1, rel_pos_bias.shape[1], 1, rel_pos_bias.shape[-1]))
|
47 |
+
rel_pos_bias_masked = torch.gather(
|
48 |
+
rel_pos_bias_masked, dim=3, index=ids_keep.unsqueeze(dim=1).unsqueeze(dim=2).repeat(1, rel_pos_bias.shape[1], ids_keep.shape[1], 1))
|
49 |
+
return rel_pos_bias_masked
|
50 |
+
|
51 |
+
def forward(self, x, ids_keep=None):
|
52 |
+
B, N, C = x.shape
|
53 |
+
qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, C //
|
54 |
+
self.num_heads).permute(2, 0, 3, 1, 4)
|
55 |
+
# make torchscript happy (cannot use tensor as tuple)
|
56 |
+
q, k, v = qkv[0], qkv[1], qkv[2]
|
57 |
+
|
58 |
+
attn = (q @ k.transpose(-2, -1)) * self.scale
|
59 |
+
if ids_keep is not None:
|
60 |
+
rp_bias = self.get_masked_rel_bias(B, ids_keep)
|
61 |
+
else:
|
62 |
+
rp_bias = self.rel_pos_bias()
|
63 |
+
attn += rp_bias
|
64 |
+
attn = attn.softmax(dim=-1)
|
65 |
+
attn = self.attn_drop(attn)
|
66 |
+
|
67 |
+
x = (attn @ v).transpose(1, 2).reshape(B, N, C)
|
68 |
+
x = self.proj(x)
|
69 |
+
x = self.proj_drop(x)
|
70 |
+
return x
|
71 |
+
|
72 |
+
|
73 |
+
class RelativePositionBias(nn.Module):
|
74 |
+
# https://github.com/microsoft/unilm/blob/master/beit/modeling_finetune.py
|
75 |
+
def __init__(self, window_size, num_heads):
|
76 |
+
super().__init__()
|
77 |
+
self.window_size = window_size
|
78 |
+
self.num_relative_distance = (
|
79 |
+
2 * window_size[0] - 1) * (2 * window_size[1] - 1) + 3
|
80 |
+
self.relative_position_bias_table = nn.Parameter(
|
81 |
+
torch.zeros(self.num_relative_distance, num_heads))
|
82 |
+
|
83 |
+
# get pair-wise relative position index for each token inside the window
|
84 |
+
coords_h = torch.arange(window_size[0])
|
85 |
+
coords_w = torch.arange(window_size[1])
|
86 |
+
coords = torch.stack(torch.meshgrid([coords_h, coords_w]))
|
87 |
+
coords_flatten = torch.flatten(coords, 1)
|
88 |
+
relative_coords = coords_flatten[:, :, None] - \
|
89 |
+
coords_flatten[:, None, :]
|
90 |
+
relative_coords = relative_coords.permute(
|
91 |
+
1, 2, 0).contiguous()
|
92 |
+
relative_coords[:, :, 0] += window_size[0] - 1
|
93 |
+
relative_coords[:, :, 1] += window_size[1] - 1
|
94 |
+
relative_coords[:, :, 0] *= 2 * window_size[1] - 1
|
95 |
+
relative_position_index = \
|
96 |
+
torch.zeros(
|
97 |
+
size=(window_size[0] * window_size[1],) * 2, dtype=relative_coords.dtype)
|
98 |
+
relative_position_index = relative_coords.sum(-1)
|
99 |
+
|
100 |
+
self.register_buffer("relative_position_index",
|
101 |
+
relative_position_index)
|
102 |
+
|
103 |
+
trunc_normal_(self.relative_position_bias_table, std=.02)
|
104 |
+
|
105 |
+
def forward(self):
|
106 |
+
relative_position_bias = \
|
107 |
+
self.relative_position_bias_table[self.relative_position_index.view(-1)].view(
|
108 |
+
self.window_size[0] * self.window_size[1],
|
109 |
+
self.window_size[0] * self.window_size[1], -1) # Wh*Ww,Wh*Ww,nH
|
110 |
+
# nH, Wh*Ww, Wh*Ww
|
111 |
+
return relative_position_bias.permute(2, 0, 1).contiguous()
|
112 |
+
|
113 |
+
#################################################################################
|
114 |
+
# Embedding Layers for Timesteps and Class Labels #
|
115 |
+
#################################################################################
|
116 |
+
|
117 |
+
|
118 |
+
class TimestepEmbedder(nn.Module):
|
119 |
+
"""
|
120 |
+
Embeds scalar timesteps into vector representations.
|
121 |
+
"""
|
122 |
+
|
123 |
+
def __init__(self, hidden_size, frequency_embedding_size=256):
|
124 |
+
super().__init__()
|
125 |
+
self.mlp = nn.Sequential(
|
126 |
+
nn.Linear(frequency_embedding_size, hidden_size, bias=True),
|
127 |
+
nn.SiLU(),
|
128 |
+
nn.Linear(hidden_size, hidden_size, bias=True),
|
129 |
+
)
|
130 |
+
self.frequency_embedding_size = frequency_embedding_size
|
131 |
+
|
132 |
+
@staticmethod
|
133 |
+
def timestep_embedding(t, dim, max_period=10000):
|
134 |
+
"""
|
135 |
+
Create sinusoidal timestep embeddings.
|
136 |
+
:param t: a 1-D Tensor of N indices, one per batch element.
|
137 |
+
These may be fractional.
|
138 |
+
:param dim: the dimension of the output.
|
139 |
+
:param max_period: controls the minimum frequency of the embeddings.
|
140 |
+
:return: an (N, D) Tensor of positional embeddings.
|
141 |
+
"""
|
142 |
+
# https://github.com/openai/glide-text2im/blob/main/glide_text2im/nn.py
|
143 |
+
half = dim // 2
|
144 |
+
freqs = torch.exp(
|
145 |
+
-math.log(max_period) * torch.arange(start=0,
|
146 |
+
end=half, dtype=torch.float32) / half
|
147 |
+
).to(device=t.device)
|
148 |
+
args = t[:, None].float() * freqs[None]
|
149 |
+
embedding = torch.cat([torch.cos(args), torch.sin(args)], dim=-1)
|
150 |
+
if dim % 2:
|
151 |
+
embedding = torch.cat(
|
152 |
+
[embedding, torch.zeros_like(embedding[:, :1])], dim=-1)
|
153 |
+
return embedding
|
154 |
+
|
155 |
+
def forward(self, t):
|
156 |
+
t_freq = self.timestep_embedding(t, self.frequency_embedding_size)
|
157 |
+
t_emb = self.mlp(t_freq)
|
158 |
+
return t_emb
|
159 |
+
|
160 |
+
|
161 |
+
class LabelEmbedder(nn.Module):
|
162 |
+
"""
|
163 |
+
Embeds class labels into vector representations. Also handles label dropout for classifier-free guidance.
|
164 |
+
"""
|
165 |
+
|
166 |
+
def __init__(self, num_classes, hidden_size, dropout_prob):
|
167 |
+
super().__init__()
|
168 |
+
use_cfg_embedding = dropout_prob > 0
|
169 |
+
self.embedding_table = nn.Embedding(
|
170 |
+
num_classes + use_cfg_embedding, hidden_size)
|
171 |
+
self.num_classes = num_classes
|
172 |
+
self.dropout_prob = dropout_prob
|
173 |
+
|
174 |
+
def token_drop(self, labels, force_drop_ids=None):
|
175 |
+
"""
|
176 |
+
Drops labels to enable classifier-free guidance.
|
177 |
+
"""
|
178 |
+
if force_drop_ids is None:
|
179 |
+
drop_ids = torch.rand(labels.shape[0]) < self.dropout_prob
|
180 |
+
else:
|
181 |
+
drop_ids = force_drop_ids == 1
|
182 |
+
|
183 |
+
labels = torch.where(drop_ids.to(labels.device),
|
184 |
+
self.num_classes, labels)
|
185 |
+
return labels
|
186 |
+
|
187 |
+
def forward(self, labels, train, force_drop_ids=None):
|
188 |
+
use_dropout = self.dropout_prob > 0
|
189 |
+
if (train and use_dropout) or (force_drop_ids is not None):
|
190 |
+
labels = self.token_drop(labels, force_drop_ids)
|
191 |
+
embeddings = self.embedding_table(labels)
|
192 |
+
return embeddings
|
193 |
+
|
194 |
+
|
195 |
+
#################################################################################
|
196 |
+
# Core MDT Model #
|
197 |
+
#################################################################################
|
198 |
+
|
199 |
+
class MDTBlock(nn.Module):
|
200 |
+
"""
|
201 |
+
A MDT block with adaptive layer norm zero (adaLN-Zero) conMDTioning.
|
202 |
+
"""
|
203 |
+
|
204 |
+
def __init__(self, hidden_size, num_heads, mlp_ratio=4.0, **block_kwargs):
|
205 |
+
super().__init__()
|
206 |
+
self.norm1 = nn.LayerNorm(
|
207 |
+
hidden_size, elementwise_affine=False, eps=1e-6)
|
208 |
+
self.attn = Attention(
|
209 |
+
hidden_size, num_heads=num_heads, qkv_bias=True, **block_kwargs)
|
210 |
+
self.norm2 = nn.LayerNorm(
|
211 |
+
hidden_size, elementwise_affine=False, eps=1e-6)
|
212 |
+
mlp_hidden_dim = int(hidden_size * mlp_ratio)
|
213 |
+
def approx_gelu(): return nn.GELU(approximate="tanh")
|
214 |
+
self.mlp = Mlp(in_features=hidden_size,
|
215 |
+
hidden_features=mlp_hidden_dim, act_layer=approx_gelu, drop=0)
|
216 |
+
self.adaLN_modulation = nn.Sequential(
|
217 |
+
nn.SiLU(),
|
218 |
+
nn.Linear(hidden_size, 6 * hidden_size, bias=True)
|
219 |
+
)
|
220 |
+
|
221 |
+
def forward(self, x, c, ids_keep=None):
|
222 |
+
shift_msa, scale_msa, gate_msa, shift_mlp, scale_mlp, gate_mlp = self.adaLN_modulation(
|
223 |
+
c).chunk(6, dim=1)
|
224 |
+
x = x + gate_msa.unsqueeze(1) * self.attn(
|
225 |
+
modulate(self.norm1(x), shift_msa, scale_msa), ids_keep=ids_keep)
|
226 |
+
x = x + \
|
227 |
+
gate_mlp.unsqueeze(
|
228 |
+
1) * self.mlp(modulate(self.norm2(x), shift_mlp, scale_mlp))
|
229 |
+
return x
|
230 |
+
|
231 |
+
|
232 |
+
class FinalLayer(nn.Module):
|
233 |
+
"""
|
234 |
+
The final layer of MDT.
|
235 |
+
"""
|
236 |
+
|
237 |
+
def __init__(self, hidden_size, patch_size, out_channels):
|
238 |
+
super().__init__()
|
239 |
+
self.norm_final = nn.LayerNorm(
|
240 |
+
hidden_size, elementwise_affine=False, eps=1e-6)
|
241 |
+
self.linear = nn.Linear(
|
242 |
+
hidden_size, patch_size * patch_size * out_channels, bias=True)
|
243 |
+
self.adaLN_modulation = nn.Sequential(
|
244 |
+
nn.SiLU(),
|
245 |
+
nn.Linear(hidden_size, 2 * hidden_size, bias=True)
|
246 |
+
)
|
247 |
+
|
248 |
+
def forward(self, x, c):
|
249 |
+
shift, scale = self.adaLN_modulation(c).chunk(2, dim=1)
|
250 |
+
x = modulate(self.norm_final(x), shift, scale)
|
251 |
+
x = self.linear(x)
|
252 |
+
return x
|
253 |
+
|
254 |
+
|
255 |
+
class MDT(nn.Module):
|
256 |
+
"""
|
257 |
+
Diffusion model with a Transformer backbone.
|
258 |
+
"""
|
259 |
+
|
260 |
+
def __init__(
|
261 |
+
self,
|
262 |
+
input_size=32,
|
263 |
+
patch_size=2,
|
264 |
+
in_channels=4,
|
265 |
+
hidden_size=1152,
|
266 |
+
depth=28,
|
267 |
+
num_heads=16,
|
268 |
+
mlp_ratio=4.0,
|
269 |
+
class_dropout_prob=0.1,
|
270 |
+
num_classes=1000,
|
271 |
+
learn_sigma=True,
|
272 |
+
mask_ratio=None,
|
273 |
+
decode_layer=None,
|
274 |
+
):
|
275 |
+
super().__init__()
|
276 |
+
self.learn_sigma = learn_sigma
|
277 |
+
self.in_channels = in_channels
|
278 |
+
self.out_channels = in_channels * 2 if learn_sigma else in_channels
|
279 |
+
self.patch_size = patch_size
|
280 |
+
self.num_heads = num_heads
|
281 |
+
|
282 |
+
self.x_embedder = PatchEmbed(
|
283 |
+
input_size, patch_size, in_channels, hidden_size, bias=True)
|
284 |
+
self.t_embedder = TimestepEmbedder(hidden_size)
|
285 |
+
self.y_embedder = LabelEmbedder(
|
286 |
+
num_classes, hidden_size, class_dropout_prob)
|
287 |
+
num_patches = self.x_embedder.num_patches
|
288 |
+
# Will use learnbale sin-cos embedding:
|
289 |
+
self.pos_embed = nn.Parameter(torch.zeros(
|
290 |
+
1, num_patches, hidden_size), requires_grad=True)
|
291 |
+
|
292 |
+
self.blocks = nn.ModuleList([
|
293 |
+
MDTBlock(hidden_size, num_heads, mlp_ratio=mlp_ratio, num_patches=num_patches) for _ in range(depth)
|
294 |
+
])
|
295 |
+
self.sideblocks = nn.ModuleList([
|
296 |
+
MDTBlock(hidden_size, num_heads, mlp_ratio=mlp_ratio, num_patches=num_patches) for _ in range(1)
|
297 |
+
])
|
298 |
+
self.final_layer = FinalLayer(
|
299 |
+
hidden_size, patch_size, self.out_channels)
|
300 |
+
|
301 |
+
self.decoder_pos_embed = nn.Parameter(torch.zeros(
|
302 |
+
1, num_patches, hidden_size), requires_grad=True)
|
303 |
+
if mask_ratio is not None:
|
304 |
+
self.mask_token = nn.Parameter(torch.zeros(1, 1, hidden_size))
|
305 |
+
self.mask_ratio = float(mask_ratio)
|
306 |
+
self.decode_layer = int(decode_layer)
|
307 |
+
else:
|
308 |
+
self.mask_token = nn.Parameter(torch.zeros(
|
309 |
+
1, 1, hidden_size), requires_grad=False)
|
310 |
+
self.mask_ratio = None
|
311 |
+
self.decode_layer = int(decode_layer)
|
312 |
+
print("mask ratio:", self.mask_ratio,
|
313 |
+
"decode_layer:", self.decode_layer)
|
314 |
+
self.initialize_weights()
|
315 |
+
|
316 |
+
def initialize_weights(self):
|
317 |
+
# Initialize transformer layers:
|
318 |
+
def _basic_init(module):
|
319 |
+
if isinstance(module, nn.Linear):
|
320 |
+
torch.nn.init.xavier_uniform_(module.weight)
|
321 |
+
if module.bias is not None:
|
322 |
+
nn.init.constant_(module.bias, 0)
|
323 |
+
self.apply(_basic_init)
|
324 |
+
|
325 |
+
# Initialize pos_embed by sin-cos embedding:
|
326 |
+
pos_embed = get_2d_sincos_pos_embed(
|
327 |
+
self.pos_embed.shape[-1], int(self.x_embedder.num_patches ** 0.5))
|
328 |
+
self.pos_embed.data.copy_(
|
329 |
+
torch.from_numpy(pos_embed).float().unsqueeze(0))
|
330 |
+
|
331 |
+
decoder_pos_embed = get_2d_sincos_pos_embed(
|
332 |
+
self.decoder_pos_embed.shape[-1], int(self.x_embedder.num_patches ** 0.5))
|
333 |
+
self.decoder_pos_embed.data.copy_(
|
334 |
+
torch.from_numpy(decoder_pos_embed).float().unsqueeze(0))
|
335 |
+
|
336 |
+
# Initialize patch_embed like nn.Linear (instead of nn.Conv2d):
|
337 |
+
w = self.x_embedder.proj.weight.data
|
338 |
+
nn.init.xavier_uniform_(w.view([w.shape[0], -1]))
|
339 |
+
nn.init.constant_(self.x_embedder.proj.bias, 0)
|
340 |
+
|
341 |
+
# Initialize label embedding table:
|
342 |
+
nn.init.normal_(self.y_embedder.embedding_table.weight, std=0.02)
|
343 |
+
|
344 |
+
# Initialize timestep embedding MLP:
|
345 |
+
nn.init.normal_(self.t_embedder.mlp[0].weight, std=0.02)
|
346 |
+
nn.init.normal_(self.t_embedder.mlp[2].weight, std=0.02)
|
347 |
+
|
348 |
+
# Zero-out adaLN modulation layers in MDT blocks:
|
349 |
+
for block in self.blocks:
|
350 |
+
nn.init.constant_(block.adaLN_modulation[-1].weight, 0)
|
351 |
+
nn.init.constant_(block.adaLN_modulation[-1].bias, 0)
|
352 |
+
|
353 |
+
for block in self.sideblocks:
|
354 |
+
nn.init.constant_(block.adaLN_modulation[-1].weight, 0)
|
355 |
+
nn.init.constant_(block.adaLN_modulation[-1].bias, 0)
|
356 |
+
|
357 |
+
# Zero-out output layers:
|
358 |
+
nn.init.constant_(self.final_layer.adaLN_modulation[-1].weight, 0)
|
359 |
+
nn.init.constant_(self.final_layer.adaLN_modulation[-1].bias, 0)
|
360 |
+
nn.init.constant_(self.final_layer.linear.weight, 0)
|
361 |
+
nn.init.constant_(self.final_layer.linear.bias, 0)
|
362 |
+
|
363 |
+
if self.mask_ratio is not None:
|
364 |
+
torch.nn.init.normal_(self.mask_token, std=.02)
|
365 |
+
|
366 |
+
def unpatchify(self, x):
|
367 |
+
"""
|
368 |
+
x: (N, T, patch_size**2 * C)
|
369 |
+
imgs: (N, H, W, C)
|
370 |
+
"""
|
371 |
+
c = self.out_channels
|
372 |
+
p = self.x_embedder.patch_size[0]
|
373 |
+
h = w = int(x.shape[1] ** 0.5)
|
374 |
+
assert h * w == x.shape[1]
|
375 |
+
|
376 |
+
x = x.reshape(shape=(x.shape[0], h, w, p, p, c))
|
377 |
+
x = torch.einsum('nhwpqc->nchpwq', x)
|
378 |
+
imgs = x.reshape(shape=(x.shape[0], c, h * p, h * p))
|
379 |
+
return imgs
|
380 |
+
|
381 |
+
def random_masking(self, x, mask_ratio):
|
382 |
+
"""
|
383 |
+
Perform per-sample random masking by per-sample shuffling.
|
384 |
+
Per-sample shuffling is done by argsort random noise.
|
385 |
+
x: [N, L, D], sequence
|
386 |
+
"""
|
387 |
+
N, L, D = x.shape # batch, length, dim
|
388 |
+
len_keep = int(L * (1 - mask_ratio))
|
389 |
+
|
390 |
+
noise = torch.rand(N, L, device=x.device) # noise in [0, 1]
|
391 |
+
|
392 |
+
# sort noise for each sample
|
393 |
+
# ascend: small is keep, large is remove
|
394 |
+
ids_shuffle = torch.argsort(noise, dim=1)
|
395 |
+
ids_restore = torch.argsort(ids_shuffle, dim=1)
|
396 |
+
|
397 |
+
# keep the first subset
|
398 |
+
ids_keep = ids_shuffle[:, :len_keep]
|
399 |
+
x_masked = torch.gather(
|
400 |
+
x, dim=1, index=ids_keep.unsqueeze(-1).repeat(1, 1, D))
|
401 |
+
|
402 |
+
# generate the binary mask: 0 is keep, 1 is remove
|
403 |
+
mask = torch.ones([N, L], device=x.device)
|
404 |
+
mask[:, :len_keep] = 0
|
405 |
+
# unshuffle to get the binary mask
|
406 |
+
mask = torch.gather(mask, dim=1, index=ids_restore)
|
407 |
+
|
408 |
+
return x_masked, mask, ids_restore, ids_keep
|
409 |
+
|
410 |
+
def forward_side_interpolater(self, x, c, mask, ids_restore):
|
411 |
+
# append mask tokens to sequence
|
412 |
+
mask_tokens = self.mask_token.repeat(
|
413 |
+
x.shape[0], ids_restore.shape[1] - x.shape[1], 1)
|
414 |
+
x_ = torch.cat([x, mask_tokens], dim=1)
|
415 |
+
x = torch.gather(
|
416 |
+
x_, dim=1, index=ids_restore.unsqueeze(-1).repeat(1, 1, x.shape[2])) # unshuffle
|
417 |
+
|
418 |
+
# add pos embed
|
419 |
+
x = x + self.decoder_pos_embed
|
420 |
+
|
421 |
+
# pass to the basic block
|
422 |
+
x_before = x
|
423 |
+
for sideblock in self.sideblocks:
|
424 |
+
x = sideblock(x, c, ids_keep=None)
|
425 |
+
|
426 |
+
# masked shortcut
|
427 |
+
mask = mask.unsqueeze(dim=-1)
|
428 |
+
x = x*mask + (1-mask)*x_before
|
429 |
+
|
430 |
+
return x
|
431 |
+
|
432 |
+
def forward(self, x, t, y, enable_mask=False):
|
433 |
+
"""
|
434 |
+
Forward pass of MDT.
|
435 |
+
x: (N, C, H, W) tensor of spatial inputs (images or latent representations of images)
|
436 |
+
t: (N,) tensor of diffusion timesteps
|
437 |
+
y: (N,) tensor of class labels
|
438 |
+
enable_mask: Use mask latent modeling
|
439 |
+
"""
|
440 |
+
x = self.x_embedder(
|
441 |
+
x) + self.pos_embed # (N, T, D), where T = H * W / patch_size ** 2
|
442 |
+
|
443 |
+
t = self.t_embedder(t) # (N, D)
|
444 |
+
y = self.y_embedder(y, self.training) # (N, D)
|
445 |
+
c = t + y # (N, D)
|
446 |
+
|
447 |
+
masked_stage = False
|
448 |
+
|
449 |
+
# masking op for training
|
450 |
+
if self.mask_ratio is not None and enable_mask:
|
451 |
+
# masking: length -> length * mask_ratio
|
452 |
+
x, mask, ids_restore, ids_keep = self.random_masking(
|
453 |
+
x, self.mask_ratio)
|
454 |
+
masked_stage = True
|
455 |
+
|
456 |
+
for i in range(len(self.blocks)):
|
457 |
+
if i == (len(self.blocks) - self.decode_layer):
|
458 |
+
if self.mask_ratio is not None and enable_mask:
|
459 |
+
x = self.forward_side_interpolater(x, c, mask, ids_restore)
|
460 |
+
masked_stage = False
|
461 |
+
else:
|
462 |
+
# add pos embed
|
463 |
+
x = x + self.decoder_pos_embed
|
464 |
+
|
465 |
+
block = self.blocks[i]
|
466 |
+
if masked_stage:
|
467 |
+
x = block(x, c, ids_keep=ids_keep)
|
468 |
+
else:
|
469 |
+
x = block(x, c, ids_keep=None)
|
470 |
+
|
471 |
+
# (N, T, patch_size ** 2 * out_channels)
|
472 |
+
x = self.final_layer(x, c)
|
473 |
+
x = self.unpatchify(x) # (N, out_channels, H, W)
|
474 |
+
return x
|
475 |
+
|
476 |
+
|
477 |
+
def forward_with_cfg(self, x, t, y, cfg_scale=None, diffusion_steps=1000, scale_pow=4.0):
|
478 |
+
"""
|
479 |
+
Forward pass of MDT, but also batches the unconditional forward pass for classifier-free guidance.
|
480 |
+
"""
|
481 |
+
# https://github.com/openai/glide-text2im/blob/main/notebooks/text2im.ipynb
|
482 |
+
if cfg_scale is not None:
|
483 |
+
half = x[: len(x) // 2]
|
484 |
+
combined = torch.cat([half, half], dim=0)
|
485 |
+
model_out = self.forward(combined, t, y)
|
486 |
+
eps, rest = model_out[:, :3], model_out[:, 3:]
|
487 |
+
cond_eps, uncond_eps = torch.split(eps, len(eps) // 2, dim=0)
|
488 |
+
|
489 |
+
scale_step = (
|
490 |
+
1-torch.cos(((1-t/diffusion_steps)**scale_pow)*math.pi))*1/2 # power-cos scaling
|
491 |
+
real_cfg_scale = (cfg_scale-1)*scale_step + 1
|
492 |
+
real_cfg_scale = real_cfg_scale[: len(x) // 2].view(-1, 1, 1, 1)
|
493 |
+
|
494 |
+
half_eps = uncond_eps + real_cfg_scale * (cond_eps - uncond_eps)
|
495 |
+
eps = torch.cat([half_eps, half_eps], dim=0)
|
496 |
+
return torch.cat([eps, rest], dim=1)
|
497 |
+
else:
|
498 |
+
model_out = self.forward(x, t, y)
|
499 |
+
eps, rest = model_out[:, :3], model_out[:, 3:]
|
500 |
+
return torch.cat([eps, rest], dim=1)
|
501 |
+
|
502 |
+
|
503 |
+
#################################################################################
|
504 |
+
# Sine/Cosine Positional Embedding Functions #
|
505 |
+
#################################################################################
|
506 |
+
# https://github.com/facebookresearch/mae/blob/main/util/pos_embed.py
|
507 |
+
|
508 |
+
|
509 |
+
def get_2d_sincos_pos_embed(embed_dim, grid_size, cls_token=False, extra_tokens=0):
|
510 |
+
"""
|
511 |
+
grid_size: int of the grid height and width
|
512 |
+
return:
|
513 |
+
pos_embed: [grid_size*grid_size, embed_dim] or [1+grid_size*grid_size, embed_dim] (w/ or w/o cls_token)
|
514 |
+
"""
|
515 |
+
grid_h = np.arange(grid_size, dtype=np.float32)
|
516 |
+
grid_w = np.arange(grid_size, dtype=np.float32)
|
517 |
+
grid = np.meshgrid(grid_w, grid_h) # here w goes first
|
518 |
+
grid = np.stack(grid, axis=0)
|
519 |
+
|
520 |
+
grid = grid.reshape([2, 1, grid_size, grid_size])
|
521 |
+
pos_embed = get_2d_sincos_pos_embed_from_grid(embed_dim, grid)
|
522 |
+
if cls_token and extra_tokens > 0:
|
523 |
+
pos_embed = np.concatenate(
|
524 |
+
[np.zeros([extra_tokens, embed_dim]), pos_embed], axis=0)
|
525 |
+
return pos_embed
|
526 |
+
|
527 |
+
|
528 |
+
def get_2d_sincos_pos_embed_from_grid(embed_dim, grid):
|
529 |
+
assert embed_dim % 2 == 0
|
530 |
+
|
531 |
+
# use half of dimensions to encode grid_h
|
532 |
+
emb_h = get_1d_sincos_pos_embed_from_grid(
|
533 |
+
embed_dim // 2, grid[0]) # (H*W, D/2)
|
534 |
+
emb_w = get_1d_sincos_pos_embed_from_grid(
|
535 |
+
embed_dim // 2, grid[1]) # (H*W, D/2)
|
536 |
+
|
537 |
+
emb = np.concatenate([emb_h, emb_w], axis=1) # (H*W, D)
|
538 |
+
return emb
|
539 |
+
|
540 |
+
|
541 |
+
def get_1d_sincos_pos_embed_from_grid(embed_dim, pos):
|
542 |
+
"""
|
543 |
+
embed_dim: output dimension for each position
|
544 |
+
pos: a list of positions to be encoded: size (M,)
|
545 |
+
out: (M, D)
|
546 |
+
"""
|
547 |
+
assert embed_dim % 2 == 0
|
548 |
+
omega = np.arange(embed_dim // 2, dtype=np.float64)
|
549 |
+
omega /= embed_dim / 2.
|
550 |
+
omega = 1. / 10000**omega # (D/2,)
|
551 |
+
|
552 |
+
pos = pos.reshape(-1) # (M,)
|
553 |
+
out = np.einsum('m,d->md', pos, omega) # (M, D/2), outer product
|
554 |
+
|
555 |
+
emb_sin = np.sin(out) # (M, D/2)
|
556 |
+
emb_cos = np.cos(out) # (M, D/2)
|
557 |
+
|
558 |
+
emb = np.concatenate([emb_sin, emb_cos], axis=1) # (M, D)
|
559 |
+
return emb
|
560 |
+
|
561 |
+
|
562 |
+
#################################################################################
|
563 |
+
# MDT Configs #
|
564 |
+
#################################################################################
|
565 |
+
|
566 |
+
def MDT_XL_2(**kwargs):
|
567 |
+
return MDT(depth=28, hidden_size=1152, patch_size=2, num_heads=16, **kwargs)
|
568 |
+
|
569 |
+
|
570 |
+
def MDT_XL_4(**kwargs):
|
571 |
+
return MDT(depth=28, hidden_size=1152, patch_size=4, num_heads=16, **kwargs)
|
572 |
+
|
573 |
+
|
574 |
+
def MDT_XL_8(**kwargs):
|
575 |
+
return MDT(depth=28, hidden_size=1152, patch_size=8, num_heads=16, **kwargs)
|
576 |
+
|
577 |
+
|
578 |
+
def MDT_L_2(**kwargs):
|
579 |
+
return MDT(depth=24, hidden_size=1024, patch_size=2, num_heads=16, **kwargs)
|
580 |
+
|
581 |
+
|
582 |
+
def MDT_L_4(**kwargs):
|
583 |
+
return MDT(depth=24, hidden_size=1024, patch_size=4, num_heads=16, **kwargs)
|
584 |
+
|
585 |
+
|
586 |
+
def MDT_L_8(**kwargs):
|
587 |
+
return MDT(depth=24, hidden_size=1024, patch_size=8, num_heads=16, **kwargs)
|
588 |
+
|
589 |
+
|
590 |
+
def MDT_B_2(**kwargs):
|
591 |
+
return MDT(depth=12, hidden_size=768, patch_size=2, num_heads=12, **kwargs)
|
592 |
+
|
593 |
+
|
594 |
+
def MDT_B_4(**kwargs):
|
595 |
+
return MDT(depth=12, hidden_size=768, patch_size=4, num_heads=12, **kwargs)
|
596 |
+
|
597 |
+
|
598 |
+
def MDT_B_8(**kwargs):
|
599 |
+
return MDT(depth=12, hidden_size=768, patch_size=8, num_heads=12, **kwargs)
|
600 |
+
|
601 |
+
|
602 |
+
def MDT_S_2(**kwargs):
|
603 |
+
return MDT(depth=12, hidden_size=384, patch_size=2, num_heads=6, **kwargs)
|
604 |
+
|
605 |
+
|
606 |
+
def MDT_S_4(**kwargs):
|
607 |
+
return MDT(depth=12, hidden_size=384, patch_size=4, num_heads=6, **kwargs)
|
608 |
+
|
609 |
+
|
610 |
+
def MDT_S_8(**kwargs):
|
611 |
+
return MDT(depth=12, hidden_size=384, patch_size=8, num_heads=6, **kwargs)
|
requirements.txt
ADDED
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
torch
|
2 |
+
torchvision
|
3 |
+
numpy
|
4 |
+
tqdm
|
5 |
+
timm
|
6 |
+
pillow
|
7 |
+
diffusers
|
8 |
+
accelerate
|