fffiloni commited on
Commit
b140fcf
·
verified ·
1 Parent(s): 85d8f14

Migrated from GitHub

Browse files
.gitattributes CHANGED
@@ -33,3 +33,11 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
 
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ img/overview.png filter=lfs diff=lfs merge=lfs -text
37
+ notebooks/examples/img2img/GIOApFAWDOc_160.wav filter=lfs diff=lfs merge=lfs -text
38
+ notebooks/examples/img2img/_GI7meqlYZk_30.wav filter=lfs diff=lfs merge=lfs -text
39
+ notebooks/examples/inpainting/14ekd4nkpwc_28.wav filter=lfs diff=lfs merge=lfs -text
40
+ notebooks/examples/inpainting/3ek-xLwr05Q_30.wav filter=lfs diff=lfs merge=lfs -text
41
+ notebooks/examples/inpainting/9z8XIRyUq9Q_30.wav filter=lfs diff=lfs merge=lfs -text
42
+ notebooks/examples/inpainting/IvfaKPDWC00_160.wav filter=lfs diff=lfs merge=lfs -text
43
+ prompt2prompt/Roboto-Regular.ttf filter=lfs diff=lfs merge=lfs -text
LICENSE ADDED
@@ -0,0 +1,437 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Attribution-NonCommercial-ShareAlike 4.0 International
2
+
3
+ =======================================================================
4
+
5
+ Creative Commons Corporation ("Creative Commons") is not a law firm and
6
+ does not provide legal services or legal advice. Distribution of
7
+ Creative Commons public licenses does not create a lawyer-client or
8
+ other relationship. Creative Commons makes its licenses and related
9
+ information available on an "as-is" basis. Creative Commons gives no
10
+ warranties regarding its licenses, any material licensed under their
11
+ terms and conditions, or any related information. Creative Commons
12
+ disclaims all liability for damages resulting from their use to the
13
+ fullest extent possible.
14
+
15
+ Using Creative Commons Public Licenses
16
+
17
+ Creative Commons public licenses provide a standard set of terms and
18
+ conditions that creators and other rights holders may use to share
19
+ original works of authorship and other material subject to copyright
20
+ and certain other rights specified in the public license below. The
21
+ following considerations are for informational purposes only, are not
22
+ exhaustive, and do not form part of our licenses.
23
+
24
+ Considerations for licensors: Our public licenses are
25
+ intended for use by those authorized to give the public
26
+ permission to use material in ways otherwise restricted by
27
+ copyright and certain other rights. Our licenses are
28
+ irrevocable. Licensors should read and understand the terms
29
+ and conditions of the license they choose before applying it.
30
+ Licensors should also secure all rights necessary before
31
+ applying our licenses so that the public can reuse the
32
+ material as expected. Licensors should clearly mark any
33
+ material not subject to the license. This includes other CC-
34
+ licensed material, or material used under an exception or
35
+ limitation to copyright. More considerations for licensors:
36
+ wiki.creativecommons.org/Considerations_for_licensors
37
+
38
+ Considerations for the public: By using one of our public
39
+ licenses, a licensor grants the public permission to use the
40
+ licensed material under specified terms and conditions. If
41
+ the licensor's permission is not necessary for any reason--for
42
+ example, because of any applicable exception or limitation to
43
+ copyright--then that use is not regulated by the license. Our
44
+ licenses grant only permissions under copyright and certain
45
+ other rights that a licensor has authority to grant. Use of
46
+ the licensed material may still be restricted for other
47
+ reasons, including because others have copyright or other
48
+ rights in the material. A licensor may make special requests,
49
+ such as asking that all changes be marked or described.
50
+ Although not required by our licenses, you are encouraged to
51
+ respect those requests where reasonable. More considerations
52
+ for the public:
53
+ wiki.creativecommons.org/Considerations_for_licensees
54
+
55
+ =======================================================================
56
+
57
+ Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International
58
+ Public License
59
+
60
+ By exercising the Licensed Rights (defined below), You accept and agree
61
+ to be bound by the terms and conditions of this Creative Commons
62
+ Attribution-NonCommercial-ShareAlike 4.0 International Public License
63
+ ("Public License"). To the extent this Public License may be
64
+ interpreted as a contract, You are granted the Licensed Rights in
65
+ consideration of Your acceptance of these terms and conditions, and the
66
+ Licensor grants You such rights in consideration of benefits the
67
+ Licensor receives from making the Licensed Material available under
68
+ these terms and conditions.
69
+
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. BY-NC-SA Compatible License means a license listed at
88
+ creativecommons.org/compatiblelicenses, approved by Creative
89
+ Commons as essentially the equivalent of this Public License.
90
+
91
+ d. Copyright and Similar Rights means copyright and/or similar rights
92
+ closely related to copyright including, without limitation,
93
+ performance, broadcast, sound recording, and Sui Generis Database
94
+ Rights, without regard to how the rights are labeled or
95
+ categorized. For purposes of this Public License, the rights
96
+ specified in Section 2(b)(1)-(2) are not Copyright and Similar
97
+ Rights.
98
+
99
+ e. Effective Technological Measures means those measures that, in the
100
+ absence of proper authority, may not be circumvented under laws
101
+ fulfilling obligations under Article 11 of the WIPO Copyright
102
+ Treaty adopted on December 20, 1996, and/or similar international
103
+ agreements.
104
+
105
+ f. Exceptions and Limitations means fair use, fair dealing, and/or
106
+ any other exception or limitation to Copyright and Similar Rights
107
+ that applies to Your use of the Licensed Material.
108
+
109
+ g. License Elements means the license attributes listed in the name
110
+ of a Creative Commons Public License. The License Elements of this
111
+ Public License are Attribution, NonCommercial, and ShareAlike.
112
+
113
+ h. Licensed Material means the artistic or literary work, database,
114
+ or other material to which the Licensor applied this Public
115
+ License.
116
+
117
+ i. Licensed Rights means the rights granted to You subject to the
118
+ terms and conditions of this Public License, which are limited to
119
+ all Copyright and Similar Rights that apply to Your use of the
120
+ Licensed Material and that the Licensor has authority to license.
121
+
122
+ j. Licensor means the individual(s) or entity(ies) granting rights
123
+ under this Public License.
124
+
125
+ k. NonCommercial means not primarily intended for or directed towards
126
+ commercial advantage or monetary compensation. For purposes of
127
+ this Public License, the exchange of the Licensed Material for
128
+ other material subject to Copyright and Similar Rights by digital
129
+ file-sharing or similar means is NonCommercial provided there is
130
+ no payment of monetary compensation in connection with the
131
+ exchange.
132
+
133
+ l. Share means to provide material to the public by any means or
134
+ process that requires permission under the Licensed Rights, such
135
+ as reproduction, public display, public performance, distribution,
136
+ dissemination, communication, or importation, and to make material
137
+ available to the public including in ways that members of the
138
+ public may access the material from a place and at a time
139
+ individually chosen by them.
140
+
141
+ m. Sui Generis Database Rights means rights other than copyright
142
+ resulting from Directive 96/9/EC of the European Parliament and of
143
+ the Council of 11 March 1996 on the legal protection of databases,
144
+ as amended and/or succeeded, as well as other essentially
145
+ equivalent rights anywhere in the world.
146
+
147
+ n. You means the individual or entity exercising the Licensed Rights
148
+ under this Public License. Your has a corresponding meaning.
149
+
150
+
151
+ Section 2 -- Scope.
152
+
153
+ a. License grant.
154
+
155
+ 1. Subject to the terms and conditions of this Public License,
156
+ the Licensor hereby grants You a worldwide, royalty-free,
157
+ non-sublicensable, non-exclusive, irrevocable license to
158
+ exercise the Licensed Rights in the Licensed Material to:
159
+
160
+ a. reproduce and Share the Licensed Material, in whole or
161
+ in part, for NonCommercial purposes only; and
162
+
163
+ b. produce, reproduce, and Share Adapted Material for
164
+ NonCommercial purposes only.
165
+
166
+ 2. Exceptions and Limitations. For the avoidance of doubt, where
167
+ Exceptions and Limitations apply to Your use, this Public
168
+ License does not apply, and You do not need to comply with
169
+ its terms and conditions.
170
+
171
+ 3. Term. The term of this Public License is specified in Section
172
+ 6(a).
173
+
174
+ 4. Media and formats; technical modifications allowed. The
175
+ Licensor authorizes You to exercise the Licensed Rights in
176
+ all media and formats whether now known or hereafter created,
177
+ and to make technical modifications necessary to do so. The
178
+ Licensor waives and/or agrees not to assert any right or
179
+ authority to forbid You from making technical modifications
180
+ necessary to exercise the Licensed Rights, including
181
+ technical modifications necessary to circumvent Effective
182
+ Technological Measures. For purposes of this Public License,
183
+ simply making modifications authorized by this Section 2(a)
184
+ (4) never produces Adapted Material.
185
+
186
+ 5. Downstream recipients.
187
+
188
+ a. Offer from the Licensor -- Licensed Material. Every
189
+ recipient of the Licensed Material automatically
190
+ receives an offer from the Licensor to exercise the
191
+ Licensed Rights under the terms and conditions of this
192
+ Public License.
193
+
194
+ b. Additional offer from the Licensor -- Adapted Material.
195
+ Every recipient of Adapted Material from You
196
+ automatically receives an offer from the Licensor to
197
+ exercise the Licensed Rights in the Adapted Material
198
+ under the conditions of the Adapter's License You apply.
199
+
200
+ c. No downstream restrictions. You may not offer or impose
201
+ any additional or different terms or conditions on, or
202
+ apply any Effective Technological Measures to, the
203
+ Licensed Material if doing so restricts exercise of the
204
+ Licensed Rights by any recipient of the Licensed
205
+ Material.
206
+
207
+ 6. No endorsement. Nothing in this Public License constitutes or
208
+ may be construed as permission to assert or imply that You
209
+ are, or that Your use of the Licensed Material is, connected
210
+ with, or sponsored, endorsed, or granted official status by,
211
+ the Licensor or others designated to receive attribution as
212
+ provided in Section 3(a)(1)(A)(i).
213
+
214
+ b. Other rights.
215
+
216
+ 1. Moral rights, such as the right of integrity, are not
217
+ licensed under this Public License, nor are publicity,
218
+ privacy, and/or other similar personality rights; however, to
219
+ the extent possible, the Licensor waives and/or agrees not to
220
+ assert any such rights held by the Licensor to the limited
221
+ extent necessary to allow You to exercise the Licensed
222
+ Rights, but not otherwise.
223
+
224
+ 2. Patent and trademark rights are not licensed under this
225
+ Public License.
226
+
227
+ 3. To the extent possible, the Licensor waives any right to
228
+ collect royalties from You for the exercise of the Licensed
229
+ Rights, whether directly or through a collecting society
230
+ under any voluntary or waivable statutory or compulsory
231
+ licensing scheme. In all other cases the Licensor expressly
232
+ reserves any right to collect such royalties, including when
233
+ the Licensed Material is used other than for NonCommercial
234
+ purposes.
235
+
236
+
237
+ Section 3 -- License Conditions.
238
+
239
+ Your exercise of the Licensed Rights is expressly made subject to the
240
+ following conditions.
241
+
242
+ a. Attribution.
243
+
244
+ 1. If You Share the Licensed Material (including in modified
245
+ form), You must:
246
+
247
+ a. retain the following if it is supplied by the Licensor
248
+ with the Licensed Material:
249
+
250
+ i. identification of the creator(s) of the Licensed
251
+ Material and any others designated to receive
252
+ attribution, in any reasonable manner requested by
253
+ the Licensor (including by pseudonym if
254
+ designated);
255
+
256
+ ii. a copyright notice;
257
+
258
+ iii. a notice that refers to this Public License;
259
+
260
+ iv. a notice that refers to the disclaimer of
261
+ warranties;
262
+
263
+ v. a URI or hyperlink to the Licensed Material to the
264
+ extent reasonably practicable;
265
+
266
+ b. indicate if You modified the Licensed Material and
267
+ retain an indication of any previous modifications; and
268
+
269
+ c. indicate the Licensed Material is licensed under this
270
+ Public License, and include the text of, or the URI or
271
+ hyperlink to, this Public License.
272
+
273
+ 2. You may satisfy the conditions in Section 3(a)(1) in any
274
+ reasonable manner based on the medium, means, and context in
275
+ which You Share the Licensed Material. For example, it may be
276
+ reasonable to satisfy the conditions by providing a URI or
277
+ hyperlink to a resource that includes the required
278
+ information.
279
+ 3. If requested by the Licensor, You must remove any of the
280
+ information required by Section 3(a)(1)(A) to the extent
281
+ reasonably practicable.
282
+
283
+ b. ShareAlike.
284
+
285
+ In addition to the conditions in Section 3(a), if You Share
286
+ Adapted Material You produce, the following conditions also apply.
287
+
288
+ 1. The Adapter's License You apply must be a Creative Commons
289
+ license with the same License Elements, this version or
290
+ later, or a BY-NC-SA Compatible License.
291
+
292
+ 2. You must include the text of, or the URI or hyperlink to, the
293
+ Adapter's License You apply. You may satisfy this condition
294
+ in any reasonable manner based on the medium, means, and
295
+ context in which You Share Adapted Material.
296
+
297
+ 3. You may not offer or impose any additional or different terms
298
+ or conditions on, or apply any Effective Technological
299
+ Measures to, Adapted Material that restrict exercise of the
300
+ rights granted under the Adapter's License You apply.
301
+
302
+
303
+ Section 4 -- Sui Generis Database Rights.
304
+
305
+ Where the Licensed Rights include Sui Generis Database Rights that
306
+ apply to Your use of the Licensed Material:
307
+
308
+ a. for the avoidance of doubt, Section 2(a)(1) grants You the right
309
+ to extract, reuse, reproduce, and Share all or a substantial
310
+ portion of the contents of the database for NonCommercial purposes
311
+ only;
312
+
313
+ b. if You include all or a substantial portion of the database
314
+ contents in a database in which You have Sui Generis Database
315
+ Rights, then the database in which You have Sui Generis Database
316
+ Rights (but not its individual contents) is Adapted Material,
317
+ including for purposes of Section 3(b); and
318
+
319
+ c. You must comply with the conditions in Section 3(a) if You Share
320
+ all or a substantial portion of the contents of the database.
321
+
322
+ For the avoidance of doubt, this Section 4 supplements and does not
323
+ replace Your obligations under this Public License where the Licensed
324
+ Rights include other Copyright and Similar Rights.
325
+
326
+
327
+ Section 5 -- Disclaimer of Warranties and Limitation of Liability.
328
+
329
+ a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE
330
+ EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS
331
+ AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF
332
+ ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS,
333
+ IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION,
334
+ WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR
335
+ PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS,
336
+ ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT
337
+ KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT
338
+ ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU.
339
+
340
+ b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE
341
+ TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION,
342
+ NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT,
343
+ INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES,
344
+ COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR
345
+ USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN
346
+ ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR
347
+ DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR
348
+ IN PART, THIS LIMITATION MAY NOT APPLY TO YOU.
349
+
350
+ c. The disclaimer of warranties and limitation of liability provided
351
+ above shall be interpreted in a manner that, to the extent
352
+ possible, most closely approximates an absolute disclaimer and
353
+ waiver of all liability.
354
+
355
+
356
+ Section 6 -- Term and Termination.
357
+
358
+ a. This Public License applies for the term of the Copyright and
359
+ Similar Rights licensed here. However, if You fail to comply with
360
+ this Public License, then Your rights under this Public License
361
+ terminate automatically.
362
+
363
+ b. Where Your right to use the Licensed Material has terminated under
364
+ Section 6(a), it reinstates:
365
+
366
+ 1. automatically as of the date the violation is cured, provided
367
+ it is cured within 30 days of Your discovery of the
368
+ violation; or
369
+
370
+ 2. upon express reinstatement by the Licensor.
371
+
372
+ For the avoidance of doubt, this Section 6(b) does not affect any
373
+ right the Licensor may have to seek remedies for Your violations
374
+ of this Public License.
375
+
376
+ c. For the avoidance of doubt, the Licensor may also offer the
377
+ Licensed Material under separate terms or conditions or stop
378
+ distributing the Licensed Material at any time; however, doing so
379
+ will not terminate this Public License.
380
+
381
+ d. Sections 1, 5, 6, 7, and 8 survive termination of this Public
382
+ License.
383
+
384
+
385
+ Section 7 -- Other Terms and Conditions.
386
+
387
+ a. The Licensor shall not be bound by any additional or different
388
+ terms or conditions communicated by You unless expressly agreed.
389
+
390
+ b. Any arrangements, understandings, or agreements regarding the
391
+ Licensed Material not stated herein are separate from and
392
+ independent of the terms and conditions of this Public License.
393
+
394
+
395
+ Section 8 -- Interpretation.
396
+
397
+ a. For the avoidance of doubt, this Public License does not, and
398
+ shall not be interpreted to, reduce, limit, restrict, or impose
399
+ conditions on any use of the Licensed Material that could lawfully
400
+ be made without permission under this Public License.
401
+
402
+ b. To the extent possible, if any provision of this Public License is
403
+ deemed unenforceable, it shall be automatically reformed to the
404
+ minimum extent necessary to make it enforceable. If the provision
405
+ cannot be reformed, it shall be severed from this Public License
406
+ without affecting the enforceability of the remaining terms and
407
+ conditions.
408
+
409
+ c. No term or condition of this Public License will be waived and no
410
+ failure to comply consented to unless expressly agreed to by the
411
+ Licensor.
412
+
413
+ d. Nothing in this Public License constitutes or may be interpreted
414
+ as a limitation upon, or waiver of, any privileges and immunities
415
+ that apply to the Licensor or You, including from the legal
416
+ processes of any jurisdiction or authority.
417
+
418
+ =======================================================================
419
+
420
+ Creative Commons is not a party to its public
421
+ licenses. Notwithstanding, Creative Commons may elect to apply one of
422
+ its public licenses to material it publishes and in those instances
423
+ will be considered the 鈥淟icensor.鈥� The text of the Creative Commons
424
+ public licenses is dedicated to the public domain under the CC0 Public
425
+ Domain Dedication. Except for the limited purpose of indicating that
426
+ material is shared under a Creative Commons public license or as
427
+ otherwise permitted by the Creative Commons policies published at
428
+ creativecommons.org/policies, Creative Commons does not authorize the
429
+ use of the trademark "Creative Commons" or any other trademark or logo
430
+ of Creative Commons without its prior written consent including,
431
+ without limitation, in connection with any unauthorized modifications
432
+ to any of its public licenses or any other arrangements,
433
+ understandings, or agreements concerning use of licensed material. For
434
+ the avoidance of doubt, this paragraph does not form part of the
435
+ public licenses.
436
+
437
+ Creative Commons may be contacted at creativecommons.org.
ORIGINAL_README.md ADDED
@@ -0,0 +1,167 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Auffusion: Leveraging the Power of Diffusion and Large Language Models for Text-to-Audio Generation
2
+
3
+
4
+ [Paper](https://arxiv.org/pdf/2401.01044) | [Model](https://huggingface.co/auffusion/auffusion) | [Website and Examples](https://auffusion.github.io) | [Audio Manipulation Notebooks](https://github.com/happylittlecat2333/Auffusion/tree/main/notebooks/README.md) | [Hugging Face Models](https://huggingface.co/auffusion) | [Google Colab](https://colab.research.google.com/drive/1JEPHT_AvHZxvlaZAsetkBnMrzCGMRKaf?usp=sharing)
5
+
6
+
7
+ ## Description
8
+
9
+ **Auffusion** is a latent diffusion model (LDM) for text-to-audio (TTA) generation. **Auffusion** can generate realistic audios including human sounds, animal sounds, natural and artificial sounds and sound effects from textual prompts. We introduce Auffusion, a TTA system adapting T2I model frameworks to TTA task, by effectively leveraging their inherent generative strengths and precise cross-modal alignment. Our objective and subjective evaluations demonstrate that Auffusion surpasses previous TTA approaches using limited data and computational resource. We release our model, inference code, and pre-trained checkpoints for the research community.
10
+
11
+
12
+ <p align="center">
13
+ <img src=img/overview.png />
14
+ </p>
15
+
16
+
17
+ ## 🚀 News
18
+ - **2024/01/02**: 📣 [Colab notebooks](notebooks/README.md) for audio manipulation is released. Feel free to try!
19
+
20
+ - **2023/12/31**: 📣 Auffusion release.[Demo website](https://auffusion.github.io/) and 3 models are released in [Hugging Face](https://huggingface.co/auffusion).
21
+
22
+
23
+ ## Auffusion Model Family
24
+
25
+ | Model Name | Model Path |
26
+ |----------------------------|------------------------------------------------------------------------------------------------------------------------ |
27
+ | Auffusion | [https://huggingface.co/auffusion/auffusion](https://huggingface.co/auffusion/auffusion) |
28
+ | Auffusion-Full | [https://huggingface.co/auffusion/auffusion-full](https://huggingface.co/auffusion/auffusion-full) |
29
+ | Auffusion-Full-no-adapter | [https://huggingface.co/auffusion/auffusion-full-no-adapter](https://huggingface.co/auffusion/auffusion-full-no-adapter)|
30
+
31
+
32
+
33
+ ## 📀 Prerequisites
34
+
35
+ Our code is built on pytorch version 2.0.1. We mention `torch==2.0.1` in the requirements file but you might need to install a specific cuda version of torch depending on your GPU device type. We also depend on `diffusers==0.18.2`.
36
+
37
+ Install `requirements.txt`.
38
+
39
+ ```bash
40
+ git clone https://github.com/happylittlecat2333/Auffusion/
41
+ cd Auffusion
42
+ pip install -r requirements.txt
43
+ ```
44
+
45
+ You might also need to install `libsndfile1` for soundfile to work properly in linux:
46
+
47
+ ```bash
48
+ (sudo) apt-get install libsndfile1
49
+ ```
50
+
51
+
52
+ ## ⭐ Quickstart Guide
53
+
54
+ Download the **Auffusion** model and generate audio from a text prompt:
55
+
56
+ ```python
57
+ import IPython, torch
58
+ import soundfile as sf
59
+ from auffusion_pipeline import AuffusionPipeline
60
+
61
+ pipeline = AuffusionPipeline.from_pretrained("auffusion/auffusion")
62
+
63
+ prompt = "Birds singing sweetly in a blooming garden"
64
+ output = pipeline(prompt=prompt)
65
+ audio = output.audios[0]
66
+ sf.write(f"{prompt}.wav", audio, samplerate=16000)
67
+ IPython.display.Audio(data=audio, rate=16000)
68
+ ```
69
+
70
+ The auffusion model will be automatically downloaded from Hugging Face and saved in cache. Subsequent runs will load the model directly from cache.
71
+
72
+ The `generate` function uses 100 steps and 7.5 guidance_scale by default to sample from the latent diffusion model. You can also vary parameters for different results.
73
+
74
+ ```python
75
+ prompt = "Rolling thunder with lightning strikes"
76
+ output = pipeline(prompt=prompt, num_inference_steps=100, guidance_scale=7.5)
77
+ audio = output.audios[0]
78
+ IPython.display.Audio(data=audio, rate=16000)
79
+ ```
80
+
81
+
82
+ More generated samples are shown [here](https://auffusion.github.io). You can also try out the [colab notebook](https://colab.research.google.com/drive/1JEPHT_AvHZxvlaZAsetkBnMrzCGMRKaf?usp=sharing) to generate your own audio samples.
83
+
84
+
85
+ ## 🐍 How to make inferences?
86
+
87
+ ### From our released checkpoints in Hugging Face Hub
88
+
89
+ To perform audio generation in AudioCaps test set from our Hugging Face checkpoints:
90
+
91
+ ```bash
92
+ python inference.py \
93
+ --pretrained_model_name_or_path="auffusion/auffusion" \
94
+ --test_data_dir="./data/test_audiocaps.raw.json" \
95
+ --output_dir="./output/auffusion_hf" \
96
+ --enable_xformers_memory_efficient_attention \
97
+ ```
98
+
99
+ ### Note
100
+
101
+ We use the evaluation tools from [https://github.com/haoheliu/audioldm_eval](https://github.com/haoheliu/audioldm_eval) to evaluate our models, and we adopt [https://huggingface.co/laion/clap-htsat-unfused](https://huggingface.co/laion/clap-htsat-unfused) to compute CLAP score.
102
+
103
+ Some data instances originally released in AudioCaps have since been removed from YouTube and are no longer available. We thus evaluated our models on all the instances which were available as June, 2023.
104
+
105
+ ## Audio Manipulation
106
+
107
+ We show some examples of audio manipulation using Auffusion. Current audio manipulation methods include:
108
+
109
+ - Text-to-audio generation: [notebook](notebooks/text_to_audio.ipynb) or [colab](https://colab.research.google.com/drive/1JEPHT_AvHZxvlaZAsetkBnMrzCGMRKaf?usp=sharing)
110
+ - Text-guided style transfer: [notebook](notebooks/img2img.ipynb) or [colab](https://colab.research.google.com/drive/1VjgryIz7kSXDzgCClqtqVgoDXIECeG0M?usp=sharing)
111
+ - Audio inpainting: [notebook](notebooks/inpainting.ipynb) or [colab](https://colab.research.google.com/drive/1NsqeiutoAynhtaZnlhzBdTXtZ27tQxVc?usp=sharing)
112
+ - attention-based word swap control: [notebook](notebooks/word_swap.ipynb) or [colab](https://colab.research.google.com/drive/18CtUoBMsPbgzeI-o0wHDYTtaErnq9KoI?usp=sharing)
113
+ - attention-based reweight control: [notebook](notebooks/reweight.ipynb) or [colab](https://colab.research.google.com/drive/18CtUoBMsPbgzeI-o0wHDYTtaErnq9KoI?usp=sharing)
114
+
115
+ The audio manipulation code examples can all be found in [notebooks](notebooks/README.md).
116
+
117
+ # TODO
118
+
119
+ [!["Buy Me A Coffee"](https://www.buymeacoffee.com/assets/img/custom_images/orange_img.png)](https://www.buymeacoffee.com/happylittlecat)
120
+
121
+ - [x] Publish demo website and arxiv link.
122
+ - [x] Publish Auffusion and Auffusion-Full checkpoints.
123
+ - [x] Add text-guided style transfer.
124
+ - [x] Add audio-to-audio generation.
125
+ - [x] Add audio inpainting.
126
+ - [x] Add word_swap and reweight prompt2prompt-based control.
127
+ - [ ] Add audio super-resolution.
128
+ - [ ] Build Gradio web application.
129
+ - [ ] Add audio-to-audio, inpainting into Gradio web application.
130
+ - [ ] Add style-transfer into Gradio web application.
131
+ - [ ] Add audio super-resolution into Gradio web application.
132
+ - [ ] Add prompt2prompt-based control into Gradio web application.
133
+ - [ ] Add data preprocess and training code.
134
+
135
+
136
+
137
+ ## 📚 Citation
138
+ Please consider citing the following article if you found our work useful:
139
+
140
+ ```bibtex
141
+ @article{xue2024auffusion,
142
+ title={Auffusion: Leveraging the Power of Diffusion and Large Language Models for Text-to-Audio Generation},
143
+ author={Jinlong Xue and Yayue Deng and Yingming Gao and Ya Li},
144
+ journal={arXiv preprint arXiv:2401.01044},
145
+ year={2024}
146
+ }
147
+ ```
148
+
149
+ ## 🙏 Acknowledgement
150
+ Part of the code is borrowed from the following repos. We would like to thank the authors of these repos for their contribution.
151
+
152
+ - https://github.com/huggingface/diffusers
153
+
154
+ - https://github.com/huggingface/transformers
155
+
156
+ - https://github.com/google/prompt-to-prompt
157
+
158
+ - https://github.com/declare-lab/tango
159
+
160
+ - https://github.com/riffusion/riffusion
161
+
162
+ - https://github.com/haoheliu/audioldm_eval
163
+
164
+
165
+ ## Contact
166
+
167
+ If you have any problems regarding the paper, code, models, or the project itself, please feel free to open an issue or contact [Jinlong Xue](mailto:[email protected]) directly :)
auffusion_pipeline.py ADDED
@@ -0,0 +1,1039 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import inspect
16
+ import warnings
17
+ from typing import Any, Callable, Dict, List, Optional, Union
18
+ from dataclasses import dataclass
19
+
20
+ import torch
21
+ from packaging import version
22
+ from transformers import CLIPImageProcessor, CLIPTextModel, CLIPTokenizer
23
+
24
+ from diffusers.configuration_utils import FrozenDict
25
+ from diffusers.image_processor import VaeImageProcessor
26
+ from diffusers.loaders import FromSingleFileMixin, LoraLoaderMixin, TextualInversionLoaderMixin
27
+ from diffusers.models import AutoencoderKL, UNet2DConditionModel
28
+ from diffusers.schedulers import KarrasDiffusionSchedulers
29
+ from diffusers.utils import (
30
+ deprecate,
31
+ is_accelerate_available,
32
+ is_accelerate_version,
33
+ logging,
34
+ randn_tensor,
35
+ replace_example_docstring,
36
+ )
37
+ from diffusers.pipelines.pipeline_utils import DiffusionPipeline
38
+ from diffusers.pipelines.stable_diffusion import StableDiffusionPipelineOutput
39
+ from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker
40
+ from huggingface_hub import snapshot_download
41
+ from diffusers import AutoencoderKL, DDPMScheduler, UNet2DConditionModel, PNDMScheduler
42
+ from transformers import PretrainedConfig, AutoTokenizer
43
+ import torch.nn as nn
44
+ import os, json, PIL
45
+ import numpy as np
46
+ import torch.nn.functional as F
47
+ from torch.nn import Conv1d, ConvTranspose1d, AvgPool1d, Conv2d
48
+ from torch.nn.utils import weight_norm, remove_weight_norm, spectral_norm
49
+ from diffusers.utils.outputs import BaseOutput
50
+ import matplotlib.pyplot as plt
51
+
52
+
53
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
54
+
55
+
56
+
57
+ def json_dump(data_json, json_save_path):
58
+ with open(json_save_path, 'w') as f:
59
+ json.dump(data_json, f, indent=4)
60
+ f.close()
61
+
62
+
63
+ def json_load(json_path):
64
+ with open(json_path, 'r') as f:
65
+ data = json.load(f)
66
+ f.close()
67
+ return data
68
+
69
+
70
+ def import_model_class_from_model_name_or_path(pretrained_model_name_or_path: str):
71
+ text_encoder_config = PretrainedConfig.from_pretrained(
72
+ pretrained_model_name_or_path
73
+ )
74
+ model_class = text_encoder_config.architectures[0]
75
+
76
+ if model_class == "CLIPTextModel":
77
+ from transformers import CLIPTextModel
78
+ return CLIPTextModel
79
+ if "t5" in model_class.lower():
80
+ from transformers import T5EncoderModel
81
+ return T5EncoderModel
82
+ if "clap" in model_class.lower():
83
+ from transformers import ClapTextModelWithProjection
84
+ return ClapTextModelWithProjection
85
+ else:
86
+ raise ValueError(f"{model_class} is not supported.")
87
+
88
+
89
+ class ConditionAdapter(nn.Module):
90
+ def __init__(self, config):
91
+ super(ConditionAdapter, self).__init__()
92
+ self.config = config
93
+ self.proj = nn.Linear(self.config["condition_dim"], self.config["cross_attention_dim"])
94
+ self.norm = torch.nn.LayerNorm(self.config["cross_attention_dim"])
95
+ print(f"INITIATED: ConditionAdapter: {self.config}")
96
+
97
+ def forward(self, x):
98
+ x = self.proj(x)
99
+ x = self.norm(x)
100
+ return x
101
+
102
+ @classmethod
103
+ def from_pretrained(cls, pretrained_model_name_or_path):
104
+ config_path = os.path.join(pretrained_model_name_or_path, "config.json")
105
+ ckpt_path = os.path.join(pretrained_model_name_or_path, "condition_adapter.pt")
106
+ config = json.loads(open(config_path).read())
107
+ instance = cls(config)
108
+ instance.load_state_dict(torch.load(ckpt_path))
109
+ print(f"LOADED: ConditionAdapter from {pretrained_model_name_or_path}")
110
+ return instance
111
+
112
+ def save_pretrained(self, pretrained_model_name_or_path):
113
+ os.makedirs(pretrained_model_name_or_path, exist_ok=True)
114
+ config_path = os.path.join(pretrained_model_name_or_path, "config.json")
115
+ ckpt_path = os.path.join(pretrained_model_name_or_path, "condition_adapter.pt")
116
+ json_dump(self.config, config_path)
117
+ torch.save(self.state_dict(), ckpt_path)
118
+ print(f"SAVED: ConditionAdapter {self.config['model_name']} to {pretrained_model_name_or_path}")
119
+
120
+
121
+ def rescale_noise_cfg(noise_cfg, noise_pred_text, guidance_rescale=0.0):
122
+ """
123
+ Rescale `noise_cfg` according to `guidance_rescale`. Based on findings of [Common Diffusion Noise Schedules and
124
+ Sample Steps are Flawed](https://arxiv.org/pdf/2305.08891.pdf). See Section 3.4
125
+ """
126
+ std_text = noise_pred_text.std(dim=list(range(1, noise_pred_text.ndim)), keepdim=True)
127
+ std_cfg = noise_cfg.std(dim=list(range(1, noise_cfg.ndim)), keepdim=True)
128
+ # rescale the results from guidance (fixes overexposure)
129
+ noise_pred_rescaled = noise_cfg * (std_text / std_cfg)
130
+ # mix with the original results from guidance by factor guidance_rescale to avoid "plain looking" images
131
+ noise_cfg = guidance_rescale * noise_pred_rescaled + (1 - guidance_rescale) * noise_cfg
132
+ return noise_cfg
133
+
134
+
135
+
136
+ LRELU_SLOPE = 0.1
137
+ MAX_WAV_VALUE = 32768.0
138
+
139
+
140
+ class AttrDict(dict):
141
+ def __init__(self, *args, **kwargs):
142
+ super(AttrDict, self).__init__(*args, **kwargs)
143
+ self.__dict__ = self
144
+
145
+
146
+ def get_config(config_path):
147
+ config = json.loads(open(config_path).read())
148
+ config = AttrDict(config)
149
+ return config
150
+
151
+ def init_weights(m, mean=0.0, std=0.01):
152
+ classname = m.__class__.__name__
153
+ if classname.find("Conv") != -1:
154
+ m.weight.data.normal_(mean, std)
155
+
156
+
157
+ def apply_weight_norm(m):
158
+ classname = m.__class__.__name__
159
+ if classname.find("Conv") != -1:
160
+ weight_norm(m)
161
+
162
+
163
+ def get_padding(kernel_size, dilation=1):
164
+ return int((kernel_size*dilation - dilation)/2)
165
+
166
+
167
+ class ResBlock1(torch.nn.Module):
168
+ def __init__(self, h, channels, kernel_size=3, dilation=(1, 3, 5)):
169
+ super(ResBlock1, self).__init__()
170
+ self.h = h
171
+ self.convs1 = nn.ModuleList([
172
+ weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=dilation[0],
173
+ padding=get_padding(kernel_size, dilation[0]))),
174
+ weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=dilation[1],
175
+ padding=get_padding(kernel_size, dilation[1]))),
176
+ weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=dilation[2],
177
+ padding=get_padding(kernel_size, dilation[2])))
178
+ ])
179
+ self.convs1.apply(init_weights)
180
+
181
+ self.convs2 = nn.ModuleList([
182
+ weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=1,
183
+ padding=get_padding(kernel_size, 1))),
184
+ weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=1,
185
+ padding=get_padding(kernel_size, 1))),
186
+ weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=1,
187
+ padding=get_padding(kernel_size, 1)))
188
+ ])
189
+ self.convs2.apply(init_weights)
190
+
191
+ def forward(self, x):
192
+ for c1, c2 in zip(self.convs1, self.convs2):
193
+ xt = F.leaky_relu(x, LRELU_SLOPE)
194
+ xt = c1(xt)
195
+ xt = F.leaky_relu(xt, LRELU_SLOPE)
196
+ xt = c2(xt)
197
+ x = xt + x
198
+ return x
199
+
200
+ def remove_weight_norm(self):
201
+ for l in self.convs1:
202
+ remove_weight_norm(l)
203
+ for l in self.convs2:
204
+ remove_weight_norm(l)
205
+
206
+
207
+ class ResBlock2(torch.nn.Module):
208
+ def __init__(self, h, channels, kernel_size=3, dilation=(1, 3)):
209
+ super(ResBlock2, self).__init__()
210
+ self.h = h
211
+ self.convs = nn.ModuleList([
212
+ weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=dilation[0],
213
+ padding=get_padding(kernel_size, dilation[0]))),
214
+ weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=dilation[1],
215
+ padding=get_padding(kernel_size, dilation[1])))
216
+ ])
217
+ self.convs.apply(init_weights)
218
+
219
+ def forward(self, x):
220
+ for c in self.convs:
221
+ xt = F.leaky_relu(x, LRELU_SLOPE)
222
+ xt = c(xt)
223
+ x = xt + x
224
+ return x
225
+
226
+ def remove_weight_norm(self):
227
+ for l in self.convs:
228
+ remove_weight_norm(l)
229
+
230
+
231
+
232
+ class Generator(torch.nn.Module):
233
+ def __init__(self, h):
234
+ super(Generator, self).__init__()
235
+ self.h = h
236
+ self.num_kernels = len(h.resblock_kernel_sizes)
237
+ self.num_upsamples = len(h.upsample_rates)
238
+ # self.conv_pre = weight_norm(Conv1d(80, h.upsample_initial_channel, 7, 1, padding=3))
239
+ self.conv_pre = weight_norm(Conv1d(h.num_mels, h.upsample_initial_channel, 7, 1, padding=3)) # change: 80 --> 512
240
+ resblock = ResBlock1 if h.resblock == '1' else ResBlock2
241
+
242
+ self.ups = nn.ModuleList()
243
+ for i, (u, k) in enumerate(zip(h.upsample_rates, h.upsample_kernel_sizes)):
244
+ if (k-u) % 2 == 0:
245
+ self.ups.append(weight_norm(
246
+ ConvTranspose1d(h.upsample_initial_channel//(2**i), h.upsample_initial_channel//(2**(i+1)),
247
+ k, u, padding=(k-u)//2)))
248
+ else:
249
+ self.ups.append(weight_norm(
250
+ ConvTranspose1d(h.upsample_initial_channel//(2**i), h.upsample_initial_channel//(2**(i+1)),
251
+ k, u, padding=(k-u)//2+1, output_padding=1)))
252
+
253
+ # self.ups.append(weight_norm(
254
+ # ConvTranspose1d(h.upsample_initial_channel//(2**i), h.upsample_initial_channel//(2**(i+1)),
255
+ # k, u, padding=(k-u)//2)))
256
+
257
+
258
+ self.resblocks = nn.ModuleList()
259
+ for i in range(len(self.ups)):
260
+ ch = h.upsample_initial_channel//(2**(i+1))
261
+ for j, (k, d) in enumerate(zip(h.resblock_kernel_sizes, h.resblock_dilation_sizes)):
262
+ self.resblocks.append(resblock(h, ch, k, d))
263
+
264
+ self.conv_post = weight_norm(Conv1d(ch, 1, 7, 1, padding=3))
265
+ self.ups.apply(init_weights)
266
+ self.conv_post.apply(init_weights)
267
+
268
+ def forward(self, x):
269
+ x = self.conv_pre(x)
270
+ for i in range(self.num_upsamples):
271
+ x = F.leaky_relu(x, LRELU_SLOPE)
272
+ x = self.ups[i](x)
273
+ xs = None
274
+ for j in range(self.num_kernels):
275
+ if xs is None:
276
+ xs = self.resblocks[i*self.num_kernels+j](x)
277
+ else:
278
+ xs += self.resblocks[i*self.num_kernels+j](x)
279
+ x = xs / self.num_kernels
280
+ x = F.leaky_relu(x)
281
+ x = self.conv_post(x)
282
+ x = torch.tanh(x)
283
+
284
+ return x
285
+
286
+ def remove_weight_norm(self):
287
+ print('Removing weight norm...')
288
+ for l in self.ups:
289
+ remove_weight_norm(l)
290
+ for l in self.resblocks:
291
+ l.remove_weight_norm()
292
+ remove_weight_norm(self.conv_pre)
293
+ remove_weight_norm(self.conv_post)
294
+
295
+ @classmethod
296
+ def from_pretrained(cls, pretrained_model_name_or_path, subfolder=None):
297
+ if subfolder is not None:
298
+ pretrained_model_name_or_path = os.path.join(pretrained_model_name_or_path, subfolder)
299
+ config_path = os.path.join(pretrained_model_name_or_path, "config.json")
300
+ ckpt_path = os.path.join(pretrained_model_name_or_path, "vocoder.pt")
301
+
302
+ config = get_config(config_path)
303
+ vocoder = cls(config)
304
+
305
+ state_dict_g = torch.load(ckpt_path)
306
+ vocoder.load_state_dict(state_dict_g["generator"])
307
+ vocoder.eval()
308
+ vocoder.remove_weight_norm()
309
+ return vocoder
310
+
311
+ @torch.no_grad()
312
+ def inference(self, mels, lengths=None):
313
+ self.eval()
314
+ with torch.no_grad():
315
+ wavs = self(mels).squeeze(1)
316
+
317
+ wavs = (wavs.cpu().numpy() * MAX_WAV_VALUE).astype("int16")
318
+
319
+ if lengths is not None:
320
+ wavs = wavs[:, :lengths]
321
+
322
+ return wavs
323
+
324
+
325
+
326
+ def normalize_spectrogram(
327
+ spectrogram: torch.Tensor,
328
+ max_value: float = 200,
329
+ min_value: float = 1e-5,
330
+ power: float = 1.,
331
+ ) -> torch.Tensor:
332
+
333
+ # Rescale to 0-1
334
+ max_value = np.log(max_value) # 5.298317366548036
335
+ min_value = np.log(min_value) # -11.512925464970229
336
+ spectrogram = torch.clamp(spectrogram, min=min_value, max=max_value)
337
+ data = (spectrogram - min_value) / (max_value - min_value)
338
+ # Apply the power curve
339
+ data = torch.pow(data, power)
340
+ # 1D -> 3D
341
+ data = data.repeat(3, 1, 1)
342
+ # Flip Y axis: image origin at the top-left corner, spectrogram origin at the bottom-left corner
343
+ data = torch.flip(data, [1])
344
+
345
+ return data
346
+
347
+
348
+ def denormalize_spectrogram(
349
+ data: torch.Tensor,
350
+ max_value: float = 200,
351
+ min_value: float = 1e-5,
352
+ power: float = 1,
353
+ ) -> torch.Tensor:
354
+
355
+ assert len(data.shape) == 3, "Expected 3 dimensions, got {}".format(len(data.shape))
356
+
357
+ max_value = np.log(max_value)
358
+ min_value = np.log(min_value)
359
+ # Flip Y axis: image origin at the top-left corner, spectrogram origin at the bottom-left corner
360
+ data = torch.flip(data, [1])
361
+ if data.shape[0] == 1:
362
+ data = data.repeat(3, 1, 1)
363
+ assert data.shape[0] == 3, "Expected 3 channels, got {}".format(data.shape[0])
364
+ data = data[0]
365
+ # Reverse the power curve
366
+ data = torch.pow(data, 1 / power)
367
+ # Rescale to max value
368
+ spectrogram = data * (max_value - min_value) + min_value
369
+
370
+ return spectrogram
371
+
372
+ @staticmethod
373
+ def pt_to_numpy(images: torch.FloatTensor) -> np.ndarray:
374
+ """
375
+ Convert a PyTorch tensor to a NumPy image.
376
+ """
377
+ images = images.cpu().permute(0, 2, 3, 1).float().numpy()
378
+ return images
379
+
380
+ @staticmethod
381
+ def numpy_to_pil(images: np.ndarray) -> PIL.Image.Image:
382
+ """
383
+ Convert a numpy image or a batch of images to a PIL image.
384
+ """
385
+ if images.ndim == 3:
386
+ images = images[None, ...]
387
+ images = (images * 255).round().astype("uint8")
388
+ if images.shape[-1] == 1:
389
+ # special case for grayscale (single channel) images
390
+ pil_images = [PIL.Image.fromarray(image.squeeze(), mode="L") for image in images]
391
+ else:
392
+ pil_images = [PIL.Image.fromarray(image) for image in images]
393
+
394
+ return pil_images
395
+
396
+
397
+ def image_add_color(spec_img):
398
+ cmap = plt.get_cmap('viridis')
399
+ cmap_r = cmap.reversed()
400
+ image = cmap(np.array(spec_img)[:,:,0])[:, :, :3] # 省略透明度通道
401
+ image = (image - image.min()) / (image.max() - image.min())
402
+ image = PIL.Image.fromarray(np.uint8(image*255))
403
+ return image
404
+
405
+
406
+ @dataclass
407
+ class PipelineOutput(BaseOutput):
408
+ """
409
+ Output class for audio pipelines.
410
+
411
+ Args:
412
+ audios (`np.ndarray`)
413
+ List of denoised audio samples of a NumPy array of shape `(batch_size, num_channels, sample_rate)`.
414
+ """
415
+
416
+ images: Union[List[PIL.Image.Image], np.ndarray]
417
+ spectrograms: Union[List[np.ndarray], np.ndarray]
418
+ audios: Union[List[np.ndarray], np.ndarray]
419
+
420
+
421
+
422
+ class AuffusionPipeline(DiffusionPipeline):
423
+
424
+ r"""
425
+ Pipeline for text-to-image generation using Stable Diffusion.
426
+
427
+ This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods the
428
+ library implements for all the pipelines (such as downloading or saving, running on a particular device, etc.)
429
+
430
+ In addition the pipeline inherits the following loading methods:
431
+ - *Textual-Inversion*: [`loaders.TextualInversionLoaderMixin.load_textual_inversion`]
432
+ - *LoRA*: [`loaders.LoraLoaderMixin.load_lora_weights`]
433
+ - *Ckpt*: [`loaders.FromSingleFileMixin.from_single_file`]
434
+
435
+ as well as the following saving methods:
436
+ - *LoRA*: [`loaders.LoraLoaderMixin.save_lora_weights`]
437
+
438
+ Args:
439
+ vae ([`AutoencoderKL`]):
440
+ Variational Auto-Encoder (VAE) Model to encode and decode images to and from latent representations.
441
+ text_encoder ([`CLIPTextModel`]):
442
+ Frozen text-encoder. Stable Diffusion uses the text portion of
443
+ [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel), specifically
444
+ the [clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14) variant.
445
+ tokenizer (`CLIPTokenizer`):
446
+ Tokenizer of class
447
+ [CLIPTokenizer](https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer).
448
+ unet ([`UNet2DConditionModel`]): Conditional U-Net architecture to denoise the encoded image latents.
449
+ scheduler ([`SchedulerMixin`]):
450
+ A scheduler to be used in combination with `unet` to denoise the encoded image latents. Can be one of
451
+ [`DDIMScheduler`], [`LMSDiscreteScheduler`], or [`PNDMScheduler`].
452
+ safety_checker ([`StableDiffusionSafetyChecker`]):
453
+ Classification module that estimates whether generated images could be considered offensive or harmful.
454
+ Please, refer to the [model card](https://huggingface.co/runwayml/stable-diffusion-v1-5) for details.
455
+ feature_extractor ([`CLIPImageProcessor`]):
456
+ Model that extracts features from generated images to be used as inputs for the `safety_checker`.
457
+ """
458
+ _optional_components = ["safety_checker", "feature_extractor", "text_encoder_list", "tokenizer_list", "adapter_list", "vocoder"]
459
+
460
+ def __init__(
461
+ self,
462
+ vae: AutoencoderKL,
463
+ unet: UNet2DConditionModel,
464
+ scheduler: KarrasDiffusionSchedulers,
465
+ safety_checker: StableDiffusionSafetyChecker,
466
+ feature_extractor: CLIPImageProcessor,
467
+ text_encoder_list: Optional[List[Callable]] = None,
468
+ tokenizer_list: Optional[List[Callable]] = None,
469
+ vocoder: Generator = None,
470
+ requires_safety_checker: bool = False,
471
+ adapter_list: Optional[List[Callable]] = None,
472
+ tokenizer_model_max_length: Optional[int] = 77, # 77 is the default value for the CLIPTokenizer(and set for other models)
473
+ ):
474
+ super().__init__()
475
+
476
+ self.text_encoder_list = text_encoder_list
477
+ self.tokenizer_list = tokenizer_list
478
+ self.vocoder = vocoder
479
+ self.adapter_list = adapter_list
480
+ self.tokenizer_model_max_length = tokenizer_model_max_length
481
+
482
+ self.register_modules(
483
+ vae=vae,
484
+ unet=unet,
485
+ scheduler=scheduler,
486
+ safety_checker=safety_checker,
487
+ feature_extractor=feature_extractor,
488
+ )
489
+
490
+ self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1)
491
+ self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor)
492
+ self.register_to_config(requires_safety_checker=requires_safety_checker)
493
+
494
+
495
+ @classmethod
496
+ def from_pretrained(
497
+ cls,
498
+ pretrained_model_name_or_path: str = "auffusion/auffusion",
499
+ dtype: torch.dtype = torch.float16,
500
+ device: str = "cuda",
501
+ ):
502
+ if not os.path.isdir(pretrained_model_name_or_path):
503
+ pretrained_model_name_or_path = snapshot_download(pretrained_model_name_or_path)
504
+
505
+ vae = AutoencoderKL.from_pretrained(pretrained_model_name_or_path, subfolder="vae")
506
+ unet = UNet2DConditionModel.from_pretrained(pretrained_model_name_or_path, subfolder="unet")
507
+ feature_extractor = CLIPImageProcessor.from_pretrained(pretrained_model_name_or_path, subfolder="feature_extractor")
508
+ scheduler = PNDMScheduler.from_pretrained(pretrained_model_name_or_path, subfolder="scheduler")
509
+
510
+ vocoder = Generator.from_pretrained(pretrained_model_name_or_path, subfolder="vocoder").to(device, dtype)
511
+
512
+ text_encoder_list, tokenizer_list, adapter_list = [], [], []
513
+
514
+ condition_json_path = os.path.join(pretrained_model_name_or_path, "condition_config.json")
515
+ condition_json_list = json.loads(open(condition_json_path).read())
516
+
517
+ for i, condition_item in enumerate(condition_json_list):
518
+
519
+ # Load Condition Adapter
520
+ text_encoder_path = os.path.join(pretrained_model_name_or_path, condition_item["text_encoder_name"])
521
+ tokenizer = AutoTokenizer.from_pretrained(text_encoder_path)
522
+ tokenizer_list.append(tokenizer)
523
+ text_encoder_cls = import_model_class_from_model_name_or_path(text_encoder_path)
524
+ text_encoder = text_encoder_cls.from_pretrained(text_encoder_path).to(device, dtype)
525
+ text_encoder_list.append(text_encoder)
526
+ print(f"LOADING CONDITION ENCODER {i}")
527
+
528
+ # Load Condition Adapter
529
+ adapter_path = os.path.join(pretrained_model_name_or_path, condition_item["condition_adapter_name"])
530
+ adapter = ConditionAdapter.from_pretrained(adapter_path).to(device, dtype)
531
+ adapter_list.append(adapter)
532
+ print(f"LOADING CONDITION ADAPTER {i}")
533
+
534
+
535
+ pipeline = cls(
536
+ vae=vae,
537
+ unet=unet,
538
+ text_encoder_list=text_encoder_list,
539
+ tokenizer_list=tokenizer_list,
540
+ vocoder=vocoder,
541
+ adapter_list=adapter_list,
542
+ scheduler=scheduler,
543
+ safety_checker=None,
544
+ feature_extractor=feature_extractor,
545
+ )
546
+ pipeline = pipeline.to(device, dtype)
547
+
548
+ return pipeline
549
+
550
+
551
+ def to(self, device, dtype=None):
552
+ super().to(device, dtype)
553
+
554
+ self.vocoder.to(device, dtype)
555
+
556
+ for text_encoder in self.text_encoder_list:
557
+ text_encoder.to(device, dtype)
558
+
559
+ if self.adapter_list is not None:
560
+ for adapter in self.adapter_list:
561
+ adapter.to(device, dtype)
562
+
563
+ return self
564
+
565
+
566
+ def enable_vae_slicing(self):
567
+ r"""
568
+ Enable sliced VAE decoding.
569
+
570
+ When this option is enabled, the VAE will split the input tensor in slices to compute decoding in several
571
+ steps. This is useful to save some memory and allow larger batch sizes.
572
+ """
573
+ self.vae.enable_slicing()
574
+
575
+ def disable_vae_slicing(self):
576
+ r"""
577
+ Disable sliced VAE decoding. If `enable_vae_slicing` was previously invoked, this method will go back to
578
+ computing decoding in one step.
579
+ """
580
+ self.vae.disable_slicing()
581
+
582
+ def enable_vae_tiling(self):
583
+ r"""
584
+ Enable tiled VAE decoding.
585
+
586
+ When this option is enabled, the VAE will split the input tensor into tiles to compute decoding and encoding in
587
+ several steps. This is useful to save a large amount of memory and to allow the processing of larger images.
588
+ """
589
+ self.vae.enable_tiling()
590
+
591
+ def disable_vae_tiling(self):
592
+ r"""
593
+ Disable tiled VAE decoding. If `enable_vae_tiling` was previously invoked, this method will go back to
594
+ computing decoding in one step.
595
+ """
596
+ self.vae.disable_tiling()
597
+
598
+ def enable_sequential_cpu_offload(self, gpu_id=0):
599
+ r"""
600
+ Offloads all models to CPU using accelerate, significantly reducing memory usage. When called, unet,
601
+ text_encoder, vae and safety checker have their state dicts saved to CPU and then are moved to a
602
+ `torch.device('meta') and loaded to GPU only when their specific submodule has its `forward` method called.
603
+ Note that offloading happens on a submodule basis. Memory savings are higher than with
604
+ `enable_model_cpu_offload`, but performance is lower.
605
+ """
606
+ if is_accelerate_available() and is_accelerate_version(">=", "0.14.0"):
607
+ from accelerate import cpu_offload
608
+ else:
609
+ raise ImportError("`enable_sequential_cpu_offload` requires `accelerate v0.14.0` or higher")
610
+
611
+ device = torch.device(f"cuda:{gpu_id}")
612
+
613
+ if self.device.type != "cpu":
614
+ self.to("cpu", silence_dtype_warnings=True)
615
+ torch.cuda.empty_cache() # otherwise we don't see the memory savings (but they probably exist)
616
+
617
+ for cpu_offloaded_model in [self.unet, self.text_encoder, self.vae]:
618
+ cpu_offload(cpu_offloaded_model, device)
619
+
620
+ if self.safety_checker is not None:
621
+ cpu_offload(self.safety_checker, execution_device=device, offload_buffers=True)
622
+
623
+ def enable_model_cpu_offload(self, gpu_id=0):
624
+ r"""
625
+ Offloads all models to CPU using accelerate, reducing memory usage with a low impact on performance. Compared
626
+ to `enable_sequential_cpu_offload`, this method moves one whole model at a time to the GPU when its `forward`
627
+ method is called, and the model remains in GPU until the next model runs. Memory savings are lower than with
628
+ `enable_sequential_cpu_offload`, but performance is much better due to the iterative execution of the `unet`.
629
+ """
630
+ if is_accelerate_available() and is_accelerate_version(">=", "0.17.0.dev0"):
631
+ from accelerate import cpu_offload_with_hook
632
+ else:
633
+ raise ImportError("`enable_model_cpu_offload` requires `accelerate v0.17.0` or higher.")
634
+
635
+ device = torch.device(f"cuda:{gpu_id}")
636
+
637
+ if self.device.type != "cpu":
638
+ self.to("cpu", silence_dtype_warnings=True)
639
+ torch.cuda.empty_cache() # otherwise we don't see the memory savings (but they probably exist)
640
+
641
+ hook = None
642
+ for cpu_offloaded_model in [self.text_encoder, self.unet, self.vae]:
643
+ _, hook = cpu_offload_with_hook(cpu_offloaded_model, device, prev_module_hook=hook)
644
+
645
+ if self.safety_checker is not None:
646
+ _, hook = cpu_offload_with_hook(self.safety_checker, device, prev_module_hook=hook)
647
+
648
+ # We'll offload the last model manually.
649
+ self.final_offload_hook = hook
650
+
651
+ @property
652
+ def _execution_device(self):
653
+ r"""
654
+ Returns the device on which the pipeline's models will be executed. After calling
655
+ `pipeline.enable_sequential_cpu_offload()` the execution device can only be inferred from Accelerate's module
656
+ hooks.
657
+ """
658
+ if not hasattr(self.unet, "_hf_hook"):
659
+ return self.device
660
+ for module in self.unet.modules():
661
+ if (
662
+ hasattr(module, "_hf_hook")
663
+ and hasattr(module._hf_hook, "execution_device")
664
+ and module._hf_hook.execution_device is not None
665
+ ):
666
+ return torch.device(module._hf_hook.execution_device)
667
+ return self.device
668
+
669
+
670
+ def _encode_prompt(
671
+ self,
672
+ prompt,
673
+ device,
674
+ num_images_per_prompt,
675
+ do_classifier_free_guidance,
676
+ negative_prompt=None,
677
+ prompt_embeds: Optional[torch.FloatTensor] = None,
678
+ negative_prompt_embeds: Optional[torch.FloatTensor] = None,
679
+ ):
680
+
681
+ assert len(self.text_encoder_list) == len(self.tokenizer_list), "Number of text_encoders must match number of tokenizers"
682
+ if self.adapter_list is not None:
683
+ assert len(self.text_encoder_list) == len(self.adapter_list), "Number of text_encoders must match number of adapters"
684
+
685
+ if prompt is not None and isinstance(prompt, str):
686
+ batch_size = 1
687
+ elif prompt is not None and isinstance(prompt, list):
688
+ batch_size = len(prompt)
689
+ else:
690
+ batch_size = prompt_embeds.shape[0]
691
+
692
+ def get_prompt_embeds(prompt_list, device):
693
+ if isinstance(prompt_list, str):
694
+ prompt_list = [prompt_list]
695
+
696
+ prompt_embeds_list = []
697
+ for prompt in prompt_list:
698
+ encoder_hidden_states_list = []
699
+
700
+ # Generate condition embedding
701
+ for j in range(len(self.text_encoder_list)):
702
+ # get condition embedding using condition encoder
703
+ input_ids = self.tokenizer_list[j](prompt, return_tensors="pt").input_ids.to(device)
704
+ cond_embs = self.text_encoder_list[j](input_ids).last_hidden_state # [bz, text_len, text_dim]
705
+ # padding to max_length
706
+ if cond_embs.shape[1] < self.tokenizer_model_max_length:
707
+ cond_embs = torch.functional.F.pad(cond_embs, (0, 0, 0, self.tokenizer_model_max_length - cond_embs.shape[1]), value=0)
708
+ else:
709
+ cond_embs = cond_embs[:, :self.tokenizer_model_max_length, :]
710
+
711
+ # use condition adapter
712
+ if self.adapter_list is not None:
713
+ cond_embs = self.adapter_list[j](cond_embs)
714
+ encoder_hidden_states_list.append(cond_embs)
715
+
716
+ prompt_embeds = torch.cat(encoder_hidden_states_list, dim=1)
717
+ prompt_embeds_list.append(prompt_embeds)
718
+
719
+ prompt_embeds = torch.cat(prompt_embeds_list, dim=0)
720
+ return prompt_embeds
721
+
722
+
723
+ if prompt_embeds is None:
724
+ prompt_embeds = get_prompt_embeds(prompt, device)
725
+
726
+ prompt_embeds = prompt_embeds.to(dtype=self.unet.dtype, device=device)
727
+
728
+ bs_embed, seq_len, _ = prompt_embeds.shape
729
+ # duplicate text embeddings for each generation per prompt, using mps friendly method
730
+ prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
731
+ prompt_embeds = prompt_embeds.view(bs_embed * num_images_per_prompt, seq_len, -1)
732
+
733
+ if do_classifier_free_guidance and negative_prompt_embeds is None:
734
+
735
+ if negative_prompt is None:
736
+ negative_prompt_embeds = torch.zeros_like(prompt_embeds).to(dtype=prompt_embeds.dtype, device=device)
737
+
738
+ elif prompt is not None and type(prompt) is not type(negative_prompt):
739
+ raise TypeError(
740
+ f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
741
+ f" {type(prompt)}."
742
+ )
743
+ elif isinstance(negative_prompt, str):
744
+ negative_prompt = [negative_prompt]
745
+ negative_prompt_embeds = get_prompt_embeds(negative_prompt, device)
746
+ elif batch_size != len(negative_prompt):
747
+ raise ValueError(
748
+ f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
749
+ f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
750
+ " the batch size of `prompt`."
751
+ )
752
+ else:
753
+ negative_prompt_embeds = get_prompt_embeds(negative_prompt, device)
754
+
755
+ if do_classifier_free_guidance:
756
+ # duplicate unconditional embeddings for each generation per prompt, using mps friendly method
757
+ seq_len = negative_prompt_embeds.shape[1]
758
+
759
+ negative_prompt_embeds = negative_prompt_embeds.to(dtype=self.unet.dtype, device=device)
760
+
761
+ negative_prompt_embeds = negative_prompt_embeds.repeat(1, num_images_per_prompt, 1)
762
+ negative_prompt_embeds = negative_prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1)
763
+
764
+ # For classifier free guidance, we need to do two forward passes.
765
+ # Here we concatenate the unconditional and text embeddings into a single batch
766
+ # to avoid doing two forward passes
767
+ prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds])
768
+
769
+ return prompt_embeds
770
+
771
+
772
+ def run_safety_checker(self, image, device, dtype):
773
+ if self.safety_checker is None:
774
+ has_nsfw_concept = None
775
+ else:
776
+ if torch.is_tensor(image):
777
+ feature_extractor_input = self.image_processor.postprocess(image, output_type="pil")
778
+ else:
779
+ feature_extractor_input = self.image_processor.numpy_to_pil(image)
780
+ safety_checker_input = self.feature_extractor(feature_extractor_input, return_tensors="pt").to(device)
781
+ image, has_nsfw_concept = self.safety_checker(
782
+ images=image, clip_input=safety_checker_input.pixel_values.to(dtype)
783
+ )
784
+ return image, has_nsfw_concept
785
+
786
+ def decode_latents(self, latents):
787
+ warnings.warn(
788
+ "The decode_latents method is deprecated and will be removed in a future version. Please"
789
+ " use VaeImageProcessor instead",
790
+ FutureWarning,
791
+ )
792
+ latents = 1 / self.vae.config.scaling_factor * latents
793
+ image = self.vae.decode(latents, return_dict=False)[0]
794
+ image = (image / 2 + 0.5).clamp(0, 1)
795
+ # we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16
796
+ image = image.cpu().permute(0, 2, 3, 1).float().numpy()
797
+ return image
798
+
799
+ def prepare_extra_step_kwargs(self, generator, eta):
800
+ # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
801
+ # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
802
+ # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
803
+ # and should be between [0, 1]
804
+
805
+ accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
806
+ extra_step_kwargs = {}
807
+ if accepts_eta:
808
+ extra_step_kwargs["eta"] = eta
809
+
810
+ # check if the scheduler accepts generator
811
+ accepts_generator = "generator" in set(inspect.signature(self.scheduler.step).parameters.keys())
812
+ if accepts_generator:
813
+ extra_step_kwargs["generator"] = generator
814
+ return extra_step_kwargs
815
+
816
+
817
+ def check_inputs(
818
+ self,
819
+ prompt,
820
+ height,
821
+ width,
822
+ callback_steps,
823
+ negative_prompt=None,
824
+ prompt_embeds=None,
825
+ negative_prompt_embeds=None,
826
+ ):
827
+ if height % 8 != 0 or width % 8 != 0:
828
+ raise ValueError(f"`height` and `width` have to be divisible by 8 but are {height} and {width}.")
829
+
830
+ if (callback_steps is None) or (
831
+ callback_steps is not None and (not isinstance(callback_steps, int) or callback_steps <= 0)
832
+ ):
833
+ raise ValueError(
834
+ f"`callback_steps` has to be a positive integer but is {callback_steps} of type"
835
+ f" {type(callback_steps)}."
836
+ )
837
+
838
+ if prompt is not None and prompt_embeds is not None:
839
+ raise ValueError(
840
+ f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
841
+ " only forward one of the two."
842
+ )
843
+ elif prompt is None and prompt_embeds is None:
844
+ raise ValueError(
845
+ "Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
846
+ )
847
+ elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
848
+ raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
849
+
850
+ if negative_prompt is not None and negative_prompt_embeds is not None:
851
+ raise ValueError(
852
+ f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`:"
853
+ f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
854
+ )
855
+
856
+ if prompt_embeds is not None and negative_prompt_embeds is not None:
857
+ if prompt_embeds.shape != negative_prompt_embeds.shape:
858
+ raise ValueError(
859
+ "`prompt_embeds` and `negative_prompt_embeds` must have the same shape when passed directly, but"
860
+ f" got: `prompt_embeds` {prompt_embeds.shape} != `negative_prompt_embeds`"
861
+ f" {negative_prompt_embeds.shape}."
862
+ )
863
+
864
+
865
+
866
+ def prepare_latents(self, batch_size, num_channels_latents, height, width, dtype, device, generator, latents=None):
867
+ shape = (batch_size, num_channels_latents, height // self.vae_scale_factor, width // self.vae_scale_factor)
868
+ if isinstance(generator, list) and len(generator) != batch_size:
869
+ raise ValueError(
870
+ f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
871
+ f" size of {batch_size}. Make sure the batch size matches the length of the generators."
872
+ )
873
+
874
+ if latents is None:
875
+ latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
876
+ else:
877
+ latents = latents.to(device)
878
+
879
+ # scale the initial noise by the standard deviation required by the scheduler
880
+ latents = latents * self.scheduler.init_noise_sigma
881
+ return latents
882
+
883
+ @torch.no_grad()
884
+ def __call__(
885
+ self,
886
+ prompt: Union[str, List[str]] = None,
887
+ height: Optional[int] = 256,
888
+ width: Optional[int] = 1024,
889
+ num_inference_steps: int = 100,
890
+ guidance_scale: float = 7.5,
891
+ negative_prompt: Optional[Union[str, List[str]]] = None,
892
+ num_images_per_prompt: Optional[int] = 1,
893
+ eta: float = 0.0,
894
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
895
+ latents: Optional[torch.FloatTensor] = None,
896
+ prompt_embeds: Optional[torch.FloatTensor] = None,
897
+ negative_prompt_embeds: Optional[torch.FloatTensor] = None,
898
+ output_type: Optional[str] = "pt",
899
+ return_dict: bool = True,
900
+ callback: Optional[Callable[[int, int, torch.FloatTensor], None]] = None,
901
+ callback_steps: int = 1,
902
+ cross_attention_kwargs: Optional[Dict[str, Any]] = None,
903
+ guidance_rescale: float = 0.0,
904
+ duration: Optional[float] = 10,
905
+ ):
906
+
907
+ # 0. Default height and width to unet
908
+ height = height or self.unet.config.sample_size * self.vae_scale_factor
909
+ width = width or self.unet.config.sample_size * self.vae_scale_factor
910
+ audio_length = int(duration * 16000)
911
+
912
+
913
+ # 1. Check inputs. Raise error if not correct
914
+ self.check_inputs(
915
+ prompt, height, width, callback_steps, negative_prompt, prompt_embeds, negative_prompt_embeds
916
+ )
917
+
918
+
919
+ # 2. Define call parameters
920
+ if prompt is not None and isinstance(prompt, str):
921
+ batch_size = 1
922
+ elif prompt is not None and isinstance(prompt, list):
923
+ batch_size = len(prompt)
924
+ else:
925
+ batch_size = prompt_embeds.shape[0]
926
+
927
+ device = self._execution_device
928
+ # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
929
+ # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
930
+ # corresponds to doing no classifier free guidance.
931
+ do_classifier_free_guidance = guidance_scale > 1.0
932
+
933
+ # 3. Encode input prompt
934
+ prompt_embeds = self._encode_prompt(
935
+ prompt,
936
+ device,
937
+ num_images_per_prompt,
938
+ do_classifier_free_guidance,
939
+ negative_prompt,
940
+ prompt_embeds=prompt_embeds,
941
+ negative_prompt_embeds=negative_prompt_embeds
942
+ )
943
+
944
+ # 4. Prepare timesteps
945
+ self.scheduler.set_timesteps(num_inference_steps, device=device)
946
+ timesteps = self.scheduler.timesteps
947
+
948
+ # 5. Prepare latent variables
949
+ num_channels_latents = self.unet.config.in_channels
950
+ latents = self.prepare_latents(
951
+ batch_size * num_images_per_prompt,
952
+ num_channels_latents,
953
+ height,
954
+ width,
955
+ prompt_embeds.dtype,
956
+ device,
957
+ generator,
958
+ latents,
959
+ )
960
+
961
+ # 6. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline
962
+ extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
963
+
964
+ # 7. Denoising loop
965
+ num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order
966
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
967
+ for i, t in enumerate(timesteps):
968
+ # expand the latents if we are doing classifier free guidance
969
+ latent_model_input = torch.cat([latents] * 2) if do_classifier_free_guidance else latents
970
+ latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
971
+
972
+ # predict the noise residual
973
+ noise_pred = self.unet(
974
+ latent_model_input,
975
+ t,
976
+ encoder_hidden_states=prompt_embeds,
977
+ cross_attention_kwargs=cross_attention_kwargs,
978
+ return_dict=False,
979
+ )[0]
980
+
981
+ # perform guidance
982
+ if do_classifier_free_guidance:
983
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
984
+ noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
985
+
986
+ if do_classifier_free_guidance and guidance_rescale > 0.0:
987
+ # Based on 3.4. in https://arxiv.org/pdf/2305.08891.pdf
988
+ noise_pred = rescale_noise_cfg(noise_pred, noise_pred_text, guidance_rescale=guidance_rescale)
989
+
990
+ # compute the previous noisy sample x_t -> x_t-1
991
+ latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs, return_dict=False)[0]
992
+
993
+ # call the callback, if provided
994
+ if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
995
+ progress_bar.update()
996
+ if callback is not None and i % callback_steps == 0:
997
+ callback(i, t, latents)
998
+
999
+ if not output_type == "latent":
1000
+ image = self.vae.decode(latents / self.vae.config.scaling_factor, return_dict=False)[0]
1001
+ image, has_nsfw_concept = self.run_safety_checker(image, device, prompt_embeds.dtype)
1002
+ else:
1003
+ image = latents
1004
+ has_nsfw_concept = None
1005
+
1006
+ if has_nsfw_concept is None:
1007
+ do_denormalize = [True] * image.shape[0]
1008
+ else:
1009
+ do_denormalize = [not has_nsfw for has_nsfw in has_nsfw_concept]
1010
+
1011
+ image = self.image_processor.postprocess(image, output_type=output_type, do_denormalize=do_denormalize)
1012
+
1013
+ # Offload last model to CPU
1014
+ if hasattr(self, "final_offload_hook") and self.final_offload_hook is not None:
1015
+ self.final_offload_hook.offload()
1016
+
1017
+
1018
+ # Generate audio
1019
+ spectrograms, audios = [], []
1020
+ for img in image:
1021
+ spectrogram = denormalize_spectrogram(img)
1022
+ audio = self.vocoder.inference(spectrogram, lengths=audio_length)[0]
1023
+ audios.append(audio)
1024
+ spectrograms.append(spectrogram)
1025
+
1026
+ # Convert to PIL
1027
+ images = pt_to_numpy(image)
1028
+ images = numpy_to_pil(images)
1029
+ images = [image_add_color(image) for image in images]
1030
+
1031
+ if not return_dict:
1032
+ return (images, audios, spectrograms)
1033
+
1034
+
1035
+ return PipelineOutput(images=images, audios=audios, spectrograms=spectrograms)
1036
+
1037
+
1038
+
1039
+
config/clip_condition_config.json ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [
2
+ {
3
+ "text_encoder_name": "text_encoder_0",
4
+ "condition_adapter_name": "condition_adapter_0",
5
+ "condition_type": "clip-vit-large-patch14_text",
6
+ "pretrained_model_name_or_path": "openai/clip-vit-large-patch14",
7
+ "condition_max_length": 77,
8
+ "condition_dim": 768,
9
+ "cross_attention_dim": 768
10
+ }
11
+ ]
converter.py ADDED
@@ -0,0 +1,375 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+
3
+ import numpy as np
4
+ from PIL import Image
5
+
6
+ import math
7
+ import os
8
+ import random
9
+ import torch
10
+ import json
11
+ import torch.utils.data
12
+ import numpy as np
13
+ import librosa
14
+ from librosa.util import normalize
15
+ from scipy.io.wavfile import read
16
+ from librosa.filters import mel as librosa_mel_fn
17
+
18
+ import torch.nn.functional as F
19
+ import torch.nn as nn
20
+ from torch.nn import Conv1d, ConvTranspose1d, AvgPool1d, Conv2d
21
+ from torch.nn.utils import weight_norm, remove_weight_norm, spectral_norm
22
+
23
+ MAX_WAV_VALUE = 32768.0
24
+
25
+
26
+ def load_wav(full_path):
27
+ sampling_rate, data = read(full_path)
28
+ return data, sampling_rate
29
+
30
+
31
+ def dynamic_range_compression(x, C=1, clip_val=1e-5):
32
+ return np.log(np.clip(x, a_min=clip_val, a_max=None) * C)
33
+
34
+
35
+ def dynamic_range_decompression(x, C=1):
36
+ return np.exp(x) / C
37
+
38
+
39
+ def dynamic_range_compression_torch(x, C=1, clip_val=1e-5):
40
+ return torch.log(torch.clamp(x, min=clip_val) * C)
41
+
42
+
43
+ def dynamic_range_decompression_torch(x, C=1):
44
+ return torch.exp(x) / C
45
+
46
+
47
+ def spectral_normalize_torch(magnitudes):
48
+ output = dynamic_range_compression_torch(magnitudes)
49
+ return output
50
+
51
+
52
+ def spectral_de_normalize_torch(magnitudes):
53
+ output = dynamic_range_decompression_torch(magnitudes)
54
+ return output
55
+
56
+
57
+ mel_basis = {}
58
+ hann_window = {}
59
+
60
+
61
+ def mel_spectrogram(y, n_fft, num_mels, sampling_rate, hop_size, win_size, fmin, fmax, center=False):
62
+ if torch.min(y) < -1.:
63
+ print('min value is ', torch.min(y))
64
+ if torch.max(y) > 1.:
65
+ print('max value is ', torch.max(y))
66
+
67
+ global mel_basis, hann_window
68
+ if fmax not in mel_basis:
69
+ mel = librosa_mel_fn(sr=sampling_rate, n_fft=n_fft, n_mels=num_mels, fmin=fmin, fmax=fmax)
70
+ mel_basis[str(fmax)+'_'+str(y.device)] = torch.from_numpy(mel).float().to(y.device)
71
+ hann_window[str(y.device)] = torch.hann_window(win_size).to(y.device)
72
+
73
+ y = torch.nn.functional.pad(y.unsqueeze(1), (int((n_fft-hop_size)/2), int((n_fft-hop_size)/2)), mode='reflect')
74
+ y = y.squeeze(1)
75
+
76
+ # complex tensor as default, then use view_as_real for future pytorch compatibility
77
+ spec = torch.stft(y, n_fft, hop_length=hop_size, win_length=win_size, window=hann_window[str(y.device)],
78
+ center=center, pad_mode='reflect', normalized=False, onesided=True, return_complex=True)
79
+ spec = torch.view_as_real(spec)
80
+ spec = torch.sqrt(spec.pow(2).sum(-1)+(1e-9))
81
+
82
+ spec = torch.matmul(mel_basis[str(fmax)+'_'+str(y.device)], spec)
83
+ spec = spectral_normalize_torch(spec)
84
+
85
+ return spec
86
+
87
+
88
+ def spectrogram(y, n_fft, num_mels, sampling_rate, hop_size, win_size, fmin, fmax, center=False):
89
+ if torch.min(y) < -1.:
90
+ print('min value is ', torch.min(y))
91
+ if torch.max(y) > 1.:
92
+ print('max value is ', torch.max(y))
93
+
94
+ global hann_window
95
+ hann_window[str(y.device)] = torch.hann_window(win_size).to(y.device)
96
+
97
+ y = torch.nn.functional.pad(y.unsqueeze(1), (int((n_fft-hop_size)/2), int((n_fft-hop_size)/2)), mode='reflect')
98
+ y = y.squeeze(1)
99
+
100
+ # complex tensor as default, then use view_as_real for future pytorch compatibility
101
+ spec = torch.stft(y, n_fft, hop_length=hop_size, win_length=win_size, window=hann_window[str(y.device)],
102
+ center=center, pad_mode='reflect', normalized=False, onesided=True, return_complex=True)
103
+ spec = torch.view_as_real(spec)
104
+ spec = torch.sqrt(spec.pow(2).sum(-1)+(1e-9))
105
+
106
+ return spec
107
+
108
+
109
+ def normalize_spectrogram(
110
+ spectrogram: torch.Tensor,
111
+ max_value: float = 200,
112
+ min_value: float = 1e-5,
113
+ power: float = 1.,
114
+ inverse: bool = False
115
+ ) -> torch.Tensor:
116
+
117
+ # Rescale to 0-1
118
+ max_value = np.log(max_value) # 5.298317366548036
119
+ min_value = np.log(min_value) # -11.512925464970229
120
+
121
+ assert spectrogram.max() <= max_value and spectrogram.min() >= min_value
122
+
123
+ data = (spectrogram - min_value) / (max_value - min_value)
124
+
125
+ # Invert
126
+ if inverse:
127
+ data = 1 - data
128
+
129
+ # Apply the power curve
130
+ data = torch.pow(data, power)
131
+
132
+ # 1D -> 3D
133
+ data = data.repeat(3, 1, 1)
134
+
135
+ # Flip Y axis: image origin at the top-left corner, spectrogram origin at the bottom-left corner
136
+ data = torch.flip(data, [1])
137
+
138
+ return data
139
+
140
+
141
+
142
+ def denormalize_spectrogram(
143
+ data: torch.Tensor,
144
+ max_value: float = 200,
145
+ min_value: float = 1e-5,
146
+ power: float = 1,
147
+ inverse: bool = False,
148
+ ) -> torch.Tensor:
149
+
150
+ max_value = np.log(max_value)
151
+ min_value = np.log(min_value)
152
+
153
+ # Flip Y axis: image origin at the top-left corner, spectrogram origin at the bottom-left corner
154
+ data = torch.flip(data, [1])
155
+
156
+ assert len(data.shape) == 3, "Expected 3 dimensions, got {}".format(len(data.shape))
157
+
158
+ if data.shape[0] == 1:
159
+ data = data.repeat(3, 1, 1)
160
+
161
+ assert data.shape[0] == 3, "Expected 3 channels, got {}".format(data.shape[0])
162
+ data = data[0]
163
+
164
+ # Reverse the power curve
165
+ data = torch.pow(data, 1 / power)
166
+
167
+ # Invert
168
+ if inverse:
169
+ data = 1 - data
170
+
171
+ # Rescale to max value
172
+ spectrogram = data * (max_value - min_value) + min_value
173
+
174
+ return spectrogram
175
+
176
+
177
+ def get_mel_spectrogram_from_audio(audio, device="cuda"):
178
+ audio = audio / MAX_WAV_VALUE
179
+ audio = librosa.util.normalize(audio) * 0.95
180
+
181
+ audio = torch.FloatTensor(audio)
182
+ audio = audio.unsqueeze(0)
183
+
184
+ waveform = audio.to(device)
185
+ spec = mel_spectrogram(waveform, n_fft=2048, num_mels=256, sampling_rate=16000, hop_size=160, win_size=1024, fmin=0, fmax=8000, center=False)
186
+ return audio, spec
187
+
188
+
189
+
190
+ LRELU_SLOPE = 0.1
191
+ MAX_WAV_VALUE = 32768.0
192
+
193
+
194
+ class AttrDict(dict):
195
+ def __init__(self, *args, **kwargs):
196
+ super(AttrDict, self).__init__(*args, **kwargs)
197
+ self.__dict__ = self
198
+
199
+
200
+ def get_config(config_path):
201
+ config = json.loads(open(config_path).read())
202
+ config = AttrDict(config)
203
+ return config
204
+
205
+ def init_weights(m, mean=0.0, std=0.01):
206
+ classname = m.__class__.__name__
207
+ if classname.find("Conv") != -1:
208
+ m.weight.data.normal_(mean, std)
209
+
210
+
211
+ def apply_weight_norm(m):
212
+ classname = m.__class__.__name__
213
+ if classname.find("Conv") != -1:
214
+ weight_norm(m)
215
+
216
+
217
+ def get_padding(kernel_size, dilation=1):
218
+ return int((kernel_size*dilation - dilation)/2)
219
+
220
+
221
+ class ResBlock1(torch.nn.Module):
222
+ def __init__(self, h, channels, kernel_size=3, dilation=(1, 3, 5)):
223
+ super(ResBlock1, self).__init__()
224
+ self.h = h
225
+ self.convs1 = nn.ModuleList([
226
+ weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=dilation[0],
227
+ padding=get_padding(kernel_size, dilation[0]))),
228
+ weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=dilation[1],
229
+ padding=get_padding(kernel_size, dilation[1]))),
230
+ weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=dilation[2],
231
+ padding=get_padding(kernel_size, dilation[2])))
232
+ ])
233
+ self.convs1.apply(init_weights)
234
+
235
+ self.convs2 = nn.ModuleList([
236
+ weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=1,
237
+ padding=get_padding(kernel_size, 1))),
238
+ weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=1,
239
+ padding=get_padding(kernel_size, 1))),
240
+ weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=1,
241
+ padding=get_padding(kernel_size, 1)))
242
+ ])
243
+ self.convs2.apply(init_weights)
244
+
245
+ def forward(self, x):
246
+ for c1, c2 in zip(self.convs1, self.convs2):
247
+ xt = F.leaky_relu(x, LRELU_SLOPE)
248
+ xt = c1(xt)
249
+ xt = F.leaky_relu(xt, LRELU_SLOPE)
250
+ xt = c2(xt)
251
+ x = xt + x
252
+ return x
253
+
254
+ def remove_weight_norm(self):
255
+ for l in self.convs1:
256
+ remove_weight_norm(l)
257
+ for l in self.convs2:
258
+ remove_weight_norm(l)
259
+
260
+
261
+ class ResBlock2(torch.nn.Module):
262
+ def __init__(self, h, channels, kernel_size=3, dilation=(1, 3)):
263
+ super(ResBlock2, self).__init__()
264
+ self.h = h
265
+ self.convs = nn.ModuleList([
266
+ weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=dilation[0],
267
+ padding=get_padding(kernel_size, dilation[0]))),
268
+ weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=dilation[1],
269
+ padding=get_padding(kernel_size, dilation[1])))
270
+ ])
271
+ self.convs.apply(init_weights)
272
+
273
+ def forward(self, x):
274
+ for c in self.convs:
275
+ xt = F.leaky_relu(x, LRELU_SLOPE)
276
+ xt = c(xt)
277
+ x = xt + x
278
+ return x
279
+
280
+ def remove_weight_norm(self):
281
+ for l in self.convs:
282
+ remove_weight_norm(l)
283
+
284
+
285
+
286
+ class Generator(torch.nn.Module):
287
+ def __init__(self, h):
288
+ super(Generator, self).__init__()
289
+ self.h = h
290
+ self.num_kernels = len(h.resblock_kernel_sizes)
291
+ self.num_upsamples = len(h.upsample_rates)
292
+ self.conv_pre = weight_norm(Conv1d(h.num_mels, h.upsample_initial_channel, 7, 1, padding=3)) # change: 80 --> 512
293
+ resblock = ResBlock1 if h.resblock == '1' else ResBlock2
294
+
295
+ self.ups = nn.ModuleList()
296
+ for i, (u, k) in enumerate(zip(h.upsample_rates, h.upsample_kernel_sizes)):
297
+ if (k-u) % 2 == 0:
298
+ self.ups.append(weight_norm(
299
+ ConvTranspose1d(h.upsample_initial_channel//(2**i), h.upsample_initial_channel//(2**(i+1)),
300
+ k, u, padding=(k-u)//2)))
301
+ else:
302
+ self.ups.append(weight_norm(
303
+ ConvTranspose1d(h.upsample_initial_channel//(2**i), h.upsample_initial_channel//(2**(i+1)),
304
+ k, u, padding=(k-u)//2+1, output_padding=1)))
305
+
306
+ # self.ups.append(weight_norm(
307
+ # ConvTranspose1d(h.upsample_initial_channel//(2**i), h.upsample_initial_channel//(2**(i+1)),
308
+ # k, u, padding=(k-u)//2)))
309
+
310
+
311
+ self.resblocks = nn.ModuleList()
312
+ for i in range(len(self.ups)):
313
+ ch = h.upsample_initial_channel//(2**(i+1))
314
+ for j, (k, d) in enumerate(zip(h.resblock_kernel_sizes, h.resblock_dilation_sizes)):
315
+ self.resblocks.append(resblock(h, ch, k, d))
316
+
317
+ self.conv_post = weight_norm(Conv1d(ch, 1, 7, 1, padding=3))
318
+ self.ups.apply(init_weights)
319
+ self.conv_post.apply(init_weights)
320
+
321
+ def forward(self, x):
322
+ x = self.conv_pre(x)
323
+ for i in range(self.num_upsamples):
324
+ x = F.leaky_relu(x, LRELU_SLOPE)
325
+ x = self.ups[i](x)
326
+ xs = None
327
+ for j in range(self.num_kernels):
328
+ if xs is None:
329
+ xs = self.resblocks[i*self.num_kernels+j](x)
330
+ else:
331
+ xs += self.resblocks[i*self.num_kernels+j](x)
332
+ x = xs / self.num_kernels
333
+ x = F.leaky_relu(x)
334
+ x = self.conv_post(x)
335
+ x = torch.tanh(x)
336
+
337
+ return x
338
+
339
+ def remove_weight_norm(self):
340
+ for l in self.ups:
341
+ remove_weight_norm(l)
342
+ for l in self.resblocks:
343
+ l.remove_weight_norm()
344
+ remove_weight_norm(self.conv_pre)
345
+ remove_weight_norm(self.conv_post)
346
+
347
+ @classmethod
348
+ def from_pretrained(cls, pretrained_model_name_or_path, subfolder=None):
349
+ if subfolder is not None:
350
+ pretrained_model_name_or_path = os.path.join(pretrained_model_name_or_path, subfolder)
351
+ config_path = os.path.join(pretrained_model_name_or_path, "config.json")
352
+ ckpt_path = os.path.join(pretrained_model_name_or_path, "vocoder.pt")
353
+
354
+ config = get_config(config_path)
355
+ vocoder = cls(config)
356
+
357
+ state_dict_g = torch.load(ckpt_path)
358
+ vocoder.load_state_dict(state_dict_g["generator"])
359
+ vocoder.eval()
360
+ vocoder.remove_weight_norm()
361
+ return vocoder
362
+
363
+
364
+ @torch.no_grad()
365
+ def inference(self, mels, lengths=None):
366
+ self.eval()
367
+ with torch.no_grad():
368
+ wavs = self(mels).squeeze(1)
369
+
370
+ wavs = (wavs.cpu().numpy() * MAX_WAV_VALUE).astype("int16")
371
+
372
+ if lengths is not None:
373
+ wavs = wavs[:, :lengths]
374
+
375
+ return wavs
data/test_audiocaps.raw.json ADDED
The diff for this file is too large to render. See raw diff
 
img/overview.png ADDED

Git LFS Details

  • SHA256: 0209a23cdeccb71395704ed1553a27e98b52bd2fb9d75685a707cf8caab6c992
  • Pointer size: 132 Bytes
  • Size of remote file: 1.68 MB
inference.py ADDED
@@ -0,0 +1,129 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ import os
3
+ import argparse
4
+ import torch
5
+ from diffusers.utils.import_utils import is_xformers_available
6
+ from datasets import load_dataset
7
+ from tqdm.auto import tqdm
8
+ from scipy.io.wavfile import write
9
+ from auffusion_pipeline import AuffusionPipeline
10
+
11
+
12
+
13
+
14
+ def parse_args():
15
+ parser = argparse.ArgumentParser(description="Simple example of a inference script.")
16
+ parser.add_argument(
17
+ "--pretrained_model_name_or_path",
18
+ type=str,
19
+ default="auffusion/auffusion",
20
+ required=True,
21
+ help="Path to pretrained model or model identifier from huggingface.co/models.",
22
+ )
23
+ parser.add_argument(
24
+ "--test_data_dir",
25
+ type=str,
26
+ default="./data/test_audiocaps.raw.json",
27
+ help="Path to test dataset in json file",
28
+ )
29
+ parser.add_argument(
30
+ "--audio_column", type=str, default="audio_path", help="The column of the dataset containing an audio."
31
+ )
32
+ parser.add_argument(
33
+ "--caption_column", type=str, default="text", help="The column of the dataset containing a caption."
34
+ )
35
+ parser.add_argument(
36
+ "--output_dir",
37
+ type=str,
38
+ default="./output/auffusion_hf",
39
+ help="The output directory where the model predictions and checkpoints will be written.",
40
+ )
41
+ parser.add_argument(
42
+ "--sample_rate", type=int, default=16000, help="The sample rate of audio."
43
+ )
44
+ parser.add_argument(
45
+ "--duration", type=int, default=10, help="The duration(s) of audio."
46
+ )
47
+ parser.add_argument("--seed", type=int, default=42, help="A seed for reproducible inference.")
48
+ parser.add_argument(
49
+ "--mixed_precision",
50
+ type=str,
51
+ default="fp16",
52
+ choices=["no", "fp16", "bf16"],
53
+ help=(
54
+ "Whether to use mixed precision. Choose between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >="
55
+ " 1.10.and an Nvidia Ampere GPU. Default to the value of accelerate config of the current system or the"
56
+ " flag passed with the `accelerate.launch` command. Use this argument to override the accelerate config."
57
+ ),
58
+ )
59
+ parser.add_argument(
60
+ "--enable_xformers_memory_efficient_attention", action="store_true", help="Whether or not to use xformers."
61
+ )
62
+ parser.add_argument(
63
+ "--guidance_scale", type=float, default=7.5, help="The scale of guidance."
64
+ )
65
+ parser.add_argument(
66
+ "--num_inference_steps", type=int, default=100, help="Number of inference steps to perform."
67
+ )
68
+ parser.add_argument(
69
+ "--width", type=int, default=1024, help="Width of the image."
70
+ )
71
+ parser.add_argument(
72
+ "--height", type=int, default=256, help="Height of the image."
73
+ )
74
+ args = parser.parse_args()
75
+
76
+ return args
77
+
78
+
79
+ def main():
80
+ args = parse_args()
81
+ os.makedirs(args.output_dir, exist_ok=True)
82
+
83
+ device = "cuda" if torch.cuda.is_available() else "cpu"
84
+ weight_dtype = torch.float16 if args.mixed_precision == "fp16" else torch.float32
85
+
86
+ pipeline = AuffusionPipeline.from_pretrained(args.pretrained_model_name_or_path)
87
+ pipeline = pipeline.to(device, weight_dtype)
88
+ pipeline.set_progress_bar_config(disable=True)
89
+
90
+ if is_xformers_available() and args.enable_xformers_memory_efficient_attention:
91
+ pipeline.enable_xformers_memory_efficient_attention()
92
+
93
+ generator = torch.Generator(device=device).manual_seed(args.seed)
94
+
95
+ # load dataset
96
+ audio_column, caption_column = args.audio_column, args.caption_column
97
+ data_files = {"test": args.test_data_dir}
98
+ dataset = load_dataset("json", data_files=data_files, split="test")
99
+
100
+ # output dir
101
+ audio_output_dir = os.path.join(args.output_dir, "audios")
102
+ os.makedirs(audio_output_dir, exist_ok=True)
103
+
104
+ # generating
105
+ audio_length = args.sample_rate * args.duration
106
+ for i in tqdm(range(len(dataset)), desc="Generating"):
107
+
108
+ prompt = dataset[i][caption_column]
109
+ audio_name = os.path.basename(dataset[i][audio_column])
110
+
111
+ audio_path = os.path.join(audio_output_dir, audio_name)
112
+
113
+ if os.path.exists(audio_path):
114
+ continue
115
+
116
+ with torch.autocast("cuda"):
117
+ output = pipeline(prompt=prompt, num_inference_steps=args.num_inference_steps, guidance_scale=args.guidance_scale, generator=generator, width=args.width, height=args.height)
118
+
119
+ audio = output.audios[0][:audio_length]
120
+
121
+ write(audio_path, args.sample_rate, audio)
122
+
123
+
124
+ if __name__ == "__main__":
125
+ main()
126
+
127
+
128
+
129
+
inference.sh ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ MODEL_NAME="auffusion/auffusion"
3
+ test_data_dir="./data/test_audiocaps.raw.json"
4
+ output_dir="./output/auffusion"
5
+ audio_column="spec_path"
6
+ caption_column="text"
7
+ num_inference_steps=100
8
+ guidance_scale=7.5
9
+
10
+
11
+ training_params="--pretrained_model_name_or_path=$MODEL_NAME \
12
+ --test_data_dir=$test_data_dir \
13
+ --output_dir=$output_dir \
14
+ --audio_column=$audio_column \
15
+ --caption_column=$caption_column \
16
+ --sample_rate=16000 \
17
+ --duration=10 \
18
+ --num_inference_steps=$num_inference_steps \
19
+ --guidance_scale=$guidance_scale \
20
+ --mixed_precision="fp16" \
21
+ --enable_xformers_memory_efficient_attention \
22
+ "
23
+
24
+ python inference.py $training_params
notebooks/README.md ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ # Audio Manipulation
2
+
3
+ We show examples of audio manipulation. Current audio manipulation methods include:
4
+
5
+ - Text-to-audio generation: [text_to_audio.ipynb](text_to_audio.ipynb) or [colab notebook](https://colab.research.google.com/drive/1JEPHT_AvHZxvlaZAsetkBnMrzCGMRKaf?usp=sharing)
6
+ - Text-guided style transfer: [img2img.ipynb](img2img.ipynb) or [colab notebook](https://colab.research.google.com/drive/1VjgryIz7kSXDzgCClqtqVgoDXIECeG0M?usp=sharing)
7
+ - Audio inpainting: [inpainting.ipynb](inpainting.ipynb) or [colab notebook](https://colab.research.google.com/drive/1NsqeiutoAynhtaZnlhzBdTXtZ27tQxVc?usp=sharing)
8
+ - attention-based word swap control: [word_swap.ipynb](word_swap.ipynb) or [colab notebook](https://colab.research.google.com/drive/18CtUoBMsPbgzeI-o0wHDYTtaErnq9KoI?usp=sharing)
9
+ - attention-based reweight control: [reweight.ipynb](reweight.ipynb) or [colab notebook](https://colab.research.google.com/drive/18CtUoBMsPbgzeI-o0wHDYTtaErnq9KoI?usp=sharing)
notebooks/examples/img2img/GIOApFAWDOc_160.wav ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9a7b9bd502a31627ddb916713233fce367b1f489b5bc4bb10702e64e857725e8
3
+ size 320044
notebooks/examples/img2img/YniwgMbB6tpQ_01.wav ADDED
Binary file (62.1 kB). View file
 
notebooks/examples/img2img/_GI7meqlYZk_30.wav ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b63901ab94e2a1bc1ad931962c8e62213ddfd5be8674f3275be578dc8314918f
3
+ size 320044
notebooks/examples/inpainting/14ekd4nkpwc_28.wav ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4116c538e8dbb7de0f06dbb36bfb3a94a781bbfd30b846ac892cfef87c835c1f
3
+ size 287186
notebooks/examples/inpainting/3ek-xLwr05Q_30.wav ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:bebed9053a4c4bc44fb2bfdda1242a8b96f4b2c94ebc7ea5e9b0484658a589ad
3
+ size 320066
notebooks/examples/inpainting/9z8XIRyUq9Q_30.wav ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4bc1a638617d4299564c404ffbf99f5edd49636f574759be84d169b644005650
3
+ size 320044
notebooks/examples/inpainting/IvfaKPDWC00_160.wav ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:204a92e7c985f370348ad8f7ed03ae974fe230796801e2902def406e72341591
3
+ size 320044
notebooks/img2img.ipynb ADDED
The diff for this file is too large to render. See raw diff
 
notebooks/inpainting.ipynb ADDED
The diff for this file is too large to render. See raw diff
 
notebooks/reweight.ipynb ADDED
The diff for this file is too large to render. See raw diff
 
notebooks/text_to_audio.ipynb ADDED
The diff for this file is too large to render. See raw diff
 
notebooks/text_to_audio_sd.ipynb ADDED
The diff for this file is too large to render. See raw diff
 
notebooks/word_swap.ipynb ADDED
The diff for this file is too large to render. See raw diff
 
prompt2prompt/Roboto-Regular.ttf ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4e147ab64b9fdf6d89d01f6b8c3ca0b3cddc59d608a8e2218f9a2504b5c98e14
3
+ size 168260
prompt2prompt/__init__.py ADDED
File without changes
prompt2prompt/pipeline_prompt2prompt.py ADDED
@@ -0,0 +1,353 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Callable, List, Optional, Union
2
+ import numpy as np
3
+ import torch
4
+ from diffusers.pipelines.stable_diffusion import StableDiffusionPipelineOutput
5
+ from diffusers.models.cross_attention import CrossAttention
6
+
7
+ #from pipeline_sd import StableDiffusionPipeline
8
+ from diffusers.pipelines.stable_diffusion import StableDiffusionPipeline
9
+ import matplotlib.pyplot as plt
10
+
11
+ from prompt2prompt.ptp_utils import AttentionStore
12
+ import prompt2prompt.ptp_utils as ptp_utils
13
+ from PIL import Image
14
+
15
+
16
+ class Prompt2PromptPipeline(StableDiffusionPipeline):
17
+ r"""
18
+ Pipeline for text-to-image generation using Stable Diffusion.
19
+ This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods the
20
+ library implements for all the pipelines (such as downloading or saving, running on a particular device, etc.)
21
+ Args:
22
+ vae ([`AutoencoderKL`]):
23
+ Variational Auto-Encoder (VAE) Model to encode and decode images to and from latent representations.
24
+ text_encoder ([`CLIPTextModel`]):
25
+ Frozen text-encoder. Stable Diffusion uses the text portion of
26
+ [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel), specifically
27
+ the [clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14) variant.
28
+ tokenizer (`CLIPTokenizer`):
29
+ Tokenizer of class
30
+ [CLIPTokenizer](https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer).
31
+ unet ([`UNet2DConditionModel`]): Conditional U-Net architecture to denoise the encoded image latents.
32
+ scheduler ([`SchedulerMixin`]):
33
+ A scheduler to be used in combination with `unet` to denoise the encoded image latents. Can be one of
34
+ [`DDIMScheduler`], [`LMSDiscreteScheduler`], or [`PNDMScheduler`].
35
+ safety_checker ([`StableDiffusionSafetyChecker`]):
36
+ Classification module that estimates whether generated images could be considered offensive or harmful.
37
+ Please, refer to the [model card](https://huggingface.co/runwayml/stable-diffusion-v1-5) for details.
38
+ feature_extractor ([`CLIPFeatureExtractor`]):
39
+ Model that extracts features from generated images to be used as inputs for the `safety_checker`.
40
+ """
41
+ _optional_components = ["safety_checker", "feature_extractor"]
42
+
43
+
44
+ @torch.no_grad()
45
+ def __call__(
46
+ self,
47
+ prompt: Union[str, List[str]],
48
+ height: Optional[int] = None,
49
+ width: Optional[int] = None,
50
+ controller: AttentionStore = None, # 传入attention_store作为p2p的控制。
51
+ num_inference_steps: int = 50,
52
+ guidance_scale: float = 7.5,
53
+ negative_prompt: Optional[Union[str, List[str]]] = None,
54
+ num_images_per_prompt: Optional[int] = 1,
55
+ eta: float = 0.0,
56
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
57
+ latents: Optional[torch.FloatTensor] = None,
58
+ output_type: Optional[str] = "pil",
59
+ return_dict: bool = True,
60
+ callback: Optional[Callable[[int, int, torch.FloatTensor], None]] = None,
61
+ callback_steps: Optional[int] = 1,
62
+ ):
63
+ r"""
64
+ Function invoked when calling the pipeline for generation.
65
+
66
+ Args:
67
+ prompt (`str` or `List[str]`):
68
+ The prompt or prompts to guide the image generation.
69
+ height (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
70
+ The height in pixels of the generated image.
71
+ width (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
72
+ The width in pixels of the generated image.
73
+ num_inference_steps (`int`, *optional*, defaults to 50):
74
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
75
+ expense of slower inference.
76
+ guidance_scale (`float`, *optional*, defaults to 7.5):
77
+ Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
78
+ `guidance_scale` is defined as `w` of equation 2. of [Imagen
79
+ Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
80
+ 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
81
+ usually at the expense of lower image quality.
82
+ negative_prompt (`str` or `List[str]`, *optional*):
83
+ The prompt or prompts not to guide the image generation. Ignored when not using guidance (i.e., ignored
84
+ if `guidance_scale` is less than `1`).
85
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
86
+ The number of images to generate per prompt.
87
+ eta (`float`, *optional*, defaults to 0.0):
88
+ Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to
89
+ [`schedulers.DDIMScheduler`], will be ignored for others.
90
+ generator (`torch.Generator`, *optional*):
91
+ One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html)
92
+ to make generation deterministic.
93
+ latents (`torch.FloatTensor`, *optional*):
94
+ Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
95
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
96
+ tensor will ge generated by sampling using the supplied random `generator`.
97
+ output_type (`str`, *optional*, defaults to `"pil"`):
98
+ The output format of the generate image. Choose between
99
+ [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
100
+ return_dict (`bool`, *optional*, defaults to `True`):
101
+ Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a
102
+ plain tuple.
103
+ callback (`Callable`, *optional*):
104
+ A function that will be called every `callback_steps` steps during inference. The function will be
105
+ called with the following arguments: `callback(step: int, timestep: int, latents: torch.FloatTensor)`.
106
+ callback_steps (`int`, *optional*, defaults to 1):
107
+ The frequency at which the `callback` function will be called. If not specified, the callback will be
108
+ called at every step.
109
+
110
+ Returns:
111
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`:
112
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] if `return_dict` is True, otherwise a `tuple.
113
+ When returning a tuple, the first element is a list with the generated images, and the second element is a
114
+ list of `bool`s denoting whether the corresponding generated image likely represents "not-safe-for-work"
115
+ (nsfw) content, according to the `safety_checker`.
116
+ """
117
+
118
+ self.register_attention_control(controller) # add attention controller
119
+
120
+ # 0. Default height and width to unet
121
+ height = height or self.unet.config.sample_size * self.vae_scale_factor
122
+ width = width or self.unet.config.sample_size * self.vae_scale_factor
123
+
124
+ # 1. Check inputs. Raise error if not correct
125
+ self.check_inputs(prompt, height, width, callback_steps)
126
+
127
+ # 2. Define call parameters
128
+ batch_size = 1 if isinstance(prompt, str) else len(prompt)
129
+ device = self._execution_device
130
+ # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
131
+ # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
132
+ # corresponds to doing no classifier free guidance.
133
+ do_classifier_free_guidance = guidance_scale > 1.0
134
+
135
+ # 3. Encode input prompt
136
+ text_embeddings = self._encode_prompt(
137
+ prompt, device, num_images_per_prompt, do_classifier_free_guidance, negative_prompt
138
+ )
139
+
140
+ # 4. Prepare timesteps
141
+ self.scheduler.set_timesteps(num_inference_steps, device=device)
142
+ timesteps = self.scheduler.timesteps
143
+
144
+ # 5. Prepare latent variables
145
+ num_channels_latents = self.unet.in_channels
146
+ latents = self.prepare_latents(
147
+ batch_size * num_images_per_prompt,
148
+ num_channels_latents,
149
+ height,
150
+ width,
151
+ text_embeddings.dtype,
152
+ device,
153
+ generator,
154
+ latents,
155
+ )
156
+
157
+ # 6. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline
158
+ extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
159
+
160
+ # 7. Denoising loop
161
+ num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order
162
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
163
+ for i, t in enumerate(timesteps):
164
+ # expand the latents if we are doing classifier free guidance
165
+ latent_model_input = torch.cat([latents] * 2) if do_classifier_free_guidance else latents
166
+ latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
167
+
168
+ # predict the noise residual
169
+ noise_pred = self.unet(latent_model_input, t, encoder_hidden_states=text_embeddings).sample
170
+
171
+ # perform guidance
172
+ if do_classifier_free_guidance:
173
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
174
+ noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
175
+
176
+ # compute the previous noisy sample x_t -> x_t-1
177
+ latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs).prev_sample
178
+
179
+ # step callback
180
+ latents = controller.step_callback(latents)
181
+
182
+ # call the callback, if provided
183
+ if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
184
+ progress_bar.update()
185
+ if callback is not None and i % callback_steps == 0:
186
+ callback(i, t, latents)
187
+
188
+ # 8. Post-processing
189
+ image = self.decode_latents(latents)
190
+
191
+ # 9. Run safety checker
192
+ image, has_nsfw_concept = self.run_safety_checker(image, device, text_embeddings.dtype)
193
+
194
+ # 10. Convert to PIL
195
+ if output_type == "pil":
196
+ image = self.numpy_to_pil(image)
197
+
198
+ if not return_dict:
199
+ return (image, has_nsfw_concept)
200
+
201
+ return StableDiffusionPipelineOutput(images=image, nsfw_content_detected=has_nsfw_concept)
202
+
203
+ def register_attention_control(self, controller):
204
+ attn_procs = {}
205
+ cross_att_count = 0
206
+ for name in self.unet.attn_processors.keys():
207
+ cross_attention_dim = None if name.endswith("attn1.processor") else self.unet.config.cross_attention_dim
208
+ if name.startswith("mid_block"):
209
+ hidden_size = self.unet.config.block_out_channels[-1]
210
+ place_in_unet = "mid"
211
+ elif name.startswith("up_blocks"):
212
+ block_id = int(name[len("up_blocks.")])
213
+ hidden_size = list(reversed(self.unet.config.block_out_channels))[block_id]
214
+ place_in_unet = "up"
215
+ elif name.startswith("down_blocks"):
216
+ block_id = int(name[len("down_blocks.")])
217
+ hidden_size = self.unet.config.block_out_channels[block_id]
218
+ place_in_unet = "down"
219
+ else:
220
+ continue
221
+ cross_att_count += 1
222
+ attn_procs[name] = P2PCrossAttnProcessor(
223
+ controller=controller, place_in_unet=place_in_unet
224
+ )
225
+
226
+ self.unet.set_attn_processor(attn_procs)
227
+ controller.num_att_layers = cross_att_count
228
+
229
+
230
+ # def aggregate_attention(self, prompts, attention_store: AttentionStore, res: int, from_where: List[str], is_cross: bool, select: int):
231
+ # out = []
232
+ # attention_maps = attention_store.get_average_attention()
233
+ # num_pixels = res ** 2
234
+ # for location in from_where:
235
+ # for item in attention_maps[f"{location}_{'cross' if is_cross else 'self'}"]:
236
+ # if item.shape[1] == num_pixels:
237
+ # cross_maps = item.reshape(len(prompts), -1, res, res, item.shape[-1])[select]
238
+ # out.append(cross_maps)
239
+ # out = torch.cat(out, dim=0)
240
+ # out = out.sum(0) / out.shape[0]
241
+ # return out.cpu()
242
+
243
+ def aggregate_attention(self, prompts, attention_store: AttentionStore, res: List[int], from_where: List[str], is_cross: bool, select: int):
244
+ out = []
245
+ attention_maps = attention_store.get_average_attention()
246
+ # num_pixels = res ** 2
247
+ num_pixels = res[0] * res[1]
248
+ for location in from_where:
249
+ for item in attention_maps[f"{location}_{'cross' if is_cross else 'self'}"]:
250
+ if item.shape[1] == num_pixels:
251
+ cross_maps = item.reshape(len(prompts), -1, res[0], res[1], item.shape[-1])[select]
252
+ out.append(cross_maps)
253
+ out = torch.cat(out, dim=0)
254
+ out = out.sum(0) / out.shape[0]
255
+ return out.cpu()
256
+
257
+ def show_cross_attention(self, prompts, attention_store: AttentionStore, res: List[int], from_where: List[str], select: int = 0, image_size: List[int]=[1024, 256], num_rows: int = 1, font_scale=2, thickness=4, cmap_name="plasma"):
258
+ tokens = self.tokenizer.encode(prompts[select])
259
+ decoder = self.tokenizer.decode
260
+ attention_maps = self.aggregate_attention(prompts, attention_store, res, from_where, True, select)
261
+ images = []
262
+
263
+ cmap = plt.get_cmap(cmap_name)
264
+ cmap_r = cmap.reversed()
265
+
266
+ for i in range(len(tokens)):
267
+ image = attention_maps[:, :, i]
268
+ image = 255 * image / image.max()
269
+ image = image.unsqueeze(-1).expand(*image.shape, 3)
270
+ image = image.numpy().astype(np.uint8)
271
+ # image = np.array(Image.fromarray(image).resize((256, 256)))
272
+ # image = np.array(Image.fromarray(image).resize((512, 128)))
273
+
274
+ image = cmap(np.array(image)[:,:,0])[:, :, :3] # 省略透明度通道
275
+ # image = image ** 2
276
+ image = (image - image.min()) / (image.max() - image.min())
277
+ image = Image.fromarray(np.uint8(image*255))
278
+ # image = np.array(image.resize((1024, 256)))
279
+ image = np.array(image.resize(image_size))
280
+
281
+
282
+ image = ptp_utils.text_under_image(image, decoder(int(tokens[i])), font_scale=font_scale, thickness=thickness)
283
+ images.append(image)
284
+ return ptp_utils.view_images(np.stack(images, axis=0), num_rows=num_rows)
285
+
286
+ # def show_cross_attention(self, prompts, attention_store: AttentionStore, res: int, from_where: List[str], select: int = 0):
287
+ # tokens = self.tokenizer.encode(prompts[select])
288
+ # decoder = self.tokenizer.decode
289
+ # attention_maps = self.aggregate_attention(prompts, attention_store, res, from_where, True, select)
290
+ # images = []
291
+ # for i in range(len(tokens)):
292
+ # image = attention_maps[:, :, i]
293
+ # image = 255 * image / image.max()
294
+ # image = image.unsqueeze(-1).expand(*image.shape, 3)
295
+ # image = image.numpy().astype(np.uint8)
296
+ # image = np.array(Image.fromarray(image).resize((256, 256)))
297
+ # image = ptp_utils.text_under_image(image, decoder(int(tokens[i])))
298
+ # images.append(image)
299
+ # ptp_utils.view_images(np.stack(images, axis=0))
300
+
301
+
302
+ def show_self_attention_comp(self, prompts, attention_store: AttentionStore, res: int, from_where: List[str],
303
+ max_com=10, select: int = 0):
304
+ attention_maps = self.aggregate_attention(prompts, attention_store, res, from_where, False, select).numpy().reshape((res ** 2, res ** 2))
305
+ u, s, vh = np.linalg.svd(attention_maps - np.mean(attention_maps, axis=1, keepdims=True))
306
+ images = []
307
+ for i in range(max_com):
308
+ image = vh[i].reshape(res, res)
309
+ image = image - image.min()
310
+ image = 255 * image / image.max()
311
+ image = np.repeat(np.expand_dims(image, axis=2), 3, axis=2).astype(np.uint8)
312
+ image = Image.fromarray(image).resize((256, 256))
313
+ image = np.array(image)
314
+ images.append(image)
315
+ ptp_utils.view_images(np.concatenate(images, axis=1))
316
+
317
+
318
+ class P2PCrossAttnProcessor:
319
+
320
+ def __init__(self, controller, place_in_unet):
321
+ super().__init__()
322
+ self.controller = controller
323
+ self.place_in_unet = place_in_unet
324
+
325
+ def __call__(self, attn: CrossAttention, hidden_states, encoder_hidden_states=None, attention_mask=None):
326
+ batch_size, sequence_length, _ = hidden_states.shape
327
+ attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size=batch_size)
328
+
329
+ query = attn.to_q(hidden_states)
330
+
331
+ is_cross = encoder_hidden_states is not None
332
+ encoder_hidden_states = encoder_hidden_states if encoder_hidden_states is not None else hidden_states
333
+ key = attn.to_k(encoder_hidden_states)
334
+ value = attn.to_v(encoder_hidden_states)
335
+
336
+ query = attn.head_to_batch_dim(query)
337
+ key = attn.head_to_batch_dim(key)
338
+ value = attn.head_to_batch_dim(value)
339
+
340
+ attention_probs = attn.get_attention_scores(query, key, attention_mask)
341
+
342
+ # one line change
343
+ self.controller(attention_probs, is_cross, self.place_in_unet)
344
+
345
+ hidden_states = torch.bmm(attention_probs, value)
346
+ hidden_states = attn.batch_to_head_dim(hidden_states)
347
+
348
+ # linear proj
349
+ hidden_states = attn.to_out[0](hidden_states)
350
+ # dropout
351
+ hidden_states = attn.to_out[1](hidden_states)
352
+
353
+ return hidden_states
prompt2prompt/ptp_utils.py ADDED
@@ -0,0 +1,557 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import abc
2
+
3
+ import cv2
4
+ import numpy as np
5
+ import torch
6
+ from IPython.display import display
7
+ from PIL import Image
8
+ from typing import Union, Tuple, List, Dict, Optional
9
+ import torch.nn.functional as nnf
10
+ from PIL import Image, ImageDraw, ImageFont
11
+
12
+
13
+ # def text_under_image(image: np.ndarray, text: str, text_color: Tuple[int, int, int] = (0, 0, 0)) -> np.ndarray:
14
+ # h, w, c = image.shape
15
+ # offset = int(h * .2)
16
+ # img = np.ones((h + offset, w, c), dtype=np.uint8) * 255
17
+ # font = cv2.FONT_HERSHEY_SIMPLEX
18
+ # img[:h] = image
19
+ # textsize = cv2.getTextSize(text, font, 1, 2)[0]
20
+ # text_x, text_y = (w - textsize[0]) // 2, h + offset - textsize[1] // 2
21
+ # cv2.putText(img, text, (text_x, text_y), font, 1, text_color, 2)
22
+ # return img
23
+
24
+ def text_under_image(image: np.ndarray, text: str, text_color: Tuple[int, int, int] = (0, 0, 0), font_scale: float = 1.0, thickness: int = 3) -> np.ndarray:
25
+ h, w, c = image.shape
26
+ # offset = int(h * .3)
27
+ offset = int(h * .2)
28
+ img = np.ones((h + offset, w, c), dtype=np.uint8) * 255
29
+ font = cv2.FONT_HERSHEY_SIMPLEX
30
+ img[:h] = image
31
+ textsize = cv2.getTextSize(text, font, font_scale, thickness)[0]
32
+ text_x, text_y = (w - textsize[0]) // 2, h + offset - textsize[1] // 2
33
+ cv2.putText(img, text, (text_x, text_y), font, font_scale, text_color, 2)
34
+ return img
35
+
36
+
37
+ def text_under_image_pil(image: np.ndarray, text: str, text_color: Tuple[int, int, int] = (0, 0, 0), font_scale: float = 1.0) -> np.ndarray:
38
+ image_pil = Image.fromarray(image)
39
+ draw = ImageDraw.Draw(image_pil)
40
+
41
+ font_size = int(font_scale * image.shape[0] / 20)
42
+ # font = ImageFont.truetype("arial.ttf", font_size)
43
+ font_path = "./Roboto-Regular.ttf"
44
+ font = ImageFont.truetype(font_path, font_size)
45
+
46
+ textsize = draw.textsize(text, font=font)
47
+ text_x = (image.shape[1] - textsize[0]) // 2
48
+ text_y = image.shape[0]
49
+
50
+ draw.text((text_x, text_y), text, font=font, fill=text_color)
51
+
52
+ return np.array(image_pil)
53
+
54
+
55
+ def view_images(images: Union[np.ndarray, List],
56
+ num_rows: int = 1,
57
+ offset_ratio: float = 0.02,
58
+ display_image: bool = True) -> Image.Image:
59
+ """ Displays a list of images in a grid. """
60
+ if type(images) is list:
61
+ num_empty = len(images) % num_rows
62
+ elif images.ndim == 4:
63
+ num_empty = images.shape[0] % num_rows
64
+ else:
65
+ images = [images]
66
+ num_empty = 0
67
+
68
+ empty_images = np.ones(images[0].shape, dtype=np.uint8) * 255
69
+ images = [image.astype(np.uint8) for image in images] + [empty_images] * num_empty
70
+ num_items = len(images)
71
+
72
+ h, w, c = images[0].shape
73
+ offset = int(h * offset_ratio)
74
+ num_cols = num_items // num_rows
75
+ image_ = np.ones((h * num_rows + offset * (num_rows - 1),
76
+ w * num_cols + offset * (num_cols - 1), 3), dtype=np.uint8) * 255
77
+ for i in range(num_rows):
78
+ for j in range(num_cols):
79
+ image_[i * (h + offset): i * (h + offset) + h:, j * (w + offset): j * (w + offset) + w] = images[
80
+ i * num_cols + j]
81
+
82
+ pil_img = Image.fromarray(image_)
83
+ if display_image:
84
+ display(pil_img)
85
+ return pil_img
86
+
87
+
88
+ def view_images_with_texts(images: Union[np.ndarray, List],
89
+ texts: Union[str, List[str]],
90
+ num_rows: int = 1,
91
+ offset_ratio: float = 0.02,
92
+ font_scale: float = 1.0,
93
+ display_image: bool = True) -> Image.Image:
94
+ """ Displays a list of images in a grid with texts below them. """
95
+
96
+ # Ensure texts is a list
97
+ if isinstance(texts, str):
98
+ texts = [texts] * len(images)
99
+
100
+ # Add text under each image
101
+ images_with_texts = [text_under_image(img, txt, font_scale=font_scale) for img, txt in zip(images, texts)]
102
+
103
+ if type(images_with_texts) is list:
104
+ num_empty = len(images_with_texts) % num_rows
105
+ elif images_with_texts.ndim == 4:
106
+ num_empty = images_with_texts.shape[0] % num_rows
107
+ else:
108
+ images_with_texts = [images_with_texts]
109
+ num_empty = 0
110
+
111
+ empty_images = np.ones(images_with_texts[0].shape, dtype=np.uint8) * 255
112
+ images_with_texts = [image.astype(np.uint8) for image in images_with_texts] + [empty_images] * num_empty
113
+ num_items = len(images_with_texts)
114
+
115
+ h, w, c = images_with_texts[0].shape
116
+ offset = int(h * offset_ratio)
117
+ num_cols = num_items // num_rows
118
+ image_ = np.ones((h * num_rows + offset * (num_rows - 1),
119
+ w * num_cols + offset * (num_cols - 1), 3), dtype=np.uint8) * 255
120
+ for i in range(num_rows):
121
+ for j in range(num_cols):
122
+ image_[i * (h + offset): i * (h + offset) + h:, j * (w + offset): j * (w + offset) + w] = images_with_texts[
123
+ i * num_cols + j]
124
+
125
+ pil_img = Image.fromarray(image_)
126
+ if display_image:
127
+ display(pil_img)
128
+ return pil_img
129
+
130
+
131
+
132
+ class AttentionControl(abc.ABC):
133
+
134
+ def step_callback(self, x_t):
135
+ return x_t
136
+
137
+ def between_steps(self):
138
+ return
139
+
140
+ @property
141
+ def num_uncond_att_layers(self):
142
+ return 0
143
+
144
+ @abc.abstractmethod
145
+ def forward (self, attn, is_cross: bool, place_in_unet: str):
146
+ raise NotImplementedError
147
+
148
+ def __call__(self, attn, is_cross: bool, place_in_unet: str):
149
+ if self.cur_att_layer >= self.num_uncond_att_layers:
150
+ h = attn.shape[0]
151
+ attn[h // 2:] = self.forward(attn[h // 2:], is_cross, place_in_unet)
152
+ self.cur_att_layer += 1
153
+ if self.cur_att_layer == self.num_att_layers + self.num_uncond_att_layers:
154
+ self.cur_att_layer = 0
155
+ self.cur_step += 1
156
+ self.between_steps()
157
+ return attn
158
+
159
+ def reset(self):
160
+ self.cur_step = 0
161
+ self.cur_att_layer = 0
162
+
163
+ def __init__(self):
164
+ self.cur_step = 0
165
+ self.num_att_layers = -1
166
+ self.cur_att_layer = 0
167
+
168
+
169
+ class EmptyControl(AttentionControl):
170
+
171
+ def forward(self, attn, is_cross: bool, place_in_unet: str):
172
+ return attn
173
+
174
+
175
+ class AttentionStore(AttentionControl):
176
+
177
+ @staticmethod
178
+ def get_empty_store():
179
+ return {"down_cross": [], "mid_cross": [], "up_cross": [],
180
+ "down_self": [], "mid_self": [], "up_self": []}
181
+
182
+ def forward(self, attn, is_cross: bool, place_in_unet: str):
183
+ key = f"{place_in_unet}_{'cross' if is_cross else 'self'}"
184
+ if attn.shape[1] <= 32 ** 2: # avoid memory overhead
185
+ self.step_store[key].append(attn)
186
+ return attn
187
+
188
+ def between_steps(self):
189
+ if len(self.attention_store) == 0:
190
+ self.attention_store = self.step_store
191
+ else:
192
+ for key in self.attention_store:
193
+ for i in range(len(self.attention_store[key])):
194
+ self.attention_store[key][i] += self.step_store[key][i]
195
+ self.step_store = self.get_empty_store()
196
+
197
+ def get_average_attention(self):
198
+ average_attention = {key: [item / self.cur_step for item in self.attention_store[key]] for key in self.attention_store}
199
+ return average_attention
200
+
201
+
202
+ def reset(self):
203
+ super(AttentionStore, self).reset()
204
+ self.step_store = self.get_empty_store()
205
+ self.attention_store = {}
206
+
207
+ def __init__(self):
208
+ super(AttentionStore, self).__init__()
209
+ self.step_store = self.get_empty_store()
210
+ self.attention_store = {}
211
+
212
+ class LocalBlend:
213
+
214
+ def __call__(self, x_t, attention_store):
215
+ k = 1
216
+ maps = attention_store["down_cross"][2:4] + attention_store["up_cross"][:3]
217
+ maps = [item.reshape(self.alpha_layers.shape[0], -1, 1, 16, 16, self.max_num_words) for item in maps]
218
+ maps = torch.cat(maps, dim=1)
219
+ maps = (maps * self.alpha_layers).sum(-1).mean(1)
220
+ mask = nnf.max_pool2d(maps, (k * 2 + 1, k * 2 +1), (1, 1), padding=(k, k))
221
+ mask = nnf.interpolate(mask, size=(x_t.shape[2:]))
222
+ mask = mask / mask.max(2, keepdims=True)[0].max(3, keepdims=True)[0]
223
+ mask = mask.gt(self.threshold)
224
+ mask = (mask[:1] + mask[1:]).float()
225
+ x_t = x_t[:1] + mask * (x_t - x_t[:1])
226
+ return x_t
227
+
228
+ def __init__(self, prompts: List[str], words: [List[List[str]]], tokenizer, device, dtype=torch.float32, threshold=.3, max_num_words=77):
229
+ self.max_num_words = 77
230
+
231
+ alpha_layers = torch.zeros(len(prompts), 1, 1, 1, 1, self.max_num_words)
232
+ for i, (prompt, words_) in enumerate(zip(prompts, words)):
233
+ if type(words_) is str:
234
+ words_ = [words_]
235
+ for word in words_:
236
+ ind = get_word_inds(prompt, word, tokenizer)
237
+ alpha_layers[i, :, :, :, :, ind] = 1
238
+ self.alpha_layers = alpha_layers.to(device, dtype)
239
+ self.threshold = threshold
240
+
241
+ class AttentionControlEdit(AttentionStore, abc.ABC):
242
+
243
+ def step_callback(self, x_t):
244
+ if self.local_blend is not None:
245
+ x_t = self.local_blend(x_t, self.attention_store)
246
+ return x_t
247
+
248
+ def replace_self_attention(self, attn_base, att_replace):
249
+ if att_replace.shape[2] <= 16 ** 2:
250
+ return attn_base.unsqueeze(0).expand(att_replace.shape[0], *attn_base.shape)
251
+ else:
252
+ return att_replace
253
+
254
+ @abc.abstractmethod
255
+ def replace_cross_attention(self, attn_base, att_replace):
256
+ raise NotImplementedError
257
+
258
+ def forward(self, attn, is_cross: bool, place_in_unet: str):
259
+ super(AttentionControlEdit, self).forward(attn, is_cross, place_in_unet)
260
+ # FIXME not replace correctly
261
+ if is_cross or (self.num_self_replace[0] <= self.cur_step < self.num_self_replace[1]):
262
+ h = attn.shape[0] // (self.batch_size)
263
+ attn = attn.reshape(self.batch_size, h, *attn.shape[1:])
264
+ attn_base, attn_repalce = attn[0], attn[1:]
265
+ if is_cross:
266
+ alpha_words = self.cross_replace_alpha[self.cur_step]
267
+ attn_repalce_new = self.replace_cross_attention(attn_base, attn_repalce) * alpha_words + (1 - alpha_words) * attn_repalce
268
+ attn[1:] = attn_repalce_new
269
+ else:
270
+ attn[1:] = self.replace_self_attention(attn_base, attn_repalce)
271
+ attn = attn.reshape(self.batch_size * h, *attn.shape[2:])
272
+ return attn
273
+
274
+ def __init__(self, prompts, num_steps: int,
275
+ cross_replace_steps: Union[float, Tuple[float, float], Dict[str, Tuple[float, float]]],
276
+ self_replace_steps: Union[float, Tuple[float, float]],
277
+ local_blend: Optional[LocalBlend],
278
+ tokenizer,
279
+ device,
280
+ dtype):
281
+ super(AttentionControlEdit, self).__init__()
282
+ # add tokenizer and device here
283
+
284
+ self.tokenizer = tokenizer
285
+ self.device = device
286
+ self.dtype = dtype
287
+
288
+ self.batch_size = len(prompts)
289
+ self.cross_replace_alpha = get_time_words_attention_alpha(prompts, num_steps, cross_replace_steps, self.tokenizer).to(self.device, self.dtype)
290
+ if type(self_replace_steps) is float:
291
+ self_replace_steps = 0, self_replace_steps
292
+ self.num_self_replace = int(num_steps * self_replace_steps[0]), int(num_steps * self_replace_steps[1])
293
+ self.local_blend = local_blend # 在外面定义后传进来
294
+
295
+ class AttentionReplace(AttentionControlEdit):
296
+
297
+ def replace_cross_attention(self, attn_base, att_replace):
298
+ return torch.einsum('hpw,bwn->bhpn', attn_base, self.mapper)
299
+
300
+ def __init__(self, prompts, num_steps: int, cross_replace_steps: float, self_replace_steps: float,
301
+ local_blend: Optional[LocalBlend] = None, tokenizer=None, device=None, dtype=torch.float32):
302
+ super(AttentionReplace, self).__init__(prompts, num_steps, cross_replace_steps, self_replace_steps, local_blend, tokenizer, device, dtype)
303
+ self.mapper = get_replacement_mapper(prompts, self.tokenizer).to(self.device, dtype=dtype)
304
+
305
+
306
+ class AttentionRefine(AttentionControlEdit):
307
+
308
+ def replace_cross_attention(self, attn_base, att_replace):
309
+ attn_base_replace = attn_base[:, :, self.mapper].permute(2, 0, 1, 3)
310
+ attn_replace = attn_base_replace * self.alphas + att_replace * (1 - self.alphas)
311
+ return attn_replace
312
+
313
+ def __init__(self, prompts, num_steps: int, cross_replace_steps: float, self_replace_steps: float,
314
+ local_blend: Optional[LocalBlend] = None, tokenizer=None, device=None, dtype=torch.float32):
315
+ super(AttentionRefine, self).__init__(prompts, num_steps, cross_replace_steps, self_replace_steps, local_blend, tokenizer, device, dtype)
316
+ self.mapper, alphas = get_refinement_mapper(prompts, self.tokenizer)
317
+ self.mapper, alphas = self.mapper.to(self.device, self.dtype), alphas.to(self.device, self.dtype)
318
+ self.alphas = alphas.reshape(alphas.shape[0], 1, 1, alphas.shape[1])
319
+
320
+ class AttentionReweight(AttentionControlEdit):
321
+
322
+ def replace_cross_attention(self, attn_base, att_replace):
323
+ if self.prev_controller is not None:
324
+ attn_base = self.prev_controller.replace_cross_attention(attn_base, att_replace)
325
+ attn_replace = attn_base[None, :, :, :] * self.equalizer[:, None, None, :]
326
+ return attn_replace
327
+
328
+ def __init__(self, prompts, num_steps: int, cross_replace_steps: float, self_replace_steps: float, equalizer,
329
+ local_blend: Optional[LocalBlend] = None, controller: Optional[AttentionControlEdit] = None, tokenizer=None, device=None, dtype=torch.float32):
330
+ super(AttentionReweight, self).__init__(prompts, num_steps, cross_replace_steps, self_replace_steps, local_blend, tokenizer, device, dtype)
331
+ self.equalizer = equalizer.to(self.device, self.dtype)
332
+ self.prev_controller = controller
333
+
334
+
335
+ def get_equalizer(text: str, word_select: Union[int, Tuple[int, ...]], values: Union[List[float], Tuple[float, ...]], tokenizer):
336
+ if type(word_select) is int or type(word_select) is str:
337
+ word_select = (word_select,)
338
+ equalizer = torch.ones(len(values), 77)
339
+ values = torch.tensor(values, dtype=torch.float32)
340
+ for word in word_select:
341
+ inds = get_word_inds(text, word, tokenizer)
342
+ equalizer[:, inds] = values
343
+ return equalizer
344
+
345
+
346
+ def update_alpha_time_word(alpha, bounds: Union[float, Tuple[float, float]], prompt_ind: int,
347
+ word_inds: Optional[torch.Tensor]=None):
348
+ if type(bounds) is float:
349
+ bounds = 0, bounds
350
+ start, end = int(bounds[0] * alpha.shape[0]), int(bounds[1] * alpha.shape[0])
351
+ if word_inds is None:
352
+ word_inds = torch.arange(alpha.shape[2])
353
+ alpha[: start, prompt_ind, word_inds] = 0
354
+ alpha[start: end, prompt_ind, word_inds] = 1
355
+ alpha[end:, prompt_ind, word_inds] = 0
356
+ return alpha
357
+
358
+ def get_time_words_attention_alpha(prompts, num_steps,
359
+ cross_replace_steps: Union[float, Dict[str, Tuple[float, float]]],
360
+ tokenizer, max_num_words=77):
361
+ if type(cross_replace_steps) is not dict:
362
+ cross_replace_steps = {"default_": cross_replace_steps}
363
+ if "default_" not in cross_replace_steps:
364
+ cross_replace_steps["default_"] = (0., 1.)
365
+ alpha_time_words = torch.zeros(num_steps + 1, len(prompts) - 1, max_num_words)
366
+ for i in range(len(prompts) - 1):
367
+ alpha_time_words = update_alpha_time_word(alpha_time_words, cross_replace_steps["default_"],
368
+ i)
369
+ for key, item in cross_replace_steps.items():
370
+ if key != "default_":
371
+ inds = [get_word_inds(prompts[i], key, tokenizer) for i in range(1, len(prompts))]
372
+ for i, ind in enumerate(inds):
373
+ if len(ind) > 0:
374
+ alpha_time_words = update_alpha_time_word(alpha_time_words, item, i, ind)
375
+ alpha_time_words = alpha_time_words.reshape(num_steps + 1, len(prompts) - 1, 1, 1, max_num_words)
376
+ return alpha_time_words
377
+
378
+
379
+
380
+ # seg_alinger
381
+ class ScoreParams:
382
+
383
+ def __init__(self, gap, match, mismatch):
384
+ self.gap = gap
385
+ self.match = match
386
+ self.mismatch = mismatch
387
+
388
+ def mis_match_char(self, x, y):
389
+ if x != y:
390
+ return self.mismatch
391
+ else:
392
+ return self.match
393
+
394
+
395
+ def get_matrix(size_x, size_y, gap):
396
+ matrix = []
397
+ for i in range(len(size_x) + 1):
398
+ sub_matrix = []
399
+ for j in range(len(size_y) + 1):
400
+ sub_matrix.append(0)
401
+ matrix.append(sub_matrix)
402
+ for j in range(1, len(size_y) + 1):
403
+ matrix[0][j] = j*gap
404
+ for i in range(1, len(size_x) + 1):
405
+ matrix[i][0] = i*gap
406
+ return matrix
407
+
408
+
409
+ def get_matrix(size_x, size_y, gap):
410
+ matrix = np.zeros((size_x + 1, size_y + 1), dtype=np.int32)
411
+ matrix[0, 1:] = (np.arange(size_y) + 1) * gap
412
+ matrix[1:, 0] = (np.arange(size_x) + 1) * gap
413
+ return matrix
414
+
415
+
416
+ def get_traceback_matrix(size_x, size_y):
417
+ matrix = np.zeros((size_x + 1, size_y +1), dtype=np.int32)
418
+ matrix[0, 1:] = 1
419
+ matrix[1:, 0] = 2
420
+ matrix[0, 0] = 4
421
+ return matrix
422
+
423
+
424
+ def global_align(x, y, score):
425
+ matrix = get_matrix(len(x), len(y), score.gap)
426
+ trace_back = get_traceback_matrix(len(x), len(y))
427
+ for i in range(1, len(x) + 1):
428
+ for j in range(1, len(y) + 1):
429
+ left = matrix[i, j - 1] + score.gap
430
+ up = matrix[i - 1, j] + score.gap
431
+ diag = matrix[i - 1, j - 1] + score.mis_match_char(x[i - 1], y[j - 1])
432
+ matrix[i, j] = max(left, up, diag)
433
+ if matrix[i, j] == left:
434
+ trace_back[i, j] = 1
435
+ elif matrix[i, j] == up:
436
+ trace_back[i, j] = 2
437
+ else:
438
+ trace_back[i, j] = 3
439
+ return matrix, trace_back
440
+
441
+
442
+ def get_aligned_sequences(x, y, trace_back):
443
+ x_seq = []
444
+ y_seq = []
445
+ i = len(x)
446
+ j = len(y)
447
+ mapper_y_to_x = []
448
+ while i > 0 or j > 0:
449
+ if trace_back[i, j] == 3:
450
+ x_seq.append(x[i-1])
451
+ y_seq.append(y[j-1])
452
+ i = i-1
453
+ j = j-1
454
+ mapper_y_to_x.append((j, i))
455
+ elif trace_back[i][j] == 1:
456
+ x_seq.append('-')
457
+ y_seq.append(y[j-1])
458
+ j = j-1
459
+ mapper_y_to_x.append((j, -1))
460
+ elif trace_back[i][j] == 2:
461
+ x_seq.append(x[i-1])
462
+ y_seq.append('-')
463
+ i = i-1
464
+ elif trace_back[i][j] == 4:
465
+ break
466
+ mapper_y_to_x.reverse()
467
+ return x_seq, y_seq, torch.tensor(mapper_y_to_x, dtype=torch.int64)
468
+
469
+
470
+ def get_mapper(x: str, y: str, tokenizer, max_len=77):
471
+ x_seq = tokenizer.encode(x)
472
+ y_seq = tokenizer.encode(y)
473
+ score = ScoreParams(0, 1, -1)
474
+ matrix, trace_back = global_align(x_seq, y_seq, score)
475
+ mapper_base = get_aligned_sequences(x_seq, y_seq, trace_back)[-1]
476
+ alphas = torch.ones(max_len)
477
+ alphas[: mapper_base.shape[0]] = mapper_base[:, 1].ne(-1).float()
478
+ mapper = torch.zeros(max_len, dtype=torch.int64)
479
+ mapper[:mapper_base.shape[0]] = mapper_base[:, 1]
480
+ mapper[mapper_base.shape[0]:] = len(y_seq) + torch.arange(max_len - len(y_seq))
481
+ return mapper, alphas
482
+
483
+
484
+ def get_refinement_mapper(prompts, tokenizer, max_len=77):
485
+ x_seq = prompts[0]
486
+ mappers, alphas = [], []
487
+ for i in range(1, len(prompts)):
488
+ mapper, alpha = get_mapper(x_seq, prompts[i], tokenizer, max_len)
489
+ mappers.append(mapper)
490
+ alphas.append(alpha)
491
+ return torch.stack(mappers), torch.stack(alphas)
492
+
493
+
494
+ def get_word_inds(text: str, word_place: int, tokenizer):
495
+ split_text = text.split(" ")
496
+ if type(word_place) is str:
497
+ word_place = [i for i, word in enumerate(split_text) if word_place == word]
498
+ elif type(word_place) is int:
499
+ word_place = [word_place]
500
+ out = []
501
+ if len(word_place) > 0:
502
+ words_encode = [tokenizer.decode([item]).strip("#") for item in tokenizer.encode(text)][1:-1]
503
+ cur_len, ptr = 0, 0
504
+
505
+ for i in range(len(words_encode)):
506
+ cur_len += len(words_encode[i])
507
+ if ptr in word_place:
508
+ out.append(i + 1)
509
+ if cur_len >= len(split_text[ptr]):
510
+ ptr += 1
511
+ cur_len = 0
512
+ return np.array(out)
513
+
514
+
515
+ def get_replacement_mapper_(x: str, y: str, tokenizer, max_len=77):
516
+ words_x = x.split(' ')
517
+ words_y = y.split(' ')
518
+ if len(words_x) != len(words_y):
519
+ raise ValueError(f"attention replacement edit can only be applied on prompts with the same length"
520
+ f" but prompt A has {len(words_x)} words and prompt B has {len(words_y)} words.")
521
+ inds_replace = [i for i in range(len(words_y)) if words_y[i] != words_x[i]]
522
+ inds_source = [get_word_inds(x, i, tokenizer) for i in inds_replace]
523
+ inds_target = [get_word_inds(y, i, tokenizer) for i in inds_replace]
524
+ mapper = np.zeros((max_len, max_len))
525
+ i = j = 0
526
+ cur_inds = 0
527
+ while i < max_len and j < max_len:
528
+ if cur_inds < len(inds_source) and inds_source[cur_inds][0] == i:
529
+ inds_source_, inds_target_ = inds_source[cur_inds], inds_target[cur_inds]
530
+ if len(inds_source_) == len(inds_target_):
531
+ mapper[inds_source_, inds_target_] = 1
532
+ else:
533
+ ratio = 1 / len(inds_target_)
534
+ for i_t in inds_target_:
535
+ mapper[inds_source_, i_t] = ratio
536
+ cur_inds += 1
537
+ i += len(inds_source_)
538
+ j += len(inds_target_)
539
+ elif cur_inds < len(inds_source):
540
+ mapper[i, j] = 1
541
+ i += 1
542
+ j += 1
543
+ else:
544
+ mapper[j, j] = 1
545
+ i += 1
546
+ j += 1
547
+
548
+ return torch.from_numpy(mapper).float()
549
+
550
+
551
+ def get_replacement_mapper(prompts, tokenizer, max_len=77):
552
+ x_seq = prompts[0]
553
+ mappers = []
554
+ for i in range(1, len(prompts)):
555
+ mapper = get_replacement_mapper_(x_seq, prompts[i], tokenizer, max_len)
556
+ mappers.append(mapper)
557
+ return torch.stack(mappers)
requirements.txt ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ accelerate
3
+ diffusers==0.18.2
4
+ einops
5
+ huggingface_hub==0.16.4
6
+ ipykernel
7
+ librosa==0.9.2
8
+ matplotlib
9
+ numpy
10
+ tqdm
11
+ scikit-learn
12
+ scipy
13
+ soundfile==0.12.1
14
+ tokenizers==0.13.3
15
+ torch==2.0.1
16
+ torchaudio==2.0.2
17
+ torchvision==0.15.2
18
+ transformers
19
+ xformers==0.0.20
utils.py ADDED
@@ -0,0 +1,319 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os, json
2
+ import math, random
3
+ from multiprocessing import Pool
4
+ from tqdm import tqdm
5
+ import numpy as np
6
+ import torch
7
+ import torch.nn as nn
8
+ import torch.nn.functional as F
9
+ from PIL import Image
10
+ import matplotlib.pyplot as plt
11
+ from torchvision import transforms
12
+ from transformers import CLIPTextModel
13
+ from transformers import PretrainedConfig
14
+
15
+
16
+ def pad_spec(spec, spec_length, pad_value=0, random_crop=True): # spec: [3, mel_dim, spec_len]
17
+ assert spec_length % 8 == 0, "spec_length must be divisible by 8"
18
+ if spec.shape[-1] < spec_length:
19
+ # pad spec to spec_length
20
+ spec = F.pad(spec, (0, spec_length - spec.shape[-1]), value=pad_value)
21
+ else:
22
+ # random crop
23
+ if random_crop:
24
+ start = random.randint(0, spec.shape[-1] - spec_length)
25
+ spec = spec[:, :, start:start+spec_length]
26
+ else:
27
+ spec = spec[:, :, :spec_length]
28
+ return spec
29
+
30
+
31
+ def load_spec(spec_path):
32
+ if spec_path.endswith(".pt"):
33
+ spec = torch.load(spec_path, map_location="cpu")
34
+ elif spec_path.endswith(".npy"):
35
+ spec = torch.from_numpy(np.load(spec_path))
36
+ else:
37
+ raise ValueError(f"Unknown spec file type {spec_path}")
38
+ assert len(spec.shape) == 3, f"spec shape must be [3, mel_dim, spec_len], got {spec.shape}"
39
+ if spec.size(0) == 1:
40
+ spec = spec.repeat(3, 1, 1)
41
+ return spec
42
+
43
+
44
+ def random_crop_spec(spec, target_spec_length, pad_value=0, frame_per_sec=100, time_step=5): # spec: [3, mel_dim, spec_len]
45
+ assert target_spec_length % 8 == 0, "spec_length must be divisible by 8"
46
+
47
+ spec_length = spec.shape[-1]
48
+ full_s = math.ceil(spec_length / frame_per_sec / time_step) * time_step # get full seconds(ceil)
49
+ start_s = random.randint(0, math.floor(spec_length / frame_per_sec / time_step)) * time_step # random get start seconds
50
+
51
+ end_s = min(start_s + math.ceil(target_spec_length / frame_per_sec), full_s) # get end seconds
52
+
53
+ spec = spec[:, :, start_s * frame_per_sec : end_s * frame_per_sec] # get spec in seconds(crop more than target_spec_length because ceiling)
54
+
55
+ if spec.shape[-1] < target_spec_length:
56
+ spec = F.pad(spec, (0, target_spec_length - spec.shape[-1]), value=pad_value) # pad to target_spec_length
57
+ else:
58
+ spec = spec[:, :, :target_spec_length] # crop to target_spec_length
59
+
60
+ return spec, int(start_s), int(end_s), int(full_s)
61
+
62
+
63
+
64
+ def load_condion_embed(text_embed_path):
65
+ if text_embed_path.endswith(".pt"):
66
+ text_embed_list = torch.load(text_embed_path, map_location="cpu")
67
+ elif text_embed_path.endswith(".npy"):
68
+ text_embed_list = torch.from_numpy(np.load(text_embed_path))
69
+ else:
70
+ raise ValueError(f"Unknown text embedding file type {text_embed_path}")
71
+ if type(text_embed_list) == list:
72
+ text_embed = random.choice(text_embed_list)
73
+ if len(text_embed.shape) == 3: # [1, text_len, text_dim]
74
+ text_embed = text_embed.squeeze(0) # random choice and return text_emb: [text_len, text_dim]
75
+ return text_embed.detach().cpu()
76
+
77
+
78
+ def process_condition_embed(cond_emb, max_length): # [text_len, text_dim], Padding 0 and random drop by CFG
79
+ if cond_emb.shape[0] < max_length:
80
+ cond_emb = F.pad(cond_emb, (0, 0, 0, max_length - cond_emb.shape[0]), value=0)
81
+ else:
82
+ cond_emb = cond_emb[:max_length, :]
83
+ return cond_emb
84
+
85
+
86
+ def import_model_class_from_model_name_or_path(pretrained_model_name_or_path: str):
87
+ text_encoder_config = PretrainedConfig.from_pretrained(
88
+ pretrained_model_name_or_path
89
+ )
90
+ model_class = text_encoder_config.architectures[0]
91
+
92
+ if model_class == "CLIPTextModel":
93
+ from transformers import CLIPTextModel
94
+ return CLIPTextModel
95
+ if "t5" in model_class.lower():
96
+ from transformers import T5EncoderModel
97
+ return T5EncoderModel
98
+ if "clap" in model_class.lower():
99
+ from transformers import ClapTextModelWithProjection
100
+ return ClapTextModelWithProjection
101
+ else:
102
+ raise ValueError(f"{model_class} is not supported.")
103
+
104
+
105
+
106
+ def str2bool(string):
107
+ str2val = {"True": True, "False": False, "true": True, "false": False, "none": False, "None": False}
108
+ if string in str2val:
109
+ return str2val[string]
110
+ else:
111
+ raise ValueError(f"Expected one of {set(str2val.keys())}, got {string}")
112
+
113
+
114
+ def str2str(string):
115
+ if string.lower() == "none" or string.lower() == "null" or string.lower() == "false" or string == "":
116
+ return None
117
+ else:
118
+ return string
119
+
120
+
121
+ def json_dump(data_json, json_save_path):
122
+ with open(json_save_path, 'w') as f:
123
+ json.dump(data_json, f, indent=4)
124
+ f.close()
125
+
126
+
127
+ def json_load(json_path):
128
+ with open(json_path, 'r') as f:
129
+ data = json.load(f)
130
+ f.close()
131
+ return data
132
+
133
+
134
+ def load_json_list(path):
135
+ with open(path, 'r', encoding='utf-8') as f:
136
+ return [json.loads(line) for line in f.readlines()]
137
+
138
+
139
+ def save_json_list(data, path):
140
+ with open(path, 'w', encoding='utf-8') as f:
141
+ for d in data:
142
+ f.write(json.dumps(d) + '\n')
143
+
144
+
145
+ def multiprocess_function(func, func_args, n_jobs=32):
146
+ with Pool(processes=n_jobs) as p:
147
+ with tqdm(total=len(func_args)) as pbar:
148
+ for i, _ in enumerate(p.imap_unordered(func, func_args)):
149
+ pbar.update()
150
+
151
+
152
+ def image_add_color(spec_img):
153
+ cmap = plt.get_cmap('viridis')
154
+ cmap_r = cmap.reversed()
155
+ image = cmap(np.array(spec_img)[:,:,0])[:, :, :3] # 省略透明度通道
156
+ image = (image - image.min()) / (image.max() - image.min())
157
+ image = Image.fromarray(np.uint8(image*255))
158
+ return image
159
+
160
+
161
+ @staticmethod
162
+ def pt_to_numpy(images: torch.FloatTensor) -> np.ndarray:
163
+ """
164
+ Convert a PyTorch tensor to a NumPy image.
165
+ """
166
+ images = images.cpu().permute(0, 2, 3, 1).float().numpy()
167
+ return images
168
+
169
+
170
+ def numpy_to_pil(images):
171
+ """
172
+ Convert a numpy image or a batch of images to a PIL image.
173
+ """
174
+ if images.ndim == 3:
175
+ images = images[None, ...]
176
+ images = (images * 255).round().astype("uint8")
177
+ if images.shape[-1] == 1:
178
+ # special case for grayscale (single channel) images
179
+ pil_images = [Image.fromarray(image.squeeze(), mode="L") for image in images]
180
+ else:
181
+ pil_images = [Image.fromarray(image) for image in images]
182
+
183
+ return pil_images
184
+
185
+ ### CODE FOR INPAITING ###
186
+ def normalize(images):
187
+ """
188
+ Normalize an image array to [-1,1].
189
+ """
190
+ if images.min() >= 0:
191
+ return 2.0 * images - 1.0
192
+ else:
193
+ return images
194
+
195
+ def denormalize(images):
196
+ """
197
+ Denormalize an image array to [0,1].
198
+ """
199
+ if images.min() < 0:
200
+ return (images / 2 + 0.5).clamp(0, 1)
201
+ else:
202
+ return images.clamp(0, 1)
203
+
204
+
205
+ def prepare_mask_and_masked_image(image, mask):
206
+ """
207
+ Prepare a binary mask and the masked image.
208
+
209
+ Parameters:
210
+ - image (torch.Tensor): The input image tensor of shape [3, height, width] with values in the range [0, 1].
211
+ - mask (torch.Tensor): The input mask tensor of shape [1, height, width].
212
+
213
+ Returns:
214
+ - tuple: A tuple containing the binary mask and the masked image.
215
+ """
216
+ # Noralize image to [0,1]
217
+ if image.max() > 1:
218
+ image = (image - image.min()) / (image.max() - image.min())
219
+ # Normalize image from [0,1] to [-1,1]
220
+ if image.min() >= 0:
221
+ image = normalize(image)
222
+ # Apply the mask to the image
223
+ masked_image = image * (mask < 0.5)
224
+
225
+ return mask, masked_image
226
+
227
+
228
+ def torch_to_pil(image):
229
+ """
230
+ Convert a torch tensor to a PIL image.
231
+ """
232
+ if image.min() < 0:
233
+ image = denormalize(image)
234
+
235
+ return transforms.ToPILImage()(image.cpu().detach().squeeze())
236
+
237
+
238
+
239
+ # class TextEncoderAdapter(nn.Module):
240
+ # def __init__(self, hidden_size, cross_attention_dim=768):
241
+ # super(TextEncoderAdapter, self).__init__()
242
+ # self.hidden_size = hidden_size
243
+ # self.cross_attention_dim = cross_attention_dim
244
+ # self.proj = nn.Linear(self.hidden_size, self.cross_attention_dim)
245
+ # self.norm = torch.nn.LayerNorm(self.cross_attention_dim)
246
+
247
+ # def forward(self, x):
248
+ # x = self.proj(x)
249
+ # x = self.norm(x)
250
+ # return x
251
+
252
+ # def save_pretrained(self, save_directory, subfolder=""):
253
+ # if subfolder:
254
+ # save_directory = os.path.join(save_directory, subfolder)
255
+ # os.makedirs(save_directory, exist_ok=True)
256
+ # ckpt_path = os.path.join(save_directory, "adapter.pt")
257
+ # config_path = os.path.join(save_directory, "config.json")
258
+ # config = {"hidden_size": self.hidden_size, "cross_attention_dim": self.cross_attention_dim}
259
+ # json_dump(config, config_path)
260
+ # torch.save(self.state_dict(), ckpt_path)
261
+ # print(f"Saving adapter model to {ckpt_path}")
262
+
263
+ # @classmethod
264
+ # def from_pretrained(cls, load_directory, subfolder=""):
265
+ # if subfolder:
266
+ # load_directory = os.path.join(load_directory, subfolder)
267
+ # ckpt_path = os.path.join(load_directory, "adapter.pt")
268
+ # config_path = os.path.join(load_directory, "config.json")
269
+ # config = json_load(config_path)
270
+ # instance = cls(**config)
271
+ # instance.load_state_dict(torch.load(ckpt_path))
272
+ # print(f"Loading adapter model from {ckpt_path}")
273
+ # return instance
274
+
275
+
276
+
277
+ class ConditionAdapter(nn.Module):
278
+ def __init__(self, config):
279
+ super(ConditionAdapter, self).__init__()
280
+ self.config = config
281
+ self.proj = nn.Linear(self.config["condition_dim"], self.config["cross_attention_dim"])
282
+ self.norm = torch.nn.LayerNorm(self.config["cross_attention_dim"])
283
+ print(f"INITIATED: ConditionAdapter: {self.config}")
284
+
285
+ def forward(self, x):
286
+ x = self.proj(x)
287
+ x = self.norm(x)
288
+ return x
289
+
290
+ @classmethod
291
+ def from_pretrained(cls, pretrained_model_name_or_path):
292
+ config_path = os.path.join(pretrained_model_name_or_path, "config.json")
293
+ ckpt_path = os.path.join(pretrained_model_name_or_path, "condition_adapter.pt")
294
+ config = json_load(config_path)
295
+ instance = cls(config)
296
+ instance.load_state_dict(torch.load(ckpt_path))
297
+ print(f"LOADED: ConditionAdapter from {pretrained_model_name_or_path}")
298
+ return instance
299
+
300
+ def save_pretrained(self, pretrained_model_name_or_path):
301
+ os.makedirs(pretrained_model_name_or_path, exist_ok=True)
302
+ config_path = os.path.join(pretrained_model_name_or_path, "config.json")
303
+ ckpt_path = os.path.join(pretrained_model_name_or_path, "condition_adapter.pt")
304
+ json_dump(self.config, config_path)
305
+ torch.save(self.state_dict(), ckpt_path)
306
+ print(f"SAVED: ConditionAdapter {self.config['condition_adapter_name']} to {pretrained_model_name_or_path}")
307
+
308
+
309
+ # class TextEncoderWrapper(CLIPTextModel):
310
+ # def __init__(self, text_encoder, text_encoder_adapter):
311
+ # super().__init__(text_encoder.config)
312
+ # self.text_encoder = text_encoder
313
+ # self.adapter = text_encoder_adapter
314
+
315
+ # def forward(self, input_ids, **kwargs):
316
+ # outputs = self.text_encoder(input_ids, **kwargs)
317
+ # adapted_output = self.adapter(outputs[0])
318
+ # return [adapted_output] # to compatible with last_hidden_state
319
+