nakas commited on
Commit
9d749c2
β€’
1 Parent(s): 79769f4

audio_diffusion_fork

Browse files
.DS_Store ADDED
Binary file (6.15 kB). View file
 
LICENSE ADDED
@@ -0,0 +1,674 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ GNU GENERAL PUBLIC LICENSE
2
+ Version 3, 29 June 2007
3
+
4
+ Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
5
+ Everyone is permitted to copy and distribute verbatim copies
6
+ of this license document, but changing it is not allowed.
7
+
8
+ Preamble
9
+
10
+ The GNU General Public License is a free, copyleft license for
11
+ software and other kinds of works.
12
+
13
+ The licenses for most software and other practical works are designed
14
+ to take away your freedom to share and change the works. By contrast,
15
+ the GNU General Public License is intended to guarantee your freedom to
16
+ share and change all versions of a program--to make sure it remains free
17
+ software for all its users. We, the Free Software Foundation, use the
18
+ GNU General Public License for most of our software; it applies also to
19
+ any other work released this way by its authors. You can apply it to
20
+ your programs, too.
21
+
22
+ When we speak of free software, we are referring to freedom, not
23
+ price. Our General Public Licenses are designed to make sure that you
24
+ have the freedom to distribute copies of free software (and charge for
25
+ them if you wish), that you receive source code or can get it if you
26
+ want it, that you can change the software or use pieces of it in new
27
+ free programs, and that you know you can do these things.
28
+
29
+ To protect your rights, we need to prevent others from denying you
30
+ these rights or asking you to surrender the rights. Therefore, you have
31
+ certain responsibilities if you distribute copies of the software, or if
32
+ you modify it: responsibilities to respect the freedom of others.
33
+
34
+ For example, if you distribute copies of such a program, whether
35
+ gratis or for a fee, you must pass on to the recipients the same
36
+ freedoms that you received. You must make sure that they, too, receive
37
+ or can get the source code. And you must show them these terms so they
38
+ know their rights.
39
+
40
+ Developers that use the GNU GPL protect your rights with two steps:
41
+ (1) assert copyright on the software, and (2) offer you this License
42
+ giving you legal permission to copy, distribute and/or modify it.
43
+
44
+ For the developers' and authors' protection, the GPL clearly explains
45
+ that there is no warranty for this free software. For both users' and
46
+ authors' sake, the GPL requires that modified versions be marked as
47
+ changed, so that their problems will not be attributed erroneously to
48
+ authors of previous versions.
49
+
50
+ Some devices are designed to deny users access to install or run
51
+ modified versions of the software inside them, although the manufacturer
52
+ can do so. This is fundamentally incompatible with the aim of
53
+ protecting users' freedom to change the software. The systematic
54
+ pattern of such abuse occurs in the area of products for individuals to
55
+ use, which is precisely where it is most unacceptable. Therefore, we
56
+ have designed this version of the GPL to prohibit the practice for those
57
+ products. If such problems arise substantially in other domains, we
58
+ stand ready to extend this provision to those domains in future versions
59
+ of the GPL, as needed to protect the freedom of users.
60
+
61
+ Finally, every program is threatened constantly by software patents.
62
+ States should not allow patents to restrict development and use of
63
+ software on general-purpose computers, but in those that do, we wish to
64
+ avoid the special danger that patents applied to a free program could
65
+ make it effectively proprietary. To prevent this, the GPL assures that
66
+ patents cannot be used to render the program non-free.
67
+
68
+ The precise terms and conditions for copying, distribution and
69
+ modification follow.
70
+
71
+ TERMS AND CONDITIONS
72
+
73
+ 0. Definitions.
74
+
75
+ "This License" refers to version 3 of the GNU General Public License.
76
+
77
+ "Copyright" also means copyright-like laws that apply to other kinds of
78
+ works, such as semiconductor masks.
79
+
80
+ "The Program" refers to any copyrightable work licensed under this
81
+ License. Each licensee is addressed as "you". "Licensees" and
82
+ "recipients" may be individuals or organizations.
83
+
84
+ To "modify" a work means to copy from or adapt all or part of the work
85
+ in a fashion requiring copyright permission, other than the making of an
86
+ exact copy. The resulting work is called a "modified version" of the
87
+ earlier work or a work "based on" the earlier work.
88
+
89
+ A "covered work" means either the unmodified Program or a work based
90
+ on the Program.
91
+
92
+ To "propagate" a work means to do anything with it that, without
93
+ permission, would make you directly or secondarily liable for
94
+ infringement under applicable copyright law, except executing it on a
95
+ computer or modifying a private copy. Propagation includes copying,
96
+ distribution (with or without modification), making available to the
97
+ public, and in some countries other activities as well.
98
+
99
+ To "convey" a work means any kind of propagation that enables other
100
+ parties to make or receive copies. Mere interaction with a user through
101
+ a computer network, with no transfer of a copy, is not conveying.
102
+
103
+ An interactive user interface displays "Appropriate Legal Notices"
104
+ to the extent that it includes a convenient and prominently visible
105
+ feature that (1) displays an appropriate copyright notice, and (2)
106
+ tells the user that there is no warranty for the work (except to the
107
+ extent that warranties are provided), that licensees may convey the
108
+ work under this License, and how to view a copy of this License. If
109
+ the interface presents a list of user commands or options, such as a
110
+ menu, a prominent item in the list meets this criterion.
111
+
112
+ 1. Source Code.
113
+
114
+ The "source code" for a work means the preferred form of the work
115
+ for making modifications to it. "Object code" means any non-source
116
+ form of a work.
117
+
118
+ A "Standard Interface" means an interface that either is an official
119
+ standard defined by a recognized standards body, or, in the case of
120
+ interfaces specified for a particular programming language, one that
121
+ is widely used among developers working in that language.
122
+
123
+ The "System Libraries" of an executable work include anything, other
124
+ than the work as a whole, that (a) is included in the normal form of
125
+ packaging a Major Component, but which is not part of that Major
126
+ Component, and (b) serves only to enable use of the work with that
127
+ Major Component, or to implement a Standard Interface for which an
128
+ implementation is available to the public in source code form. A
129
+ "Major Component", in this context, means a major essential component
130
+ (kernel, window system, and so on) of the specific operating system
131
+ (if any) on which the executable work runs, or a compiler used to
132
+ produce the work, or an object code interpreter used to run it.
133
+
134
+ The "Corresponding Source" for a work in object code form means all
135
+ the source code needed to generate, install, and (for an executable
136
+ work) run the object code and to modify the work, including scripts to
137
+ control those activities. However, it does not include the work's
138
+ System Libraries, or general-purpose tools or generally available free
139
+ programs which are used unmodified in performing those activities but
140
+ which are not part of the work. For example, Corresponding Source
141
+ includes interface definition files associated with source files for
142
+ the work, and the source code for shared libraries and dynamically
143
+ linked subprograms that the work is specifically designed to require,
144
+ such as by intimate data communication or control flow between those
145
+ subprograms and other parts of the work.
146
+
147
+ The Corresponding Source need not include anything that users
148
+ can regenerate automatically from other parts of the Corresponding
149
+ Source.
150
+
151
+ The Corresponding Source for a work in source code form is that
152
+ same work.
153
+
154
+ 2. Basic Permissions.
155
+
156
+ All rights granted under this License are granted for the term of
157
+ copyright on the Program, and are irrevocable provided the stated
158
+ conditions are met. This License explicitly affirms your unlimited
159
+ permission to run the unmodified Program. The output from running a
160
+ covered work is covered by this License only if the output, given its
161
+ content, constitutes a covered work. This License acknowledges your
162
+ rights of fair use or other equivalent, as provided by copyright law.
163
+
164
+ You may make, run and propagate covered works that you do not
165
+ convey, without conditions so long as your license otherwise remains
166
+ in force. You may convey covered works to others for the sole purpose
167
+ of having them make modifications exclusively for you, or provide you
168
+ with facilities for running those works, provided that you comply with
169
+ the terms of this License in conveying all material for which you do
170
+ not control copyright. Those thus making or running the covered works
171
+ for you must do so exclusively on your behalf, under your direction
172
+ and control, on terms that prohibit them from making any copies of
173
+ your copyrighted material outside their relationship with you.
174
+
175
+ Conveying under any other circumstances is permitted solely under
176
+ the conditions stated below. Sublicensing is not allowed; section 10
177
+ makes it unnecessary.
178
+
179
+ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180
+
181
+ No covered work shall be deemed part of an effective technological
182
+ measure under any applicable law fulfilling obligations under article
183
+ 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184
+ similar laws prohibiting or restricting circumvention of such
185
+ measures.
186
+
187
+ When you convey a covered work, you waive any legal power to forbid
188
+ circumvention of technological measures to the extent such circumvention
189
+ is effected by exercising rights under this License with respect to
190
+ the covered work, and you disclaim any intention to limit operation or
191
+ modification of the work as a means of enforcing, against the work's
192
+ users, your or third parties' legal rights to forbid circumvention of
193
+ technological measures.
194
+
195
+ 4. Conveying Verbatim Copies.
196
+
197
+ You may convey verbatim copies of the Program's source code as you
198
+ receive it, in any medium, provided that you conspicuously and
199
+ appropriately publish on each copy an appropriate copyright notice;
200
+ keep intact all notices stating that this License and any
201
+ non-permissive terms added in accord with section 7 apply to the code;
202
+ keep intact all notices of the absence of any warranty; and give all
203
+ recipients a copy of this License along with the Program.
204
+
205
+ You may charge any price or no price for each copy that you convey,
206
+ and you may offer support or warranty protection for a fee.
207
+
208
+ 5. Conveying Modified Source Versions.
209
+
210
+ You may convey a work based on the Program, or the modifications to
211
+ produce it from the Program, in the form of source code under the
212
+ terms of section 4, provided that you also meet all of these conditions:
213
+
214
+ a) The work must carry prominent notices stating that you modified
215
+ it, and giving a relevant date.
216
+
217
+ b) The work must carry prominent notices stating that it is
218
+ released under this License and any conditions added under section
219
+ 7. This requirement modifies the requirement in section 4 to
220
+ "keep intact all notices".
221
+
222
+ c) You must license the entire work, as a whole, under this
223
+ License to anyone who comes into possession of a copy. This
224
+ License will therefore apply, along with any applicable section 7
225
+ additional terms, to the whole of the work, and all its parts,
226
+ regardless of how they are packaged. This License gives no
227
+ permission to license the work in any other way, but it does not
228
+ invalidate such permission if you have separately received it.
229
+
230
+ d) If the work has interactive user interfaces, each must display
231
+ Appropriate Legal Notices; however, if the Program has interactive
232
+ interfaces that do not display Appropriate Legal Notices, your
233
+ work need not make them do so.
234
+
235
+ A compilation of a covered work with other separate and independent
236
+ works, which are not by their nature extensions of the covered work,
237
+ and which are not combined with it such as to form a larger program,
238
+ in or on a volume of a storage or distribution medium, is called an
239
+ "aggregate" if the compilation and its resulting copyright are not
240
+ used to limit the access or legal rights of the compilation's users
241
+ beyond what the individual works permit. Inclusion of a covered work
242
+ in an aggregate does not cause this License to apply to the other
243
+ parts of the aggregate.
244
+
245
+ 6. Conveying Non-Source Forms.
246
+
247
+ You may convey a covered work in object code form under the terms
248
+ of sections 4 and 5, provided that you also convey the
249
+ machine-readable Corresponding Source under the terms of this License,
250
+ in one of these ways:
251
+
252
+ a) Convey the object code in, or embodied in, a physical product
253
+ (including a physical distribution medium), accompanied by the
254
+ Corresponding Source fixed on a durable physical medium
255
+ customarily used for software interchange.
256
+
257
+ b) Convey the object code in, or embodied in, a physical product
258
+ (including a physical distribution medium), accompanied by a
259
+ written offer, valid for at least three years and valid for as
260
+ long as you offer spare parts or customer support for that product
261
+ model, to give anyone who possesses the object code either (1) a
262
+ copy of the Corresponding Source for all the software in the
263
+ product that is covered by this License, on a durable physical
264
+ medium customarily used for software interchange, for a price no
265
+ more than your reasonable cost of physically performing this
266
+ conveying of source, or (2) access to copy the
267
+ Corresponding Source from a network server at no charge.
268
+
269
+ c) Convey individual copies of the object code with a copy of the
270
+ written offer to provide the Corresponding Source. This
271
+ alternative is allowed only occasionally and noncommercially, and
272
+ only if you received the object code with such an offer, in accord
273
+ with subsection 6b.
274
+
275
+ d) Convey the object code by offering access from a designated
276
+ place (gratis or for a charge), and offer equivalent access to the
277
+ Corresponding Source in the same way through the same place at no
278
+ further charge. You need not require recipients to copy the
279
+ Corresponding Source along with the object code. If the place to
280
+ copy the object code is a network server, the Corresponding Source
281
+ may be on a different server (operated by you or a third party)
282
+ that supports equivalent copying facilities, provided you maintain
283
+ clear directions next to the object code saying where to find the
284
+ Corresponding Source. Regardless of what server hosts the
285
+ Corresponding Source, you remain obligated to ensure that it is
286
+ available for as long as needed to satisfy these requirements.
287
+
288
+ e) Convey the object code using peer-to-peer transmission, provided
289
+ you inform other peers where the object code and Corresponding
290
+ Source of the work are being offered to the general public at no
291
+ charge under subsection 6d.
292
+
293
+ A separable portion of the object code, whose source code is excluded
294
+ from the Corresponding Source as a System Library, need not be
295
+ included in conveying the object code work.
296
+
297
+ A "User Product" is either (1) a "consumer product", which means any
298
+ tangible personal property which is normally used for personal, family,
299
+ or household purposes, or (2) anything designed or sold for incorporation
300
+ into a dwelling. In determining whether a product is a consumer product,
301
+ doubtful cases shall be resolved in favor of coverage. For a particular
302
+ product received by a particular user, "normally used" refers to a
303
+ typical or common use of that class of product, regardless of the status
304
+ of the particular user or of the way in which the particular user
305
+ actually uses, or expects or is expected to use, the product. A product
306
+ is a consumer product regardless of whether the product has substantial
307
+ commercial, industrial or non-consumer uses, unless such uses represent
308
+ the only significant mode of use of the product.
309
+
310
+ "Installation Information" for a User Product means any methods,
311
+ procedures, authorization keys, or other information required to install
312
+ and execute modified versions of a covered work in that User Product from
313
+ a modified version of its Corresponding Source. The information must
314
+ suffice to ensure that the continued functioning of the modified object
315
+ code is in no case prevented or interfered with solely because
316
+ modification has been made.
317
+
318
+ If you convey an object code work under this section in, or with, or
319
+ specifically for use in, a User Product, and the conveying occurs as
320
+ part of a transaction in which the right of possession and use of the
321
+ User Product is transferred to the recipient in perpetuity or for a
322
+ fixed term (regardless of how the transaction is characterized), the
323
+ Corresponding Source conveyed under this section must be accompanied
324
+ by the Installation Information. But this requirement does not apply
325
+ if neither you nor any third party retains the ability to install
326
+ modified object code on the User Product (for example, the work has
327
+ been installed in ROM).
328
+
329
+ The requirement to provide Installation Information does not include a
330
+ requirement to continue to provide support service, warranty, or updates
331
+ for a work that has been modified or installed by the recipient, or for
332
+ the User Product in which it has been modified or installed. Access to a
333
+ network may be denied when the modification itself materially and
334
+ adversely affects the operation of the network or violates the rules and
335
+ protocols for communication across the network.
336
+
337
+ Corresponding Source conveyed, and Installation Information provided,
338
+ in accord with this section must be in a format that is publicly
339
+ documented (and with an implementation available to the public in
340
+ source code form), and must require no special password or key for
341
+ unpacking, reading or copying.
342
+
343
+ 7. Additional Terms.
344
+
345
+ "Additional permissions" are terms that supplement the terms of this
346
+ License by making exceptions from one or more of its conditions.
347
+ Additional permissions that are applicable to the entire Program shall
348
+ be treated as though they were included in this License, to the extent
349
+ that they are valid under applicable law. If additional permissions
350
+ apply only to part of the Program, that part may be used separately
351
+ under those permissions, but the entire Program remains governed by
352
+ this License without regard to the additional permissions.
353
+
354
+ When you convey a copy of a covered work, you may at your option
355
+ remove any additional permissions from that copy, or from any part of
356
+ it. (Additional permissions may be written to require their own
357
+ removal in certain cases when you modify the work.) You may place
358
+ additional permissions on material, added by you to a covered work,
359
+ for which you have or can give appropriate copyright permission.
360
+
361
+ Notwithstanding any other provision of this License, for material you
362
+ add to a covered work, you may (if authorized by the copyright holders of
363
+ that material) supplement the terms of this License with terms:
364
+
365
+ a) Disclaiming warranty or limiting liability differently from the
366
+ terms of sections 15 and 16 of this License; or
367
+
368
+ b) Requiring preservation of specified reasonable legal notices or
369
+ author attributions in that material or in the Appropriate Legal
370
+ Notices displayed by works containing it; or
371
+
372
+ c) Prohibiting misrepresentation of the origin of that material, or
373
+ requiring that modified versions of such material be marked in
374
+ reasonable ways as different from the original version; or
375
+
376
+ d) Limiting the use for publicity purposes of names of licensors or
377
+ authors of the material; or
378
+
379
+ e) Declining to grant rights under trademark law for use of some
380
+ trade names, trademarks, or service marks; or
381
+
382
+ f) Requiring indemnification of licensors and authors of that
383
+ material by anyone who conveys the material (or modified versions of
384
+ it) with contractual assumptions of liability to the recipient, for
385
+ any liability that these contractual assumptions directly impose on
386
+ those licensors and authors.
387
+
388
+ All other non-permissive additional terms are considered "further
389
+ restrictions" within the meaning of section 10. If the Program as you
390
+ received it, or any part of it, contains a notice stating that it is
391
+ governed by this License along with a term that is a further
392
+ restriction, you may remove that term. If a license document contains
393
+ a further restriction but permits relicensing or conveying under this
394
+ License, you may add to a covered work material governed by the terms
395
+ of that license document, provided that the further restriction does
396
+ not survive such relicensing or conveying.
397
+
398
+ If you add terms to a covered work in accord with this section, you
399
+ must place, in the relevant source files, a statement of the
400
+ additional terms that apply to those files, or a notice indicating
401
+ where to find the applicable terms.
402
+
403
+ Additional terms, permissive or non-permissive, may be stated in the
404
+ form of a separately written license, or stated as exceptions;
405
+ the above requirements apply either way.
406
+
407
+ 8. Termination.
408
+
409
+ You may not propagate or modify a covered work except as expressly
410
+ provided under this License. Any attempt otherwise to propagate or
411
+ modify it is void, and will automatically terminate your rights under
412
+ this License (including any patent licenses granted under the third
413
+ paragraph of section 11).
414
+
415
+ However, if you cease all violation of this License, then your
416
+ license from a particular copyright holder is reinstated (a)
417
+ provisionally, unless and until the copyright holder explicitly and
418
+ finally terminates your license, and (b) permanently, if the copyright
419
+ holder fails to notify you of the violation by some reasonable means
420
+ prior to 60 days after the cessation.
421
+
422
+ Moreover, your license from a particular copyright holder is
423
+ reinstated permanently if the copyright holder notifies you of the
424
+ violation by some reasonable means, this is the first time you have
425
+ received notice of violation of this License (for any work) from that
426
+ copyright holder, and you cure the violation prior to 30 days after
427
+ your receipt of the notice.
428
+
429
+ Termination of your rights under this section does not terminate the
430
+ licenses of parties who have received copies or rights from you under
431
+ this License. If your rights have been terminated and not permanently
432
+ reinstated, you do not qualify to receive new licenses for the same
433
+ material under section 10.
434
+
435
+ 9. Acceptance Not Required for Having Copies.
436
+
437
+ You are not required to accept this License in order to receive or
438
+ run a copy of the Program. Ancillary propagation of a covered work
439
+ occurring solely as a consequence of using peer-to-peer transmission
440
+ to receive a copy likewise does not require acceptance. However,
441
+ nothing other than this License grants you permission to propagate or
442
+ modify any covered work. These actions infringe copyright if you do
443
+ not accept this License. Therefore, by modifying or propagating a
444
+ covered work, you indicate your acceptance of this License to do so.
445
+
446
+ 10. Automatic Licensing of Downstream Recipients.
447
+
448
+ Each time you convey a covered work, the recipient automatically
449
+ receives a license from the original licensors, to run, modify and
450
+ propagate that work, subject to this License. You are not responsible
451
+ for enforcing compliance by third parties with this License.
452
+
453
+ An "entity transaction" is a transaction transferring control of an
454
+ organization, or substantially all assets of one, or subdividing an
455
+ organization, or merging organizations. If propagation of a covered
456
+ work results from an entity transaction, each party to that
457
+ transaction who receives a copy of the work also receives whatever
458
+ licenses to the work the party's predecessor in interest had or could
459
+ give under the previous paragraph, plus a right to possession of the
460
+ Corresponding Source of the work from the predecessor in interest, if
461
+ the predecessor has it or can get it with reasonable efforts.
462
+
463
+ You may not impose any further restrictions on the exercise of the
464
+ rights granted or affirmed under this License. For example, you may
465
+ not impose a license fee, royalty, or other charge for exercise of
466
+ rights granted under this License, and you may not initiate litigation
467
+ (including a cross-claim or counterclaim in a lawsuit) alleging that
468
+ any patent claim is infringed by making, using, selling, offering for
469
+ sale, or importing the Program or any portion of it.
470
+
471
+ 11. Patents.
472
+
473
+ A "contributor" is a copyright holder who authorizes use under this
474
+ License of the Program or a work on which the Program is based. The
475
+ work thus licensed is called the contributor's "contributor version".
476
+
477
+ A contributor's "essential patent claims" are all patent claims
478
+ owned or controlled by the contributor, whether already acquired or
479
+ hereafter acquired, that would be infringed by some manner, permitted
480
+ by this License, of making, using, or selling its contributor version,
481
+ but do not include claims that would be infringed only as a
482
+ consequence of further modification of the contributor version. For
483
+ purposes of this definition, "control" includes the right to grant
484
+ patent sublicenses in a manner consistent with the requirements of
485
+ this License.
486
+
487
+ Each contributor grants you a non-exclusive, worldwide, royalty-free
488
+ patent license under the contributor's essential patent claims, to
489
+ make, use, sell, offer for sale, import and otherwise run, modify and
490
+ propagate the contents of its contributor version.
491
+
492
+ In the following three paragraphs, a "patent license" is any express
493
+ agreement or commitment, however denominated, not to enforce a patent
494
+ (such as an express permission to practice a patent or covenant not to
495
+ sue for patent infringement). To "grant" such a patent license to a
496
+ party means to make such an agreement or commitment not to enforce a
497
+ patent against the party.
498
+
499
+ If you convey a covered work, knowingly relying on a patent license,
500
+ and the Corresponding Source of the work is not available for anyone
501
+ to copy, free of charge and under the terms of this License, through a
502
+ publicly available network server or other readily accessible means,
503
+ then you must either (1) cause the Corresponding Source to be so
504
+ available, or (2) arrange to deprive yourself of the benefit of the
505
+ patent license for this particular work, or (3) arrange, in a manner
506
+ consistent with the requirements of this License, to extend the patent
507
+ license to downstream recipients. "Knowingly relying" means you have
508
+ actual knowledge that, but for the patent license, your conveying the
509
+ covered work in a country, or your recipient's use of the covered work
510
+ in a country, would infringe one or more identifiable patents in that
511
+ country that you have reason to believe are valid.
512
+
513
+ If, pursuant to or in connection with a single transaction or
514
+ arrangement, you convey, or propagate by procuring conveyance of, a
515
+ covered work, and grant a patent license to some of the parties
516
+ receiving the covered work authorizing them to use, propagate, modify
517
+ or convey a specific copy of the covered work, then the patent license
518
+ you grant is automatically extended to all recipients of the covered
519
+ work and works based on it.
520
+
521
+ A patent license is "discriminatory" if it does not include within
522
+ the scope of its coverage, prohibits the exercise of, or is
523
+ conditioned on the non-exercise of one or more of the rights that are
524
+ specifically granted under this License. You may not convey a covered
525
+ work if you are a party to an arrangement with a third party that is
526
+ in the business of distributing software, under which you make payment
527
+ to the third party based on the extent of your activity of conveying
528
+ the work, and under which the third party grants, to any of the
529
+ parties who would receive the covered work from you, a discriminatory
530
+ patent license (a) in connection with copies of the covered work
531
+ conveyed by you (or copies made from those copies), or (b) primarily
532
+ for and in connection with specific products or compilations that
533
+ contain the covered work, unless you entered into that arrangement,
534
+ or that patent license was granted, prior to 28 March 2007.
535
+
536
+ Nothing in this License shall be construed as excluding or limiting
537
+ any implied license or other defenses to infringement that may
538
+ otherwise be available to you under applicable patent law.
539
+
540
+ 12. No Surrender of Others' Freedom.
541
+
542
+ If conditions are imposed on you (whether by court order, agreement or
543
+ otherwise) that contradict the conditions of this License, they do not
544
+ excuse you from the conditions of this License. If you cannot convey a
545
+ covered work so as to satisfy simultaneously your obligations under this
546
+ License and any other pertinent obligations, then as a consequence you may
547
+ not convey it at all. For example, if you agree to terms that obligate you
548
+ to collect a royalty for further conveying from those to whom you convey
549
+ the Program, the only way you could satisfy both those terms and this
550
+ License would be to refrain entirely from conveying the Program.
551
+
552
+ 13. Use with the GNU Affero General Public License.
553
+
554
+ Notwithstanding any other provision of this License, you have
555
+ permission to link or combine any covered work with a work licensed
556
+ under version 3 of the GNU Affero General Public License into a single
557
+ combined work, and to convey the resulting work. The terms of this
558
+ License will continue to apply to the part which is the covered work,
559
+ but the special requirements of the GNU Affero General Public License,
560
+ section 13, concerning interaction through a network will apply to the
561
+ combination as such.
562
+
563
+ 14. Revised Versions of this License.
564
+
565
+ The Free Software Foundation may publish revised and/or new versions of
566
+ the GNU General Public License from time to time. Such new versions will
567
+ be similar in spirit to the present version, but may differ in detail to
568
+ address new problems or concerns.
569
+
570
+ Each version is given a distinguishing version number. If the
571
+ Program specifies that a certain numbered version of the GNU General
572
+ Public License "or any later version" applies to it, you have the
573
+ option of following the terms and conditions either of that numbered
574
+ version or of any later version published by the Free Software
575
+ Foundation. If the Program does not specify a version number of the
576
+ GNU General Public License, you may choose any version ever published
577
+ by the Free Software Foundation.
578
+
579
+ If the Program specifies that a proxy can decide which future
580
+ versions of the GNU General Public License can be used, that proxy's
581
+ public statement of acceptance of a version permanently authorizes you
582
+ to choose that version for the Program.
583
+
584
+ Later license versions may give you additional or different
585
+ permissions. However, no additional obligations are imposed on any
586
+ author or copyright holder as a result of your choosing to follow a
587
+ later version.
588
+
589
+ 15. Disclaimer of Warranty.
590
+
591
+ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592
+ APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593
+ HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594
+ OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595
+ THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596
+ PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597
+ IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598
+ ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599
+
600
+ 16. Limitation of Liability.
601
+
602
+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603
+ WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604
+ THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605
+ GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606
+ USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607
+ DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608
+ PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609
+ EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610
+ SUCH DAMAGES.
611
+
612
+ 17. Interpretation of Sections 15 and 16.
613
+
614
+ If the disclaimer of warranty and limitation of liability provided
615
+ above cannot be given local legal effect according to their terms,
616
+ reviewing courts shall apply local law that most closely approximates
617
+ an absolute waiver of all civil liability in connection with the
618
+ Program, unless a warranty or assumption of liability accompanies a
619
+ copy of the Program in return for a fee.
620
+
621
+ END OF TERMS AND CONDITIONS
622
+
623
+ How to Apply These Terms to Your New Programs
624
+
625
+ If you develop a new program, and you want it to be of the greatest
626
+ possible use to the public, the best way to achieve this is to make it
627
+ free software which everyone can redistribute and change under these terms.
628
+
629
+ To do so, attach the following notices to the program. It is safest
630
+ to attach them to the start of each source file to most effectively
631
+ state the exclusion of warranty; and each file should have at least
632
+ the "copyright" line and a pointer to where the full notice is found.
633
+
634
+ <one line to give the program's name and a brief idea of what it does.>
635
+ Copyright (C) <year> <name of author>
636
+
637
+ This program is free software: you can redistribute it and/or modify
638
+ it under the terms of the GNU General Public License as published by
639
+ the Free Software Foundation, either version 3 of the License, or
640
+ (at your option) any later version.
641
+
642
+ This program is distributed in the hope that it will be useful,
643
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
644
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645
+ GNU General Public License for more details.
646
+
647
+ You should have received a copy of the GNU General Public License
648
+ along with this program. If not, see <https://www.gnu.org/licenses/>.
649
+
650
+ Also add information on how to contact you by electronic and paper mail.
651
+
652
+ If the program does terminal interaction, make it output a short
653
+ notice like this when it starts in an interactive mode:
654
+
655
+ <program> Copyright (C) <year> <name of author>
656
+ This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657
+ This is free software, and you are welcome to redistribute it
658
+ under certain conditions; type `show c' for details.
659
+
660
+ The hypothetical commands `show w' and `show c' should show the appropriate
661
+ parts of the General Public License. Of course, your program's commands
662
+ might be different; for a GUI interface, you would use an "about box".
663
+
664
+ You should also get your employer (if you work as a programmer) or school,
665
+ if any, to sign a "copyright disclaimer" for the program, if necessary.
666
+ For more information on this, and how to apply and follow the GNU GPL, see
667
+ <https://www.gnu.org/licenses/>.
668
+
669
+ The GNU General Public License does not permit incorporating your program
670
+ into proprietary programs. If your program is a subroutine library, you
671
+ may consider it more useful to permit linking proprietary applications with
672
+ the library. If this is what you want to do, use the GNU Lesser General
673
+ Public License instead of this License. But first, please read
674
+ <https://www.gnu.org/licenses/why-not-lgpl.html>.
README.md CHANGED
@@ -1,13 +1,163 @@
1
  ---
2
- title: Audio-diffusion Style Transfer
3
- emoji: πŸƒ
4
- colorFrom: indigo
5
- colorTo: pink
6
  sdk: gradio
7
- sdk_version: 3.9
8
  app_file: app.py
9
  pinned: false
10
  license: gpl-3.0
11
  ---
 
12
 
13
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
+ title: Audio Diffusion
3
+ emoji: 🎡
4
+ colorFrom: pink
5
+ colorTo: blue
6
  sdk: gradio
7
+ sdk_version: 3.1.4
8
  app_file: app.py
9
  pinned: false
10
  license: gpl-3.0
11
  ---
12
+ # audio-diffusion [![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/teticio/audio-diffusion/blob/master/notebooks/gradio_app.ipynb)
13
 
14
+ ### Apply diffusion models to synthesize music instead of images using the new Hugging Face [diffusers](https://github.com/huggingface/diffusers) package.
15
+
16
+ ---
17
+
18
+ **UPDATES**:
19
+
20
+ **22/10/2022**. Added DDIM encoder and ability to interpolate between audios in latent "noise" space. Mel spectrograms no longer have to be square (thanks to Tristan for this one), so you can set the vertical (frequency) and horizontal (time) resolutions independently.
21
+
22
+ **15/10/2022**. Added latent audio diffusion (see below). Also added the possibility to train a DDIM ([De-noising Diffusion Implicit Models](https://arxiv.org/pdf/2010.02502.pdf)). These have the benefit that samples can be generated with much fewer steps (~50) than used in training.
23
+
24
+ **4/10/2022**. It is now possible to mask parts of the input audio during generation which means you can stitch several samples together (think "out-painting").
25
+
26
+ **27/9/2022**. You can now generate an audio based on a previous one. You can use this to generate variations of the same audio or even to "remix" a track (via a sort of "style transfer"). You can find examples of how to do this in the [`test_model.ipynb`](https://colab.research.google.com/github/teticio/audio-diffusion/blob/master/notebooks/test_model.ipynb) notebook.
27
+
28
+ ---
29
+
30
+ ![mel spectrogram](mel.png)
31
+
32
+ ---
33
+
34
+ ## DDPM ([De-noising Diffusion Probabilistic Models](https://arxiv.org/abs/2006.11239))
35
+
36
+ Audio can be represented as images by transforming to a [mel spectrogram](https://en.wikipedia.org/wiki/Mel-frequency_cepstrum), such as the one shown above. The class `Mel` in `mel.py` can convert a slice of audio into a mel spectrogram of `x_res` x `y_res` and vice versa. The higher the resolution, the less audio information will be lost. You can see how this works in the [`test_mel.ipynb`](https://github.com/teticio/audio-diffusion/blob/main/notebooks/test_mel.ipynb) notebook.
37
+
38
+ A DDPM is trained on a set of mel spectrograms that have been generated from a directory of audio files. It is then used to synthesize similar mel spectrograms, which are then converted back into audio.
39
+
40
+ You can play around with some pre-trained models on [Google Colab](https://colab.research.google.com/github/teticio/audio-diffusion/blob/master/notebooks/test_model.ipynb) or [Hugging Face spaces](https://huggingface.co/spaces/teticio/audio-diffusion). Check out some automatically generated loops [here](https://soundcloud.com/teticio2/sets/audio-diffusion-loops).
41
+
42
+
43
+ | Model | Dataset | Description |
44
+ |-------|---------|-------------|
45
+ | [teticio/audio-diffusion-256](https://huggingface.co/teticio/audio-diffusion-256) | [teticio/audio-diffusion-256](https://huggingface.co/datasets/teticio/audio-diffusion-256) | My "liked" Spotify playlist |
46
+ | [teticio/audio-diffusion-breaks-256](https://huggingface.co/teticio/audio-diffusion-breaks-256) | [teticio/audio-diffusion-breaks-256](https://huggingface.co/datasets/teticio/audio-diffusion-breaks-256) | Samples that have been used in music, sourced from [WhoSampled](https://whosampled.com) and [YouTube](https://youtube.com) |
47
+ | [teticio/audio-diffusion-instrumental-hiphop-256](https://huggingface.co/teticio/audio-diffusion-instrumental-hiphop-256) | [teticio/audio-diffusion-instrumental-hiphop-256](https://huggingface.co/datasets/teticio/audio-diffusion-instrumental-hiphop-256) | Instrumental Hip Hop music |
48
+
49
+ ---
50
+
51
+ ## Generate Mel spectrogram dataset from directory of audio files
52
+ #### Install
53
+ ```bash
54
+ pip install .
55
+ ```
56
+
57
+ #### Training can be run with Mel spectrograms of resolution 64x64 on a single commercial grade GPU (e.g. RTX 2080 Ti). The `hop_length` should be set to 1024 for better results.
58
+ ```bash
59
+ python scripts/audio_to_images.py \
60
+ --resolution 64,64 \
61
+ --hop_length 1024 \
62
+ --input_dir path-to-audio-files \
63
+ --output_dir path-to-output-data
64
+ ```
65
+
66
+ #### Generate dataset of 256x256 Mel spectrograms and push to hub (you will need to be authenticated with `huggingface-cli login`).
67
+ ```bash
68
+ python scripts/audio_to_images.py \
69
+ --resolution 256 \
70
+ --input_dir path-to-audio-files \
71
+ --output_dir data/audio-diffusion-256 \
72
+ --push_to_hub teticio/audio-diffusion-256
73
+ ```
74
+
75
+ ## Train model
76
+ #### Run training on local machine.
77
+ ```bash
78
+ accelerate launch --config_file config/accelerate_local.yaml \
79
+ scripts/train_unconditional.py \
80
+ --dataset_name data/audio-diffusion-64 \
81
+ --hop_length 1024 \
82
+ --output_dir models/ddpm-ema-audio-64 \
83
+ --train_batch_size 16 \
84
+ --num_epochs 100 \
85
+ --gradient_accumulation_steps 1 \
86
+ --learning_rate 1e-4 \
87
+ --lr_warmup_steps 500 \
88
+ --mixed_precision no
89
+ ```
90
+
91
+ #### Run training on local machine with `batch_size` of 2 and `gradient_accumulation_steps` 8 to compensate, so that 256x256 resolution model fits on commercial grade GPU and push to hub.
92
+ ```bash
93
+ accelerate launch --config_file config/accelerate_local.yaml \
94
+ scripts/train_unconditional.py \
95
+ --dataset_name teticio/audio-diffusion-256 \
96
+ --output_dir models/audio-diffusion-256 \
97
+ --num_epochs 100 \
98
+ --train_batch_size 2 \
99
+ --eval_batch_size 2 \
100
+ --gradient_accumulation_steps 8 \
101
+ --learning_rate 1e-4 \
102
+ --lr_warmup_steps 500 \
103
+ --mixed_precision no \
104
+ --push_to_hub True \
105
+ --hub_model_id audio-diffusion-256 \
106
+ --hub_token $(cat $HOME/.huggingface/token)
107
+ ```
108
+
109
+ #### Run training on SageMaker.
110
+ ```bash
111
+ accelerate launch --config_file config/accelerate_sagemaker.yaml \
112
+ scripts/train_unconditional.py \
113
+ --dataset_name teticio/audio-diffusion-256 \
114
+ --output_dir models/ddpm-ema-audio-256 \
115
+ --train_batch_size 16 \
116
+ --num_epochs 100 \
117
+ --gradient_accumulation_steps 1 \
118
+ --learning_rate 1e-4 \
119
+ --lr_warmup_steps 500 \
120
+ --mixed_precision no
121
+ ```
122
+
123
+ ## DDIM ([De-noising Diffusion Implicit Models](https://arxiv.org/pdf/2010.02502.pdf))
124
+ #### A DDIM can be trained by adding the parameter
125
+ ```bash
126
+ --scheduler ddim
127
+ ```
128
+
129
+ Inference can the be run with far fewer steps than the number used for training (e.g., ~50), allowing for much faster generation. Without retraining, the parameter `eta` can be used to replicate a DDPM if it is set to 1 or a DDIM if it is set to 0, with all values in between being valid. When `eta` is 0 (the default value), the de-noising procedure is deterministic, which means that it can be run in reverse as a kind of encoder that recovers the original noise used in generation. A function `encode` has been added to `AudioDiffusionPipeline` for this purpose. It is then possible to interpolate between audios in the latent "noise" space using the function `slerp` (Spherical Linear intERPolation).
130
+
131
+ ## Latent Audio Diffusion
132
+ Rather than de-noising images directly, it is interesting to work in the "latent space" after first encoding images using an autoencoder. This has a number of advantages. Firstly, the information in the images is compressed into a latent space of a much lower dimension, so it is much faster to train de-noising diffusion models and run inference with them. Secondly, similar images tend to be clustered together and interpolating between two images in latent space can produce meaningful combinations.
133
+
134
+ At the time of writing, the Hugging Face `diffusers` library is geared towards inference and lacking in training functionality (rather like its cousin `transformers` in the early days of development). In order to train a VAE (Variational AutoEncoder), I use the [stable-diffusion](https://github.com/CompVis/stable-diffusion) repo from CompVis and convert the checkpoints to `diffusers` format. Note that it uses a perceptual loss function for images; it would be nice to try a perceptual *audio* loss function.
135
+
136
+ #### Train latent diffusion model using pre-trained VAE.
137
+ ```bash
138
+ accelerate launch ...
139
+ ...
140
+ --vae teticio/latent-audio-diffusion-256
141
+ ```
142
+
143
+ #### Install dependencies to train with Stable Diffusion.
144
+ ```
145
+ pip install omegaconf pytorch_lightning
146
+ pip install -e git+https://github.com/CompVis/stable-diffusion.git@main#egg=latent-diffusion
147
+ pip install -e git+https://github.com/CompVis/taming-transformers.git@master#egg=taming-transformers
148
+ ```
149
+
150
+ #### Train an autoencoder.
151
+ ```bash
152
+ python scripts/train_vae.py \
153
+ --dataset_name teticio/audio-diffusion-256 \
154
+ --batch_size 2 \
155
+ --gradient_accumulation_steps 12
156
+ ```
157
+
158
+ #### Train latent diffusion model.
159
+ ```bash
160
+ accelerate launch ...
161
+ ...
162
+ --vae models/autoencoder-kl
163
+ ```
app.py ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+
3
+ import gradio as gr
4
+
5
+ from audiodiffusion import AudioDiffusion
6
+
7
+
8
+ def generate_spectrogram_audio_and_loop(model_id):
9
+ audio_diffusion = AudioDiffusion(model_id=model_id)
10
+ image, (sample_rate,
11
+ audio) = audio_diffusion.generate_spectrogram_and_audio()
12
+ loop = AudioDiffusion.loop_it(audio, sample_rate)
13
+ if loop is None:
14
+ loop = audio
15
+ return image, (sample_rate, audio), (sample_rate, loop)
16
+
17
+
18
+ demo = gr.Interface(fn=generate_spectrogram_audio_and_loop,
19
+ title="Audio Diffusion",
20
+ description="Generate audio using Huggingface diffusers.\
21
+ This takes about 20 minutes without a GPU, so why not make yourself a \
22
+ cup of tea in the meantime? (Or try the teticio/audio-diffusion-ddim-256 \
23
+ model which is faster.)",
24
+ inputs=[
25
+ gr.Dropdown(label="Model",
26
+ choices=[
27
+ "teticio/audio-diffusion-256",
28
+ "teticio/audio-diffusion-breaks-256",
29
+ "teticio/audio-diffusion-instrumental-hiphop-256",
30
+ "teticio/audio-diffusion-ddim-256"
31
+ ],
32
+ value="teticio/audio-diffusion-256")
33
+ ],
34
+ outputs=[
35
+ gr.Image(label="Mel spectrogram", image_mode="L"),
36
+ gr.Audio(label="Audio"),
37
+ gr.Audio(label="Loop"),
38
+ ],
39
+ allow_flagging="never")
40
+
41
+ if __name__ == "__main__":
42
+ parser = argparse.ArgumentParser()
43
+ parser.add_argument("--port", type=int)
44
+ parser.add_argument("--server", type=int)
45
+ args = parser.parse_args()
46
+ demo.launch(server_name=args.server or "0.0.0.0", server_port=args.port)
audiodiffusion/__init__.py ADDED
@@ -0,0 +1,369 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from math import acos, sin
2
+ from typing import Iterable, Tuple, Union, List
3
+
4
+ import torch
5
+ import numpy as np
6
+ from PIL import Image
7
+ from tqdm.auto import tqdm
8
+ from librosa.beat import beat_track
9
+ from diffusers import (DiffusionPipeline, UNet2DConditionModel, DDIMScheduler,
10
+ DDPMScheduler, AutoencoderKL)
11
+
12
+ from .mel import Mel
13
+
14
+ VERSION = "1.2.5"
15
+
16
+
17
+ class AudioDiffusion:
18
+
19
+ def __init__(self,
20
+ model_id: str = "teticio/audio-diffusion-256",
21
+ sample_rate: int = 22050,
22
+ n_fft: int = 2048,
23
+ hop_length: int = 512,
24
+ top_db: int = 80,
25
+ cuda: bool = torch.cuda.is_available(),
26
+ progress_bar: Iterable = tqdm):
27
+ """Class for generating audio using De-noising Diffusion Probabilistic Models.
28
+
29
+ Args:
30
+ model_id (String): name of model (local directory or Hugging Face Hub)
31
+ sample_rate (int): sample rate of audio
32
+ n_fft (int): number of Fast Fourier Transforms
33
+ hop_length (int): hop length (a higher number is recommended for lower than 256 y_res)
34
+ top_db (int): loudest in decibels
35
+ cuda (bool): use CUDA?
36
+ progress_bar (iterable): iterable callback for progress updates or None
37
+ """
38
+ self.model_id = model_id
39
+ pipeline = {
40
+ 'LatentAudioDiffusionPipeline': LatentAudioDiffusionPipeline,
41
+ 'AudioDiffusionPipeline': AudioDiffusionPipeline
42
+ }.get(
43
+ DiffusionPipeline.get_config_dict(self.model_id)['_class_name'],
44
+ AudioDiffusionPipeline)
45
+ self.pipe = pipeline.from_pretrained(self.model_id)
46
+ if cuda:
47
+ self.pipe.to("cuda")
48
+ self.progress_bar = progress_bar or (lambda _: _)
49
+
50
+ # For backwards compatibility
51
+ sample_size = (self.pipe.unet.sample_size,
52
+ self.pipe.unet.sample_size) if type(
53
+ self.pipe.unet.sample_size
54
+ ) == int else self.pipe.unet.sample_size
55
+ self.mel = Mel(x_res=sample_size[1],
56
+ y_res=sample_size[0],
57
+ sample_rate=sample_rate,
58
+ n_fft=n_fft,
59
+ hop_length=hop_length,
60
+ top_db=top_db)
61
+
62
+ def generate_spectrogram_and_audio(
63
+ self,
64
+ steps: int = None,
65
+ generator: torch.Generator = None,
66
+ step_generator: torch.Generator = None,
67
+ eta: float = 0,
68
+ noise: torch.Tensor = None
69
+ ) -> Tuple[Image.Image, Tuple[int, np.ndarray]]:
70
+ """Generate random mel spectrogram and convert to audio.
71
+
72
+ Args:
73
+ steps (int): number of de-noising steps (defaults to 50 for DDIM, 1000 for DDPM)
74
+ generator (torch.Generator): random number generator or None
75
+ step_generator (torch.Generator): random number generator used to de-noise or None
76
+ eta (float): parameter between 0 and 1 used with DDIM scheduler
77
+ noise (torch.Tensor): noisy image or None
78
+
79
+ Returns:
80
+ PIL Image: mel spectrogram
81
+ (float, np.ndarray): sample rate and raw audio
82
+ """
83
+ images, (sample_rate,
84
+ audios) = self.pipe(mel=self.mel,
85
+ batch_size=1,
86
+ steps=steps,
87
+ generator=generator,
88
+ step_generator=step_generator,
89
+ eta=eta,
90
+ noise=noise)
91
+ return images[0], (sample_rate, audios[0])
92
+
93
+ def generate_spectrogram_and_audio_from_audio(
94
+ self,
95
+ audio_file: str = None,
96
+ raw_audio: np.ndarray = None,
97
+ slice: int = 0,
98
+ start_step: int = 0,
99
+ steps: int = None,
100
+ generator: torch.Generator = None,
101
+ mask_start_secs: float = 0,
102
+ mask_end_secs: float = 0,
103
+ step_generator: torch.Generator = None,
104
+ eta: float = 0,
105
+ noise: torch.Tensor = None
106
+ ) -> Tuple[Image.Image, Tuple[int, np.ndarray]]:
107
+ """Generate random mel spectrogram from audio input and convert to audio.
108
+
109
+ Args:
110
+ audio_file (str): must be a file on disk due to Librosa limitation or
111
+ raw_audio (np.ndarray): audio as numpy array
112
+ slice (int): slice number of audio to convert
113
+ start_step (int): step to start from
114
+ steps (int): number of de-noising steps (defaults to 50 for DDIM, 1000 for DDPM)
115
+ generator (torch.Generator): random number generator or None
116
+ mask_start_secs (float): number of seconds of audio to mask (not generate) at start
117
+ mask_end_secs (float): number of seconds of audio to mask (not generate) at end
118
+ step_generator (torch.Generator): random number generator used to de-noise or None
119
+ eta (float): parameter between 0 and 1 used with DDIM scheduler
120
+ noise (torch.Tensor): noisy image or None
121
+
122
+ Returns:
123
+ PIL Image: mel spectrogram
124
+ (float, np.ndarray): sample rate and raw audio
125
+ """
126
+
127
+ images, (sample_rate,
128
+ audios) = self.pipe(mel=self.mel,
129
+ batch_size=1,
130
+ audio_file=audio_file,
131
+ raw_audio=raw_audio,
132
+ slice=slice,
133
+ start_step=start_step,
134
+ steps=steps,
135
+ generator=generator,
136
+ mask_start_secs=mask_start_secs,
137
+ mask_end_secs=mask_end_secs,
138
+ step_generator=step_generator,
139
+ eta=eta,
140
+ noise=noise)
141
+ return images[0], (sample_rate, audios[0])
142
+
143
+ @staticmethod
144
+ def loop_it(audio: np.ndarray,
145
+ sample_rate: int,
146
+ loops: int = 12) -> np.ndarray:
147
+ """Loop audio
148
+
149
+ Args:
150
+ audio (np.ndarray): audio as numpy array
151
+ sample_rate (int): sample rate of audio
152
+ loops (int): number of times to loop
153
+
154
+ Returns:
155
+ (float, np.ndarray): sample rate and raw audio or None
156
+ """
157
+ _, beats = beat_track(y=audio, sr=sample_rate, units='samples')
158
+ for beats_in_bar in [16, 12, 8, 4]:
159
+ if len(beats) > beats_in_bar:
160
+ return np.tile(audio[beats[0]:beats[beats_in_bar]], loops)
161
+ return None
162
+
163
+
164
+ class AudioDiffusionPipeline(DiffusionPipeline):
165
+
166
+ def __init__(self, unet: UNet2DConditionModel,
167
+ scheduler: Union[DDIMScheduler, DDPMScheduler]):
168
+ super().__init__()
169
+ self.register_modules(unet=unet, scheduler=scheduler)
170
+
171
+ @torch.no_grad()
172
+ def __call__(
173
+ self,
174
+ mel: Mel,
175
+ batch_size: int = 1,
176
+ audio_file: str = None,
177
+ raw_audio: np.ndarray = None,
178
+ slice: int = 0,
179
+ start_step: int = 0,
180
+ steps: int = None,
181
+ generator: torch.Generator = None,
182
+ mask_start_secs: float = 0,
183
+ mask_end_secs: float = 0,
184
+ step_generator: torch.Generator = None,
185
+ eta: float = 0,
186
+ noise: torch.Tensor = None
187
+ ) -> Tuple[List[Image.Image], Tuple[int, List[np.ndarray]]]:
188
+ """Generate random mel spectrogram from audio input and convert to audio.
189
+
190
+ Args:
191
+ mel (Mel): instance of Mel class to perform image <-> audio
192
+ batch_size (int): number of samples to generate
193
+ audio_file (str): must be a file on disk due to Librosa limitation or
194
+ raw_audio (np.ndarray): audio as numpy array
195
+ slice (int): slice number of audio to convert
196
+ start_step (int): step to start from
197
+ steps (int): number of de-noising steps (defaults to 50 for DDIM, 1000 for DDPM)
198
+ generator (torch.Generator): random number generator or None
199
+ mask_start_secs (float): number of seconds of audio to mask (not generate) at start
200
+ mask_end_secs (float): number of seconds of audio to mask (not generate) at end
201
+ step_generator (torch.Generator): random number generator used to de-noise or None
202
+ eta (float): parameter between 0 and 1 used with DDIM scheduler
203
+ noise (torch.Tensor): noise tensor of shape (batch_size, 1, height, width) or None
204
+
205
+ Returns:
206
+ List[PIL Image]: mel spectrograms
207
+ (float, List[np.ndarray]): sample rate and raw audios
208
+ """
209
+
210
+ steps = steps or 50 if isinstance(self.scheduler,
211
+ DDIMScheduler) else 1000
212
+ self.scheduler.set_timesteps(steps)
213
+ step_generator = step_generator or generator
214
+ # For backwards compatibility
215
+ if type(self.unet.sample_size) == int:
216
+ self.unet.sample_size = (self.unet.sample_size,
217
+ self.unet.sample_size)
218
+ if noise is None:
219
+ noise = torch.randn(
220
+ (batch_size, self.unet.in_channels, self.unet.sample_size[0],
221
+ self.unet.sample_size[1]),
222
+ generator=generator)
223
+ images = noise
224
+ mask = None
225
+
226
+ if audio_file is not None or raw_audio is not None:
227
+ mel.load_audio(audio_file, raw_audio)
228
+ input_image = mel.audio_slice_to_image(slice)
229
+ input_image = np.frombuffer(input_image.tobytes(),
230
+ dtype="uint8").reshape(
231
+ (input_image.height,
232
+ input_image.width))
233
+ input_image = ((input_image / 255) * 2 - 1)
234
+ input_images = np.tile(input_image, (batch_size, 1, 1, 1))
235
+
236
+ if hasattr(self, 'vqvae'):
237
+ input_images = self.vqvae.encode(
238
+ input_images).latent_dist.sample(generator=generator)
239
+ input_images = 0.18215 * input_images
240
+
241
+ if start_step > 0:
242
+ images[0, 0] = self.scheduler.add_noise(
243
+ torch.tensor(input_images[:, np.newaxis, np.newaxis, :]),
244
+ noise, torch.tensor(steps - start_step))
245
+
246
+ pixels_per_second = (self.unet.sample_size[1] *
247
+ mel.get_sample_rate() / mel.x_res /
248
+ mel.hop_length)
249
+ mask_start = int(mask_start_secs * pixels_per_second)
250
+ mask_end = int(mask_end_secs * pixels_per_second)
251
+ mask = self.scheduler.add_noise(
252
+ torch.tensor(input_images[:, np.newaxis, :]), noise,
253
+ torch.tensor(self.scheduler.timesteps[start_step:]))
254
+
255
+ images = images.to(self.device)
256
+ for step, t in enumerate(
257
+ self.progress_bar(self.scheduler.timesteps[start_step:])):
258
+ model_output = self.unet(images, t)['sample']
259
+
260
+ if isinstance(self.scheduler, DDIMScheduler):
261
+ images = self.scheduler.step(
262
+ model_output=model_output,
263
+ timestep=t,
264
+ sample=images,
265
+ eta=eta,
266
+ generator=step_generator)['prev_sample']
267
+ else:
268
+ images = self.scheduler.step(
269
+ model_output=model_output,
270
+ timestep=t,
271
+ sample=images,
272
+ generator=step_generator)['prev_sample']
273
+
274
+ if mask is not None:
275
+ if mask_start > 0:
276
+ images[:, :, :, :mask_start] = mask[
277
+ step, :, :, :, :mask_start]
278
+ if mask_end > 0:
279
+ images[:, :, :, -mask_end:] = mask[step, :, :, :,
280
+ -mask_end:]
281
+
282
+ if hasattr(self, 'vqvae'):
283
+ # 0.18215 was scaling factor used in training to ensure unit variance
284
+ images = 1 / 0.18215 * images
285
+ images = self.vqvae.decode(images)['sample']
286
+
287
+ images = (images / 2 + 0.5).clamp(0, 1)
288
+ images = images.cpu().permute(0, 2, 3, 1).numpy()
289
+ images = (images * 255).round().astype("uint8")
290
+ images = list(
291
+ map(lambda _: Image.fromarray(_[:, :, 0]), images) if images.
292
+ shape[3] == 1 else map(
293
+ lambda _: Image.fromarray(_, mode='RGB').convert('L'), images))
294
+
295
+ audios = list(map(lambda _: mel.image_to_audio(_), images))
296
+ return images, (mel.get_sample_rate(), audios)
297
+
298
+ @torch.no_grad()
299
+ def encode(self, images: List[Image.Image], steps: int = 50) -> np.ndarray:
300
+ """Reverse step process: recover noisy image from generated image.
301
+
302
+ Args:
303
+ images (List[PIL Image]): list of images to encode
304
+ steps (int): number of encoding steps to perform (defaults to 50)
305
+
306
+ Returns:
307
+ np.ndarray: noise tensor of shape (batch_size, 1, height, width)
308
+ """
309
+
310
+ # Only works with DDIM as this method is deterministic
311
+ assert isinstance(self.scheduler, DDIMScheduler)
312
+ self.scheduler.set_timesteps(steps)
313
+ sample = np.array([
314
+ np.frombuffer(image.tobytes(), dtype="uint8").reshape(
315
+ (1, image.height, image.width)) for image in images
316
+ ])
317
+ sample = ((sample / 255) * 2 - 1)
318
+ sample = torch.Tensor(sample).to(self.device)
319
+
320
+ for t in self.progress_bar(torch.flip(self.scheduler.timesteps,
321
+ (0, ))):
322
+ prev_timestep = (t - self.scheduler.num_train_timesteps //
323
+ self.scheduler.num_inference_steps)
324
+ alpha_prod_t = self.scheduler.alphas_cumprod[t]
325
+ alpha_prod_t_prev = (self.scheduler.alphas_cumprod[prev_timestep]
326
+ if prev_timestep >= 0 else
327
+ self.scheduler.final_alpha_cumprod)
328
+ beta_prod_t = 1 - alpha_prod_t
329
+ model_output = self.unet(sample, t)['sample']
330
+ pred_sample_direction = (1 -
331
+ alpha_prod_t_prev)**(0.5) * model_output
332
+ sample = (sample -
333
+ pred_sample_direction) * alpha_prod_t_prev**(-0.5)
334
+ sample = sample * alpha_prod_t**(0.5) + beta_prod_t**(
335
+ 0.5) * model_output
336
+
337
+ return sample
338
+
339
+ @staticmethod
340
+ def slerp(x0: torch.Tensor, x1: torch.Tensor,
341
+ alpha: float) -> torch.Tensor:
342
+ """Spherical Linear intERPolation
343
+
344
+ Args:
345
+ x0 (torch.Tensor): first tensor to interpolate between
346
+ x1 (torch.Tensor): seconds tensor to interpolate between
347
+ alpha (float): interpolation between 0 and 1
348
+
349
+ Returns:
350
+ torch.Tensor: interpolated tensor
351
+ """
352
+
353
+ theta = acos(
354
+ torch.dot(torch.flatten(x0), torch.flatten(x1)) / torch.norm(x0) /
355
+ torch.norm(x1))
356
+ return sin((1 - alpha) * theta) * x0 / sin(theta) + sin(
357
+ alpha * theta) * x1 / sin(theta)
358
+
359
+
360
+ class LatentAudioDiffusionPipeline(AudioDiffusionPipeline):
361
+
362
+ def __init__(self, unet: UNet2DConditionModel,
363
+ scheduler: Union[DDIMScheduler,
364
+ DDPMScheduler], vqvae: AutoencoderKL):
365
+ super().__init__(unet=unet, scheduler=scheduler)
366
+ self.register_modules(vqvae=vqvae)
367
+
368
+ def __call__(self, *args, **kwargs):
369
+ return super().__call__(*args, **kwargs)
audiodiffusion/mel.py ADDED
@@ -0,0 +1,127 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import warnings
2
+
3
+ warnings.filterwarnings('ignore')
4
+
5
+ import librosa
6
+ import numpy as np
7
+ from PIL import Image
8
+
9
+
10
+ class Mel:
11
+
12
+ def __init__(
13
+ self,
14
+ x_res: int = 256,
15
+ y_res: int = 256,
16
+ sample_rate: int = 22050,
17
+ n_fft: int = 2048,
18
+ hop_length: int = 512,
19
+ top_db: int = 80,
20
+ ):
21
+ """Class to convert audio to mel spectrograms and vice versa.
22
+
23
+ Args:
24
+ x_res (int): x resolution of spectrogram (time)
25
+ y_res (int): y resolution of spectrogram (frequency bins)
26
+ sample_rate (int): sample rate of audio
27
+ n_fft (int): number of Fast Fourier Transforms
28
+ hop_length (int): hop length (a higher number is recommended for lower than 256 y_res)
29
+ top_db (int): loudest in decibels
30
+ """
31
+ self.x_res = x_res
32
+ self.y_res = y_res
33
+ self.sr = sample_rate
34
+ self.n_fft = n_fft
35
+ self.hop_length = hop_length
36
+ self.n_mels = self.y_res
37
+ self.slice_size = self.x_res * self.hop_length - 1
38
+ self.fmax = self.sr / 2
39
+ self.top_db = top_db
40
+ self.audio = None
41
+
42
+ def load_audio(self, audio_file: str = None, raw_audio: np.ndarray = None):
43
+ """Load audio.
44
+
45
+ Args:
46
+ audio_file (str): must be a file on disk due to Librosa limitation or
47
+ raw_audio (np.ndarray): audio as numpy array
48
+ """
49
+ if audio_file is not None:
50
+ self.audio, _ = librosa.load(audio_file, mono=True, sr=self.sr)
51
+ else:
52
+ self.audio = raw_audio
53
+
54
+ # Pad with silence if necessary.
55
+ if len(self.audio) < self.x_res * self.hop_length:
56
+ self.audio = np.concatenate([
57
+ self.audio,
58
+ np.zeros((self.x_res * self.hop_length - len(self.audio), ))
59
+ ])
60
+
61
+ def get_number_of_slices(self) -> int:
62
+ """Get number of slices in audio.
63
+
64
+ Returns:
65
+ int: number of spectograms audio can be sliced into
66
+ """
67
+ return len(self.audio) // self.slice_size
68
+
69
+ def get_audio_slice(self, slice: int = 0) -> np.ndarray:
70
+ """Get slice of audio.
71
+
72
+ Args:
73
+ slice (int): slice number of audio (out of get_number_of_slices())
74
+
75
+ Returns:
76
+ np.ndarray: audio as numpy array
77
+ """
78
+ return self.audio[self.slice_size * slice:self.slice_size *
79
+ (slice + 1)]
80
+
81
+ def get_sample_rate(self) -> int:
82
+ """Get sample rate:
83
+
84
+ Returns:
85
+ int: sample rate of audio
86
+ """
87
+ return self.sr
88
+
89
+ def audio_slice_to_image(self, slice: int) -> Image.Image:
90
+ """Convert slice of audio to spectrogram.
91
+
92
+ Args:
93
+ slice (int): slice number of audio to convert (out of get_number_of_slices())
94
+
95
+ Returns:
96
+ PIL Image: grayscale image of x_res x y_res
97
+ """
98
+ S = librosa.feature.melspectrogram(
99
+ y=self.get_audio_slice(slice),
100
+ sr=self.sr,
101
+ n_fft=self.n_fft,
102
+ hop_length=self.hop_length,
103
+ n_mels=self.n_mels,
104
+ fmax=self.fmax,
105
+ )
106
+ log_S = librosa.power_to_db(S, ref=np.max, top_db=self.top_db)
107
+ bytedata = (((log_S + self.top_db) * 255 / self.top_db).clip(0, 255) +
108
+ 0.5).astype(np.uint8)
109
+ image = Image.fromarray(bytedata)
110
+ return image
111
+
112
+ def image_to_audio(self, image: Image.Image) -> np.ndarray:
113
+ """Converts spectrogram to audio.
114
+
115
+ Args:
116
+ image (PIL Image): x_res x y_res grayscale image
117
+
118
+ Returns:
119
+ audio (np.ndarray): raw audio
120
+ """
121
+ bytedata = np.frombuffer(image.tobytes(), dtype="uint8").reshape(
122
+ (image.height, image.width))
123
+ log_S = bytedata.astype("float") * self.top_db / 255 - self.top_db
124
+ S = librosa.db_to_power(log_S)
125
+ audio = librosa.feature.inverse.mel_to_audio(
126
+ S, sr=self.sr, n_fft=self.n_fft, hop_length=self.hop_length)
127
+ return audio
audiodiffusion/utils.py ADDED
@@ -0,0 +1,342 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # adpated from https://github.com/huggingface/diffusers/blob/main/scripts/convert_original_stable_diffusion_to_diffusers.py
2
+
3
+ import torch
4
+ from diffusers import AutoencoderKL
5
+
6
+
7
+ def shave_segments(path, n_shave_prefix_segments=1):
8
+ """
9
+ Removes segments. Positive values shave the first segments, negative shave the last segments.
10
+ """
11
+ if n_shave_prefix_segments >= 0:
12
+ return ".".join(path.split(".")[n_shave_prefix_segments:])
13
+ else:
14
+ return ".".join(path.split(".")[:n_shave_prefix_segments])
15
+
16
+
17
+ def renew_vae_resnet_paths(old_list, n_shave_prefix_segments=0):
18
+ """
19
+ Updates paths inside resnets to the new naming scheme (local renaming)
20
+ """
21
+ mapping = []
22
+ for old_item in old_list:
23
+ new_item = old_item
24
+
25
+ new_item = new_item.replace("nin_shortcut", "conv_shortcut")
26
+ new_item = shave_segments(
27
+ new_item, n_shave_prefix_segments=n_shave_prefix_segments)
28
+
29
+ mapping.append({"old": old_item, "new": new_item})
30
+
31
+ return mapping
32
+
33
+
34
+ def renew_vae_attention_paths(old_list, n_shave_prefix_segments=0):
35
+ """
36
+ Updates paths inside attentions to the new naming scheme (local renaming)
37
+ """
38
+ mapping = []
39
+ for old_item in old_list:
40
+ new_item = old_item
41
+
42
+ new_item = new_item.replace("norm.weight", "group_norm.weight")
43
+ new_item = new_item.replace("norm.bias", "group_norm.bias")
44
+
45
+ new_item = new_item.replace("q.weight", "query.weight")
46
+ new_item = new_item.replace("q.bias", "query.bias")
47
+
48
+ new_item = new_item.replace("k.weight", "key.weight")
49
+ new_item = new_item.replace("k.bias", "key.bias")
50
+
51
+ new_item = new_item.replace("v.weight", "value.weight")
52
+ new_item = new_item.replace("v.bias", "value.bias")
53
+
54
+ new_item = new_item.replace("proj_out.weight", "proj_attn.weight")
55
+ new_item = new_item.replace("proj_out.bias", "proj_attn.bias")
56
+
57
+ new_item = shave_segments(
58
+ new_item, n_shave_prefix_segments=n_shave_prefix_segments)
59
+
60
+ mapping.append({"old": old_item, "new": new_item})
61
+
62
+ return mapping
63
+
64
+
65
+ def assign_to_checkpoint(paths,
66
+ checkpoint,
67
+ old_checkpoint,
68
+ attention_paths_to_split=None,
69
+ additional_replacements=None,
70
+ config=None):
71
+ """
72
+ This does the final conversion step: take locally converted weights and apply a global renaming
73
+ to them. It splits attention layers, and takes into account additional replacements
74
+ that may arise.
75
+
76
+ Assigns the weights to the new checkpoint.
77
+ """
78
+ assert isinstance(
79
+ paths, list
80
+ ), "Paths should be a list of dicts containing 'old' and 'new' keys."
81
+
82
+ # Splits the attention layers into three variables.
83
+ if attention_paths_to_split is not None:
84
+ for path, path_map in attention_paths_to_split.items():
85
+ old_tensor = old_checkpoint[path]
86
+ channels = old_tensor.shape[0] // 3
87
+
88
+ target_shape = (-1,
89
+ channels) if len(old_tensor.shape) == 3 else (-1)
90
+
91
+ num_heads = old_tensor.shape[0] // config["num_head_channels"] // 3
92
+
93
+ old_tensor = old_tensor.reshape((num_heads, 3 * channels //
94
+ num_heads) + old_tensor.shape[1:])
95
+ query, key, value = old_tensor.split(channels // num_heads, dim=1)
96
+
97
+ checkpoint[path_map["query"]] = query.reshape(target_shape)
98
+ checkpoint[path_map["key"]] = key.reshape(target_shape)
99
+ checkpoint[path_map["value"]] = value.reshape(target_shape)
100
+
101
+ for path in paths:
102
+ new_path = path["new"]
103
+
104
+ # These have already been assigned
105
+ if attention_paths_to_split is not None and new_path in attention_paths_to_split:
106
+ continue
107
+
108
+ # Global renaming happens here
109
+ new_path = new_path.replace("middle_block.0", "mid_block.resnets.0")
110
+ new_path = new_path.replace("middle_block.1", "mid_block.attentions.0")
111
+ new_path = new_path.replace("middle_block.2", "mid_block.resnets.1")
112
+
113
+ if additional_replacements is not None:
114
+ for replacement in additional_replacements:
115
+ new_path = new_path.replace(replacement["old"],
116
+ replacement["new"])
117
+
118
+ # proj_attn.weight has to be converted from conv 1D to linear
119
+ if "proj_attn.weight" in new_path:
120
+ checkpoint[new_path] = old_checkpoint[path["old"]][:, :, 0]
121
+ else:
122
+ checkpoint[new_path] = old_checkpoint[path["old"]]
123
+
124
+
125
+ def conv_attn_to_linear(checkpoint):
126
+ keys = list(checkpoint.keys())
127
+ attn_keys = ["query.weight", "key.weight", "value.weight"]
128
+ for key in keys:
129
+ if ".".join(key.split(".")[-2:]) in attn_keys:
130
+ if checkpoint[key].ndim > 2:
131
+ checkpoint[key] = checkpoint[key][:, :, 0, 0]
132
+ elif "proj_attn.weight" in key:
133
+ if checkpoint[key].ndim > 2:
134
+ checkpoint[key] = checkpoint[key][:, :, 0]
135
+
136
+
137
+ def create_vae_diffusers_config(original_config):
138
+ """
139
+ Creates a config for the diffusers based on the config of the LDM model.
140
+ """
141
+ vae_params = original_config.model.params.ddconfig
142
+ _ = original_config.model.params.embed_dim
143
+
144
+ block_out_channels = [vae_params.ch * mult for mult in vae_params.ch_mult]
145
+ down_block_types = ["DownEncoderBlock2D"] * len(block_out_channels)
146
+ up_block_types = ["UpDecoderBlock2D"] * len(block_out_channels)
147
+
148
+ config = dict(
149
+ sample_size=vae_params.resolution,
150
+ in_channels=vae_params.in_channels,
151
+ out_channels=vae_params.out_ch,
152
+ down_block_types=tuple(down_block_types),
153
+ up_block_types=tuple(up_block_types),
154
+ block_out_channels=tuple(block_out_channels),
155
+ latent_channels=vae_params.z_channels,
156
+ layers_per_block=vae_params.num_res_blocks,
157
+ )
158
+ return config
159
+
160
+
161
+ def convert_ldm_vae_checkpoint(checkpoint, config):
162
+ # extract state dict for VAE
163
+ vae_state_dict = checkpoint
164
+
165
+ new_checkpoint = {}
166
+
167
+ new_checkpoint["encoder.conv_in.weight"] = vae_state_dict[
168
+ "encoder.conv_in.weight"]
169
+ new_checkpoint["encoder.conv_in.bias"] = vae_state_dict[
170
+ "encoder.conv_in.bias"]
171
+ new_checkpoint["encoder.conv_out.weight"] = vae_state_dict[
172
+ "encoder.conv_out.weight"]
173
+ new_checkpoint["encoder.conv_out.bias"] = vae_state_dict[
174
+ "encoder.conv_out.bias"]
175
+ new_checkpoint["encoder.conv_norm_out.weight"] = vae_state_dict[
176
+ "encoder.norm_out.weight"]
177
+ new_checkpoint["encoder.conv_norm_out.bias"] = vae_state_dict[
178
+ "encoder.norm_out.bias"]
179
+
180
+ new_checkpoint["decoder.conv_in.weight"] = vae_state_dict[
181
+ "decoder.conv_in.weight"]
182
+ new_checkpoint["decoder.conv_in.bias"] = vae_state_dict[
183
+ "decoder.conv_in.bias"]
184
+ new_checkpoint["decoder.conv_out.weight"] = vae_state_dict[
185
+ "decoder.conv_out.weight"]
186
+ new_checkpoint["decoder.conv_out.bias"] = vae_state_dict[
187
+ "decoder.conv_out.bias"]
188
+ new_checkpoint["decoder.conv_norm_out.weight"] = vae_state_dict[
189
+ "decoder.norm_out.weight"]
190
+ new_checkpoint["decoder.conv_norm_out.bias"] = vae_state_dict[
191
+ "decoder.norm_out.bias"]
192
+
193
+ new_checkpoint["quant_conv.weight"] = vae_state_dict["quant_conv.weight"]
194
+ new_checkpoint["quant_conv.bias"] = vae_state_dict["quant_conv.bias"]
195
+ new_checkpoint["post_quant_conv.weight"] = vae_state_dict[
196
+ "post_quant_conv.weight"]
197
+ new_checkpoint["post_quant_conv.bias"] = vae_state_dict[
198
+ "post_quant_conv.bias"]
199
+
200
+ # Retrieves the keys for the encoder down blocks only
201
+ num_down_blocks = len({
202
+ ".".join(layer.split(".")[:3])
203
+ for layer in vae_state_dict if "encoder.down" in layer
204
+ })
205
+ down_blocks = {
206
+ layer_id: [key for key in vae_state_dict if f"down.{layer_id}" in key]
207
+ for layer_id in range(num_down_blocks)
208
+ }
209
+
210
+ # Retrieves the keys for the decoder up blocks only
211
+ num_up_blocks = len({
212
+ ".".join(layer.split(".")[:3])
213
+ for layer in vae_state_dict if "decoder.up" in layer
214
+ })
215
+ up_blocks = {
216
+ layer_id: [key for key in vae_state_dict if f"up.{layer_id}" in key]
217
+ for layer_id in range(num_up_blocks)
218
+ }
219
+
220
+ for i in range(num_down_blocks):
221
+ resnets = [
222
+ key for key in down_blocks[i]
223
+ if f"down.{i}" in key and f"down.{i}.downsample" not in key
224
+ ]
225
+
226
+ if f"encoder.down.{i}.downsample.conv.weight" in vae_state_dict:
227
+ new_checkpoint[
228
+ f"encoder.down_blocks.{i}.downsamplers.0.conv.weight"] = vae_state_dict.pop(
229
+ f"encoder.down.{i}.downsample.conv.weight")
230
+ new_checkpoint[
231
+ f"encoder.down_blocks.{i}.downsamplers.0.conv.bias"] = vae_state_dict.pop(
232
+ f"encoder.down.{i}.downsample.conv.bias")
233
+
234
+ paths = renew_vae_resnet_paths(resnets)
235
+ meta_path = {
236
+ "old": f"down.{i}.block",
237
+ "new": f"down_blocks.{i}.resnets"
238
+ }
239
+ assign_to_checkpoint(paths,
240
+ new_checkpoint,
241
+ vae_state_dict,
242
+ additional_replacements=[meta_path],
243
+ config=config)
244
+
245
+ mid_resnets = [key for key in vae_state_dict if "encoder.mid.block" in key]
246
+ num_mid_res_blocks = 2
247
+ for i in range(1, num_mid_res_blocks + 1):
248
+ resnets = [
249
+ key for key in mid_resnets if f"encoder.mid.block_{i}" in key
250
+ ]
251
+
252
+ paths = renew_vae_resnet_paths(resnets)
253
+ meta_path = {
254
+ "old": f"mid.block_{i}",
255
+ "new": f"mid_block.resnets.{i - 1}"
256
+ }
257
+ assign_to_checkpoint(paths,
258
+ new_checkpoint,
259
+ vae_state_dict,
260
+ additional_replacements=[meta_path],
261
+ config=config)
262
+
263
+ mid_attentions = [
264
+ key for key in vae_state_dict if "encoder.mid.attn" in key
265
+ ]
266
+ paths = renew_vae_attention_paths(mid_attentions)
267
+ meta_path = {"old": "mid.attn_1", "new": "mid_block.attentions.0"}
268
+ assign_to_checkpoint(paths,
269
+ new_checkpoint,
270
+ vae_state_dict,
271
+ additional_replacements=[meta_path],
272
+ config=config)
273
+ conv_attn_to_linear(new_checkpoint)
274
+
275
+ for i in range(num_up_blocks):
276
+ block_id = num_up_blocks - 1 - i
277
+ resnets = [
278
+ key for key in up_blocks[block_id]
279
+ if f"up.{block_id}" in key and f"up.{block_id}.upsample" not in key
280
+ ]
281
+
282
+ if f"decoder.up.{block_id}.upsample.conv.weight" in vae_state_dict:
283
+ new_checkpoint[
284
+ f"decoder.up_blocks.{i}.upsamplers.0.conv.weight"] = vae_state_dict[
285
+ f"decoder.up.{block_id}.upsample.conv.weight"]
286
+ new_checkpoint[
287
+ f"decoder.up_blocks.{i}.upsamplers.0.conv.bias"] = vae_state_dict[
288
+ f"decoder.up.{block_id}.upsample.conv.bias"]
289
+
290
+ paths = renew_vae_resnet_paths(resnets)
291
+ meta_path = {
292
+ "old": f"up.{block_id}.block",
293
+ "new": f"up_blocks.{i}.resnets"
294
+ }
295
+ assign_to_checkpoint(paths,
296
+ new_checkpoint,
297
+ vae_state_dict,
298
+ additional_replacements=[meta_path],
299
+ config=config)
300
+
301
+ mid_resnets = [key for key in vae_state_dict if "decoder.mid.block" in key]
302
+ num_mid_res_blocks = 2
303
+ for i in range(1, num_mid_res_blocks + 1):
304
+ resnets = [
305
+ key for key in mid_resnets if f"decoder.mid.block_{i}" in key
306
+ ]
307
+
308
+ paths = renew_vae_resnet_paths(resnets)
309
+ meta_path = {
310
+ "old": f"mid.block_{i}",
311
+ "new": f"mid_block.resnets.{i - 1}"
312
+ }
313
+ assign_to_checkpoint(paths,
314
+ new_checkpoint,
315
+ vae_state_dict,
316
+ additional_replacements=[meta_path],
317
+ config=config)
318
+
319
+ mid_attentions = [
320
+ key for key in vae_state_dict if "decoder.mid.attn" in key
321
+ ]
322
+ paths = renew_vae_attention_paths(mid_attentions)
323
+ meta_path = {"old": "mid.attn_1", "new": "mid_block.attentions.0"}
324
+ assign_to_checkpoint(paths,
325
+ new_checkpoint,
326
+ vae_state_dict,
327
+ additional_replacements=[meta_path],
328
+ config=config)
329
+ conv_attn_to_linear(new_checkpoint)
330
+ return new_checkpoint
331
+
332
+ def convert_ldm_to_hf_vae(ldm_checkpoint, ldm_config, hf_checkpoint):
333
+ checkpoint = torch.load(ldm_checkpoint)["state_dict"]
334
+
335
+ # Convert the VAE model.
336
+ vae_config = create_vae_diffusers_config(ldm_config)
337
+ converted_vae_checkpoint = convert_ldm_vae_checkpoint(
338
+ checkpoint, vae_config)
339
+
340
+ vae = AutoencoderKL(**vae_config)
341
+ vae.load_state_dict(converted_vae_checkpoint)
342
+ vae.save_pretrained(hf_checkpoint)
config/accelerate_deepspeed.yaml ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ compute_environment: LOCAL_MACHINE
2
+ deepspeed_config:
3
+ gradient_accumulation_steps: 1
4
+ offload_optimizer_device: cpu
5
+ offload_param_device: cpu
6
+ zero3_init_flag: false
7
+ zero_stage: 2
8
+ distributed_type: DEEPSPEED
9
+ downcast_bf16: 'no'
10
+ fsdp_config: {}
11
+ machine_rank: 0
12
+ main_process_ip: null
13
+ main_process_port: null
14
+ main_training_function: main
15
+ mixed_precision: 'no'
16
+ num_machines: 1
17
+ num_processes: 1
18
+ use_cpu: false
config/accelerate_local.yaml ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ compute_environment: LOCAL_MACHINE
2
+ deepspeed_config: {}
3
+ distributed_type: 'NO'
4
+ downcast_bf16: 'no'
5
+ fsdp_config: {}
6
+ machine_rank: 0
7
+ main_process_ip: null
8
+ main_process_port: null
9
+ main_training_function: main
10
+ mixed_precision: 'no'
11
+ num_machines: 1
12
+ num_processes: 1
13
+ use_cpu: false
config/accelerate_sagemaker.yaml ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ base_job_name: accelerate-sagemaker-1
2
+ compute_environment: AMAZON_SAGEMAKER
3
+ distributed_type: 'NO'
4
+ ec2_instance_type: ml.p3.8xlarge
5
+ iam_role_name: accelerate_sagemaker_execution_role
6
+ image_uri: null
7
+ mixed_precision: 'No'
8
+ num_machines: 1
9
+ profile: default
10
+ py_version: py38
11
+ pytorch_version: 1.10.2
12
+ region: eu-west-2
13
+ sagemaker_inputs_file: null
14
+ sagemaker_metrics_file: null
15
+ transformers_version: 4.17.0
16
+ use_cpu: false
config/ldm_autoencoder_kl.yaml ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ # based on https://github.com/CompVis/stable-diffusion/blob/main/configs/autoencoder/autoencoder_kl_32x32x4.yaml
3
+
4
+ model:
5
+ base_learning_rate: 4.5e-6
6
+ target: ldm.models.autoencoder.AutoencoderKL
7
+ params:
8
+ monitor: "val/rec_loss"
9
+ embed_dim: 1 # = in_channels
10
+ lossconfig:
11
+ target: ldm.modules.losses.LPIPSWithDiscriminator
12
+ params:
13
+ disc_start: 50001
14
+ kl_weight: 0.000001
15
+ disc_weight: 0.5
16
+ disc_in_channels: 1 # = out_ch
17
+
18
+ ddconfig:
19
+ double_z: True
20
+ z_channels: 1 # must = embed_dim due to HF limitation
21
+ resolution: 256
22
+ in_channels: 1
23
+ out_ch: 1
24
+ ch: 128
25
+ ch_mult: [ 1,2,4,4 ] # num_down = len(ch_mult)-1
26
+ num_res_blocks: 2
27
+ attn_resolutions: [ ]
28
+ dropout: 0.0
29
+
30
+ lightning:
31
+ trainer:
32
+ benchmark: True
33
+ accelerator: gpu
34
+ devices: 1
mel.png ADDED
notebooks/gradio_app.ipynb ADDED
@@ -0,0 +1,101 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "markdown",
5
+ "id": "a489aa44",
6
+ "metadata": {},
7
+ "source": [
8
+ "<a href=\"https://colab.research.google.com/github/teticio/audio-diffusion/blob/master/notebooks/gradio_app.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>"
9
+ ]
10
+ },
11
+ {
12
+ "cell_type": "code",
13
+ "execution_count": 1,
14
+ "id": "9502ffa7",
15
+ "metadata": {},
16
+ "outputs": [],
17
+ "source": [
18
+ "try:\n",
19
+ " # are we running on Google Colab?\n",
20
+ " import google.colab\n",
21
+ " !git clone -q https://github.com/teticio/audio-diffusion.git\n",
22
+ " %cd audio-diffusion\n",
23
+ " !pip install -q -r requirements.txt\n",
24
+ "except:\n",
25
+ " pass"
26
+ ]
27
+ },
28
+ {
29
+ "cell_type": "code",
30
+ "execution_count": 2,
31
+ "id": "8f8b6e43",
32
+ "metadata": {},
33
+ "outputs": [],
34
+ "source": [
35
+ "import os\n",
36
+ "import sys\n",
37
+ "sys.path.insert(0, os.path.dirname(os.path.abspath(\"\")))"
38
+ ]
39
+ },
40
+ {
41
+ "cell_type": "code",
42
+ "execution_count": null,
43
+ "id": "2d948967",
44
+ "metadata": {
45
+ "scrolled": false
46
+ },
47
+ "outputs": [],
48
+ "source": [
49
+ "import app\n",
50
+ "app.demo.launch(share=True);"
51
+ ]
52
+ },
53
+ {
54
+ "cell_type": "code",
55
+ "execution_count": null,
56
+ "id": "46f03607",
57
+ "metadata": {},
58
+ "outputs": [],
59
+ "source": []
60
+ }
61
+ ],
62
+ "metadata": {
63
+ "accelerator": "GPU",
64
+ "colab": {
65
+ "provenance": []
66
+ },
67
+ "gpuClass": "standard",
68
+ "kernelspec": {
69
+ "display_name": "huggingface",
70
+ "language": "python",
71
+ "name": "huggingface"
72
+ },
73
+ "language_info": {
74
+ "codemirror_mode": {
75
+ "name": "ipython",
76
+ "version": 3
77
+ },
78
+ "file_extension": ".py",
79
+ "mimetype": "text/x-python",
80
+ "name": "python",
81
+ "nbconvert_exporter": "python",
82
+ "pygments_lexer": "ipython3",
83
+ "version": "3.10.4"
84
+ },
85
+ "toc": {
86
+ "base_numbering": 1,
87
+ "nav_menu": {},
88
+ "number_sections": true,
89
+ "sideBar": true,
90
+ "skip_h1_title": false,
91
+ "title_cell": "Table of Contents",
92
+ "title_sidebar": "Contents",
93
+ "toc_cell": false,
94
+ "toc_position": {},
95
+ "toc_section_display": true,
96
+ "toc_window_display": false
97
+ }
98
+ },
99
+ "nbformat": 4,
100
+ "nbformat_minor": 5
101
+ }
notebooks/test_mel.ipynb ADDED
@@ -0,0 +1,148 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "execution_count": null,
6
+ "id": "2a61d194",
7
+ "metadata": {},
8
+ "outputs": [],
9
+ "source": [
10
+ "%load_ext autoreload\n",
11
+ "%autoreload 2"
12
+ ]
13
+ },
14
+ {
15
+ "cell_type": "code",
16
+ "execution_count": null,
17
+ "id": "21f27189",
18
+ "metadata": {},
19
+ "outputs": [],
20
+ "source": [
21
+ "import os\n",
22
+ "import sys\n",
23
+ "sys.path.insert(0, os.path.dirname(os.path.abspath(\"\")))"
24
+ ]
25
+ },
26
+ {
27
+ "cell_type": "code",
28
+ "execution_count": null,
29
+ "id": "218fcdf1",
30
+ "metadata": {},
31
+ "outputs": [],
32
+ "source": [
33
+ "from IPython.display import Audio\n",
34
+ "from audiodiffusion.mel import Mel"
35
+ ]
36
+ },
37
+ {
38
+ "cell_type": "code",
39
+ "execution_count": null,
40
+ "id": "5e4f8ee5",
41
+ "metadata": {},
42
+ "outputs": [],
43
+ "source": [
44
+ "mel = Mel()"
45
+ ]
46
+ },
47
+ {
48
+ "cell_type": "markdown",
49
+ "id": "b2178c3f",
50
+ "metadata": {},
51
+ "source": [
52
+ "### Transform slice of audio to mel spectrogram"
53
+ ]
54
+ },
55
+ {
56
+ "cell_type": "code",
57
+ "execution_count": null,
58
+ "id": "61dbcd2e",
59
+ "metadata": {},
60
+ "outputs": [],
61
+ "source": [
62
+ "mel.load_audio('/home/teticio/Music/Music/A Tribe Called Quest/The Anthology/08 Can I Kick It_.mp3')"
63
+ ]
64
+ },
65
+ {
66
+ "cell_type": "code",
67
+ "execution_count": null,
68
+ "id": "ccadcc0f",
69
+ "metadata": {},
70
+ "outputs": [],
71
+ "source": [
72
+ "image = mel.audio_slice_to_image(15)\n",
73
+ "image"
74
+ ]
75
+ },
76
+ {
77
+ "cell_type": "code",
78
+ "execution_count": null,
79
+ "id": "8cec79c6",
80
+ "metadata": {},
81
+ "outputs": [],
82
+ "source": [
83
+ "image.width, image.height"
84
+ ]
85
+ },
86
+ {
87
+ "cell_type": "markdown",
88
+ "id": "fe112fef",
89
+ "metadata": {},
90
+ "source": [
91
+ "### Transform mel spectrogram back to audio"
92
+ ]
93
+ },
94
+ {
95
+ "cell_type": "code",
96
+ "execution_count": null,
97
+ "id": "0b268a54",
98
+ "metadata": {},
99
+ "outputs": [],
100
+ "source": [
101
+ "audio = mel.image_to_audio(image)\n",
102
+ "Audio(data=audio, rate=mel.get_sample_rate())"
103
+ ]
104
+ },
105
+ {
106
+ "cell_type": "code",
107
+ "execution_count": null,
108
+ "id": "a0dffbc4",
109
+ "metadata": {},
110
+ "outputs": [],
111
+ "source": []
112
+ }
113
+ ],
114
+ "metadata": {
115
+ "kernelspec": {
116
+ "display_name": "huggingface",
117
+ "language": "python",
118
+ "name": "huggingface"
119
+ },
120
+ "language_info": {
121
+ "codemirror_mode": {
122
+ "name": "ipython",
123
+ "version": 3
124
+ },
125
+ "file_extension": ".py",
126
+ "mimetype": "text/x-python",
127
+ "name": "python",
128
+ "nbconvert_exporter": "python",
129
+ "pygments_lexer": "ipython3",
130
+ "version": "3.10.6"
131
+ },
132
+ "toc": {
133
+ "base_numbering": 1,
134
+ "nav_menu": {},
135
+ "number_sections": true,
136
+ "sideBar": true,
137
+ "skip_h1_title": false,
138
+ "title_cell": "Table of Contents",
139
+ "title_sidebar": "Contents",
140
+ "toc_cell": false,
141
+ "toc_position": {},
142
+ "toc_section_display": true,
143
+ "toc_window_display": false
144
+ }
145
+ },
146
+ "nbformat": 4,
147
+ "nbformat_minor": 5
148
+ }
notebooks/test_model.ipynb ADDED
@@ -0,0 +1,541 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "markdown",
5
+ "id": "62c5865f",
6
+ "metadata": {},
7
+ "source": [
8
+ "<a href=\"https://colab.research.google.com/github/teticio/audio-diffusion/blob/master/notebooks/test_model.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>"
9
+ ]
10
+ },
11
+ {
12
+ "cell_type": "code",
13
+ "execution_count": null,
14
+ "id": "6c7800a6",
15
+ "metadata": {},
16
+ "outputs": [],
17
+ "source": [
18
+ "try:\n",
19
+ " # are we running on Google Colab?\n",
20
+ " import google.colab\n",
21
+ " !git clone -q https://github.com/teticio/audio-diffusion.git\n",
22
+ " %cd audio-diffusion\n",
23
+ " !pip install -q -r requirements.txt\n",
24
+ "except:\n",
25
+ " pass"
26
+ ]
27
+ },
28
+ {
29
+ "cell_type": "code",
30
+ "execution_count": null,
31
+ "id": "b447e2c4",
32
+ "metadata": {},
33
+ "outputs": [],
34
+ "source": [
35
+ "import os\n",
36
+ "import sys\n",
37
+ "sys.path.insert(0, os.path.dirname(os.path.abspath(\"\")))"
38
+ ]
39
+ },
40
+ {
41
+ "cell_type": "code",
42
+ "execution_count": null,
43
+ "id": "c2fc0e7a",
44
+ "metadata": {},
45
+ "outputs": [],
46
+ "source": [
47
+ "import torch\n",
48
+ "import random\n",
49
+ "import numpy as np\n",
50
+ "from datasets import load_dataset\n",
51
+ "from IPython.display import Audio\n",
52
+ "from audiodiffusion.mel import Mel\n",
53
+ "from audiodiffusion import AudioDiffusion"
54
+ ]
55
+ },
56
+ {
57
+ "cell_type": "code",
58
+ "execution_count": null,
59
+ "id": "b294a94a",
60
+ "metadata": {},
61
+ "outputs": [],
62
+ "source": [
63
+ "mel = Mel(x_res=256, y_res=256)\n",
64
+ "generator = torch.Generator()"
65
+ ]
66
+ },
67
+ {
68
+ "cell_type": "markdown",
69
+ "id": "f3feb265",
70
+ "metadata": {},
71
+ "source": [
72
+ "## DDPM (De-noising Diffusion Probabilistic Models)"
73
+ ]
74
+ },
75
+ {
76
+ "cell_type": "markdown",
77
+ "id": "7fd945bb",
78
+ "metadata": {},
79
+ "source": [
80
+ "### Select model"
81
+ ]
82
+ },
83
+ {
84
+ "cell_type": "code",
85
+ "execution_count": null,
86
+ "id": "97f24046",
87
+ "metadata": {},
88
+ "outputs": [],
89
+ "source": [
90
+ "#@markdown teticio/audio-diffusion-256 - trained on my Spotify \"liked\" playlist\n",
91
+ "\n",
92
+ "#@markdown teticio/audio-diffusion-breaks-256 - trained on samples used in music\n",
93
+ "\n",
94
+ "#@markdown teticio/audio-diffusion-instrumental-hiphop-256 - trained on instrumental hiphop\n",
95
+ "\n",
96
+ "model_id = \"teticio/audio-diffusion-256\" #@param [\"teticio/audio-diffusion-256\", \"teticio/audio-diffusion-breaks-256\", \"audio-diffusion-instrumenal-hiphop-256\", \"teticio/audio-diffusion-ddim-256\"]"
97
+ ]
98
+ },
99
+ {
100
+ "cell_type": "code",
101
+ "execution_count": null,
102
+ "id": "a3d45c36",
103
+ "metadata": {},
104
+ "outputs": [],
105
+ "source": [
106
+ "audio_diffusion = AudioDiffusion(model_id=model_id)"
107
+ ]
108
+ },
109
+ {
110
+ "cell_type": "markdown",
111
+ "id": "011fb5a1",
112
+ "metadata": {},
113
+ "source": [
114
+ "### Run model inference to generate mel spectrogram, audios and loops"
115
+ ]
116
+ },
117
+ {
118
+ "cell_type": "code",
119
+ "execution_count": null,
120
+ "id": "b809fed5",
121
+ "metadata": {},
122
+ "outputs": [],
123
+ "source": [
124
+ "for _ in range(10):\n",
125
+ " seed = generator.seed()\n",
126
+ " print(f'Seed = {seed}')\n",
127
+ " generator.manual_seed(seed)\n",
128
+ " image, (sample_rate,\n",
129
+ " audio) = audio_diffusion.generate_spectrogram_and_audio(\n",
130
+ " generator=generator)\n",
131
+ " display(image)\n",
132
+ " display(Audio(audio, rate=sample_rate))\n",
133
+ " loop = AudioDiffusion.loop_it(audio, sample_rate)\n",
134
+ " if loop is not None:\n",
135
+ " display(Audio(loop, rate=sample_rate))\n",
136
+ " else:\n",
137
+ " print(\"Unable to determine loop points\")"
138
+ ]
139
+ },
140
+ {
141
+ "cell_type": "markdown",
142
+ "id": "0bb03e33",
143
+ "metadata": {},
144
+ "source": [
145
+ "### Generate variations of audios"
146
+ ]
147
+ },
148
+ {
149
+ "cell_type": "markdown",
150
+ "id": "80e5b5fa",
151
+ "metadata": {},
152
+ "source": [
153
+ "Try playing around with `start_steps`. Values closer to zero will produce new samples, while values closer to 1,000 will produce samples more faithful to the original."
154
+ ]
155
+ },
156
+ {
157
+ "cell_type": "code",
158
+ "execution_count": null,
159
+ "id": "5074ec11",
160
+ "metadata": {},
161
+ "outputs": [],
162
+ "source": [
163
+ "seed = 16183389798189209330 #@param {type:\"integer\"}\n",
164
+ "generator.manual_seed(seed)\n",
165
+ "image, (sample_rate, audio) = audio_diffusion.generate_spectrogram_and_audio(\n",
166
+ " generator=generator)\n",
167
+ "display(image)\n",
168
+ "display(Audio(audio, rate=sample_rate))"
169
+ ]
170
+ },
171
+ {
172
+ "cell_type": "code",
173
+ "execution_count": null,
174
+ "id": "a0fefe28",
175
+ "metadata": {
176
+ "scrolled": false
177
+ },
178
+ "outputs": [],
179
+ "source": [
180
+ "start_steps = 500 #@param {type:\"slider\", min:0, max:1000, step:10}\n",
181
+ "track = AudioDiffusion.loop_it(audio, sample_rate, loops=1)\n",
182
+ "for variation in range(12):\n",
183
+ " image2, (\n",
184
+ " sample_rate,\n",
185
+ " audio2) = audio_diffusion.generate_spectrogram_and_audio_from_audio(\n",
186
+ " raw_audio=audio, start_step=start_steps)\n",
187
+ " display(image2)\n",
188
+ " display(Audio(audio2, rate=sample_rate))\n",
189
+ " track = np.concatenate(\n",
190
+ " [track, AudioDiffusion.loop_it(audio2, sample_rate, loops=1)])\n",
191
+ "display(Audio(track, rate=sample_rate))"
192
+ ]
193
+ },
194
+ {
195
+ "cell_type": "markdown",
196
+ "id": "58a876c1",
197
+ "metadata": {},
198
+ "source": [
199
+ "### Generate continuations (\"out-painting\")"
200
+ ]
201
+ },
202
+ {
203
+ "cell_type": "code",
204
+ "execution_count": null,
205
+ "id": "b95d5780",
206
+ "metadata": {},
207
+ "outputs": [],
208
+ "source": [
209
+ "overlap_secs = 2 #@param {type:\"integer\"}\n",
210
+ "start_step = 0 #@param {type:\"slider\", min:0, max:1000, step:10}\n",
211
+ "overlap_samples = overlap_secs * sample_rate\n",
212
+ "track = audio\n",
213
+ "for variation in range(12):\n",
214
+ " image2, (\n",
215
+ " sample_rate,\n",
216
+ " audio2) = audio_diffusion.generate_spectrogram_and_audio_from_audio(\n",
217
+ " raw_audio=audio[-overlap_samples:],\n",
218
+ " start_step=start_step,\n",
219
+ " mask_start_secs=overlap_secs)\n",
220
+ " display(image2)\n",
221
+ " display(Audio(audio2, rate=sample_rate))\n",
222
+ " track = np.concatenate([track, audio2[overlap_samples:]])\n",
223
+ " audio = audio2\n",
224
+ "display(Audio(track, rate=sample_rate))"
225
+ ]
226
+ },
227
+ {
228
+ "cell_type": "markdown",
229
+ "id": "b6434d3f",
230
+ "metadata": {},
231
+ "source": [
232
+ "### Remix (style transfer)"
233
+ ]
234
+ },
235
+ {
236
+ "cell_type": "markdown",
237
+ "id": "0da030b2",
238
+ "metadata": {},
239
+ "source": [
240
+ "Alternatively, you can start from another audio altogether, resulting in a kind of style transfer. Maintaining the same seed during generation fixes the style, while masking helps stitch consecutive segments together more smoothly."
241
+ ]
242
+ },
243
+ {
244
+ "cell_type": "code",
245
+ "execution_count": null,
246
+ "id": "fc620a80",
247
+ "metadata": {},
248
+ "outputs": [],
249
+ "source": [
250
+ "try:\n",
251
+ " # are we running on Google Colab?\n",
252
+ " from google.colab import files\n",
253
+ " audio_file = list(files.upload().keys())[0]\n",
254
+ "except:\n",
255
+ " audio_file = \"/home/teticio/Music/liked/El Michels Affair - Glaciers Of Ice.mp3\""
256
+ ]
257
+ },
258
+ {
259
+ "cell_type": "code",
260
+ "execution_count": null,
261
+ "id": "5a257e69",
262
+ "metadata": {
263
+ "scrolled": false
264
+ },
265
+ "outputs": [],
266
+ "source": [
267
+ "start_step = 500 #@param {type:\"slider\", min:0, max:1000, step:10}\n",
268
+ "overlap_secs = 2 #@param {type:\"integer\"}\n",
269
+ "mel.load_audio(audio_file)\n",
270
+ "overlap_samples = overlap_secs * mel.get_sample_rate()\n",
271
+ "slice_size = mel.x_res * mel.hop_length\n",
272
+ "stride = slice_size - overlap_samples\n",
273
+ "generator = torch.Generator()\n",
274
+ "seed = generator.seed()\n",
275
+ "print(f'Seed = {seed}')\n",
276
+ "track = np.array([])\n",
277
+ "not_first = 0\n",
278
+ "for sample in range(len(mel.audio) // stride):\n",
279
+ " generator.manual_seed(seed)\n",
280
+ " audio = np.array(mel.audio[sample * stride:sample * stride + slice_size])\n",
281
+ " if not_first:\n",
282
+ " # Normalize and re-insert generated audio\n",
283
+ " audio[:overlap_samples] = audio2[-overlap_samples:] * np.max(\n",
284
+ " audio[:overlap_samples]) / np.max(audio2[-overlap_samples:])\n",
285
+ " _, (sample_rate,\n",
286
+ " audio2) = audio_diffusion.generate_spectrogram_and_audio_from_audio(\n",
287
+ " raw_audio=audio,\n",
288
+ " start_step=start_step,\n",
289
+ " generator=generator,\n",
290
+ " mask_start_secs=overlap_secs * not_first)\n",
291
+ " track = np.concatenate([track, audio2[overlap_samples * not_first:]])\n",
292
+ " not_first = 1\n",
293
+ " display(Audio(track, rate=sample_rate))"
294
+ ]
295
+ },
296
+ {
297
+ "cell_type": "markdown",
298
+ "id": "924ff9d5",
299
+ "metadata": {},
300
+ "source": [
301
+ "### Fill the gap (\"in-painting\")"
302
+ ]
303
+ },
304
+ {
305
+ "cell_type": "code",
306
+ "execution_count": null,
307
+ "id": "0200264c",
308
+ "metadata": {},
309
+ "outputs": [],
310
+ "source": [
311
+ "slice = 3 #@param {type:\"integer\"}\n",
312
+ "audio = mel.get_audio_slice(slice)\n",
313
+ "_, (sample_rate,\n",
314
+ " audio2) = audio_diffusion.generate_spectrogram_and_audio_from_audio(\n",
315
+ " raw_audio=mel.get_audio_slice(slice),\n",
316
+ " mask_start_secs=1,\n",
317
+ " mask_end_secs=1,\n",
318
+ " step_generator=torch.Generator())\n",
319
+ "display(Audio(audio, rate=sample_rate))\n",
320
+ "display(Audio(audio2, rate=sample_rate))"
321
+ ]
322
+ },
323
+ {
324
+ "cell_type": "markdown",
325
+ "id": "efc32dae",
326
+ "metadata": {},
327
+ "source": [
328
+ "## DDIM (De-noising Diffusion Implicit Models)"
329
+ ]
330
+ },
331
+ {
332
+ "cell_type": "code",
333
+ "execution_count": null,
334
+ "id": "a021f78a",
335
+ "metadata": {},
336
+ "outputs": [],
337
+ "source": [
338
+ "audio_diffusion = AudioDiffusion(model_id='teticio/audio-diffusion-ddim-256')"
339
+ ]
340
+ },
341
+ {
342
+ "cell_type": "markdown",
343
+ "id": "deb23339",
344
+ "metadata": {},
345
+ "source": [
346
+ "### Generation can be done in many fewer steps with DDIMs"
347
+ ]
348
+ },
349
+ {
350
+ "cell_type": "code",
351
+ "execution_count": null,
352
+ "id": "c105a497",
353
+ "metadata": {},
354
+ "outputs": [],
355
+ "source": [
356
+ "for _ in range(10):\n",
357
+ " seed = generator.seed()\n",
358
+ " print(f'Seed = {seed}')\n",
359
+ " generator.manual_seed(seed)\n",
360
+ " image, (sample_rate,\n",
361
+ " audio) = audio_diffusion.generate_spectrogram_and_audio(\n",
362
+ " generator=generator)\n",
363
+ " display(image)\n",
364
+ " display(Audio(audio, rate=sample_rate))\n",
365
+ " loop = AudioDiffusion.loop_it(audio, sample_rate)\n",
366
+ " if loop is not None:\n",
367
+ " display(Audio(loop, rate=sample_rate))\n",
368
+ " else:\n",
369
+ " print(\"Unable to determine loop points\")"
370
+ ]
371
+ },
372
+ {
373
+ "cell_type": "markdown",
374
+ "id": "cab4692c",
375
+ "metadata": {},
376
+ "source": [
377
+ "The parameter eta controls the variance:\n",
378
+ "* 0 - DDIM (deterministic)\n",
379
+ "* 1 - DDPM (De-noising Diffusion Probabilistic Model)"
380
+ ]
381
+ },
382
+ {
383
+ "cell_type": "code",
384
+ "execution_count": null,
385
+ "id": "72bdd207",
386
+ "metadata": {},
387
+ "outputs": [],
388
+ "source": [
389
+ "image, (sample_rate, audio) = audio_diffusion.generate_spectrogram_and_audio(\n",
390
+ " steps=1000, generator=generator, eta=1)\n",
391
+ "display(image)\n",
392
+ "display(Audio(audio, rate=sample_rate))"
393
+ ]
394
+ },
395
+ {
396
+ "cell_type": "markdown",
397
+ "id": "b8d5442c",
398
+ "metadata": {},
399
+ "source": [
400
+ "### DDIMs can be used as encoders..."
401
+ ]
402
+ },
403
+ {
404
+ "cell_type": "code",
405
+ "execution_count": null,
406
+ "id": "269ee816",
407
+ "metadata": {},
408
+ "outputs": [],
409
+ "source": [
410
+ "# Doesn't have to be an audio from the train dataset, this is just for convenience\n",
411
+ "ds = load_dataset('teticio/audio-diffusion-256')"
412
+ ]
413
+ },
414
+ {
415
+ "cell_type": "code",
416
+ "execution_count": null,
417
+ "id": "278d1d80",
418
+ "metadata": {},
419
+ "outputs": [],
420
+ "source": [
421
+ "image = ds['train'][264]['image']\n",
422
+ "display(Audio(mel.image_to_audio(image), rate=mel.get_sample_rate()))"
423
+ ]
424
+ },
425
+ {
426
+ "cell_type": "code",
427
+ "execution_count": null,
428
+ "id": "912b54e4",
429
+ "metadata": {},
430
+ "outputs": [],
431
+ "source": [
432
+ "noise = audio_diffusion.pipe.encode([image])"
433
+ ]
434
+ },
435
+ {
436
+ "cell_type": "code",
437
+ "execution_count": null,
438
+ "id": "c7b31f97",
439
+ "metadata": {},
440
+ "outputs": [],
441
+ "source": [
442
+ "# Reconstruct original audio from noise\n",
443
+ "_, (sample_rate, audio) = audio_diffusion.generate_spectrogram_and_audio(\n",
444
+ " noise=noise, generator=generator)\n",
445
+ "display(Audio(audio, rate=sample_rate))"
446
+ ]
447
+ },
448
+ {
449
+ "cell_type": "markdown",
450
+ "id": "998c776b",
451
+ "metadata": {},
452
+ "source": [
453
+ "### ...or to interpolate between audios"
454
+ ]
455
+ },
456
+ {
457
+ "cell_type": "code",
458
+ "execution_count": null,
459
+ "id": "33f82367",
460
+ "metadata": {},
461
+ "outputs": [],
462
+ "source": [
463
+ "image2 = ds['train'][15978]['image']\n",
464
+ "display(Audio(mel.image_to_audio(image2), rate=mel.get_sample_rate()))"
465
+ ]
466
+ },
467
+ {
468
+ "cell_type": "code",
469
+ "execution_count": null,
470
+ "id": "f93fb6c0",
471
+ "metadata": {},
472
+ "outputs": [],
473
+ "source": [
474
+ "noise2 = audio_diffusion.pipe.encode([image2], steps=1000)"
475
+ ]
476
+ },
477
+ {
478
+ "cell_type": "code",
479
+ "execution_count": null,
480
+ "id": "a4190563",
481
+ "metadata": {},
482
+ "outputs": [],
483
+ "source": [
484
+ "alpha = 0.5 #@param {type:\"slider\", min:0, max:1, step:0.1}\n",
485
+ "_, (sample_rate, audio) = audio_diffusion.generate_spectrogram_and_audio(\n",
486
+ " noise=audio_diffusion.pipe.slerp(noise, noise2, alpha),\n",
487
+ " generator=generator)\n",
488
+ "display(Audio(mel.image_to_audio(image), rate=mel.get_sample_rate()))\n",
489
+ "display(Audio(mel.image_to_audio(image2), rate=mel.get_sample_rate()))\n",
490
+ "display(Audio(audio, rate=sample_rate))"
491
+ ]
492
+ },
493
+ {
494
+ "cell_type": "code",
495
+ "execution_count": null,
496
+ "id": "0b05539f",
497
+ "metadata": {},
498
+ "outputs": [],
499
+ "source": []
500
+ }
501
+ ],
502
+ "metadata": {
503
+ "accelerator": "GPU",
504
+ "colab": {
505
+ "provenance": []
506
+ },
507
+ "gpuClass": "standard",
508
+ "kernelspec": {
509
+ "display_name": "huggingface",
510
+ "language": "python",
511
+ "name": "huggingface"
512
+ },
513
+ "language_info": {
514
+ "codemirror_mode": {
515
+ "name": "ipython",
516
+ "version": 3
517
+ },
518
+ "file_extension": ".py",
519
+ "mimetype": "text/x-python",
520
+ "name": "python",
521
+ "nbconvert_exporter": "python",
522
+ "pygments_lexer": "ipython3",
523
+ "version": "3.8.9 (default, Apr 13 2022, 08:48:06) \n[Clang 13.1.6 (clang-1316.0.21.2.5)]"
524
+ },
525
+ "toc": {
526
+ "base_numbering": 1,
527
+ "nav_menu": {},
528
+ "number_sections": true,
529
+ "sideBar": true,
530
+ "skip_h1_title": false,
531
+ "title_cell": "Table of Contents",
532
+ "title_sidebar": "Contents",
533
+ "toc_cell": false,
534
+ "toc_position": {},
535
+ "toc_section_display": true,
536
+ "toc_window_display": false
537
+ }
538
+ },
539
+ "nbformat": 4,
540
+ "nbformat_minor": 5
541
+ }
notebooks/test_vae.ipynb ADDED
The diff for this file is too large to render. See raw diff
 
notebooks/train_model.ipynb ADDED
@@ -0,0 +1,599 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "markdown",
5
+ "id": "62c5865f",
6
+ "metadata": {
7
+ "id": "62c5865f"
8
+ },
9
+ "source": [
10
+ "<a href=\"https://colab.research.google.com/github/teticio/audio-diffusion/blob/master/notebooks/train_model.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>"
11
+ ]
12
+ },
13
+ {
14
+ "cell_type": "code",
15
+ "execution_count": null,
16
+ "id": "6c7800a6",
17
+ "metadata": {
18
+ "colab": {
19
+ "base_uri": "https://localhost:8080/"
20
+ },
21
+ "id": "6c7800a6",
22
+ "outputId": "ed18f4a9-ccea-4d7c-c82b-1749f1041f6c"
23
+ },
24
+ "outputs": [],
25
+ "source": [
26
+ "try:\n",
27
+ " # are we running on Google Colab?\n",
28
+ " import google.colab\n",
29
+ " !git clone -q https://github.com/teticio/audio-diffusion.git\n",
30
+ " %cd audio-diffusion\n",
31
+ " !pip install -q -r requirements.txt .\n",
32
+ "except:\n",
33
+ " pass"
34
+ ]
35
+ },
36
+ {
37
+ "cell_type": "code",
38
+ "execution_count": null,
39
+ "id": "c2fc0e7a",
40
+ "metadata": {
41
+ "id": "c2fc0e7a"
42
+ },
43
+ "outputs": [],
44
+ "source": [
45
+ "from IPython.display import Audio\n",
46
+ "from audiodiffusion import AudioDiffusion"
47
+ ]
48
+ },
49
+ {
50
+ "cell_type": "markdown",
51
+ "id": "MqlpL75_mDVv",
52
+ "metadata": {
53
+ "id": "MqlpL75_mDVv"
54
+ },
55
+ "source": [
56
+ "### Upload / specify audio files to train on\n",
57
+ "Provide some MP3 or WAV files that will be split into samples and converted to Mel spectrograms. For a resolution of 256, the samples will be about 5 seconds long."
58
+ ]
59
+ },
60
+ {
61
+ "cell_type": "code",
62
+ "execution_count": null,
63
+ "id": "jg1zAHVsmCBG",
64
+ "metadata": {
65
+ "colab": {
66
+ "base_uri": "https://localhost:8080/",
67
+ "height": 73
68
+ },
69
+ "id": "jg1zAHVsmCBG",
70
+ "outputId": "414244c9-02b6-4ccf-cbfd-83f9022a0fc1"
71
+ },
72
+ "outputs": [],
73
+ "source": [
74
+ "try:\n",
75
+ " # are we running on Google Colab?\n",
76
+ " from google.colab import files\n",
77
+ " input_dir = '.'\n",
78
+ " files.upload();\n",
79
+ "except:\n",
80
+ " input_dir = \"/home/teticio/Music/liked\""
81
+ ]
82
+ },
83
+ {
84
+ "cell_type": "markdown",
85
+ "id": "10v0RCSUu75P",
86
+ "metadata": {
87
+ "id": "10v0RCSUu75P"
88
+ },
89
+ "source": [
90
+ "### Prepare dataset"
91
+ ]
92
+ },
93
+ {
94
+ "cell_type": "code",
95
+ "execution_count": null,
96
+ "id": "NJNeEU6ftaTM",
97
+ "metadata": {
98
+ "colab": {
99
+ "base_uri": "https://localhost:8080/"
100
+ },
101
+ "id": "NJNeEU6ftaTM",
102
+ "outputId": "6c5bed15-c821-4def-eb90-3ab1a17b3c3d"
103
+ },
104
+ "outputs": [],
105
+ "source": [
106
+ "!python scripts/audio_to_images.py \\\n",
107
+ " --resolution 256,256 \\\n",
108
+ " --input_dir {input_dir} \\\n",
109
+ " --output_dir data"
110
+ ]
111
+ },
112
+ {
113
+ "cell_type": "markdown",
114
+ "id": "5mGeXyJFvQCO",
115
+ "metadata": {
116
+ "id": "5mGeXyJFvQCO"
117
+ },
118
+ "source": [
119
+ "### Train model\n",
120
+ "The DDIM scheduler generates samples much faster."
121
+ ]
122
+ },
123
+ {
124
+ "cell_type": "code",
125
+ "execution_count": null,
126
+ "id": "JGnlePbLvTOH",
127
+ "metadata": {
128
+ "colab": {
129
+ "base_uri": "https://localhost:8080/"
130
+ },
131
+ "id": "JGnlePbLvTOH",
132
+ "outputId": "69b6f53e-25a3-4c59-e205-2eab42889cd8"
133
+ },
134
+ "outputs": [],
135
+ "source": [
136
+ "!python scripts/train_unconditional.py \\\n",
137
+ " --dataset_name data \\\n",
138
+ " --output_dir model \\\n",
139
+ " --num_epochs 10 \\\n",
140
+ " --train_batch_size 2 \\\n",
141
+ " --eval_batch_size 2 \\\n",
142
+ " --gradient_accumulation_steps 8 \\\n",
143
+ " --save_images_epochs 100 \\\n",
144
+ " --save_model_epochs 1 \\\n",
145
+ " --scheduler ddim"
146
+ ]
147
+ },
148
+ {
149
+ "cell_type": "markdown",
150
+ "id": "nTMAYEtMxtt0",
151
+ "metadata": {
152
+ "id": "nTMAYEtMxtt0"
153
+ },
154
+ "source": [
155
+ "### Generate samples with model"
156
+ ]
157
+ },
158
+ {
159
+ "cell_type": "code",
160
+ "execution_count": null,
161
+ "id": "b294a94a",
162
+ "metadata": {
163
+ "id": "b294a94a"
164
+ },
165
+ "outputs": [],
166
+ "source": [
167
+ "audio_diffusion = AudioDiffusion('model')"
168
+ ]
169
+ },
170
+ {
171
+ "cell_type": "code",
172
+ "execution_count": null,
173
+ "id": "k2bKq3aqyAIM",
174
+ "metadata": {
175
+ "colab": {
176
+ "base_uri": "https://localhost:8080/",
177
+ "height": 363,
178
+ "referenced_widgets": [
179
+ "474d4db933d54e0497da4076a7fe135b",
180
+ "a849a3a1b46947db830a6a087411ec68",
181
+ "378f819239274ac88d913714bc27bf06",
182
+ "cc3b33e508744206955b26a417fbbdec",
183
+ "6015e5a9e6774e9abf7db273bca57363",
184
+ "629c21c68d22447185bb961e22bce4a6",
185
+ "2d5abefbc2ed4b72aed8c4f8ddc7a00c",
186
+ "11d1dbae00764a1c9dcc899c0b0f67dc",
187
+ "acdb5ddc7bda411a948689787b18b21e",
188
+ "9c4955f9d0f443a7b28ed827c5cdb37f",
189
+ "f9a1a976d82148f8961e80c357bc2764"
190
+ ]
191
+ },
192
+ "id": "k2bKq3aqyAIM",
193
+ "outputId": "d48238fe-ae36-4736-e67b-b69e3729304a"
194
+ },
195
+ "outputs": [],
196
+ "source": [
197
+ "image, (sample_rate, audio) = audio_diffusion.generate_spectrogram_and_audio()\n",
198
+ "display(image)\n",
199
+ "display(Audio(audio, rate=sample_rate))"
200
+ ]
201
+ },
202
+ {
203
+ "cell_type": "code",
204
+ "execution_count": null,
205
+ "id": "K2qAIJzg2DNK",
206
+ "metadata": {
207
+ "id": "K2qAIJzg2DNK"
208
+ },
209
+ "outputs": [],
210
+ "source": []
211
+ }
212
+ ],
213
+ "metadata": {
214
+ "accelerator": "GPU",
215
+ "colab": {
216
+ "collapsed_sections": [],
217
+ "provenance": []
218
+ },
219
+ "gpuClass": "standard",
220
+ "kernelspec": {
221
+ "display_name": "huggingface",
222
+ "language": "python",
223
+ "name": "huggingface"
224
+ },
225
+ "language_info": {
226
+ "codemirror_mode": {
227
+ "name": "ipython",
228
+ "version": 3
229
+ },
230
+ "file_extension": ".py",
231
+ "mimetype": "text/x-python",
232
+ "name": "python",
233
+ "nbconvert_exporter": "python",
234
+ "pygments_lexer": "ipython3",
235
+ "version": "3.10.6"
236
+ },
237
+ "toc": {
238
+ "base_numbering": 1,
239
+ "nav_menu": {},
240
+ "number_sections": true,
241
+ "sideBar": true,
242
+ "skip_h1_title": false,
243
+ "title_cell": "Table of Contents",
244
+ "title_sidebar": "Contents",
245
+ "toc_cell": false,
246
+ "toc_position": {},
247
+ "toc_section_display": true,
248
+ "toc_window_display": false
249
+ },
250
+ "widgets": {
251
+ "application/vnd.jupyter.widget-state+json": {
252
+ "11d1dbae00764a1c9dcc899c0b0f67dc": {
253
+ "model_module": "@jupyter-widgets/base",
254
+ "model_module_version": "1.2.0",
255
+ "model_name": "LayoutModel",
256
+ "state": {
257
+ "_model_module": "@jupyter-widgets/base",
258
+ "_model_module_version": "1.2.0",
259
+ "_model_name": "LayoutModel",
260
+ "_view_count": null,
261
+ "_view_module": "@jupyter-widgets/base",
262
+ "_view_module_version": "1.2.0",
263
+ "_view_name": "LayoutView",
264
+ "align_content": null,
265
+ "align_items": null,
266
+ "align_self": null,
267
+ "border": null,
268
+ "bottom": null,
269
+ "display": null,
270
+ "flex": null,
271
+ "flex_flow": null,
272
+ "grid_area": null,
273
+ "grid_auto_columns": null,
274
+ "grid_auto_flow": null,
275
+ "grid_auto_rows": null,
276
+ "grid_column": null,
277
+ "grid_gap": null,
278
+ "grid_row": null,
279
+ "grid_template_areas": null,
280
+ "grid_template_columns": null,
281
+ "grid_template_rows": null,
282
+ "height": null,
283
+ "justify_content": null,
284
+ "justify_items": null,
285
+ "left": null,
286
+ "margin": null,
287
+ "max_height": null,
288
+ "max_width": null,
289
+ "min_height": null,
290
+ "min_width": null,
291
+ "object_fit": null,
292
+ "object_position": null,
293
+ "order": null,
294
+ "overflow": null,
295
+ "overflow_x": null,
296
+ "overflow_y": null,
297
+ "padding": null,
298
+ "right": null,
299
+ "top": null,
300
+ "visibility": null,
301
+ "width": null
302
+ }
303
+ },
304
+ "2d5abefbc2ed4b72aed8c4f8ddc7a00c": {
305
+ "model_module": "@jupyter-widgets/controls",
306
+ "model_module_version": "1.5.0",
307
+ "model_name": "DescriptionStyleModel",
308
+ "state": {
309
+ "_model_module": "@jupyter-widgets/controls",
310
+ "_model_module_version": "1.5.0",
311
+ "_model_name": "DescriptionStyleModel",
312
+ "_view_count": null,
313
+ "_view_module": "@jupyter-widgets/base",
314
+ "_view_module_version": "1.2.0",
315
+ "_view_name": "StyleView",
316
+ "description_width": ""
317
+ }
318
+ },
319
+ "378f819239274ac88d913714bc27bf06": {
320
+ "model_module": "@jupyter-widgets/controls",
321
+ "model_module_version": "1.5.0",
322
+ "model_name": "FloatProgressModel",
323
+ "state": {
324
+ "_dom_classes": [],
325
+ "_model_module": "@jupyter-widgets/controls",
326
+ "_model_module_version": "1.5.0",
327
+ "_model_name": "FloatProgressModel",
328
+ "_view_count": null,
329
+ "_view_module": "@jupyter-widgets/controls",
330
+ "_view_module_version": "1.5.0",
331
+ "_view_name": "ProgressView",
332
+ "bar_style": "success",
333
+ "description": "",
334
+ "description_tooltip": null,
335
+ "layout": "IPY_MODEL_11d1dbae00764a1c9dcc899c0b0f67dc",
336
+ "max": 50,
337
+ "min": 0,
338
+ "orientation": "horizontal",
339
+ "style": "IPY_MODEL_acdb5ddc7bda411a948689787b18b21e",
340
+ "value": 50
341
+ }
342
+ },
343
+ "474d4db933d54e0497da4076a7fe135b": {
344
+ "model_module": "@jupyter-widgets/controls",
345
+ "model_module_version": "1.5.0",
346
+ "model_name": "HBoxModel",
347
+ "state": {
348
+ "_dom_classes": [],
349
+ "_model_module": "@jupyter-widgets/controls",
350
+ "_model_module_version": "1.5.0",
351
+ "_model_name": "HBoxModel",
352
+ "_view_count": null,
353
+ "_view_module": "@jupyter-widgets/controls",
354
+ "_view_module_version": "1.5.0",
355
+ "_view_name": "HBoxView",
356
+ "box_style": "",
357
+ "children": [
358
+ "IPY_MODEL_a849a3a1b46947db830a6a087411ec68",
359
+ "IPY_MODEL_378f819239274ac88d913714bc27bf06",
360
+ "IPY_MODEL_cc3b33e508744206955b26a417fbbdec"
361
+ ],
362
+ "layout": "IPY_MODEL_6015e5a9e6774e9abf7db273bca57363"
363
+ }
364
+ },
365
+ "6015e5a9e6774e9abf7db273bca57363": {
366
+ "model_module": "@jupyter-widgets/base",
367
+ "model_module_version": "1.2.0",
368
+ "model_name": "LayoutModel",
369
+ "state": {
370
+ "_model_module": "@jupyter-widgets/base",
371
+ "_model_module_version": "1.2.0",
372
+ "_model_name": "LayoutModel",
373
+ "_view_count": null,
374
+ "_view_module": "@jupyter-widgets/base",
375
+ "_view_module_version": "1.2.0",
376
+ "_view_name": "LayoutView",
377
+ "align_content": null,
378
+ "align_items": null,
379
+ "align_self": null,
380
+ "border": null,
381
+ "bottom": null,
382
+ "display": null,
383
+ "flex": null,
384
+ "flex_flow": null,
385
+ "grid_area": null,
386
+ "grid_auto_columns": null,
387
+ "grid_auto_flow": null,
388
+ "grid_auto_rows": null,
389
+ "grid_column": null,
390
+ "grid_gap": null,
391
+ "grid_row": null,
392
+ "grid_template_areas": null,
393
+ "grid_template_columns": null,
394
+ "grid_template_rows": null,
395
+ "height": null,
396
+ "justify_content": null,
397
+ "justify_items": null,
398
+ "left": null,
399
+ "margin": null,
400
+ "max_height": null,
401
+ "max_width": null,
402
+ "min_height": null,
403
+ "min_width": null,
404
+ "object_fit": null,
405
+ "object_position": null,
406
+ "order": null,
407
+ "overflow": null,
408
+ "overflow_x": null,
409
+ "overflow_y": null,
410
+ "padding": null,
411
+ "right": null,
412
+ "top": null,
413
+ "visibility": null,
414
+ "width": null
415
+ }
416
+ },
417
+ "629c21c68d22447185bb961e22bce4a6": {
418
+ "model_module": "@jupyter-widgets/base",
419
+ "model_module_version": "1.2.0",
420
+ "model_name": "LayoutModel",
421
+ "state": {
422
+ "_model_module": "@jupyter-widgets/base",
423
+ "_model_module_version": "1.2.0",
424
+ "_model_name": "LayoutModel",
425
+ "_view_count": null,
426
+ "_view_module": "@jupyter-widgets/base",
427
+ "_view_module_version": "1.2.0",
428
+ "_view_name": "LayoutView",
429
+ "align_content": null,
430
+ "align_items": null,
431
+ "align_self": null,
432
+ "border": null,
433
+ "bottom": null,
434
+ "display": null,
435
+ "flex": null,
436
+ "flex_flow": null,
437
+ "grid_area": null,
438
+ "grid_auto_columns": null,
439
+ "grid_auto_flow": null,
440
+ "grid_auto_rows": null,
441
+ "grid_column": null,
442
+ "grid_gap": null,
443
+ "grid_row": null,
444
+ "grid_template_areas": null,
445
+ "grid_template_columns": null,
446
+ "grid_template_rows": null,
447
+ "height": null,
448
+ "justify_content": null,
449
+ "justify_items": null,
450
+ "left": null,
451
+ "margin": null,
452
+ "max_height": null,
453
+ "max_width": null,
454
+ "min_height": null,
455
+ "min_width": null,
456
+ "object_fit": null,
457
+ "object_position": null,
458
+ "order": null,
459
+ "overflow": null,
460
+ "overflow_x": null,
461
+ "overflow_y": null,
462
+ "padding": null,
463
+ "right": null,
464
+ "top": null,
465
+ "visibility": null,
466
+ "width": null
467
+ }
468
+ },
469
+ "9c4955f9d0f443a7b28ed827c5cdb37f": {
470
+ "model_module": "@jupyter-widgets/base",
471
+ "model_module_version": "1.2.0",
472
+ "model_name": "LayoutModel",
473
+ "state": {
474
+ "_model_module": "@jupyter-widgets/base",
475
+ "_model_module_version": "1.2.0",
476
+ "_model_name": "LayoutModel",
477
+ "_view_count": null,
478
+ "_view_module": "@jupyter-widgets/base",
479
+ "_view_module_version": "1.2.0",
480
+ "_view_name": "LayoutView",
481
+ "align_content": null,
482
+ "align_items": null,
483
+ "align_self": null,
484
+ "border": null,
485
+ "bottom": null,
486
+ "display": null,
487
+ "flex": null,
488
+ "flex_flow": null,
489
+ "grid_area": null,
490
+ "grid_auto_columns": null,
491
+ "grid_auto_flow": null,
492
+ "grid_auto_rows": null,
493
+ "grid_column": null,
494
+ "grid_gap": null,
495
+ "grid_row": null,
496
+ "grid_template_areas": null,
497
+ "grid_template_columns": null,
498
+ "grid_template_rows": null,
499
+ "height": null,
500
+ "justify_content": null,
501
+ "justify_items": null,
502
+ "left": null,
503
+ "margin": null,
504
+ "max_height": null,
505
+ "max_width": null,
506
+ "min_height": null,
507
+ "min_width": null,
508
+ "object_fit": null,
509
+ "object_position": null,
510
+ "order": null,
511
+ "overflow": null,
512
+ "overflow_x": null,
513
+ "overflow_y": null,
514
+ "padding": null,
515
+ "right": null,
516
+ "top": null,
517
+ "visibility": null,
518
+ "width": null
519
+ }
520
+ },
521
+ "a849a3a1b46947db830a6a087411ec68": {
522
+ "model_module": "@jupyter-widgets/controls",
523
+ "model_module_version": "1.5.0",
524
+ "model_name": "HTMLModel",
525
+ "state": {
526
+ "_dom_classes": [],
527
+ "_model_module": "@jupyter-widgets/controls",
528
+ "_model_module_version": "1.5.0",
529
+ "_model_name": "HTMLModel",
530
+ "_view_count": null,
531
+ "_view_module": "@jupyter-widgets/controls",
532
+ "_view_module_version": "1.5.0",
533
+ "_view_name": "HTMLView",
534
+ "description": "",
535
+ "description_tooltip": null,
536
+ "layout": "IPY_MODEL_629c21c68d22447185bb961e22bce4a6",
537
+ "placeholder": "​",
538
+ "style": "IPY_MODEL_2d5abefbc2ed4b72aed8c4f8ddc7a00c",
539
+ "value": "100%"
540
+ }
541
+ },
542
+ "acdb5ddc7bda411a948689787b18b21e": {
543
+ "model_module": "@jupyter-widgets/controls",
544
+ "model_module_version": "1.5.0",
545
+ "model_name": "ProgressStyleModel",
546
+ "state": {
547
+ "_model_module": "@jupyter-widgets/controls",
548
+ "_model_module_version": "1.5.0",
549
+ "_model_name": "ProgressStyleModel",
550
+ "_view_count": null,
551
+ "_view_module": "@jupyter-widgets/base",
552
+ "_view_module_version": "1.2.0",
553
+ "_view_name": "StyleView",
554
+ "bar_color": null,
555
+ "description_width": ""
556
+ }
557
+ },
558
+ "cc3b33e508744206955b26a417fbbdec": {
559
+ "model_module": "@jupyter-widgets/controls",
560
+ "model_module_version": "1.5.0",
561
+ "model_name": "HTMLModel",
562
+ "state": {
563
+ "_dom_classes": [],
564
+ "_model_module": "@jupyter-widgets/controls",
565
+ "_model_module_version": "1.5.0",
566
+ "_model_name": "HTMLModel",
567
+ "_view_count": null,
568
+ "_view_module": "@jupyter-widgets/controls",
569
+ "_view_module_version": "1.5.0",
570
+ "_view_name": "HTMLView",
571
+ "description": "",
572
+ "description_tooltip": null,
573
+ "layout": "IPY_MODEL_9c4955f9d0f443a7b28ed827c5cdb37f",
574
+ "placeholder": "​",
575
+ "style": "IPY_MODEL_f9a1a976d82148f8961e80c357bc2764",
576
+ "value": " 50/50 [00:07&lt;00:00, 8.13it/s]"
577
+ }
578
+ },
579
+ "f9a1a976d82148f8961e80c357bc2764": {
580
+ "model_module": "@jupyter-widgets/controls",
581
+ "model_module_version": "1.5.0",
582
+ "model_name": "DescriptionStyleModel",
583
+ "state": {
584
+ "_model_module": "@jupyter-widgets/controls",
585
+ "_model_module_version": "1.5.0",
586
+ "_model_name": "DescriptionStyleModel",
587
+ "_view_count": null,
588
+ "_view_module": "@jupyter-widgets/base",
589
+ "_view_module_version": "1.2.0",
590
+ "_view_name": "StyleView",
591
+ "description_width": ""
592
+ }
593
+ }
594
+ }
595
+ }
596
+ },
597
+ "nbformat": 4,
598
+ "nbformat_minor": 5
599
+ }
requirements-lock.txt ADDED
@@ -0,0 +1,182 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ absl-py==1.2.0
2
+ accelerate==0.12.0
3
+ aiohttp==3.8.1
4
+ aiosignal==1.2.0
5
+ altair==4.2.0
6
+ analytics-python==1.4.0
7
+ anyio==3.6.1
8
+ appdirs==1.4.4
9
+ argon2-cffi==21.3.0
10
+ argon2-cffi-bindings==21.2.0
11
+ asttokens==2.0.8
12
+ async-timeout==4.0.2
13
+ attrs==22.1.0
14
+ audioread==3.0.0
15
+ backcall==0.2.0
16
+ backoff==1.10.0
17
+ bcrypt==4.0.0
18
+ beautifulsoup4==4.11.1
19
+ bleach==5.0.1
20
+ blinker==1.5
21
+ cachetools==5.2.0
22
+ certifi==2022.6.15
23
+ cffi==1.15.1
24
+ charset-normalizer==2.1.1
25
+ click==8.1.3
26
+ commonmark==0.9.1
27
+ cryptography==37.0.4
28
+ cycler==0.11.0
29
+ datasets==2.4.0
30
+ debugpy==1.6.3
31
+ decorator==5.1.1
32
+ defusedxml==0.7.1
33
+ diffusers==0.2.4
34
+ dill==0.3.5.1
35
+ entrypoints==0.4
36
+ executing==0.10.0
37
+ fastapi==0.81.0
38
+ fastjsonschema==2.16.1
39
+ ffmpy==0.3.0
40
+ filelock==3.8.0
41
+ fonttools==4.37.1
42
+ frozenlist==1.3.1
43
+ fsspec==2022.7.1
44
+ ftfy==6.1.1
45
+ gitdb==4.0.9
46
+ GitPython==3.1.27
47
+ google-auth==2.11.0
48
+ google-auth-oauthlib==0.4.6
49
+ gradio==3.1.7
50
+ grpcio==1.47.0
51
+ h11==0.12.0
52
+ httpcore==0.15.0
53
+ httpx==0.23.0
54
+ huggingface-hub==0.9.0
55
+ idna==3.3
56
+ importlib-metadata==4.12.0
57
+ ipykernel==6.15.1
58
+ ipython==8.4.0
59
+ ipython-genutils==0.2.0
60
+ ipywidgets==7.7.1
61
+ jedi==0.18.1
62
+ Jinja2==3.1.2
63
+ joblib==1.1.0
64
+ jsonschema==4.14.0
65
+ jupyter-client==7.3.4
66
+ jupyter-console==6.4.4
67
+ jupyter-core==4.11.1
68
+ jupyterlab-pygments==0.2.2
69
+ jupyterlab-widgets==3.0.2
70
+ kiwisolver==1.4.4
71
+ librosa==0.9.2
72
+ linkify-it-py==1.0.3
73
+ llvmlite==0.39.0
74
+ lxml==4.9.1
75
+ Markdown==3.4.1
76
+ markdown-it-py==2.1.0
77
+ MarkupSafe==2.1.1
78
+ matplotlib==3.5.3
79
+ matplotlib-inline==0.1.6
80
+ mdit-py-plugins==0.3.0
81
+ mdurl==0.1.2
82
+ mistune==2.0.4
83
+ monotonic==1.6
84
+ multidict==6.0.2
85
+ multiprocess==0.70.13
86
+ nbclient==0.6.7
87
+ nbconvert==7.0.0
88
+ nbformat==5.4.0
89
+ nest-asyncio==1.5.5
90
+ notebook==6.4.12
91
+ numba==0.56.0
92
+ numpy==1.22.4
93
+ oauthlib==3.2.0
94
+ orjson==3.8.0
95
+ packaging==21.3
96
+ pandas==1.4.3
97
+ pandocfilters==1.5.0
98
+ paramiko==2.11.0
99
+ parso==0.8.3
100
+ pexpect==4.8.0
101
+ pickleshare==0.7.5
102
+ Pillow==9.2.0
103
+ pooch==1.6.0
104
+ prometheus-client==0.14.1
105
+ prompt-toolkit==3.0.30
106
+ protobuf==3.19.4
107
+ psutil==5.9.1
108
+ ptyprocess==0.7.0
109
+ pure-eval==0.2.2
110
+ pyarrow==9.0.0
111
+ pyasn1==0.4.8
112
+ pyasn1-modules==0.2.8
113
+ pycparser==2.21
114
+ pycryptodome==3.15.0
115
+ pydantic==1.9.2
116
+ pydeck==0.8.0b1
117
+ pydub==0.25.1
118
+ Pygments==2.13.0
119
+ Pympler==1.0.1
120
+ PyNaCl==1.5.0
121
+ pyparsing==3.0.9
122
+ pyrsistent==0.18.1
123
+ python-dateutil==2.8.2
124
+ python-multipart==0.0.5
125
+ pytz==2022.2.1
126
+ pytz-deprecation-shim==0.1.0.post0
127
+ PyYAML==6.0
128
+ pyzmq==23.2.1
129
+ qtconsole==5.3.1
130
+ QtPy==2.2.0
131
+ regex==2022.8.17
132
+ requests==2.28.1
133
+ requests-oauthlib==1.3.1
134
+ resampy==0.4.0
135
+ responses==0.18.0
136
+ rfc3986==1.5.0
137
+ rich==12.5.1
138
+ rsa==4.9
139
+ scikit-learn==1.1.2
140
+ scipy==1.9.0
141
+ semver==2.13.0
142
+ Send2Trash==1.8.0
143
+ six==1.16.0
144
+ smmap==5.0.0
145
+ sniffio==1.2.0
146
+ SoundFile==0.10.3.post1
147
+ soupsieve==2.3.2.post1
148
+ stack-data==0.4.0
149
+ starlette==0.19.1
150
+ streamlit==1.12.2
151
+ tensorboard==2.10.0
152
+ tensorboard-data-server==0.6.1
153
+ tensorboard-plugin-wit==1.8.1
154
+ terminado==0.15.0
155
+ threadpoolctl==3.1.0
156
+ tinycss2==1.1.1
157
+ tokenizers==0.12.1
158
+ toml==0.10.2
159
+ toolz==0.12.0
160
+ torch==1.12.1
161
+ torchvision==0.13.1
162
+ tornado==6.2
163
+ tqdm==4.64.0
164
+ traitlets==5.3.0
165
+ transformers==4.21.1
166
+ typing_extensions==4.3.0
167
+ tzdata==2022.2
168
+ tzlocal==4.2
169
+ uc-micro-py==1.0.1
170
+ urllib3==1.26.12
171
+ uvicorn==0.18.3
172
+ validators==0.20.0
173
+ watchdog==2.1.9
174
+ wcwidth==0.2.5
175
+ webencodings==0.5.1
176
+ websockets==10.3
177
+ Werkzeug==2.2.2
178
+ widgetsnbextension==3.6.1
179
+ xxhash==3.0.0
180
+ yapf==0.32.0
181
+ yarl==1.8.1
182
+ zipp==3.8.1
requirements.txt ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ torch
2
+ numpy
3
+ Pillow
4
+ diffusers>=0.4.1
5
+ librosa
6
+ datasets
7
+ gradio
8
+ streamlit
9
+ tensorboard
10
+ accelerate
scripts/audio_to_images.py ADDED
@@ -0,0 +1,109 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import re
3
+ import io
4
+ import logging
5
+ import argparse
6
+
7
+ import numpy as np
8
+ import pandas as pd
9
+ from tqdm.auto import tqdm
10
+ from datasets import Dataset, DatasetDict, Features, Image, Value
11
+
12
+ from audiodiffusion.mel import Mel
13
+
14
+ logging.basicConfig(level=logging.WARN)
15
+ logger = logging.getLogger('audio_to_images')
16
+
17
+
18
+ def main(args):
19
+ mel = Mel(x_res=args.resolution[0],
20
+ y_res=args.resolution[1],
21
+ hop_length=args.hop_length,
22
+ sample_rate=args.sample_rate)
23
+ os.makedirs(args.output_dir, exist_ok=True)
24
+ audio_files = [
25
+ os.path.join(root, file) for root, _, files in os.walk(args.input_dir)
26
+ for file in files if re.search("\.(mp3|wav|m4a)$", file, re.IGNORECASE)
27
+ ]
28
+ examples = []
29
+ try:
30
+ for audio_file in tqdm(audio_files):
31
+ try:
32
+ mel.load_audio(audio_file)
33
+ except KeyboardInterrupt:
34
+ raise
35
+ except:
36
+ continue
37
+ for slice in range(mel.get_number_of_slices()):
38
+ image = mel.audio_slice_to_image(slice)
39
+ assert (image.width == args.resolution[0] and image.height
40
+ == args.resolution[1]), "Wrong resolution"
41
+ # skip completely silent slices
42
+ if all(np.frombuffer(image.tobytes(), dtype=np.uint8) == 255):
43
+ logger.warn('File %s slice %d is completely silent',
44
+ audio_file, slice)
45
+ continue
46
+ with io.BytesIO() as output:
47
+ image.save(output, format="PNG")
48
+ bytes = output.getvalue()
49
+ examples.extend([{
50
+ "image": {
51
+ "bytes": bytes
52
+ },
53
+ "audio_file": audio_file,
54
+ "slice": slice,
55
+ }])
56
+ except Exception as e:
57
+ print(e)
58
+ finally:
59
+ if len(examples) == 0:
60
+ logger.warn('No valid audio files were found.')
61
+ return
62
+ ds = Dataset.from_pandas(
63
+ pd.DataFrame(examples),
64
+ features=Features({
65
+ "image": Image(),
66
+ "audio_file": Value(dtype="string"),
67
+ "slice": Value(dtype="int16"),
68
+ }),
69
+ )
70
+ dsd = DatasetDict({"train": ds})
71
+ dsd.save_to_disk(os.path.join(args.output_dir))
72
+ if args.push_to_hub:
73
+ dsd.push_to_hub(args.push_to_hub)
74
+
75
+
76
+ if __name__ == "__main__":
77
+ parser = argparse.ArgumentParser(
78
+ description=
79
+ "Create dataset of Mel spectrograms from directory of audio files.")
80
+ parser.add_argument("--input_dir", type=str)
81
+ parser.add_argument("--output_dir", type=str, default="data")
82
+ parser.add_argument("--resolution",
83
+ type=str,
84
+ default="256",
85
+ help="Either square resolution or width,height.")
86
+ parser.add_argument("--hop_length", type=int, default=512)
87
+ parser.add_argument("--push_to_hub", type=str, default=None)
88
+ parser.add_argument("--sample_rate", type=int, default=22050)
89
+ args = parser.parse_args()
90
+
91
+ if args.input_dir is None:
92
+ raise ValueError(
93
+ "You must specify an input directory for the audio files.")
94
+
95
+ # Handle the resolutions.
96
+ try:
97
+ args.resolution = (int(args.resolution), int(args.resolution))
98
+ except ValueError:
99
+ try:
100
+ args.resolution = tuple(int(x) for x in args.resolution.split(","))
101
+ if len(args.resolution) != 2:
102
+ raise ValueError
103
+ except ValueError:
104
+ raise ValueError(
105
+ "Resolution must be a tuple of two integers or a single integer."
106
+ )
107
+ assert isinstance(args.resolution, tuple)
108
+
109
+ main(args)
scripts/train_unconditional.py ADDED
@@ -0,0 +1,390 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # based on https://github.com/huggingface/diffusers/blob/main/examples/train_unconditional.py
2
+
3
+ import argparse
4
+ import os
5
+
6
+ import torch
7
+ import torch.nn.functional as F
8
+
9
+ from accelerate import Accelerator
10
+ from accelerate.logging import get_logger
11
+ from datasets import load_from_disk, load_dataset
12
+ from diffusers import (DiffusionPipeline, DDPMScheduler, UNet2DModel,
13
+ DDIMScheduler, AutoencoderKL)
14
+ from diffusers.hub_utils import init_git_repo, push_to_hub
15
+ from diffusers.optimization import get_scheduler
16
+ from diffusers.training_utils import EMAModel
17
+ from torchvision.transforms import (
18
+ Compose,
19
+ Normalize,
20
+ ToTensor,
21
+ )
22
+ import numpy as np
23
+ from tqdm.auto import tqdm
24
+ from librosa.util import normalize
25
+
26
+ from audiodiffusion.mel import Mel
27
+ from audiodiffusion import LatentAudioDiffusionPipeline, AudioDiffusionPipeline
28
+
29
+ logger = get_logger(__name__)
30
+
31
+
32
+ def main(args):
33
+ output_dir = os.environ.get("SM_MODEL_DIR", None) or args.output_dir
34
+ logging_dir = os.path.join(output_dir, args.logging_dir)
35
+ accelerator = Accelerator(
36
+ gradient_accumulation_steps=args.gradient_accumulation_steps,
37
+ mixed_precision=args.mixed_precision,
38
+ log_with="tensorboard",
39
+ logging_dir=logging_dir,
40
+ )
41
+
42
+ if args.dataset_name is not None:
43
+ if os.path.exists(args.dataset_name):
44
+ dataset = load_from_disk(args.dataset_name,
45
+ args.dataset_config_name)["train"]
46
+ else:
47
+ dataset = load_dataset(
48
+ args.dataset_name,
49
+ args.dataset_config_name,
50
+ cache_dir=args.cache_dir,
51
+ use_auth_token=True if args.use_auth_token else None,
52
+ split="train",
53
+ )
54
+ else:
55
+ dataset = load_dataset(
56
+ "imagefolder",
57
+ data_dir=args.train_data_dir,
58
+ cache_dir=args.cache_dir,
59
+ split="train",
60
+ )
61
+ # Determine image resolution
62
+ resolution = dataset[0]['image'].height, dataset[0]['image'].width
63
+
64
+ augmentations = Compose([
65
+ ToTensor(),
66
+ Normalize([0.5], [0.5]),
67
+ ])
68
+
69
+ def transforms(examples):
70
+ if args.vae is not None and vqvae.config['in_channels'] == 3:
71
+ images = [
72
+ augmentations(image.convert('RGB'))
73
+ for image in examples["image"]
74
+ ]
75
+ else:
76
+ images = [augmentations(image) for image in examples["image"]]
77
+ return {"input": images}
78
+
79
+ dataset.set_transform(transforms)
80
+ train_dataloader = torch.utils.data.DataLoader(
81
+ dataset, batch_size=args.train_batch_size, shuffle=True)
82
+
83
+ vqvae = None
84
+ if args.vae is not None:
85
+ try:
86
+ vqvae = AutoencoderKL.from_pretrained(args.vae)
87
+ except EnvironmentError:
88
+ vqvae = LatentAudioDiffusionPipeline.from_pretrained(
89
+ args.vae).vqvae
90
+ # Determine latent resolution
91
+ with torch.no_grad():
92
+ latent_resolution = vqvae.encode(
93
+ torch.zeros((1, 1) +
94
+ resolution)).latent_dist.sample().shape[2:]
95
+
96
+ if args.from_pretrained is not None:
97
+ pipeline = {
98
+ 'LatentAudioDiffusionPipeline': LatentAudioDiffusionPipeline,
99
+ 'AudioDiffusionPipeline': AudioDiffusionPipeline
100
+ }.get(
101
+ DiffusionPipeline.get_config_dict(
102
+ args.from_pretrained)['_class_name'], AudioDiffusionPipeline)
103
+ pipeline = pipeline.from_pretrained(args.from_pretrained)
104
+ model = pipeline.unet
105
+ if hasattr(pipeline, 'vqvae'):
106
+ vqvae = pipeline.vqvae
107
+ else:
108
+ model = UNet2DModel(
109
+ sample_size=resolution if vqvae is None else latent_resolution,
110
+ in_channels=1
111
+ if vqvae is None else vqvae.config['latent_channels'],
112
+ out_channels=1
113
+ if vqvae is None else vqvae.config['latent_channels'],
114
+ layers_per_block=2,
115
+ block_out_channels=(128, 128, 256, 256, 512, 512),
116
+ down_block_types=(
117
+ "DownBlock2D",
118
+ "DownBlock2D",
119
+ "DownBlock2D",
120
+ "DownBlock2D",
121
+ "AttnDownBlock2D",
122
+ "DownBlock2D",
123
+ ),
124
+ up_block_types=(
125
+ "UpBlock2D",
126
+ "AttnUpBlock2D",
127
+ "UpBlock2D",
128
+ "UpBlock2D",
129
+ "UpBlock2D",
130
+ "UpBlock2D",
131
+ ),
132
+ )
133
+
134
+ if args.scheduler == "ddpm":
135
+ noise_scheduler = DDPMScheduler(
136
+ num_train_timesteps=args.num_train_steps)
137
+ else:
138
+ noise_scheduler = DDIMScheduler(
139
+ num_train_timesteps=args.num_train_steps)
140
+
141
+ optimizer = torch.optim.AdamW(
142
+ model.parameters(),
143
+ lr=args.learning_rate,
144
+ betas=(args.adam_beta1, args.adam_beta2),
145
+ weight_decay=args.adam_weight_decay,
146
+ eps=args.adam_epsilon,
147
+ )
148
+
149
+ lr_scheduler = get_scheduler(
150
+ args.lr_scheduler,
151
+ optimizer=optimizer,
152
+ num_warmup_steps=args.lr_warmup_steps,
153
+ num_training_steps=(len(train_dataloader) * args.num_epochs) //
154
+ args.gradient_accumulation_steps,
155
+ )
156
+
157
+ model, optimizer, train_dataloader, lr_scheduler = accelerator.prepare(
158
+ model, optimizer, train_dataloader, lr_scheduler)
159
+
160
+ ema_model = EMAModel(
161
+ getattr(model, "module", model),
162
+ inv_gamma=args.ema_inv_gamma,
163
+ power=args.ema_power,
164
+ max_value=args.ema_max_decay,
165
+ )
166
+
167
+ if args.push_to_hub:
168
+ repo = init_git_repo(args, at_init=True)
169
+
170
+ if accelerator.is_main_process:
171
+ run = os.path.split(__file__)[-1].split(".")[0]
172
+ accelerator.init_trackers(run)
173
+
174
+ mel = Mel(x_res=resolution[1],
175
+ y_res=resolution[0],
176
+ hop_length=args.hop_length)
177
+
178
+ global_step = 0
179
+ for epoch in range(args.num_epochs):
180
+ progress_bar = tqdm(total=len(train_dataloader),
181
+ disable=not accelerator.is_local_main_process)
182
+ progress_bar.set_description(f"Epoch {epoch}")
183
+
184
+ if epoch < args.start_epoch:
185
+ for step in range(len(train_dataloader)):
186
+ optimizer.step()
187
+ lr_scheduler.step()
188
+ progress_bar.update(1)
189
+ global_step += 1
190
+ if epoch == args.start_epoch - 1 and args.use_ema:
191
+ ema_model.optimization_step = global_step
192
+ continue
193
+
194
+ model.train()
195
+ for step, batch in enumerate(train_dataloader):
196
+ clean_images = batch["input"]
197
+
198
+ if vqvae is not None:
199
+ vqvae.to(clean_images.device)
200
+ with torch.no_grad():
201
+ clean_images = vqvae.encode(
202
+ clean_images).latent_dist.sample()
203
+ # Scale latent images to ensure approximately unit variance
204
+ clean_images = clean_images * 0.18215
205
+
206
+ # Sample noise that we'll add to the images
207
+ noise = torch.randn(clean_images.shape).to(clean_images.device)
208
+ bsz = clean_images.shape[0]
209
+ # Sample a random timestep for each image
210
+ timesteps = torch.randint(
211
+ 0,
212
+ noise_scheduler.num_train_timesteps,
213
+ (bsz, ),
214
+ device=clean_images.device,
215
+ ).long()
216
+
217
+ # Add noise to the clean images according to the noise magnitude at each timestep
218
+ # (this is the forward diffusion process)
219
+ noisy_images = noise_scheduler.add_noise(clean_images, noise,
220
+ timesteps)
221
+
222
+ with accelerator.accumulate(model):
223
+ # Predict the noise residual
224
+ noise_pred = model(noisy_images, timesteps)["sample"]
225
+ loss = F.mse_loss(noise_pred, noise)
226
+ accelerator.backward(loss)
227
+
228
+ if accelerator.sync_gradients:
229
+ accelerator.clip_grad_norm_(model.parameters(), 1.0)
230
+ optimizer.step()
231
+ lr_scheduler.step()
232
+ if args.use_ema:
233
+ ema_model.step(model)
234
+ optimizer.zero_grad()
235
+
236
+ progress_bar.update(1)
237
+ global_step += 1
238
+
239
+ logs = {
240
+ "loss": loss.detach().item(),
241
+ "lr": lr_scheduler.get_last_lr()[0],
242
+ "step": global_step,
243
+ }
244
+ if args.use_ema:
245
+ logs["ema_decay"] = ema_model.decay
246
+ progress_bar.set_postfix(**logs)
247
+ accelerator.log(logs, step=global_step)
248
+ progress_bar.close()
249
+
250
+ accelerator.wait_for_everyone()
251
+
252
+ # Generate sample images for visual inspection
253
+ if accelerator.is_main_process:
254
+ if (
255
+ epoch + 1
256
+ ) % args.save_model_epochs == 0 or epoch == args.num_epochs - 1:
257
+ if vqvae is not None:
258
+ pipeline = LatentAudioDiffusionPipeline(
259
+ unet=accelerator.unwrap_model(
260
+ ema_model.averaged_model if args.use_ema else model
261
+ ),
262
+ vqvae=vqvae,
263
+ scheduler=noise_scheduler)
264
+ else:
265
+ pipeline = AudioDiffusionPipeline(
266
+ unet=accelerator.unwrap_model(
267
+ ema_model.averaged_model if args.use_ema else model
268
+ ),
269
+ scheduler=noise_scheduler,
270
+ )
271
+
272
+ # save the model
273
+ if args.push_to_hub:
274
+ try:
275
+ push_to_hub(
276
+ args,
277
+ pipeline,
278
+ repo,
279
+ commit_message=f"Epoch {epoch}",
280
+ blocking=False,
281
+ )
282
+ except NameError: # current version of diffusers has a little bug
283
+ pass
284
+ else:
285
+ pipeline.save_pretrained(output_dir)
286
+
287
+ if (epoch + 1) % args.save_images_epochs == 0:
288
+ generator = torch.manual_seed(42)
289
+ # run pipeline in inference (sample random noise and denoise)
290
+ images, (sample_rate, audios) = pipeline(
291
+ mel=mel,
292
+ generator=generator,
293
+ batch_size=args.eval_batch_size,
294
+ )
295
+
296
+ # denormalize the images and save to tensorboard
297
+ images = np.array([
298
+ np.frombuffer(image.tobytes(), dtype="uint8").reshape(
299
+ (len(image.getbands()), image.height, image.width))
300
+ for image in images
301
+ ])
302
+ accelerator.trackers[0].writer.add_images(
303
+ "test_samples", images, epoch)
304
+ for _, audio in enumerate(audios):
305
+ accelerator.trackers[0].writer.add_audio(
306
+ f"test_audio_{_}",
307
+ normalize(audio),
308
+ epoch,
309
+ sample_rate=sample_rate,
310
+ )
311
+ accelerator.wait_for_everyone()
312
+
313
+ accelerator.end_training()
314
+
315
+
316
+ if __name__ == "__main__":
317
+ parser = argparse.ArgumentParser(
318
+ description="Simple example of a training script.")
319
+ parser.add_argument("--local_rank", type=int, default=-1)
320
+ parser.add_argument("--dataset_name", type=str, default=None)
321
+ parser.add_argument("--dataset_config_name", type=str, default=None)
322
+ parser.add_argument(
323
+ "--train_data_dir",
324
+ type=str,
325
+ default=None,
326
+ help="A folder containing the training data.",
327
+ )
328
+ parser.add_argument("--output_dir", type=str, default="ddpm-model-64")
329
+ parser.add_argument("--overwrite_output_dir", type=bool, default=False)
330
+ parser.add_argument("--cache_dir", type=str, default=None)
331
+ parser.add_argument("--train_batch_size", type=int, default=16)
332
+ parser.add_argument("--eval_batch_size", type=int, default=16)
333
+ parser.add_argument("--num_epochs", type=int, default=100)
334
+ parser.add_argument("--save_images_epochs", type=int, default=10)
335
+ parser.add_argument("--save_model_epochs", type=int, default=10)
336
+ parser.add_argument("--gradient_accumulation_steps", type=int, default=1)
337
+ parser.add_argument("--learning_rate", type=float, default=1e-4)
338
+ parser.add_argument("--lr_scheduler", type=str, default="cosine")
339
+ parser.add_argument("--lr_warmup_steps", type=int, default=500)
340
+ parser.add_argument("--adam_beta1", type=float, default=0.95)
341
+ parser.add_argument("--adam_beta2", type=float, default=0.999)
342
+ parser.add_argument("--adam_weight_decay", type=float, default=1e-6)
343
+ parser.add_argument("--adam_epsilon", type=float, default=1e-08)
344
+ parser.add_argument("--use_ema", type=bool, default=True)
345
+ parser.add_argument("--ema_inv_gamma", type=float, default=1.0)
346
+ parser.add_argument("--ema_power", type=float, default=3 / 4)
347
+ parser.add_argument("--ema_max_decay", type=float, default=0.9999)
348
+ parser.add_argument("--push_to_hub", type=bool, default=False)
349
+ parser.add_argument("--use_auth_token", type=bool, default=False)
350
+ parser.add_argument("--hub_token", type=str, default=None)
351
+ parser.add_argument("--hub_model_id", type=str, default=None)
352
+ parser.add_argument("--hub_private_repo", type=bool, default=False)
353
+ parser.add_argument("--logging_dir", type=str, default="logs")
354
+ parser.add_argument(
355
+ "--mixed_precision",
356
+ type=str,
357
+ default="no",
358
+ choices=["no", "fp16", "bf16"],
359
+ help=(
360
+ "Whether to use mixed precision. Choose"
361
+ "between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10."
362
+ "and an Nvidia Ampere GPU."),
363
+ )
364
+ parser.add_argument("--hop_length", type=int, default=512)
365
+ parser.add_argument("--from_pretrained", type=str, default=None)
366
+ parser.add_argument("--start_epoch", type=int, default=0)
367
+ parser.add_argument("--num_train_steps", type=int, default=1000)
368
+ parser.add_argument("--scheduler",
369
+ type=str,
370
+ default="ddpm",
371
+ help="ddpm or ddim")
372
+ parser.add_argument("--vae",
373
+ type=str,
374
+ default=None,
375
+ help="pretrained VAE model for latent diffusion")
376
+
377
+ args = parser.parse_args()
378
+ env_local_rank = int(os.environ.get("LOCAL_RANK", -1))
379
+ if env_local_rank != -1 and env_local_rank != args.local_rank:
380
+ args.local_rank = env_local_rank
381
+
382
+ if args.dataset_name is None and args.train_data_dir is None:
383
+ raise ValueError(
384
+ "You must specify either a dataset name from the hub or a train data directory."
385
+ )
386
+ if args.dataset_name is not None and args.dataset_name == args.hub_model_id:
387
+ raise ValueError(
388
+ "The local dataset name must be different from the hub model id.")
389
+
390
+ main(args)
scripts/train_vae.py ADDED
@@ -0,0 +1,177 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # based on https://github.com/CompVis/stable-diffusion/blob/main/main.py
2
+
3
+ import os
4
+ import argparse
5
+
6
+ import torch
7
+ import torchvision
8
+ import numpy as np
9
+ from PIL import Image
10
+ import pytorch_lightning as pl
11
+ from omegaconf import OmegaConf
12
+ from librosa.util import normalize
13
+ from ldm.util import instantiate_from_config
14
+ from pytorch_lightning.trainer import Trainer
15
+ from torch.utils.data import DataLoader, Dataset
16
+ from datasets import load_from_disk, load_dataset
17
+ from pytorch_lightning.callbacks import Callback, ModelCheckpoint
18
+ from pytorch_lightning.utilities.distributed import rank_zero_only
19
+
20
+ from audiodiffusion.mel import Mel
21
+ from audiodiffusion.utils import convert_ldm_to_hf_vae
22
+
23
+
24
+ class AudioDiffusion(Dataset):
25
+
26
+ def __init__(self, model_id, channels=3):
27
+ super().__init__()
28
+ self.channels = channels
29
+ if os.path.exists(model_id):
30
+ self.hf_dataset = load_from_disk(model_id)['train']
31
+ else:
32
+ self.hf_dataset = load_dataset(model_id)['train']
33
+
34
+ def __len__(self):
35
+ return len(self.hf_dataset)
36
+
37
+ def __getitem__(self, idx):
38
+ image = self.hf_dataset[idx]['image']
39
+ if self.channels == 3:
40
+ image = image.convert('RGB')
41
+ image = np.frombuffer(image.tobytes(), dtype="uint8").reshape(
42
+ (image.height, image.width, self.channels))
43
+ image = ((image / 255) * 2 - 1)
44
+ return {'image': image}
45
+
46
+
47
+ class AudioDiffusionDataModule(pl.LightningDataModule):
48
+
49
+ def __init__(self, model_id, batch_size, channels):
50
+ super().__init__()
51
+ self.batch_size = batch_size
52
+ self.dataset = AudioDiffusion(model_id=model_id, channels=channels)
53
+ self.num_workers = 1
54
+
55
+ def train_dataloader(self):
56
+ return DataLoader(self.dataset,
57
+ batch_size=self.batch_size,
58
+ num_workers=self.num_workers)
59
+
60
+
61
+ class ImageLogger(Callback):
62
+
63
+ def __init__(self, every=1000, hop_length=512):
64
+ super().__init__()
65
+ self.every = every
66
+ self.hop_length = hop_length
67
+
68
+ @rank_zero_only
69
+ def log_images_and_audios(self, pl_module, batch):
70
+ pl_module.eval()
71
+ with torch.no_grad():
72
+ images = pl_module.log_images(batch, split='train')
73
+ pl_module.train()
74
+
75
+ image_shape = next(iter(images.values())).shape
76
+ channels = image_shape[1]
77
+ mel = Mel(x_res=image_shape[2],
78
+ y_res=image_shape[3],
79
+ hop_length=self.hop_length)
80
+
81
+ for k in images:
82
+ images[k] = images[k].detach().cpu()
83
+ images[k] = torch.clamp(images[k], -1., 1.)
84
+ images[k] = (images[k] + 1.0) / 2.0 # -1,1 -> 0,1; c,h,w
85
+ grid = torchvision.utils.make_grid(images[k])
86
+
87
+ tag = f"train/{k}"
88
+ pl_module.logger.experiment.add_image(
89
+ tag, grid, global_step=pl_module.global_step)
90
+
91
+ images[k] = (images[k].numpy() *
92
+ 255).round().astype("uint8").transpose(0, 2, 3, 1)
93
+ for _, image in enumerate(images[k]):
94
+ audio = mel.image_to_audio(
95
+ Image.fromarray(image, mode='RGB').convert('L')
96
+ if channels == 3 else Image.fromarray(image[:, :, 0]))
97
+ pl_module.logger.experiment.add_audio(
98
+ tag + f"/{_}",
99
+ normalize(audio),
100
+ global_step=pl_module.global_step,
101
+ sample_rate=mel.get_sample_rate())
102
+
103
+ def on_train_batch_end(self, trainer, pl_module, outputs, batch,
104
+ batch_idx):
105
+ if (batch_idx + 1) % self.every != 0:
106
+ return
107
+ self.log_images_and_audios(pl_module, batch)
108
+
109
+
110
+ class HFModelCheckpoint(ModelCheckpoint):
111
+
112
+ def __init__(self, ldm_config, hf_checkpoint, *args, **kwargs):
113
+ super().__init__(*args, **kwargs)
114
+ self.ldm_config = ldm_config
115
+ self.hf_checkpoint = hf_checkpoint
116
+
117
+ def on_train_epoch_end(self, trainer, pl_module):
118
+ ldm_checkpoint = self._get_metric_interpolated_filepath_name(
119
+ {'epoch': trainer.current_epoch}, trainer)
120
+ super().on_train_epoch_end(trainer, pl_module)
121
+ convert_ldm_to_hf_vae(ldm_checkpoint, self.ldm_config,
122
+ self.hf_checkpoint)
123
+
124
+
125
+ if __name__ == "__main__":
126
+ parser = argparse.ArgumentParser(description="Train VAE using ldm.")
127
+ parser.add_argument("-d", "--dataset_name", type=str, default=None)
128
+ parser.add_argument("-b", "--batch_size", type=int, default=1)
129
+ parser.add_argument("-c",
130
+ "--ldm_config_file",
131
+ type=str,
132
+ default="config/ldm_autoencoder_kl.yaml")
133
+ parser.add_argument("--ldm_checkpoint_dir",
134
+ type=str,
135
+ default="models/ldm-autoencoder-kl")
136
+ parser.add_argument("--hf_checkpoint_dir",
137
+ type=str,
138
+ default="models/autoencoder-kl")
139
+ parser.add_argument("-r",
140
+ "--resume_from_checkpoint",
141
+ type=str,
142
+ default=None)
143
+ parser.add_argument("-g",
144
+ "--gradient_accumulation_steps",
145
+ type=int,
146
+ default=1)
147
+ parser.add_argument("--hop_length", type=int, default=512)
148
+ parser.add_argument("--save_images_batches", type=int, default=1000)
149
+ parser.add_argument("--max_epochs", type=int, default=100)
150
+ args = parser.parse_args()
151
+
152
+ config = OmegaConf.load(args.ldm_config_file)
153
+ model = instantiate_from_config(config.model)
154
+ model.learning_rate = config.model.base_learning_rate
155
+ data = AudioDiffusionDataModule(
156
+ model_id=args.dataset_name,
157
+ batch_size=args.batch_size,
158
+ channels=config.model.params.ddconfig.in_channels)
159
+ lightning_config = config.pop("lightning", OmegaConf.create())
160
+ trainer_config = lightning_config.get("trainer", OmegaConf.create())
161
+ trainer_config.accumulate_grad_batches = args.gradient_accumulation_steps
162
+ trainer_opt = argparse.Namespace(**trainer_config)
163
+ trainer = Trainer.from_argparse_args(
164
+ trainer_opt,
165
+ max_epochs=args.max_epochs,
166
+ resume_from_checkpoint=args.resume_from_checkpoint,
167
+ callbacks=[
168
+ ImageLogger(every=args.save_images_batches,
169
+ hop_length=args.hop_length),
170
+ HFModelCheckpoint(ldm_config=config,
171
+ hf_checkpoint=args.hf_checkpoint_dir,
172
+ dirpath=args.ldm_checkpoint_dir,
173
+ filename='{epoch:06}',
174
+ verbose=True,
175
+ save_last=True)
176
+ ])
177
+ trainer.fit(model, data)
setup.cfg ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [metadata]
2
+ name = audiodiffusion
3
+ version = attr: audiodiffusion.VERSION
4
+ description = Generate Mel spectrogram dataset from directory of audio files.
5
+ long_description = file: README.md
6
+ license = GPL3
7
+ classifiers =
8
+ Programming Language :: Python :: 3
9
+
10
+ [options]
11
+ zip_safe = False
12
+ packages = audiodiffusion
13
+ install_requires =
14
+ torch
15
+ numpy
16
+ Pillow
17
+ diffusers>=0.4.1
18
+ librosa
19
+ datasets
setup.py ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+
3
+ from setuptools import setup
4
+
5
+ if __name__ == "__main__":
6
+ setup()
streamlit_app.py ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from io import BytesIO
2
+ import streamlit as st
3
+ import soundfile as sf
4
+ from librosa.util import normalize
5
+ from librosa.beat import beat_track
6
+
7
+ from audiodiffusion import AudioDiffusion
8
+
9
+ if __name__ == "__main__":
10
+ st.header("Audio Diffusion")
11
+ st.markdown("Generate audio using Huggingface diffusers.\
12
+ This takes about 20 minutes without a GPU, so why not make yourself a \
13
+ cup of tea in the meantime? (Or try the teticio/audio-diffusion-ddim-256 \
14
+ model which is faster.)")
15
+
16
+ model_id = st.selectbox("Model", [
17
+ "teticio/audio-diffusion-256", "teticio/audio-diffusion-breaks-256",
18
+ "teticio/audio-diffusion-instrumental-hiphop-256",
19
+ "teticio/audio-diffusion-ddim-256"
20
+ ])
21
+ audio_diffusion = AudioDiffusion(model_id=model_id)
22
+
23
+ if st.button("Generate"):
24
+ st.markdown("Generating...")
25
+ image, (sample_rate,
26
+ audio) = audio_diffusion.generate_spectrogram_and_audio()
27
+ st.image(image, caption="Mel spectrogram")
28
+ buffer = BytesIO()
29
+ sf.write(buffer, normalize(audio), sample_rate, format="WAV")
30
+ st.audio(buffer, format="audio/wav")
31
+
32
+ audio = AudioDiffusion.loop_it(audio, sample_rate)
33
+ if audio is not None:
34
+ st.markdown("Loop")
35
+ buffer = BytesIO()
36
+ sf.write(buffer, normalize(audio), sample_rate, format="WAV")
37
+ st.audio(buffer, format="audio/wav")