yoinked commited on
Commit
9f76d9a
1 Parent(s): b561aed
.gitattributes CHANGED
@@ -2,13 +2,11 @@
2
  *.arrow filter=lfs diff=lfs merge=lfs -text
3
  *.bin filter=lfs diff=lfs merge=lfs -text
4
  *.bz2 filter=lfs diff=lfs merge=lfs -text
5
- *.ckpt filter=lfs diff=lfs merge=lfs -text
6
  *.ftz filter=lfs diff=lfs merge=lfs -text
7
  *.gz filter=lfs diff=lfs merge=lfs -text
8
  *.h5 filter=lfs diff=lfs merge=lfs -text
9
  *.joblib filter=lfs diff=lfs merge=lfs -text
10
  *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
- *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
  *.model filter=lfs diff=lfs merge=lfs -text
13
  *.msgpack filter=lfs diff=lfs merge=lfs -text
14
  *.npy filter=lfs diff=lfs merge=lfs -text
@@ -16,13 +14,12 @@
16
  *.onnx filter=lfs diff=lfs merge=lfs -text
17
  *.ot filter=lfs diff=lfs merge=lfs -text
18
  *.parquet filter=lfs diff=lfs merge=lfs -text
19
- *.pb filter=lfs diff=lfs merge=lfs -text
20
  *.pickle filter=lfs diff=lfs merge=lfs -text
21
  *.pkl filter=lfs diff=lfs merge=lfs -text
 
22
  *.pt filter=lfs diff=lfs merge=lfs -text
23
  *.pth filter=lfs diff=lfs merge=lfs -text
24
  *.rar filter=lfs diff=lfs merge=lfs -text
25
- *.safetensors filter=lfs diff=lfs merge=lfs -text
26
  saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
  *.tar.* filter=lfs diff=lfs merge=lfs -text
28
  *.tflite filter=lfs diff=lfs merge=lfs -text
 
2
  *.arrow filter=lfs diff=lfs merge=lfs -text
3
  *.bin filter=lfs diff=lfs merge=lfs -text
4
  *.bz2 filter=lfs diff=lfs merge=lfs -text
 
5
  *.ftz filter=lfs diff=lfs merge=lfs -text
6
  *.gz filter=lfs diff=lfs merge=lfs -text
7
  *.h5 filter=lfs diff=lfs merge=lfs -text
8
  *.joblib filter=lfs diff=lfs merge=lfs -text
9
  *.lfs.* filter=lfs diff=lfs merge=lfs -text
 
10
  *.model filter=lfs diff=lfs merge=lfs -text
11
  *.msgpack filter=lfs diff=lfs merge=lfs -text
12
  *.npy filter=lfs diff=lfs merge=lfs -text
 
14
  *.onnx filter=lfs diff=lfs merge=lfs -text
15
  *.ot filter=lfs diff=lfs merge=lfs -text
16
  *.parquet filter=lfs diff=lfs merge=lfs -text
 
17
  *.pickle filter=lfs diff=lfs merge=lfs -text
18
  *.pkl filter=lfs diff=lfs merge=lfs -text
19
+ *.pb filter=lfs diff=lfs merge=lfs -text
20
  *.pt filter=lfs diff=lfs merge=lfs -text
21
  *.pth filter=lfs diff=lfs merge=lfs -text
22
  *.rar filter=lfs diff=lfs merge=lfs -text
 
23
  saved_model/**/* filter=lfs diff=lfs merge=lfs -text
24
  *.tar.* filter=lfs diff=lfs merge=lfs -text
25
  *.tflite filter=lfs diff=lfs merge=lfs -text
.gitignore ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ .vscode
2
+ __pycache__
3
+ .ipynb_checkpoints
4
+ data
5
+ models
6
+ flagged
7
+ build
8
+ dist
9
+ audiodiffusion.egg-info
10
+ lightning_logs
11
+ taming
12
+ checkpoints
13
+ Pipfile
14
+ Pipfile.lock
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,234 @@
1
  ---
2
  title: Audio Diffusion
3
- emoji: 🔉
4
- colorFrom: gray
5
- colorTo: gray
6
  sdk: gradio
7
- sdk_version: 3.28.0
8
  app_file: app.py
9
  pinned: false
10
  license: gpl-3.0
11
  ---
 
12
 
13
- taken from teticio's take on audio diffusion
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ #### Sample automatically generated loop
18
+
19
+ https://user-images.githubusercontent.com/44233095/204103172-27f25d63-5e77-40ca-91ab-d04a45d4726f.mp4
20
+
21
+ Go to https://soundcloud.com/teticio2/sets/audio-diffusion-loops for more examples.
22
+
23
+ ---
24
+ #### Updates
25
+
26
+ **25/12/2022**. Now it is possible to train models conditional on an encoding (of text or audio, for example). See the section on Conditional Audio Generation below.
27
+
28
+ **5/12/2022**. 🤗 Exciting news! `AudioDiffusionPipeline` has been migrated to the Hugging Face `diffusers` package so that it is even easier for others to use and contribute.
29
+
30
+ **2/12/2022**. Added Mel to pipeline and updated the pretrained models to save Mel config (they are now no longer compatible with previous versions of this repo). It is relatively straightforward to migrate previously trained models to the new format (see https://huggingface.co/teticio/audio-diffusion-256).
31
+
32
+ **7/11/2022**. Added pre-trained latent audio diffusion models [teticio/latent-audio-diffusion-256](https://huggingface.co/teticio/latent-audio-diffusion-256) and [teticio/latent-audio-diffusion-ddim-256](https://huggingface.co/teticio/latent-audio-diffusion-ddim-256). You can use the pre-trained VAE to train your own latent diffusion models on a different set of audio files.
33
+
34
+ **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.
35
+
36
+ **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.
37
+
38
+ **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").
39
+
40
+ **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.
41
+
42
+ ---
43
+
44
+ ![mel spectrogram](https://user-images.githubusercontent.com/44233095/205305826-8b39c917-26c5-49b4-887c-776f5d69e970.png)
45
+
46
+ ---
47
+
48
+ ## DDPM ([De-noising Diffusion Probabilistic Models](https://arxiv.org/abs/2006.11239))
49
+
50
+ 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.
51
+
52
+ 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.
53
+
54
+ 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).
55
+
56
+ | Model | Dataset | Description |
57
+ |-------|---------|-------------|
58
+ | [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 |
59
+ | [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) |
60
+ | [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 |
61
+ | [teticio/audio-diffusion-ddim-256](https://huggingface.co/teticio/audio-diffusion-ddim-256) | [teticio/audio-diffusion-256](https://huggingface.co/datasets/teticio/audio-diffusion-256) | De-noising Diffusion Implicit Model |
62
+ | [teticio/latent-audio-diffusion-256](https://huggingface.co/teticio/latent-audio-diffusion-256) | [teticio/audio-diffusion-256](https://huggingface.co/datasets/teticio/audio-diffusion-256) | Latent Audio Diffusion model |
63
+ | [teticio/latent-audio-diffusion-ddim-256](https://huggingface.co/teticio/latent-audio-diffusion-ddim-256) | [teticio/audio-diffusion-256](https://huggingface.co/datasets/teticio/audio-diffusion-256) | Latent Audio Diffusion Implicit Model |
64
+ | [teticio/conditional-latent-audio-diffusion-512](https://huggingface.co/teticio/latent-audio-diffusion-512) | [teticio/audio-diffusion-512](https://huggingface.co/datasets/teticio/audio-diffusion-512) | Conditional Latent Audio Diffusion Model |
65
+
66
+ ---
67
+
68
+ ## Generate Mel spectrogram dataset from directory of audio files
69
+
70
+ #### Install from GitHub (includes training scripts)
71
+
72
+ ```bash
73
+ git clone https://github.com/teticio/audio-diffusion.git
74
+ cd audio-diffusion
75
+ pip install .
76
+ ```
77
+
78
+ #### Install from PyPI
79
+
80
+ ```bash
81
+ pip install audiodiffusion
82
+ ```
83
+
84
+ #### 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
85
+
86
+ ```bash
87
+ python scripts/audio_to_images.py \
88
+ --resolution 64,64 \
89
+ --hop_length 1024 \
90
+ --input_dir path-to-audio-files \
91
+ --output_dir path-to-output-data
92
+ ```
93
+
94
+ #### Generate dataset of 256x256 Mel spectrograms and push to hub (you will need to be authenticated with `huggingface-cli login`)
95
+
96
+ ```bash
97
+ python scripts/audio_to_images.py \
98
+ --resolution 256 \
99
+ --input_dir path-to-audio-files \
100
+ --output_dir data/audio-diffusion-256 \
101
+ --push_to_hub teticio/audio-diffusion-256
102
+ ```
103
+
104
+ Note that the default `sample_rate` is 22050 and audios will be resampled if they are at a different rate. If you change this value, you may find that the results in the `test_mel.ipynb` notebook are not good (for example, if `sample_rate` is 48000) and that it is necessary to adjust `n_fft` (for example, to 2000 instead of the default value of 2048; alternatively, you can resample to a `sample_rate` of 44100). Make sure you use the same parameters for training and inference. You should also bear in mind that not all resolutions work with the neural network architecture as currently configured - you should be safe if you stick to powers of 2.
105
+
106
+ ## Train model
107
+
108
+ #### Run training on local machine
109
+
110
+ ```bash
111
+ accelerate launch --config_file config/accelerate_local.yaml \
112
+ scripts/train_unet.py \
113
+ --dataset_name data/audio-diffusion-64 \
114
+ --hop_length 1024 \
115
+ --output_dir models/ddpm-ema-audio-64 \
116
+ --train_batch_size 16 \
117
+ --num_epochs 100 \
118
+ --gradient_accumulation_steps 1 \
119
+ --learning_rate 1e-4 \
120
+ --lr_warmup_steps 500 \
121
+ --mixed_precision no
122
+ ```
123
+
124
+ #### 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
125
+
126
+ ```bash
127
+ accelerate launch --config_file config/accelerate_local.yaml \
128
+ scripts/train_unet.py \
129
+ --dataset_name teticio/audio-diffusion-256 \
130
+ --output_dir models/audio-diffusion-256 \
131
+ --num_epochs 100 \
132
+ --train_batch_size 2 \
133
+ --eval_batch_size 2 \
134
+ --gradient_accumulation_steps 8 \
135
+ --learning_rate 1e-4 \
136
+ --lr_warmup_steps 500 \
137
+ --mixed_precision no \
138
+ --push_to_hub True \
139
+ --hub_model_id audio-diffusion-256 \
140
+ --hub_token $(cat $HOME/.huggingface/token)
141
+ ```
142
+
143
+ #### Run training on SageMaker
144
+
145
+ ```bash
146
+ accelerate launch --config_file config/accelerate_sagemaker.yaml \
147
+ scripts/train_unet.py \
148
+ --dataset_name teticio/audio-diffusion-256 \
149
+ --output_dir models/ddpm-ema-audio-256 \
150
+ --train_batch_size 16 \
151
+ --num_epochs 100 \
152
+ --gradient_accumulation_steps 1 \
153
+ --learning_rate 1e-4 \
154
+ --lr_warmup_steps 500 \
155
+ --mixed_precision no
156
+ ```
157
+
158
+ ## DDIM ([De-noising Diffusion Implicit Models](https://arxiv.org/pdf/2010.02502.pdf))
159
+
160
+ #### A DDIM can be trained by adding the parameter
161
+
162
+ ```bash
163
+ --scheduler ddim
164
+ ```
165
+
166
+ 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).
167
+
168
+ ## Latent Audio Diffusion
169
+
170
+ 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.
171
+
172
+ 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.
173
+
174
+ #### Train latent diffusion model using pre-trained VAE
175
+
176
+ ```bash
177
+ accelerate launch ...
178
+ ...
179
+ --vae teticio/latent-audio-diffusion-256
180
+ ```
181
+
182
+ #### Install dependencies to train with Stable Diffusion
183
+
184
+ ```bash
185
+ pip install omegaconf pytorch_lightning==1.7.7 torchvision einops
186
+ pip install -e git+https://github.com/CompVis/stable-diffusion.git@main#egg=latent-diffusion
187
+ pip install -e git+https://github.com/CompVis/taming-transformers.git@master#egg=taming-transformers
188
+ ```
189
+
190
+ #### Train an autoencoder
191
+
192
+ ```bash
193
+ python scripts/train_vae.py \
194
+ --dataset_name teticio/audio-diffusion-256 \
195
+ --batch_size 2 \
196
+ --gradient_accumulation_steps 12
197
+ ```
198
+
199
+ #### Train latent diffusion model
200
+
201
+ ```bash
202
+ accelerate launch ...
203
+ ...
204
+ --vae models/autoencoder-kl
205
+ ```
206
+
207
+ ## Conditional Audio Generation
208
+
209
+ We can generate audio conditional on a text prompt - or indeed anything which can be encoded into a bunch of numbers - much like DALL-E2, Midjourney and Stable Diffusion. It is generally harder to find good quality datasets of audios together with descriptions, although the people behind the dataset used to train Stable Diffusion are making some very interesting progress [here](https://github.com/LAION-AI/audio-dataset). I have chosen to encode the audio directly instead based on "how it sounds", using a [model which I trained on hundreds of thousands of Spotify playlists](https://github.com/teticio/Deej-AI). To encode an audio into a 100 dimensional vector
210
+
211
+ ```python
212
+ from audiodiffusion.audio_encoder import AudioEncoder
213
+
214
+ audio_encoder = AudioEncoder.from_pretrained("teticio/audio-encoder")
215
+ audio_encoder.encode(['/home/teticio/Music/liked/Agua Re - Holy Dance - Large Sound Mix.mp3'])
216
+ ```
217
+
218
+ Once you have prepared a dataset, you can encode the audio files with this script
219
+
220
+ ```bash
221
+ python scripts/encode_audio \
222
+ --dataset_name teticio/audio-diffusion-256 \
223
+ --out_file data/encodings.p
224
+ ```
225
+
226
+ Then you can train a model with
227
+
228
+ ```bash
229
+ accelerate launch ...
230
+ ...
231
+ --encodings data/encodings.p
232
+ ```
233
+
234
+ When generating audios, you will need to pass an `encodings` Tensor. See the [`conditional_generation.ipynb`](https://colab.research.google.com/github/teticio/audio-diffusion/blob/master/notebooks/conditional_generation.ipynb) notebook for an example that uses encodings of Spotify track previews to influence the generation.
app.py ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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(
19
+ fn=generate_spectrogram_audio_and_loop,
20
+ title="Audio Diffusion",
21
+ description="Generate audio using Huggingface diffusers.\
22
+ The models without 'latent' or 'ddim' give better results but take about \
23
+ 20 minutes without a GPU. For GPU, you can use \
24
+ [colab](https://colab.research.google.com/github/teticio/audio-diffusion/blob/master/notebooks/gradio_app.ipynb) \
25
+ to run this app.",
26
+ inputs=[
27
+ gr.Dropdown(label="Model",
28
+ choices=[
29
+ "teticio/audio-diffusion-256",
30
+ "teticio/audio-diffusion-breaks-256",
31
+ "teticio/audio-diffusion-instrumental-hiphop-256",
32
+ "teticio/audio-diffusion-ddim-256",
33
+ "teticio/latent-audio-diffusion-256",
34
+ "teticio/latent-audio-diffusion-ddim-256"
35
+ ],
36
+ value="teticio/latent-audio-diffusion-ddim-256")
37
+ ],
38
+ outputs=[
39
+ gr.Image(label="Mel spectrogram", image_mode="L"),
40
+ gr.Audio(label="Audio"),
41
+ gr.Audio(label="Loop"),
42
+ ],
43
+ allow_flagging="never")
44
+
45
+ if __name__ == "__main__":
46
+ parser = argparse.ArgumentParser()
47
+ parser.add_argument("--port", type=int)
48
+ parser.add_argument("--server", type=int)
49
+ args = parser.parse_args()
50
+ demo.launch(server_name=args.server or "0.0.0.0", server_port=args.port)
audiodiffusion/__init__.py ADDED
@@ -0,0 +1,140 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Iterable, Tuple
2
+
3
+ import numpy as np
4
+ import torch
5
+ from librosa.beat import beat_track
6
+ from PIL import Image
7
+ from tqdm.auto import tqdm
8
+
9
+ # from diffusers import AudioDiffusionPipeline
10
+ from .pipeline_audio_diffusion import AudioDiffusionPipeline
11
+
12
+ VERSION = "1.5.3"
13
+
14
+
15
+ class AudioDiffusion:
16
+ def __init__(
17
+ self,
18
+ model_id: str = "teticio/audio-diffusion-256",
19
+ cuda: bool = torch.cuda.is_available(),
20
+ progress_bar: Iterable = tqdm,
21
+ ):
22
+ """Class for generating audio using De-noising Diffusion Probabilistic Models.
23
+
24
+ Args:
25
+ model_id (String): name of model (local directory or Hugging Face Hub)
26
+ cuda (bool): use CUDA?
27
+ progress_bar (iterable): iterable callback for progress updates or None
28
+ """
29
+ self.model_id = model_id
30
+ self.pipe = AudioDiffusionPipeline.from_pretrained(self.model_id)
31
+ if cuda:
32
+ self.pipe.to("cuda")
33
+ self.progress_bar = progress_bar or (lambda _: _)
34
+
35
+ def generate_spectrogram_and_audio(
36
+ self,
37
+ steps: int = None,
38
+ generator: torch.Generator = None,
39
+ step_generator: torch.Generator = None,
40
+ eta: float = 0,
41
+ noise: torch.Tensor = None,
42
+ encoding: torch.Tensor = None,
43
+ ) -> Tuple[Image.Image, Tuple[int, np.ndarray]]:
44
+ """Generate random mel spectrogram and convert to audio.
45
+
46
+ Args:
47
+ steps (int): number of de-noising steps (defaults to 50 for DDIM, 1000 for DDPM)
48
+ generator (torch.Generator): random number generator or None
49
+ step_generator (torch.Generator): random number generator used to de-noise or None
50
+ eta (float): parameter between 0 and 1 used with DDIM scheduler
51
+ noise (torch.Tensor): noisy image or None
52
+ encoding (`torch.Tensor`): for UNet2DConditionModel shape (batch_size, seq_length, cross_attention_dim)
53
+
54
+ Returns:
55
+ PIL Image: mel spectrogram
56
+ (float, np.ndarray): sample rate and raw audio
57
+ """
58
+ images, (sample_rate, audios) = self.pipe(
59
+ batch_size=1,
60
+ steps=steps,
61
+ generator=generator,
62
+ step_generator=step_generator,
63
+ eta=eta,
64
+ noise=noise,
65
+ encoding=encoding,
66
+ return_dict=False,
67
+ )
68
+ return images[0], (sample_rate, audios[0])
69
+
70
+ def generate_spectrogram_and_audio_from_audio(
71
+ self,
72
+ audio_file: str = None,
73
+ raw_audio: np.ndarray = None,
74
+ slice: int = 0,
75
+ start_step: int = 0,
76
+ steps: int = None,
77
+ generator: torch.Generator = None,
78
+ mask_start_secs: float = 0,
79
+ mask_end_secs: float = 0,
80
+ step_generator: torch.Generator = None,
81
+ eta: float = 0,
82
+ encoding: torch.Tensor = None,
83
+ noise: torch.Tensor = None,
84
+ ) -> Tuple[Image.Image, Tuple[int, np.ndarray]]:
85
+ """Generate random mel spectrogram from audio input and convert to audio.
86
+
87
+ Args:
88
+ audio_file (str): must be a file on disk due to Librosa limitation or
89
+ raw_audio (np.ndarray): audio as numpy array
90
+ slice (int): slice number of audio to convert
91
+ start_step (int): step to start from
92
+ steps (int): number of de-noising steps (defaults to 50 for DDIM, 1000 for DDPM)
93
+ generator (torch.Generator): random number generator or None
94
+ mask_start_secs (float): number of seconds of audio to mask (not generate) at start
95
+ mask_end_secs (float): number of seconds of audio to mask (not generate) at end
96
+ step_generator (torch.Generator): random number generator used to de-noise or None
97
+ eta (float): parameter between 0 and 1 used with DDIM scheduler
98
+ encoding (`torch.Tensor`): for UNet2DConditionModel shape (batch_size, seq_length, cross_attention_dim)
99
+ noise (torch.Tensor): noisy image or None
100
+
101
+ Returns:
102
+ PIL Image: mel spectrogram
103
+ (float, np.ndarray): sample rate and raw audio
104
+ """
105
+
106
+ images, (sample_rate, audios) = self.pipe(
107
+ batch_size=1,
108
+ audio_file=audio_file,
109
+ raw_audio=raw_audio,
110
+ slice=slice,
111
+ start_step=start_step,
112
+ steps=steps,
113
+ generator=generator,
114
+ mask_start_secs=mask_start_secs,
115
+ mask_end_secs=mask_end_secs,
116
+ step_generator=step_generator,
117
+ eta=eta,
118
+ noise=noise,
119
+ encoding=encoding,
120
+ return_dict=False,
121
+ )
122
+ return images[0], (sample_rate, audios[0])
123
+
124
+ @staticmethod
125
+ def loop_it(audio: np.ndarray, sample_rate: int, loops: int = 12) -> np.ndarray:
126
+ """Loop audio
127
+
128
+ Args:
129
+ audio (np.ndarray): audio as numpy array
130
+ sample_rate (int): sample rate of audio
131
+ loops (int): number of times to loop
132
+
133
+ Returns:
134
+ (float, np.ndarray): sample rate and raw audio or None
135
+ """
136
+ _, beats = beat_track(y=audio, sr=sample_rate, units="samples")
137
+ beats_in_bar = (len(beats) - 1) // 4 * 4
138
+ if beats_in_bar > 0:
139
+ return np.tile(audio[beats[0] : beats[beats_in_bar]], loops)
140
+ return None
audiodiffusion/audio_encoder.py ADDED
@@ -0,0 +1,107 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import torch
3
+ from diffusers import ConfigMixin, Mel, ModelMixin
4
+ from torch import nn
5
+
6
+
7
+ class SeparableConv2d(nn.Module):
8
+ def __init__(self, in_channels, out_channels, kernel_size):
9
+ super(SeparableConv2d, self).__init__()
10
+ self.depthwise = nn.Conv2d(
11
+ in_channels,
12
+ in_channels,
13
+ kernel_size=kernel_size,
14
+ groups=in_channels,
15
+ bias=False,
16
+ padding=1,
17
+ )
18
+ self.pointwise = nn.Conv2d(in_channels, out_channels, kernel_size=1, bias=True)
19
+
20
+ def forward(self, x):
21
+ out = self.depthwise(x)
22
+ out = self.pointwise(out)
23
+ return out
24
+
25
+
26
+ class ConvBlock(nn.Module):
27
+ def __init__(self, in_channels, out_channels, dropout_rate):
28
+ super(ConvBlock, self).__init__()
29
+ self.sep_conv = SeparableConv2d(in_channels, out_channels, (3, 3))
30
+ self.leaky_relu = nn.LeakyReLU(0.2)
31
+ self.batch_norm = nn.BatchNorm2d(out_channels, eps=0.001, momentum=0.01)
32
+ self.max_pool = nn.MaxPool2d((2, 2))
33
+ self.dropout = nn.Dropout(dropout_rate)
34
+
35
+ def forward(self, x):
36
+ x = self.sep_conv(x)
37
+ x = self.leaky_relu(x)
38
+ x = self.batch_norm(x)
39
+ x = self.max_pool(x)
40
+ x = self.dropout(x)
41
+ return x
42
+
43
+
44
+ class DenseBlock(nn.Module):
45
+ def __init__(self, in_features, out_features, dropout_rate):
46
+ super(DenseBlock, self).__init__()
47
+ self.flatten = nn.Flatten()
48
+ self.dense = nn.Linear(in_features, out_features)
49
+ self.leaky_relu = nn.LeakyReLU(0.2)
50
+ self.batch_norm = nn.BatchNorm1d(out_features, eps=0.001, momentum=0.01)
51
+ self.dropout = nn.Dropout(dropout_rate)
52
+
53
+ def forward(self, x):
54
+ x = self.flatten(x.permute(0, 2, 3, 1))
55
+ x = self.dense(x)
56
+ x = self.leaky_relu(x)
57
+ x = self.batch_norm(x)
58
+ x = self.dropout(x)
59
+ return x
60
+
61
+
62
+ class AudioEncoder(ModelMixin, ConfigMixin):
63
+ def __init__(self):
64
+ super().__init__()
65
+ self.mel = Mel(
66
+ x_res=216,
67
+ y_res=96,
68
+ sample_rate=22050,
69
+ n_fft=2048,
70
+ hop_length=512,
71
+ top_db=80,
72
+ )
73
+ self.conv_blocks = nn.ModuleList([ConvBlock(1, 32, 0.2), ConvBlock(32, 64, 0.3), ConvBlock(64, 128, 0.4)])
74
+ self.dense_block = DenseBlock(41472, 1024, 0.5)
75
+ self.embedding = nn.Linear(1024, 100)
76
+
77
+ def forward(self, x):
78
+ for conv_block in self.conv_blocks:
79
+ x = conv_block(x)
80
+ x = self.dense_block(x)
81
+ x = self.embedding(x)
82
+ return x
83
+
84
+ @torch.no_grad()
85
+ def encode(self, audio_files):
86
+ self.eval()
87
+ y = []
88
+ for audio_file in audio_files:
89
+ self.mel.load_audio(audio_file)
90
+ x = [
91
+ np.expand_dims(
92
+ np.frombuffer(self.mel.audio_slice_to_image(slice).tobytes(), dtype="uint8").reshape(
93
+ (self.mel.y_res, self.mel.x_res)
94
+ )
95
+ / 255,
96
+ axis=0,
97
+ )
98
+ for slice in range(self.mel.get_number_of_slices())
99
+ ]
100
+ y += [torch.mean(self(torch.Tensor(x)), dim=0)]
101
+ return torch.stack(y)
102
+
103
+
104
+ # from diffusers import Mel
105
+ # from audiodiffusion.audio_encoder import AudioEncoder
106
+ # audio_encoder = AudioEncoder.from_pretrained("teticio/audio-encoder")
107
+ # audio_encoder.encode(['/home/teticio/Music/liked/Agua Re - Holy Dance - Large Sound Mix.mp3'])
audiodiffusion/mel.py ADDED
@@ -0,0 +1,167 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This code has been migrated to diffusers but can be run locally with
2
+ # pipe = DiffusionPipeline.from_pretrained("teticio/audio-diffusion-256", custom_pipeline="audio-diffusion/audiodiffusion/pipeline_audio_diffusion.py")
3
+
4
+ # Copyright 2022 The HuggingFace Team. All rights reserved.
5
+ #
6
+ # Licensed under the Apache License, Version 2.0 (the "License");
7
+ # you may not use this file except in compliance with the License.
8
+ # You may obtain a copy of the License at
9
+ #
10
+ # http://www.apache.org/licenses/LICENSE-2.0
11
+ #
12
+ # Unless required by applicable law or agreed to in writing, software
13
+ # distributed under the License is distributed on an "AS IS" BASIS,
14
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
+ # See the License for the specific language governing permissions and
16
+ # limitations under the License.
17
+
18
+
19
+ import warnings
20
+
21
+ from diffusers.configuration_utils import ConfigMixin, register_to_config
22
+ from diffusers.schedulers.scheduling_utils import SchedulerMixin
23
+
24
+ warnings.filterwarnings("ignore")
25
+
26
+ import numpy as np # noqa: E402
27
+
28
+
29
+ try:
30
+ import librosa # noqa: E402
31
+
32
+ _librosa_can_be_imported = True
33
+ _import_error = ""
34
+ except Exception as e:
35
+ _librosa_can_be_imported = False
36
+ _import_error = (
37
+ f"Cannot import librosa because {e}. Make sure to correctly install librosa to be able to install it."
38
+ )
39
+
40
+
41
+ from PIL import Image # noqa: E402
42
+
43
+
44
+ class Mel(ConfigMixin, SchedulerMixin):
45
+ """
46
+ Parameters:
47
+ x_res (`int`): x resolution of spectrogram (time)
48
+ y_res (`int`): y resolution of spectrogram (frequency bins)
49
+ sample_rate (`int`): sample rate of audio
50
+ n_fft (`int`): number of Fast Fourier Transforms
51
+ hop_length (`int`): hop length (a higher number is recommended for lower than 256 y_res)
52
+ top_db (`int`): loudest in decibels
53
+ n_iter (`int`): number of iterations for Griffin Linn mel inversion
54
+ """
55
+
56
+ config_name = "mel_config.json"
57
+
58
+ @register_to_config
59
+ def __init__(
60
+ self,
61
+ x_res: int = 256,
62
+ y_res: int = 256,
63
+ sample_rate: int = 22050,
64
+ n_fft: int = 2048,
65
+ hop_length: int = 512,
66
+ top_db: int = 80,
67
+ n_iter: int = 32,
68
+ ):
69
+ self.hop_length = hop_length
70
+ self.sr = sample_rate
71
+ self.n_fft = n_fft
72
+ self.top_db = top_db
73
+ self.n_iter = n_iter
74
+ self.set_resolution(x_res, y_res)
75
+ self.audio = None
76
+
77
+ if not _librosa_can_be_imported:
78
+ raise ValueError(_import_error)
79
+
80
+ def set_resolution(self, x_res: int, y_res: int):
81
+ """Set resolution.
82
+
83
+ Args:
84
+ x_res (`int`): x resolution of spectrogram (time)
85
+ y_res (`int`): y resolution of spectrogram (frequency bins)
86
+ """
87
+ self.x_res = x_res
88
+ self.y_res = y_res
89
+ self.n_mels = self.y_res
90
+ self.slice_size = self.x_res * self.hop_length - 1
91
+
92
+ def load_audio(self, audio_file: str = None, raw_audio: np.ndarray = None):
93
+ """Load audio.
94
+
95
+ Args:
96
+ audio_file (`str`): must be a file on disk due to Librosa limitation or
97
+ raw_audio (`np.ndarray`): audio as numpy array
98
+ """
99
+ if audio_file is not None:
100
+ self.audio, _ = librosa.load(audio_file, mono=True, sr=self.sr)
101
+ else:
102
+ self.audio = raw_audio
103
+
104
+ # Pad with silence if necessary.
105
+ if len(self.audio) < self.x_res * self.hop_length:
106
+ self.audio = np.concatenate([self.audio, np.zeros((self.x_res * self.hop_length - len(self.audio),))])
107
+
108
+ def get_number_of_slices(self) -> int:
109
+ """Get number of slices in audio.
110
+
111
+ Returns:
112
+ `int`: number of spectograms audio can be sliced into
113
+ """
114
+ return len(self.audio) // self.slice_size
115
+
116
+ def get_audio_slice(self, slice: int = 0) -> np.ndarray:
117
+ """Get slice of audio.
118
+
119
+ Args:
120
+ slice (`int`): slice number of audio (out of get_number_of_slices())
121
+
122
+ Returns:
123
+ `np.ndarray`: audio as numpy array
124
+ """
125
+ return self.audio[self.slice_size * slice : self.slice_size * (slice + 1)]
126
+
127
+ def get_sample_rate(self) -> int:
128
+ """Get sample rate:
129
+
130
+ Returns:
131
+ `int`: sample rate of audio
132
+ """
133
+ return self.sr
134
+
135
+ def audio_slice_to_image(self, slice: int) -> Image.Image:
136
+ """Convert slice of audio to spectrogram.
137
+
138
+ Args:
139
+ slice (`int`): slice number of audio to convert (out of get_number_of_slices())
140
+
141
+ Returns:
142
+ `PIL Image`: grayscale image of x_res x y_res
143
+ """
144
+ S = librosa.feature.melspectrogram(
145
+ y=self.get_audio_slice(slice), sr=self.sr, n_fft=self.n_fft, hop_length=self.hop_length, n_mels=self.n_mels
146
+ )
147
+ log_S = librosa.power_to_db(S, ref=np.max, top_db=self.top_db)
148
+ bytedata = (((log_S + self.top_db) * 255 / self.top_db).clip(0, 255) + 0.5).astype(np.uint8)
149
+ image = Image.fromarray(bytedata)
150
+ return image
151
+
152
+ def image_to_audio(self, image: Image.Image) -> np.ndarray:
153
+ """Converts spectrogram to audio.
154
+
155
+ Args:
156
+ image (`PIL Image`): x_res x y_res grayscale image
157
+
158
+ Returns:
159
+ audio (`np.ndarray`): raw audio
160
+ """
161
+ bytedata = np.frombuffer(image.tobytes(), dtype="uint8").reshape((image.height, image.width))
162
+ log_S = bytedata.astype("float") * self.top_db / 255 - self.top_db
163
+ S = librosa.db_to_power(log_S)
164
+ audio = librosa.feature.inverse.mel_to_audio(
165
+ S, sr=self.sr, n_fft=self.n_fft, hop_length=self.hop_length, n_iter=self.n_iter
166
+ )
167
+ return audio
audiodiffusion/pipeline_audio_diffusion.py ADDED
@@ -0,0 +1,257 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This code has been migrated to diffusers but can be run locally with
2
+ # pipe = DiffusionPipeline.from_pretrained("teticio/audio-diffusion-256", custom_pipeline="audio-diffusion/audiodiffusion/pipeline_audio_diffusion.py")
3
+
4
+ # Copyright 2022 The HuggingFace Team. All rights reserved.
5
+ #
6
+ # Licensed under the Apache License, Version 2.0 (the "License");
7
+ # you may not use this file except in compliance with the License.
8
+ # You may obtain a copy of the License at
9
+ #
10
+ # http://www.apache.org/licenses/LICENSE-2.0
11
+ #
12
+ # Unless required by applicable law or agreed to in writing, software
13
+ # distributed under the License is distributed on an "AS IS" BASIS,
14
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
+ # See the License for the specific language governing permissions and
16
+ # limitations under the License.
17
+
18
+
19
+ from math import acos, sin
20
+ from typing import List, Tuple, Union
21
+
22
+ import numpy as np
23
+ import torch
24
+ from diffusers import (
25
+ AudioPipelineOutput,
26
+ AutoencoderKL,
27
+ DDIMScheduler,
28
+ DDPMScheduler,
29
+ DiffusionPipeline,
30
+ ImagePipelineOutput,
31
+ UNet2DConditionModel,
32
+ )
33
+ from diffusers.utils import BaseOutput
34
+ from PIL import Image
35
+
36
+ from .mel import Mel
37
+
38
+ class AudioDiffusionPipeline(DiffusionPipeline):
39
+ """
40
+ This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods the
41
+ library implements for all the pipelines (such as downloading or saving, running on a particular device, etc.)
42
+
43
+ Parameters:
44
+ vqae ([`AutoencoderKL`]): Variational AutoEncoder for Latent Audio Diffusion or None
45
+ unet ([`UNet2DConditionModel`]): UNET model
46
+ mel ([`Mel`]): transform audio <-> spectrogram
47
+ scheduler ([`DDIMScheduler` or `DDPMScheduler`]): de-noising scheduler
48
+ """
49
+
50
+ _optional_components = ["vqvae"]
51
+
52
+ def __init__(
53
+ self,
54
+ vqvae: AutoencoderKL,
55
+ unet: UNet2DConditionModel,
56
+ mel: Mel,
57
+ scheduler: Union[DDIMScheduler, DDPMScheduler],
58
+ ):
59
+ super().__init__()
60
+ self.register_modules(unet=unet, scheduler=scheduler, mel=mel, vqvae=vqvae)
61
+
62
+ def get_default_steps(self) -> int:
63
+ """Returns default number of steps recommended for inference
64
+
65
+ Returns:
66
+ `int`: number of steps
67
+ """
68
+ return 50 if isinstance(self.scheduler, DDIMScheduler) else 1000
69
+
70
+ @torch.no_grad()
71
+ def __call__(
72
+ self,
73
+ batch_size: int = 1,
74
+ audio_file: str = None,
75
+ raw_audio: np.ndarray = None,
76
+ slice: int = 0,
77
+ start_step: int = 0,
78
+ steps: int = None,
79
+ generator: torch.Generator = None,
80
+ mask_start_secs: float = 0,
81
+ mask_end_secs: float = 0,
82
+ step_generator: torch.Generator = None,
83
+ eta: float = 0,
84
+ noise: torch.Tensor = None,
85
+ encoding: torch.Tensor = None,
86
+ return_dict=True,
87
+ ) -> Union[
88
+ Union[AudioPipelineOutput, ImagePipelineOutput],
89
+ Tuple[List[Image.Image], Tuple[int, List[np.ndarray]]],
90
+ ]:
91
+ """Generate random mel spectrogram from audio input and convert to audio.
92
+
93
+ Args:
94
+ batch_size (`int`): number of samples to generate
95
+ audio_file (`str`): must be a file on disk due to Librosa limitation or
96
+ raw_audio (`np.ndarray`): audio as numpy array
97
+ slice (`int`): slice number of audio to convert
98
+ start_step (int): step to start from
99
+ steps (`int`): number of de-noising steps (defaults to 50 for DDIM, 1000 for DDPM)
100
+ generator (`torch.Generator`): random number generator or None
101
+ mask_start_secs (`float`): number of seconds of audio to mask (not generate) at start
102
+ mask_end_secs (`float`): number of seconds of audio to mask (not generate) at end
103
+ step_generator (`torch.Generator`): random number generator used to de-noise or None
104
+ eta (`float`): parameter between 0 and 1 used with DDIM scheduler
105
+ noise (`torch.Tensor`): noise tensor of shape (batch_size, 1, height, width) or None
106
+ encoding (`torch.Tensor`): for UNet2DConditionModel shape (batch_size, seq_length, cross_attention_dim)
107
+ return_dict (`bool`): if True return AudioPipelineOutput, ImagePipelineOutput else Tuple
108
+
109
+ Returns:
110
+ `List[PIL Image]`: mel spectrograms (`float`, `List[np.ndarray]`): sample rate and raw audios
111
+ """
112
+
113
+ steps = steps or self.get_default_steps()
114
+ self.scheduler.set_timesteps(steps)
115
+ step_generator = step_generator or generator
116
+ # For backwards compatibility
117
+ if type(self.unet.sample_size) == int:
118
+ self.unet.sample_size = (self.unet.sample_size, self.unet.sample_size)
119
+ if noise is None:
120
+ noise = torch.randn(
121
+ (
122
+ batch_size,
123
+ self.unet.in_channels,
124
+ self.unet.sample_size[0],
125
+ self.unet.sample_size[1],
126
+ ),
127
+ generator=generator,
128
+ device=self.device,
129
+ )
130
+ images = noise
131
+ mask = None
132
+
133
+ if audio_file is not None or raw_audio is not None:
134
+ self.mel.load_audio(audio_file, raw_audio)
135
+ input_image = self.mel.audio_slice_to_image(slice)
136
+ input_image = np.frombuffer(input_image.tobytes(), dtype="uint8").reshape(
137
+ (input_image.height, input_image.width)
138
+ )
139
+ input_image = (input_image / 255) * 2 - 1
140
+ input_images = torch.tensor(input_image[np.newaxis, :, :], dtype=torch.float).to(self.device)
141
+
142
+ if self.vqvae is not None:
143
+ input_images = self.vqvae.encode(torch.unsqueeze(input_images, 0)).latent_dist.sample(
144
+ generator=generator
145
+ )[0]
146
+ input_images = 0.18215 * input_images
147
+
148
+ if start_step > 0:
149
+ images[0, 0] = self.scheduler.add_noise(input_images, noise, self.scheduler.timesteps[start_step - 1])
150
+
151
+ pixels_per_second = (
152
+ self.unet.sample_size[1] * self.mel.get_sample_rate() / self.mel.x_res / self.mel.hop_length
153
+ )
154
+ mask_start = int(mask_start_secs * pixels_per_second)
155
+ mask_end = int(mask_end_secs * pixels_per_second)
156
+ mask = self.scheduler.add_noise(input_images, noise, torch.tensor(self.scheduler.timesteps[start_step:]))
157
+
158
+ for step, t in enumerate(self.progress_bar(self.scheduler.timesteps[start_step:])):
159
+ if isinstance(self.unet, UNet2DConditionModel):
160
+ model_output = self.unet(images, t, encoding)["sample"]
161
+ else:
162
+ model_output = self.unet(images, t)["sample"]
163
+
164
+ if isinstance(self.scheduler, DDIMScheduler):
165
+ images = self.scheduler.step(
166
+ model_output=model_output,
167
+ timestep=t,
168
+ sample=images,
169
+ eta=eta,
170
+ generator=step_generator,
171
+ )["prev_sample"]
172
+ else:
173
+ images = self.scheduler.step(
174
+ model_output=model_output,
175
+ timestep=t,
176
+ sample=images,
177
+ generator=step_generator,
178
+ )["prev_sample"]
179
+
180
+ if mask is not None:
181
+ if mask_start > 0:
182
+ images[:, :, :, :mask_start] = mask[:, step, :, :mask_start]
183
+ if mask_end > 0:
184
+ images[:, :, :, -mask_end:] = mask[:, step, :, -mask_end:]
185
+
186
+ if self.vqvae is not None:
187
+ # 0.18215 was scaling factor used in training to ensure unit variance
188
+ images = 1 / 0.18215 * images
189
+ images = self.vqvae.decode(images)["sample"]
190
+
191
+ images = (images / 2 + 0.5).clamp(0, 1)
192
+ images = images.cpu().permute(0, 2, 3, 1).numpy()
193
+ images = (images * 255).round().astype("uint8")
194
+ images = list(
195
+ map(lambda _: Image.fromarray(_[:, :, 0]), images)
196
+ if images.shape[3] == 1
197
+ else map(lambda _: Image.fromarray(_, mode="RGB").convert("L"), images)
198
+ )
199
+
200
+ audios = list(map(lambda _: self.mel.image_to_audio(_), images))
201
+ if not return_dict:
202
+ return images, (self.mel.get_sample_rate(), audios)
203
+
204
+ return BaseOutput(**AudioPipelineOutput(np.array(audios)[:, np.newaxis, :]), **ImagePipelineOutput(images))
205
+
206
+ @torch.no_grad()
207
+ def encode(self, images: List[Image.Image], steps: int = 50) -> np.ndarray:
208
+ """Reverse step process: recover noisy image from generated image.
209
+
210
+ Args:
211
+ images (`List[PIL Image]`): list of images to encode
212
+ steps (`int`): number of encoding steps to perform (defaults to 50)
213
+
214
+ Returns:
215
+ `np.ndarray`: noise tensor of shape (batch_size, 1, height, width)
216
+ """
217
+
218
+ # Only works with DDIM as this method is deterministic
219
+ assert isinstance(self.scheduler, DDIMScheduler)
220
+ self.scheduler.set_timesteps(steps)
221
+ sample = np.array(
222
+ [np.frombuffer(image.tobytes(), dtype="uint8").reshape((1, image.height, image.width)) for image in images]
223
+ )
224
+ sample = (sample / 255) * 2 - 1
225
+ sample = torch.Tensor(sample).to(self.device)
226
+
227
+ for t in self.progress_bar(torch.flip(self.scheduler.timesteps, (0,))):
228
+ prev_timestep = t - self.scheduler.config.num_train_timesteps // self.scheduler.num_inference_steps
229
+ alpha_prod_t = self.scheduler.alphas_cumprod[t]
230
+ alpha_prod_t_prev = (
231
+ self.scheduler.alphas_cumprod[prev_timestep]
232
+ if prev_timestep >= 0
233
+ else self.scheduler.final_alpha_cumprod
234
+ )
235
+ beta_prod_t = 1 - alpha_prod_t
236
+ model_output = self.unet(sample, t)["sample"]
237
+ pred_sample_direction = (1 - alpha_prod_t_prev) ** (0.5) * model_output
238
+ sample = (sample - pred_sample_direction) * alpha_prod_t_prev ** (-0.5)
239
+ sample = sample * alpha_prod_t ** (0.5) + beta_prod_t ** (0.5) * model_output
240
+
241
+ return sample
242
+
243
+ @staticmethod
244
+ def slerp(x0: torch.Tensor, x1: torch.Tensor, alpha: float) -> torch.Tensor:
245
+ """Spherical Linear intERPolation
246
+
247
+ Args:
248
+ x0 (`torch.Tensor`): first tensor to interpolate between
249
+ x1 (`torch.Tensor`): seconds tensor to interpolate between
250
+ alpha (`float`): interpolation between 0 and 1
251
+
252
+ Returns:
253
+ `torch.Tensor`: interpolated tensor
254
+ """
255
+
256
+ theta = acos(torch.dot(torch.flatten(x0), torch.flatten(x1)) / torch.norm(x0) / torch.norm(x1))
257
+ return sin((1 - alpha) * theta) * x0 / sin(theta) + sin(alpha * theta) * x1 / sin(theta)
audiodiffusion/utils.py ADDED
@@ -0,0 +1,303 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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(new_item, n_shave_prefix_segments=n_shave_prefix_segments)
27
+
28
+ mapping.append({"old": old_item, "new": new_item})
29
+
30
+ return mapping
31
+
32
+
33
+ def renew_vae_attention_paths(old_list, n_shave_prefix_segments=0):
34
+ """
35
+ Updates paths inside attentions to the new naming scheme (local renaming)
36
+ """
37
+ mapping = []
38
+ for old_item in old_list:
39
+ new_item = old_item
40
+
41
+ new_item = new_item.replace("norm.weight", "group_norm.weight")
42
+ new_item = new_item.replace("norm.bias", "group_norm.bias")
43
+
44
+ new_item = new_item.replace("q.weight", "query.weight")
45
+ new_item = new_item.replace("q.bias", "query.bias")
46
+
47
+ new_item = new_item.replace("k.weight", "key.weight")
48
+ new_item = new_item.replace("k.bias", "key.bias")
49
+
50
+ new_item = new_item.replace("v.weight", "value.weight")
51
+ new_item = new_item.replace("v.bias", "value.bias")
52
+
53
+ new_item = new_item.replace("proj_out.weight", "proj_attn.weight")
54
+ new_item = new_item.replace("proj_out.bias", "proj_attn.bias")
55
+
56
+ new_item = shave_segments(new_item, n_shave_prefix_segments=n_shave_prefix_segments)
57
+
58
+ mapping.append({"old": old_item, "new": new_item})
59
+
60
+ return mapping
61
+
62
+
63
+ def assign_to_checkpoint(
64
+ paths,
65
+ checkpoint,
66
+ old_checkpoint,
67
+ attention_paths_to_split=None,
68
+ additional_replacements=None,
69
+ config=None,
70
+ ):
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(paths, list), "Paths should be a list of dicts containing 'old' and 'new' keys."
79
+
80
+ # Splits the attention layers into three variables.
81
+ if attention_paths_to_split is not None:
82
+ for path, path_map in attention_paths_to_split.items():
83
+ old_tensor = old_checkpoint[path]
84
+ channels = old_tensor.shape[0] // 3
85
+
86
+ target_shape = (-1, channels) if len(old_tensor.shape) == 3 else (-1)
87
+
88
+ num_heads = old_tensor.shape[0] // config["num_head_channels"] // 3
89
+
90
+ old_tensor = old_tensor.reshape((num_heads, 3 * channels // num_heads) + old_tensor.shape[1:])
91
+ query, key, value = old_tensor.split(channels // num_heads, dim=1)
92
+
93
+ checkpoint[path_map["query"]] = query.reshape(target_shape)
94
+ checkpoint[path_map["key"]] = key.reshape(target_shape)
95
+ checkpoint[path_map["value"]] = value.reshape(target_shape)
96
+
97
+ for path in paths:
98
+ new_path = path["new"]
99
+
100
+ # These have already been assigned
101
+ if attention_paths_to_split is not None and new_path in attention_paths_to_split:
102
+ continue
103
+
104
+ # Global renaming happens here
105
+ new_path = new_path.replace("middle_block.0", "mid_block.resnets.0")
106
+ new_path = new_path.replace("middle_block.1", "mid_block.attentions.0")
107
+ new_path = new_path.replace("middle_block.2", "mid_block.resnets.1")
108
+
109
+ if additional_replacements is not None:
110
+ for replacement in additional_replacements:
111
+ new_path = new_path.replace(replacement["old"], replacement["new"])
112
+
113
+ # proj_attn.weight has to be converted from conv 1D to linear
114
+ if "proj_attn.weight" in new_path:
115
+ checkpoint[new_path] = old_checkpoint[path["old"]][:, :, 0]
116
+ else:
117
+ checkpoint[new_path] = old_checkpoint[path["old"]]
118
+
119
+
120
+ def conv_attn_to_linear(checkpoint):
121
+ keys = list(checkpoint.keys())
122
+ attn_keys = ["query.weight", "key.weight", "value.weight"]
123
+ for key in keys:
124
+ if ".".join(key.split(".")[-2:]) in attn_keys:
125
+ if checkpoint[key].ndim > 2:
126
+ checkpoint[key] = checkpoint[key][:, :, 0, 0]
127
+ elif "proj_attn.weight" in key:
128
+ if checkpoint[key].ndim > 2:
129
+ checkpoint[key] = checkpoint[key][:, :, 0]
130
+
131
+
132
+ def create_vae_diffusers_config(original_config):
133
+ """
134
+ Creates a config for the diffusers based on the config of the LDM model.
135
+ """
136
+ vae_params = original_config.model.params.ddconfig
137
+ _ = original_config.model.params.embed_dim
138
+
139
+ block_out_channels = [vae_params.ch * mult for mult in vae_params.ch_mult]
140
+ down_block_types = ["DownEncoderBlock2D"] * len(block_out_channels)
141
+ up_block_types = ["UpDecoderBlock2D"] * len(block_out_channels)
142
+
143
+ config = dict(
144
+ sample_size=tuple(vae_params.resolution),
145
+ in_channels=vae_params.in_channels,
146
+ out_channels=vae_params.out_ch,
147
+ down_block_types=tuple(down_block_types),
148
+ up_block_types=tuple(up_block_types),
149
+ block_out_channels=tuple(block_out_channels),
150
+ latent_channels=vae_params.z_channels,
151
+ layers_per_block=vae_params.num_res_blocks,
152
+ )
153
+ return config
154
+
155
+
156
+ def convert_ldm_vae_checkpoint(checkpoint, config):
157
+ # extract state dict for VAE
158
+ vae_state_dict = checkpoint
159
+
160
+ new_checkpoint = {}
161
+
162
+ new_checkpoint["encoder.conv_in.weight"] = vae_state_dict["encoder.conv_in.weight"]
163
+ new_checkpoint["encoder.conv_in.bias"] = vae_state_dict["encoder.conv_in.bias"]
164
+ new_checkpoint["encoder.conv_out.weight"] = vae_state_dict["encoder.conv_out.weight"]
165
+ new_checkpoint["encoder.conv_out.bias"] = vae_state_dict["encoder.conv_out.bias"]
166
+ new_checkpoint["encoder.conv_norm_out.weight"] = vae_state_dict["encoder.norm_out.weight"]
167
+ new_checkpoint["encoder.conv_norm_out.bias"] = vae_state_dict["encoder.norm_out.bias"]
168
+
169
+ new_checkpoint["decoder.conv_in.weight"] = vae_state_dict["decoder.conv_in.weight"]
170
+ new_checkpoint["decoder.conv_in.bias"] = vae_state_dict["decoder.conv_in.bias"]
171
+ new_checkpoint["decoder.conv_out.weight"] = vae_state_dict["decoder.conv_out.weight"]
172
+ new_checkpoint["decoder.conv_out.bias"] = vae_state_dict["decoder.conv_out.bias"]
173
+ new_checkpoint["decoder.conv_norm_out.weight"] = vae_state_dict["decoder.norm_out.weight"]
174
+ new_checkpoint["decoder.conv_norm_out.bias"] = vae_state_dict["decoder.norm_out.bias"]
175
+
176
+ new_checkpoint["quant_conv.weight"] = vae_state_dict["quant_conv.weight"]
177
+ new_checkpoint["quant_conv.bias"] = vae_state_dict["quant_conv.bias"]
178
+ new_checkpoint["post_quant_conv.weight"] = vae_state_dict["post_quant_conv.weight"]
179
+ new_checkpoint["post_quant_conv.bias"] = vae_state_dict["post_quant_conv.bias"]
180
+
181
+ # Retrieves the keys for the encoder down blocks only
182
+ num_down_blocks = len({".".join(layer.split(".")[:3]) for layer in vae_state_dict if "encoder.down" in layer})
183
+ down_blocks = {
184
+ layer_id: [key for key in vae_state_dict if f"down.{layer_id}" in key] for layer_id in range(num_down_blocks)
185
+ }
186
+
187
+ # Retrieves the keys for the decoder up blocks only
188
+ num_up_blocks = len({".".join(layer.split(".")[:3]) for layer in vae_state_dict if "decoder.up" in layer})
189
+ up_blocks = {
190
+ layer_id: [key for key in vae_state_dict if f"up.{layer_id}" in key] for layer_id in range(num_up_blocks)
191
+ }
192
+
193
+ for i in range(num_down_blocks):
194
+ resnets = [key for key in down_blocks[i] if f"down.{i}" in key and f"down.{i}.downsample" not in key]
195
+
196
+ if f"encoder.down.{i}.downsample.conv.weight" in vae_state_dict:
197
+ new_checkpoint[f"encoder.down_blocks.{i}.downsamplers.0.conv.weight"] = vae_state_dict.pop(
198
+ f"encoder.down.{i}.downsample.conv.weight"
199
+ )
200
+ new_checkpoint[f"encoder.down_blocks.{i}.downsamplers.0.conv.bias"] = vae_state_dict.pop(
201
+ f"encoder.down.{i}.downsample.conv.bias"
202
+ )
203
+
204
+ paths = renew_vae_resnet_paths(resnets)
205
+ meta_path = {"old": f"down.{i}.block", "new": f"down_blocks.{i}.resnets"}
206
+ assign_to_checkpoint(
207
+ paths,
208
+ new_checkpoint,
209
+ vae_state_dict,
210
+ additional_replacements=[meta_path],
211
+ config=config,
212
+ )
213
+
214
+ mid_resnets = [key for key in vae_state_dict if "encoder.mid.block" in key]
215
+ num_mid_res_blocks = 2
216
+ for i in range(1, num_mid_res_blocks + 1):
217
+ resnets = [key for key in mid_resnets if f"encoder.mid.block_{i}" in key]
218
+
219
+ paths = renew_vae_resnet_paths(resnets)
220
+ meta_path = {"old": f"mid.block_{i}", "new": f"mid_block.resnets.{i - 1}"}
221
+ assign_to_checkpoint(
222
+ paths,
223
+ new_checkpoint,
224
+ vae_state_dict,
225
+ additional_replacements=[meta_path],
226
+ config=config,
227
+ )
228
+
229
+ mid_attentions = [key for key in vae_state_dict if "encoder.mid.attn" in key]
230
+ paths = renew_vae_attention_paths(mid_attentions)
231
+ meta_path = {"old": "mid.attn_1", "new": "mid_block.attentions.0"}
232
+ assign_to_checkpoint(
233
+ paths,
234
+ new_checkpoint,
235
+ vae_state_dict,
236
+ additional_replacements=[meta_path],
237
+ config=config,
238
+ )
239
+ conv_attn_to_linear(new_checkpoint)
240
+
241
+ for i in range(num_up_blocks):
242
+ block_id = num_up_blocks - 1 - i
243
+ resnets = [
244
+ key for key in up_blocks[block_id] if f"up.{block_id}" in key and f"up.{block_id}.upsample" not in key
245
+ ]
246
+
247
+ if f"decoder.up.{block_id}.upsample.conv.weight" in vae_state_dict:
248
+ new_checkpoint[f"decoder.up_blocks.{i}.upsamplers.0.conv.weight"] = vae_state_dict[
249
+ f"decoder.up.{block_id}.upsample.conv.weight"
250
+ ]
251
+ new_checkpoint[f"decoder.up_blocks.{i}.upsamplers.0.conv.bias"] = vae_state_dict[
252
+ f"decoder.up.{block_id}.upsample.conv.bias"
253
+ ]
254
+
255
+ paths = renew_vae_resnet_paths(resnets)
256
+ meta_path = {"old": f"up.{block_id}.block", "new": f"up_blocks.{i}.resnets"}
257
+ assign_to_checkpoint(
258
+ paths,
259
+ new_checkpoint,
260
+ vae_state_dict,
261
+ additional_replacements=[meta_path],
262
+ config=config,
263
+ )
264
+
265
+ mid_resnets = [key for key in vae_state_dict if "decoder.mid.block" in key]
266
+ num_mid_res_blocks = 2
267
+ for i in range(1, num_mid_res_blocks + 1):
268
+ resnets = [key for key in mid_resnets if f"decoder.mid.block_{i}" in key]
269
+
270
+ paths = renew_vae_resnet_paths(resnets)
271
+ meta_path = {"old": f"mid.block_{i}", "new": f"mid_block.resnets.{i - 1}"}
272
+ assign_to_checkpoint(
273
+ paths,
274
+ new_checkpoint,
275
+ vae_state_dict,
276
+ additional_replacements=[meta_path],
277
+ config=config,
278
+ )
279
+
280
+ mid_attentions = [key for key in vae_state_dict if "decoder.mid.attn" in key]
281
+ paths = renew_vae_attention_paths(mid_attentions)
282
+ meta_path = {"old": "mid.attn_1", "new": "mid_block.attentions.0"}
283
+ assign_to_checkpoint(
284
+ paths,
285
+ new_checkpoint,
286
+ vae_state_dict,
287
+ additional_replacements=[meta_path],
288
+ config=config,
289
+ )
290
+ conv_attn_to_linear(new_checkpoint)
291
+ return new_checkpoint
292
+
293
+
294
+ def convert_ldm_to_hf_vae(ldm_checkpoint, ldm_config, hf_checkpoint, sample_size):
295
+ checkpoint = torch.load(ldm_checkpoint)["state_dict"]
296
+
297
+ # Convert the VAE model.
298
+ vae_config = create_vae_diffusers_config(ldm_config)
299
+ converted_vae_checkpoint = convert_ldm_vae_checkpoint(checkpoint, vae_config)
300
+
301
+ vae = AutoencoderKL(**vae_config)
302
+ vae.load_state_dict(converted_vae_checkpoint)
303
+ 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 # overriden by input image size
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
notebooks/audio_diffusion_pipeline.ipynb ADDED
@@ -0,0 +1,687 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "markdown",
5
+ "id": "fef7e1fb",
6
+ "metadata": {},
7
+ "source": [
8
+ "<a href=\"https://colab.research.google.com/github/teticio/audio-diffusion/blob/master/notebooks/audio_diffusion_pipeline.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": "markdown",
13
+ "id": "2ada074b",
14
+ "metadata": {},
15
+ "source": [
16
+ "# Audio Diffusion\n",
17
+ "For training scripts and notebooks visit https://github.com/teticio/audio-diffusion"
18
+ ]
19
+ },
20
+ {
21
+ "cell_type": "code",
22
+ "execution_count": null,
23
+ "id": "6c7800a6",
24
+ "metadata": {},
25
+ "outputs": [],
26
+ "source": [
27
+ "try:\n",
28
+ " # are we running on Google Colab?\n",
29
+ " import google.colab\n",
30
+ " %pip install -q diffusers torch librosa datasets\n",
31
+ "except:\n",
32
+ " pass"
33
+ ]
34
+ },
35
+ {
36
+ "cell_type": "code",
37
+ "execution_count": null,
38
+ "id": "c2fc0e7a",
39
+ "metadata": {},
40
+ "outputs": [],
41
+ "source": [
42
+ "import torch\n",
43
+ "import random\n",
44
+ "import librosa\n",
45
+ "import numpy as np\n",
46
+ "from datasets import load_dataset\n",
47
+ "from IPython.display import Audio\n",
48
+ "from librosa.beat import beat_track\n",
49
+ "from diffusers import DiffusionPipeline"
50
+ ]
51
+ },
52
+ {
53
+ "cell_type": "code",
54
+ "execution_count": null,
55
+ "id": "b294a94a",
56
+ "metadata": {},
57
+ "outputs": [],
58
+ "source": [
59
+ "device = \"cuda\" if torch.cuda.is_available() else \"cpu\"\n",
60
+ "generator = torch.Generator(device=device)"
61
+ ]
62
+ },
63
+ {
64
+ "cell_type": "markdown",
65
+ "id": "f3feb265",
66
+ "metadata": {},
67
+ "source": [
68
+ "## DDPM (De-noising Diffusion Probabilistic Models)"
69
+ ]
70
+ },
71
+ {
72
+ "cell_type": "markdown",
73
+ "id": "7fd945bb",
74
+ "metadata": {},
75
+ "source": [
76
+ "### Select model"
77
+ ]
78
+ },
79
+ {
80
+ "cell_type": "code",
81
+ "execution_count": null,
82
+ "id": "97f24046",
83
+ "metadata": {},
84
+ "outputs": [],
85
+ "source": [
86
+ "#@markdown teticio/audio-diffusion-256 - trained on my Spotify \"liked\" playlist\n",
87
+ "\n",
88
+ "#@markdown teticio/audio-diffusion-breaks-256 - trained on samples used in music\n",
89
+ "\n",
90
+ "#@markdown teticio/audio-diffusion-instrumental-hiphop-256 - trained on instrumental hiphop\n",
91
+ "\n",
92
+ "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\"]"
93
+ ]
94
+ },
95
+ {
96
+ "cell_type": "code",
97
+ "execution_count": null,
98
+ "id": "a3d45c36",
99
+ "metadata": {},
100
+ "outputs": [],
101
+ "source": [
102
+ "audio_diffusion = DiffusionPipeline.from_pretrained(model_id).to(device)\n",
103
+ "mel = audio_diffusion.mel\n",
104
+ "sample_rate = mel.get_sample_rate()"
105
+ ]
106
+ },
107
+ {
108
+ "cell_type": "code",
109
+ "execution_count": null,
110
+ "id": "ab0d705c",
111
+ "metadata": {},
112
+ "outputs": [],
113
+ "source": [
114
+ "def loop_it(audio: np.ndarray,\n",
115
+ " sample_rate: int,\n",
116
+ " loops: int = 12) -> np.ndarray:\n",
117
+ " \"\"\"Loop audio\n",
118
+ "\n",
119
+ " Args:\n",
120
+ " audio (np.ndarray): audio as numpy array\n",
121
+ " sample_rate (int): sample rate of audio\n",
122
+ " loops (int): number of times to loop\n",
123
+ "\n",
124
+ " Returns:\n",
125
+ " (float, np.ndarray): sample rate and raw audio or None\n",
126
+ " \"\"\"\n",
127
+ " _, beats = beat_track(y=audio, sr=sample_rate, units='samples')\n",
128
+ " for beats_in_bar in [16, 12, 8, 4]:\n",
129
+ " if len(beats) > beats_in_bar:\n",
130
+ " return np.tile(audio[beats[0]:beats[beats_in_bar]], loops)\n",
131
+ " return None"
132
+ ]
133
+ },
134
+ {
135
+ "cell_type": "markdown",
136
+ "id": "011fb5a1",
137
+ "metadata": {},
138
+ "source": [
139
+ "### Run model inference to generate mel spectrogram, audios and loops"
140
+ ]
141
+ },
142
+ {
143
+ "cell_type": "code",
144
+ "execution_count": null,
145
+ "id": "b809fed5",
146
+ "metadata": {},
147
+ "outputs": [],
148
+ "source": [
149
+ "for _ in range(10):\n",
150
+ " seed = generator.seed()\n",
151
+ " print(f'Seed = {seed}')\n",
152
+ " generator.manual_seed(seed)\n",
153
+ " output = audio_diffusion(generator=generator)\n",
154
+ " image = output.images[0]\n",
155
+ " audio = output.audios[0, 0]\n",
156
+ " display(image)\n",
157
+ " display(Audio(audio, rate=sample_rate))\n",
158
+ " loop = loop_it(audio, sample_rate)\n",
159
+ " if loop is not None:\n",
160
+ " display(Audio(loop, rate=sample_rate))\n",
161
+ " else:\n",
162
+ " print(\"Unable to determine loop points\")"
163
+ ]
164
+ },
165
+ {
166
+ "cell_type": "markdown",
167
+ "id": "0bb03e33",
168
+ "metadata": {},
169
+ "source": [
170
+ "### Generate variations of audios"
171
+ ]
172
+ },
173
+ {
174
+ "cell_type": "markdown",
175
+ "id": "80e5b5fa",
176
+ "metadata": {},
177
+ "source": [
178
+ "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."
179
+ ]
180
+ },
181
+ {
182
+ "cell_type": "code",
183
+ "execution_count": null,
184
+ "id": "5074ec11",
185
+ "metadata": {},
186
+ "outputs": [],
187
+ "source": [
188
+ "seed = 2391504374279719 #@param {type:\"integer\"}\n",
189
+ "generator.manual_seed(seed)\n",
190
+ "output = audio_diffusion(generator=generator)\n",
191
+ "image = output.images[0]\n",
192
+ "audio = output.audios[0, 0]\n",
193
+ "display(image)\n",
194
+ "display(Audio(audio, rate=sample_rate))"
195
+ ]
196
+ },
197
+ {
198
+ "cell_type": "code",
199
+ "execution_count": null,
200
+ "id": "a0fefe28",
201
+ "metadata": {
202
+ "scrolled": false
203
+ },
204
+ "outputs": [],
205
+ "source": [
206
+ "start_step = 500 #@param {type:\"slider\", min:0, max:1000, step:10}\n",
207
+ "track = loop_it(audio, sample_rate, loops=1)\n",
208
+ "for variation in range(12):\n",
209
+ " output = audio_diffusion(raw_audio=audio, start_step=start_step)\n",
210
+ " image2 = output.images[0]\n",
211
+ " audio2 = output.audios[0, 0]\n",
212
+ " display(image2)\n",
213
+ " display(Audio(audio2, rate=sample_rate))\n",
214
+ " track = np.concatenate([track, loop_it(audio2, sample_rate, loops=1)])\n",
215
+ "display(Audio(track, rate=sample_rate))"
216
+ ]
217
+ },
218
+ {
219
+ "cell_type": "markdown",
220
+ "id": "58a876c1",
221
+ "metadata": {},
222
+ "source": [
223
+ "### Generate continuations (\"out-painting\")"
224
+ ]
225
+ },
226
+ {
227
+ "cell_type": "code",
228
+ "execution_count": null,
229
+ "id": "b95d5780",
230
+ "metadata": {},
231
+ "outputs": [],
232
+ "source": [
233
+ "overlap_secs = 2 #@param {type:\"integer\"}\n",
234
+ "start_step = 0 #@param {type:\"slider\", min:0, max:1000, step:10}\n",
235
+ "overlap_samples = overlap_secs * sample_rate\n",
236
+ "track = audio\n",
237
+ "for variation in range(12):\n",
238
+ " output = audio_diffusion(raw_audio=audio[-overlap_samples:],\n",
239
+ " start_step=start_step,\n",
240
+ " mask_start_secs=overlap_secs)\n",
241
+ " image2 = output.images[0]\n",
242
+ " audio2 = output.audios[0, 0]\n",
243
+ " display(image2)\n",
244
+ " display(Audio(audio2, rate=sample_rate))\n",
245
+ " track = np.concatenate([track, audio2[overlap_samples:]])\n",
246
+ " audio = audio2\n",
247
+ "display(Audio(track, rate=sample_rate))"
248
+ ]
249
+ },
250
+ {
251
+ "cell_type": "markdown",
252
+ "id": "b6434d3f",
253
+ "metadata": {},
254
+ "source": [
255
+ "### Remix (style transfer)"
256
+ ]
257
+ },
258
+ {
259
+ "cell_type": "markdown",
260
+ "id": "0da030b2",
261
+ "metadata": {},
262
+ "source": [
263
+ "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."
264
+ ]
265
+ },
266
+ {
267
+ "cell_type": "code",
268
+ "execution_count": null,
269
+ "id": "fc620a80",
270
+ "metadata": {},
271
+ "outputs": [],
272
+ "source": [
273
+ "try:\n",
274
+ " # are we running on Google Colab?\n",
275
+ " from google.colab import files\n",
276
+ " audio_file = list(files.upload().keys())[0]\n",
277
+ "except:\n",
278
+ " audio_file = \"/home/teticio/Music/liked/El Michels Affair - Glaciers Of Ice.mp3\""
279
+ ]
280
+ },
281
+ {
282
+ "cell_type": "code",
283
+ "execution_count": null,
284
+ "id": "5a257e69",
285
+ "metadata": {
286
+ "scrolled": false
287
+ },
288
+ "outputs": [],
289
+ "source": [
290
+ "start_step = 500 #@param {type:\"slider\", min:0, max:1000, step:10}\n",
291
+ "overlap_secs = 2 #@param {type:\"integer\"}\n",
292
+ "track_audio, _ = librosa.load(audio_file, mono=True, sr=sample_rate)\n",
293
+ "overlap_samples = overlap_secs * sample_rate\n",
294
+ "slice_size = mel.x_res * mel.hop_length\n",
295
+ "stride = slice_size - overlap_samples\n",
296
+ "generator = torch.Generator(device=device)\n",
297
+ "seed = generator.seed()\n",
298
+ "print(f'Seed = {seed}')\n",
299
+ "track = np.array([])\n",
300
+ "not_first = 0\n",
301
+ "for sample in range(len(track_audio) // stride):\n",
302
+ " generator.manual_seed(seed)\n",
303
+ " audio = np.array(track_audio[sample * stride:sample * stride + slice_size])\n",
304
+ " if not_first:\n",
305
+ " # Normalize and re-insert generated audio\n",
306
+ " audio[:overlap_samples] = audio2[-overlap_samples:] * np.max(\n",
307
+ " audio[:overlap_samples]) / np.max(audio2[-overlap_samples:])\n",
308
+ " output = audio_diffusion(raw_audio=audio,\n",
309
+ " start_step=start_step,\n",
310
+ " generator=generator,\n",
311
+ " mask_start_secs=overlap_secs * not_first)\n",
312
+ " audio2 = output.audios[0, 0]\n",
313
+ " track = np.concatenate([track, audio2[overlap_samples * not_first:]])\n",
314
+ " not_first = 1\n",
315
+ " display(Audio(track, rate=sample_rate))"
316
+ ]
317
+ },
318
+ {
319
+ "cell_type": "markdown",
320
+ "id": "924ff9d5",
321
+ "metadata": {},
322
+ "source": [
323
+ "### Fill the gap (\"in-painting\")"
324
+ ]
325
+ },
326
+ {
327
+ "cell_type": "code",
328
+ "execution_count": null,
329
+ "id": "0200264c",
330
+ "metadata": {},
331
+ "outputs": [],
332
+ "source": [
333
+ "sample = 3 #@param {type:\"integer\"}\n",
334
+ "raw_audio = track_audio[sample * stride:sample * stride + slice_size]\n",
335
+ "output = audio_diffusion(raw_audio=raw_audio,\n",
336
+ " mask_start_secs=1,\n",
337
+ " mask_end_secs=1,\n",
338
+ " step_generator=torch.Generator(device=device))\n",
339
+ "audio2 = output.audios[0, 0]\n",
340
+ "display(Audio(audio, rate=sample_rate))\n",
341
+ "display(Audio(audio2, rate=sample_rate))"
342
+ ]
343
+ },
344
+ {
345
+ "cell_type": "markdown",
346
+ "id": "efc32dae",
347
+ "metadata": {},
348
+ "source": [
349
+ "## DDIM (De-noising Diffusion Implicit Models)"
350
+ ]
351
+ },
352
+ {
353
+ "cell_type": "code",
354
+ "execution_count": null,
355
+ "id": "a021f78a",
356
+ "metadata": {},
357
+ "outputs": [],
358
+ "source": [
359
+ "audio_diffusion = DiffusionPipeline.from_pretrained('teticio/audio-diffusion-ddim-256').to(device)\n",
360
+ "mel = audio_diffusion.mel\n",
361
+ "sample_rate = mel.get_sample_rate()"
362
+ ]
363
+ },
364
+ {
365
+ "cell_type": "markdown",
366
+ "id": "deb23339",
367
+ "metadata": {},
368
+ "source": [
369
+ "### Generation can be done in many fewer steps with DDIMs"
370
+ ]
371
+ },
372
+ {
373
+ "cell_type": "code",
374
+ "execution_count": null,
375
+ "id": "c105a497",
376
+ "metadata": {},
377
+ "outputs": [],
378
+ "source": [
379
+ "for _ in range(10):\n",
380
+ " seed = generator.seed()\n",
381
+ " print(f'Seed = {seed}')\n",
382
+ " generator.manual_seed(seed)\n",
383
+ " output = audio_diffusion(generator=generator)\n",
384
+ " image = output.images[0]\n",
385
+ " audio = output.audios[0, 0]\n",
386
+ " display(image)\n",
387
+ " display(Audio(audio, rate=sample_rate))\n",
388
+ " loop = loop_it(audio, sample_rate)\n",
389
+ " if loop is not None:\n",
390
+ " display(Audio(loop, rate=sample_rate))\n",
391
+ " else:\n",
392
+ " print(\"Unable to determine loop points\")"
393
+ ]
394
+ },
395
+ {
396
+ "cell_type": "markdown",
397
+ "id": "cab4692c",
398
+ "metadata": {},
399
+ "source": [
400
+ "The parameter eta controls the variance:\n",
401
+ "* 0 - DDIM (deterministic)\n",
402
+ "* 1 - DDPM (De-noising Diffusion Probabilistic Model)"
403
+ ]
404
+ },
405
+ {
406
+ "cell_type": "code",
407
+ "execution_count": null,
408
+ "id": "72bdd207",
409
+ "metadata": {},
410
+ "outputs": [],
411
+ "source": [
412
+ "output = audio_diffusion(steps=1000, generator=generator, eta=1)\n",
413
+ "image = output.images[0]\n",
414
+ "audio = output.audios[0, 0]\n",
415
+ "display(image)\n",
416
+ "display(Audio(audio, rate=sample_rate))"
417
+ ]
418
+ },
419
+ {
420
+ "cell_type": "markdown",
421
+ "id": "b8d5442c",
422
+ "metadata": {},
423
+ "source": [
424
+ "### DDIMs can be used as encoders..."
425
+ ]
426
+ },
427
+ {
428
+ "cell_type": "code",
429
+ "execution_count": null,
430
+ "id": "269ee816",
431
+ "metadata": {},
432
+ "outputs": [],
433
+ "source": [
434
+ "# Doesn't have to be an audio from the train dataset, this is just for convenience\n",
435
+ "ds = load_dataset('teticio/audio-diffusion-256')"
436
+ ]
437
+ },
438
+ {
439
+ "cell_type": "code",
440
+ "execution_count": null,
441
+ "id": "278d1d80",
442
+ "metadata": {},
443
+ "outputs": [],
444
+ "source": [
445
+ "image = ds['train'][264]['image']\n",
446
+ "display(Audio(mel.image_to_audio(image), rate=sample_rate))"
447
+ ]
448
+ },
449
+ {
450
+ "cell_type": "code",
451
+ "execution_count": null,
452
+ "id": "912b54e4",
453
+ "metadata": {},
454
+ "outputs": [],
455
+ "source": [
456
+ "noise = audio_diffusion.encode([image])"
457
+ ]
458
+ },
459
+ {
460
+ "cell_type": "code",
461
+ "execution_count": null,
462
+ "id": "c7b31f97",
463
+ "metadata": {},
464
+ "outputs": [],
465
+ "source": [
466
+ "# Reconstruct original audio from noise\n",
467
+ "output = audio_diffusion(noise=noise, generator=generator)\n",
468
+ "image = output.images[0]\n",
469
+ "audio = output.audios[0, 0]\n",
470
+ "display(Audio(audio, rate=sample_rate))"
471
+ ]
472
+ },
473
+ {
474
+ "cell_type": "markdown",
475
+ "id": "998c776b",
476
+ "metadata": {},
477
+ "source": [
478
+ "### ...or to interpolate between audios"
479
+ ]
480
+ },
481
+ {
482
+ "cell_type": "code",
483
+ "execution_count": null,
484
+ "id": "33f82367",
485
+ "metadata": {},
486
+ "outputs": [],
487
+ "source": [
488
+ "image2 = ds['train'][15978]['image']\n",
489
+ "display(Audio(mel.image_to_audio(image2), rate=sample_rate))"
490
+ ]
491
+ },
492
+ {
493
+ "cell_type": "code",
494
+ "execution_count": null,
495
+ "id": "f93fb6c0",
496
+ "metadata": {},
497
+ "outputs": [],
498
+ "source": [
499
+ "noise2 = audio_diffusion.encode([image2])"
500
+ ]
501
+ },
502
+ {
503
+ "cell_type": "code",
504
+ "execution_count": null,
505
+ "id": "a4190563",
506
+ "metadata": {},
507
+ "outputs": [],
508
+ "source": [
509
+ "alpha = 0.5 #@param {type:\"slider\", min:0, max:1, step:0.1}\n",
510
+ "output = audio_diffusion(\n",
511
+ " noise=audio_diffusion.slerp(noise, noise2, alpha),\n",
512
+ " generator=generator)\n",
513
+ "audio = output.audios[0, 0]\n",
514
+ "display(Audio(mel.image_to_audio(image), rate=sample_rate))\n",
515
+ "display(Audio(mel.image_to_audio(image2), rate=sample_rate))\n",
516
+ "display(Audio(audio, rate=sample_rate))"
517
+ ]
518
+ },
519
+ {
520
+ "cell_type": "markdown",
521
+ "id": "9b244547",
522
+ "metadata": {},
523
+ "source": [
524
+ "## Latent Audio Diffusion\n",
525
+ "Instead of de-noising images directly in the pixel space, we can work in the latent space of a pre-trained VAE (Variational AutoEncoder). This is much faster to train and run inference on, although the quality suffers as there are now three stages involved in encoding / decoding: mel spectrogram, VAE and de-noising."
526
+ ]
527
+ },
528
+ {
529
+ "cell_type": "code",
530
+ "execution_count": null,
531
+ "id": "a88b3fbb",
532
+ "metadata": {},
533
+ "outputs": [],
534
+ "source": [
535
+ "model_id = \"teticio/latent-audio-diffusion-ddim-256\" #@param [\"teticio/latent-audio-diffusion-256\", \"teticio/latent-audio-diffusion-ddim-256\"]"
536
+ ]
537
+ },
538
+ {
539
+ "cell_type": "code",
540
+ "execution_count": null,
541
+ "id": "15e353ee",
542
+ "metadata": {},
543
+ "outputs": [],
544
+ "source": [
545
+ "audio_diffusion = DiffusionPipeline.from_pretrained(model_id).to(device)\n",
546
+ "mel = audio_diffusion.mel\n",
547
+ "sample_rate = mel.get_sample_rate()"
548
+ ]
549
+ },
550
+ {
551
+ "cell_type": "code",
552
+ "execution_count": null,
553
+ "id": "fa0f0c8c",
554
+ "metadata": {},
555
+ "outputs": [],
556
+ "source": [
557
+ "seed = 3412253600050855 #@param {type:\"integer\"}\n",
558
+ "generator.manual_seed(seed)\n",
559
+ "output = audio_diffusion(generator=generator)\n",
560
+ "image = output.images[0]\n",
561
+ "audio = output.audios[0, 0]\n",
562
+ "display(image)\n",
563
+ "display(Audio(audio, rate=sample_rate))"
564
+ ]
565
+ },
566
+ {
567
+ "cell_type": "code",
568
+ "execution_count": null,
569
+ "id": "73dc575d",
570
+ "metadata": {},
571
+ "outputs": [],
572
+ "source": [
573
+ "seed2 = 7016114633369557 #@param {type:\"integer\"}\n",
574
+ "generator.manual_seed(seed2)\n",
575
+ "output = audio_diffusion(generator=generator)\n",
576
+ "image2 = output.images[0]\n",
577
+ "audio2 = output.audios[0, 0]\n",
578
+ "display(image2)\n",
579
+ "display(Audio(audio2, rate=sample_rate))"
580
+ ]
581
+ },
582
+ {
583
+ "cell_type": "markdown",
584
+ "id": "428d2d67",
585
+ "metadata": {},
586
+ "source": [
587
+ "### Interpolation in latent space\n",
588
+ "As the VAE forces a more compact, lower dimensional representation for the spectrograms, interpolation in latent space can lead to meaningful combinations of audios. In combination with the (deterministic) DDIM from the previous section, the model can be used as an encoder / decoder to a lower dimensional space."
589
+ ]
590
+ },
591
+ {
592
+ "cell_type": "code",
593
+ "execution_count": null,
594
+ "id": "72211c2b",
595
+ "metadata": {},
596
+ "outputs": [],
597
+ "source": [
598
+ "generator.manual_seed(seed)\n",
599
+ "latents = torch.randn(\n",
600
+ " (1, audio_diffusion.unet.in_channels, audio_diffusion.unet.sample_size[0],\n",
601
+ " audio_diffusion.unet.sample_size[1]),\n",
602
+ " generator=generator, device=device)\n",
603
+ "latents.shape"
604
+ ]
605
+ },
606
+ {
607
+ "cell_type": "code",
608
+ "execution_count": null,
609
+ "id": "6c732dbe",
610
+ "metadata": {},
611
+ "outputs": [],
612
+ "source": [
613
+ "generator.manual_seed(seed2)\n",
614
+ "latents2 = torch.randn(\n",
615
+ " (1, audio_diffusion.unet.in_channels, audio_diffusion.unet.sample_size[0],\n",
616
+ " audio_diffusion.unet.sample_size[1]),\n",
617
+ " generator=generator,\n",
618
+ " device=device)\n",
619
+ "latents2.shape"
620
+ ]
621
+ },
622
+ {
623
+ "cell_type": "code",
624
+ "execution_count": null,
625
+ "id": "159bcfc4",
626
+ "metadata": {},
627
+ "outputs": [],
628
+ "source": [
629
+ "alpha = 0.5 #@param {type:\"slider\", min:0, max:1, step:0.1}\n",
630
+ "output = audio_diffusion(\n",
631
+ " noise=audio_diffusion.slerp(latents, latents2, alpha),\n",
632
+ " generator=generator)\n",
633
+ "audio3 = output.audios[0, 0]\n",
634
+ "display(Audio(audio, rate=mel.get_sample_rate()))\n",
635
+ "display(Audio(audio2, rate=mel.get_sample_rate()))\n",
636
+ "display(Audio(audio3, rate=sample_rate))"
637
+ ]
638
+ },
639
+ {
640
+ "cell_type": "code",
641
+ "execution_count": null,
642
+ "id": "ce6c9cc1",
643
+ "metadata": {},
644
+ "outputs": [],
645
+ "source": []
646
+ }
647
+ ],
648
+ "metadata": {
649
+ "accelerator": "GPU",
650
+ "colab": {
651
+ "provenance": []
652
+ },
653
+ "gpuClass": "standard",
654
+ "kernelspec": {
655
+ "display_name": "huggingface",
656
+ "language": "python",
657
+ "name": "huggingface"
658
+ },
659
+ "language_info": {
660
+ "codemirror_mode": {
661
+ "name": "ipython",
662
+ "version": 3
663
+ },
664
+ "file_extension": ".py",
665
+ "mimetype": "text/x-python",
666
+ "name": "python",
667
+ "nbconvert_exporter": "python",
668
+ "pygments_lexer": "ipython3",
669
+ "version": "3.10.6"
670
+ },
671
+ "toc": {
672
+ "base_numbering": 1,
673
+ "nav_menu": {},
674
+ "number_sections": true,
675
+ "sideBar": true,
676
+ "skip_h1_title": false,
677
+ "title_cell": "Table of Contents",
678
+ "title_sidebar": "Contents",
679
+ "toc_cell": false,
680
+ "toc_position": {},
681
+ "toc_section_display": true,
682
+ "toc_window_display": false
683
+ }
684
+ },
685
+ "nbformat": 4,
686
+ "nbformat_minor": 5
687
+ }
notebooks/audio_encoder.ipynb ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "execution_count": null,
6
+ "id": "592fff30",
7
+ "metadata": {},
8
+ "outputs": [],
9
+ "source": [
10
+ "from audiodiffusion.audio_encoder import AudioEncoder"
11
+ ]
12
+ },
13
+ {
14
+ "cell_type": "code",
15
+ "execution_count": null,
16
+ "id": "d99ef523",
17
+ "metadata": {},
18
+ "outputs": [],
19
+ "source": [
20
+ "audio_encoder = AudioEncoder.from_pretrained(\"teticio/audio-encoder\")"
21
+ ]
22
+ },
23
+ {
24
+ "cell_type": "code",
25
+ "execution_count": null,
26
+ "id": "4eb3bbd7",
27
+ "metadata": {},
28
+ "outputs": [],
29
+ "source": [
30
+ "audio_encoder.encode(['/home/teticio/Music/liked/Agua Re - Holy Dance - Large Sound Mix.mp3'])"
31
+ ]
32
+ }
33
+ ],
34
+ "metadata": {
35
+ "kernelspec": {
36
+ "display_name": "huggingface",
37
+ "language": "python",
38
+ "name": "huggingface"
39
+ },
40
+ "language_info": {
41
+ "codemirror_mode": {
42
+ "name": "ipython",
43
+ "version": 3
44
+ },
45
+ "file_extension": ".py",
46
+ "mimetype": "text/x-python",
47
+ "name": "python",
48
+ "nbconvert_exporter": "python",
49
+ "pygments_lexer": "ipython3",
50
+ "version": "3.10.6"
51
+ },
52
+ "toc": {
53
+ "base_numbering": 1,
54
+ "nav_menu": {},
55
+ "number_sections": true,
56
+ "sideBar": true,
57
+ "skip_h1_title": false,
58
+ "title_cell": "Table of Contents",
59
+ "title_sidebar": "Contents",
60
+ "toc_cell": false,
61
+ "toc_position": {},
62
+ "toc_section_display": true,
63
+ "toc_window_display": false
64
+ }
65
+ },
66
+ "nbformat": 4,
67
+ "nbformat_minor": 5
68
+ }
notebooks/conditional_generation.ipynb ADDED
@@ -0,0 +1,226 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "markdown",
5
+ "id": "5f6c6cc2",
6
+ "metadata": {},
7
+ "source": [
8
+ "<a href=\"https://colab.research.google.com/github/teticio/audio-diffusion/blob/master/notebooks/conditional_generation.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": "f1935544",
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": "b0e656c9",
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": "d448b299",
44
+ "metadata": {},
45
+ "outputs": [],
46
+ "source": [
47
+ "import torch\n",
48
+ "import urllib\n",
49
+ "import requests\n",
50
+ "from IPython.display import Audio\n",
51
+ "from audiodiffusion import AudioDiffusion\n",
52
+ "from audiodiffusion.audio_encoder import AudioEncoder"
53
+ ]
54
+ },
55
+ {
56
+ "cell_type": "code",
57
+ "execution_count": null,
58
+ "id": "f1548971",
59
+ "metadata": {},
60
+ "outputs": [],
61
+ "source": [
62
+ "device = \"cuda\" if torch.cuda.is_available() else \"cpu\"\n",
63
+ "generator = torch.Generator(device=device)"
64
+ ]
65
+ },
66
+ {
67
+ "cell_type": "code",
68
+ "execution_count": null,
69
+ "id": "056f179c",
70
+ "metadata": {},
71
+ "outputs": [],
72
+ "source": [
73
+ "audio_diffusion = AudioDiffusion(model_id=\"teticio/conditional-latent-audio-diffusion-512\")"
74
+ ]
75
+ },
76
+ {
77
+ "cell_type": "code",
78
+ "execution_count": null,
79
+ "id": "b4a08500",
80
+ "metadata": {},
81
+ "outputs": [],
82
+ "source": [
83
+ "audio_encoder = AudioEncoder.from_pretrained(\"teticio/audio-encoder\")"
84
+ ]
85
+ },
86
+ {
87
+ "cell_type": "code",
88
+ "execution_count": null,
89
+ "id": "387550ac",
90
+ "metadata": {},
91
+ "outputs": [],
92
+ "source": [
93
+ "# Uncomment for faster (but slightly lower quality) generation\n",
94
+ "#from diffusers import DDIMScheduler\n",
95
+ "#audio_diffusion.pipe.scheduler = DDIMScheduler()"
96
+ ]
97
+ },
98
+ {
99
+ "cell_type": "markdown",
100
+ "id": "9936a72f",
101
+ "metadata": {},
102
+ "source": [
103
+ "## Download and encode preview track from Spotify"
104
+ ]
105
+ },
106
+ {
107
+ "cell_type": "code",
108
+ "execution_count": null,
109
+ "id": "57a9b134",
110
+ "metadata": {},
111
+ "outputs": [],
112
+ "source": [
113
+ "# Get temporary API credentials\n",
114
+ "credentials = requests.get(\n",
115
+ " \"https://open.spotify.com/get_access_token?reason=transport&productType=embed\"\n",
116
+ ").json()\n",
117
+ "headers = {\n",
118
+ " \"Accept\": \"application/json\",\n",
119
+ " \"Content-Type\": \"application/json\",\n",
120
+ " \"Authorization\": \"Bearer \" + credentials[\"accessToken\"]\n",
121
+ "}\n",
122
+ "\n",
123
+ "# Search for tracks\n",
124
+ "search_string = input(\"Search: \")\n",
125
+ "response = requests.get(\n",
126
+ " f\"https://api.spotify.com/v1/search?q={urllib.parse.quote(search_string)}&type=track\",\n",
127
+ " headers=headers).json()\n",
128
+ "\n",
129
+ "# List results\n",
130
+ "for _, track in enumerate(response[\"tracks\"][\"items\"]):\n",
131
+ " print(f\"{_ + 1}. {track['artists'][0]['name']} - {track['name']}\")\n",
132
+ "selection = input(\"Select a track: \")\n",
133
+ "\n",
134
+ "# Download and encode selection\n",
135
+ "r = requests.get(response[\"tracks\"][\"items\"][int(selection) -\n",
136
+ " 1][\"preview_url\"],\n",
137
+ " stream=True)\n",
138
+ "with open(\"temp.mp3\", \"wb\") as f:\n",
139
+ " for chunk in r:\n",
140
+ " f.write(chunk)\n",
141
+ "encoding = torch.unsqueeze(audio_encoder.encode([\"temp.mp3\"]),\n",
142
+ " axis=1).to(device)\n",
143
+ "os.remove(\"temp.mp3\")"
144
+ ]
145
+ },
146
+ {
147
+ "cell_type": "markdown",
148
+ "id": "8af863f5",
149
+ "metadata": {},
150
+ "source": [
151
+ "## Conditional Generation\n",
152
+ "Bear in mind that the generative model can only generate music similar to that on which it was trained. The audio encoding will influence the generation within those limitations."
153
+ ]
154
+ },
155
+ {
156
+ "cell_type": "code",
157
+ "execution_count": null,
158
+ "id": "8f119ddd",
159
+ "metadata": {},
160
+ "outputs": [],
161
+ "source": [
162
+ "for _ in range(10):\n",
163
+ " seed = generator.seed()\n",
164
+ " print(f'Seed = {seed}')\n",
165
+ " generator.manual_seed(seed)\n",
166
+ " image, (sample_rate,\n",
167
+ " audio) = audio_diffusion.generate_spectrogram_and_audio(\n",
168
+ " generator=generator, encoding=encoding)\n",
169
+ " display(image)\n",
170
+ " display(Audio(audio, rate=sample_rate))\n",
171
+ " loop = AudioDiffusion.loop_it(audio, sample_rate)\n",
172
+ " if loop is not None:\n",
173
+ " display(Audio(loop, rate=sample_rate))\n",
174
+ " else:\n",
175
+ " print(\"Unable to determine loop points\")"
176
+ ]
177
+ },
178
+ {
179
+ "cell_type": "code",
180
+ "execution_count": null,
181
+ "id": "d0bd18c0",
182
+ "metadata": {},
183
+ "outputs": [],
184
+ "source": []
185
+ }
186
+ ],
187
+ "metadata": {
188
+ "accelerator": "GPU",
189
+ "colab": {
190
+ "provenance": []
191
+ },
192
+ "gpuClass": "standard",
193
+ "kernelspec": {
194
+ "display_name": "huggingface",
195
+ "language": "python",
196
+ "name": "huggingface"
197
+ },
198
+ "language_info": {
199
+ "codemirror_mode": {
200
+ "name": "ipython",
201
+ "version": 3
202
+ },
203
+ "file_extension": ".py",
204
+ "mimetype": "text/x-python",
205
+ "name": "python",
206
+ "nbconvert_exporter": "python",
207
+ "pygments_lexer": "ipython3",
208
+ "version": "3.10.6"
209
+ },
210
+ "toc": {
211
+ "base_numbering": 1,
212
+ "nav_menu": {},
213
+ "number_sections": true,
214
+ "sideBar": true,
215
+ "skip_h1_title": false,
216
+ "title_cell": "Table of Contents",
217
+ "title_sidebar": "Contents",
218
+ "toc_cell": false,
219
+ "toc_position": {},
220
+ "toc_section_display": true,
221
+ "toc_window_display": false
222
+ }
223
+ },
224
+ "nbformat": 4,
225
+ "nbformat_minor": 5
226
+ }
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.6"
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,220 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "markdown",
5
+ "id": "3de63898",
6
+ "metadata": {},
7
+ "source": [
8
+ "<a href=\"https://colab.research.google.com/github/teticio/audio-diffusion/blob/master/notebooks/test_mel.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": "81fbd495",
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": "218fcdf1",
32
+ "metadata": {},
33
+ "outputs": [],
34
+ "source": [
35
+ "from datasets import load_dataset\n",
36
+ "from IPython.display import Audio\n",
37
+ "from diffusers import Mel"
38
+ ]
39
+ },
40
+ {
41
+ "cell_type": "code",
42
+ "execution_count": null,
43
+ "id": "5e4f8ee5",
44
+ "metadata": {},
45
+ "outputs": [],
46
+ "source": [
47
+ "# These are the default parameters. If you change any of them, you may have to adjust the others.\n",
48
+ "mel = Mel(x_res=256,\n",
49
+ " y_res=256,\n",
50
+ " hop_length=512,\n",
51
+ " sample_rate=22050,\n",
52
+ " n_fft=2048,\n",
53
+ " n_iter=32)"
54
+ ]
55
+ },
56
+ {
57
+ "cell_type": "markdown",
58
+ "id": "b2178c3f",
59
+ "metadata": {},
60
+ "source": [
61
+ "### Transform slice of audio to mel spectrogram"
62
+ ]
63
+ },
64
+ {
65
+ "cell_type": "code",
66
+ "execution_count": null,
67
+ "id": "f32bb35e",
68
+ "metadata": {},
69
+ "outputs": [],
70
+ "source": [
71
+ "try:\n",
72
+ " # are we running on Google Colab?\n",
73
+ " from google.colab import files\n",
74
+ " audio_file = list(files.upload().keys())[0]\n",
75
+ "except:\n",
76
+ " audio_file = \"/home/teticio/Music/Music/A Tribe Called Quest/The Anthology/08 Can I Kick It_.mp3\""
77
+ ]
78
+ },
79
+ {
80
+ "cell_type": "code",
81
+ "execution_count": null,
82
+ "id": "61dbcd2e",
83
+ "metadata": {},
84
+ "outputs": [],
85
+ "source": [
86
+ "mel.load_audio(audio_file)"
87
+ ]
88
+ },
89
+ {
90
+ "cell_type": "code",
91
+ "execution_count": null,
92
+ "id": "ccadcc0f",
93
+ "metadata": {},
94
+ "outputs": [],
95
+ "source": [
96
+ "image = mel.audio_slice_to_image(15)\n",
97
+ "image"
98
+ ]
99
+ },
100
+ {
101
+ "cell_type": "code",
102
+ "execution_count": null,
103
+ "id": "8cec79c6",
104
+ "metadata": {},
105
+ "outputs": [],
106
+ "source": [
107
+ "image.width, image.height"
108
+ ]
109
+ },
110
+ {
111
+ "cell_type": "markdown",
112
+ "id": "fe112fef",
113
+ "metadata": {},
114
+ "source": [
115
+ "### Transform mel spectrogram back to audio"
116
+ ]
117
+ },
118
+ {
119
+ "cell_type": "code",
120
+ "execution_count": null,
121
+ "id": "0b268a54",
122
+ "metadata": {},
123
+ "outputs": [],
124
+ "source": [
125
+ "audio = mel.image_to_audio(image)\n",
126
+ "Audio(data=audio, rate=mel.get_sample_rate())"
127
+ ]
128
+ },
129
+ {
130
+ "cell_type": "markdown",
131
+ "id": "0f1f2006",
132
+ "metadata": {},
133
+ "source": [
134
+ "### Select a random image from the training set"
135
+ ]
136
+ },
137
+ {
138
+ "cell_type": "code",
139
+ "execution_count": null,
140
+ "id": "1f29f025",
141
+ "metadata": {},
142
+ "outputs": [],
143
+ "source": [
144
+ "ds = load_dataset('teticio/audio-diffusion-256')"
145
+ ]
146
+ },
147
+ {
148
+ "cell_type": "code",
149
+ "execution_count": null,
150
+ "id": "e002482d",
151
+ "metadata": {},
152
+ "outputs": [],
153
+ "source": [
154
+ "image = ds['train'].shuffle().select(range(1))['image'][0]\n",
155
+ "image"
156
+ ]
157
+ },
158
+ {
159
+ "cell_type": "markdown",
160
+ "id": "6a801fc5",
161
+ "metadata": {},
162
+ "source": [
163
+ "### Convert to audio"
164
+ ]
165
+ },
166
+ {
167
+ "cell_type": "code",
168
+ "execution_count": null,
169
+ "id": "a2421827",
170
+ "metadata": {},
171
+ "outputs": [],
172
+ "source": [
173
+ "audio = mel.image_to_audio(image)\n",
174
+ "Audio(data=audio, rate=mel.get_sample_rate())"
175
+ ]
176
+ },
177
+ {
178
+ "cell_type": "code",
179
+ "execution_count": null,
180
+ "id": "2281fb55",
181
+ "metadata": {},
182
+ "outputs": [],
183
+ "source": []
184
+ }
185
+ ],
186
+ "metadata": {
187
+ "kernelspec": {
188
+ "display_name": "huggingface",
189
+ "language": "python",
190
+ "name": "huggingface"
191
+ },
192
+ "language_info": {
193
+ "codemirror_mode": {
194
+ "name": "ipython",
195
+ "version": 3
196
+ },
197
+ "file_extension": ".py",
198
+ "mimetype": "text/x-python",
199
+ "name": "python",
200
+ "nbconvert_exporter": "python",
201
+ "pygments_lexer": "ipython3",
202
+ "version": "3.10.6"
203
+ },
204
+ "toc": {
205
+ "base_numbering": 1,
206
+ "nav_menu": {},
207
+ "number_sections": true,
208
+ "sideBar": true,
209
+ "skip_h1_title": false,
210
+ "title_cell": "Table of Contents",
211
+ "title_sidebar": "Contents",
212
+ "toc_cell": false,
213
+ "toc_position": {},
214
+ "toc_section_display": true,
215
+ "toc_window_display": false
216
+ }
217
+ },
218
+ "nbformat": 4,
219
+ "nbformat_minor": 5
220
+ }
notebooks/test_model.ipynb ADDED
@@ -0,0 +1,660 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 librosa\n",
50
+ "import numpy as np\n",
51
+ "from datasets import load_dataset\n",
52
+ "from IPython.display import Audio\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
+ "device = \"cuda\" if torch.cuda.is_available() else \"cpu\"\n",
64
+ "generator = torch.Generator(device=device)"
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)\n",
107
+ "mel = audio_diffusion.pipe.mel"
108
+ ]
109
+ },
110
+ {
111
+ "cell_type": "markdown",
112
+ "id": "011fb5a1",
113
+ "metadata": {},
114
+ "source": [
115
+ "### Run model inference to generate mel spectrogram, audios and loops"
116
+ ]
117
+ },
118
+ {
119
+ "cell_type": "code",
120
+ "execution_count": null,
121
+ "id": "b809fed5",
122
+ "metadata": {},
123
+ "outputs": [],
124
+ "source": [
125
+ "for _ in range(10):\n",
126
+ " seed = generator.seed()\n",
127
+ " print(f'Seed = {seed}')\n",
128
+ " generator.manual_seed(seed)\n",
129
+ " image, (sample_rate,\n",
130
+ " audio) = audio_diffusion.generate_spectrogram_and_audio(\n",
131
+ " generator=generator)\n",
132
+ " display(image)\n",
133
+ " display(Audio(audio, rate=sample_rate))\n",
134
+ " loop = AudioDiffusion.loop_it(audio, sample_rate)\n",
135
+ " if loop is not None:\n",
136
+ " display(Audio(loop, rate=sample_rate))\n",
137
+ " else:\n",
138
+ " print(\"Unable to determine loop points\")"
139
+ ]
140
+ },
141
+ {
142
+ "cell_type": "markdown",
143
+ "id": "0bb03e33",
144
+ "metadata": {},
145
+ "source": [
146
+ "### Generate variations of audios"
147
+ ]
148
+ },
149
+ {
150
+ "cell_type": "markdown",
151
+ "id": "80e5b5fa",
152
+ "metadata": {},
153
+ "source": [
154
+ "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."
155
+ ]
156
+ },
157
+ {
158
+ "cell_type": "code",
159
+ "execution_count": null,
160
+ "id": "5074ec11",
161
+ "metadata": {},
162
+ "outputs": [],
163
+ "source": [
164
+ "seed = 2391504374279719 #@param {type:\"integer\"}\n",
165
+ "generator.manual_seed(seed)\n",
166
+ "image, (sample_rate, audio) = audio_diffusion.generate_spectrogram_and_audio(\n",
167
+ " generator=generator)\n",
168
+ "display(image)\n",
169
+ "display(Audio(audio, rate=sample_rate))"
170
+ ]
171
+ },
172
+ {
173
+ "cell_type": "code",
174
+ "execution_count": null,
175
+ "id": "a0fefe28",
176
+ "metadata": {
177
+ "scrolled": false
178
+ },
179
+ "outputs": [],
180
+ "source": [
181
+ "start_step = 500 #@param {type:\"slider\", min:0, max:1000, step:10}\n",
182
+ "track = AudioDiffusion.loop_it(audio, sample_rate, loops=1)\n",
183
+ "for variation in range(12):\n",
184
+ " image2, (\n",
185
+ " sample_rate,\n",
186
+ " audio2) = audio_diffusion.generate_spectrogram_and_audio_from_audio(\n",
187
+ " raw_audio=audio, start_step=start_step)\n",
188
+ " display(image2)\n",
189
+ " display(Audio(audio2, rate=sample_rate))\n",
190
+ " track = np.concatenate(\n",
191
+ " [track, AudioDiffusion.loop_it(audio2, sample_rate, loops=1)])\n",
192
+ "display(Audio(track, rate=sample_rate))"
193
+ ]
194
+ },
195
+ {
196
+ "cell_type": "markdown",
197
+ "id": "58a876c1",
198
+ "metadata": {},
199
+ "source": [
200
+ "### Generate continuations (\"out-painting\")"
201
+ ]
202
+ },
203
+ {
204
+ "cell_type": "code",
205
+ "execution_count": null,
206
+ "id": "b95d5780",
207
+ "metadata": {},
208
+ "outputs": [],
209
+ "source": [
210
+ "overlap_secs = 2 #@param {type:\"integer\"}\n",
211
+ "start_step = 0 #@param {type:\"slider\", min:0, max:1000, step:10}\n",
212
+ "overlap_samples = overlap_secs * sample_rate\n",
213
+ "track = audio\n",
214
+ "for variation in range(12):\n",
215
+ " image2, (\n",
216
+ " sample_rate,\n",
217
+ " audio2) = audio_diffusion.generate_spectrogram_and_audio_from_audio(\n",
218
+ " raw_audio=audio[-overlap_samples:],\n",
219
+ " start_step=start_step,\n",
220
+ " mask_start_secs=overlap_secs)\n",
221
+ " display(image2)\n",
222
+ " display(Audio(audio2, rate=sample_rate))\n",
223
+ " track = np.concatenate([track, audio2[overlap_samples:]])\n",
224
+ " audio = audio2\n",
225
+ "display(Audio(track, rate=sample_rate))"
226
+ ]
227
+ },
228
+ {
229
+ "cell_type": "markdown",
230
+ "id": "b6434d3f",
231
+ "metadata": {},
232
+ "source": [
233
+ "### Remix (style transfer)"
234
+ ]
235
+ },
236
+ {
237
+ "cell_type": "markdown",
238
+ "id": "0da030b2",
239
+ "metadata": {},
240
+ "source": [
241
+ "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."
242
+ ]
243
+ },
244
+ {
245
+ "cell_type": "code",
246
+ "execution_count": null,
247
+ "id": "fc620a80",
248
+ "metadata": {},
249
+ "outputs": [],
250
+ "source": [
251
+ "try:\n",
252
+ " # are we running on Google Colab?\n",
253
+ " from google.colab import files\n",
254
+ " audio_file = list(files.upload().keys())[0]\n",
255
+ "except:\n",
256
+ " audio_file = \"/home/teticio/Music/liked/El Michels Affair - Glaciers Of Ice.mp3\""
257
+ ]
258
+ },
259
+ {
260
+ "cell_type": "code",
261
+ "execution_count": null,
262
+ "id": "5a257e69",
263
+ "metadata": {
264
+ "scrolled": false
265
+ },
266
+ "outputs": [],
267
+ "source": [
268
+ "start_step = 500 #@param {type:\"slider\", min:0, max:1000, step:10}\n",
269
+ "overlap_secs = 2 #@param {type:\"integer\"}\n",
270
+ "track_audio, _ = librosa.load(audio_file, mono=True, sr=mel.get_sample_rate())\n",
271
+ "overlap_samples = overlap_secs * sample_rate\n",
272
+ "slice_size = mel.x_res * mel.hop_length\n",
273
+ "stride = slice_size - overlap_samples\n",
274
+ "generator = torch.Generator(device=device)\n",
275
+ "seed = generator.seed()\n",
276
+ "print(f'Seed = {seed}')\n",
277
+ "track = np.array([])\n",
278
+ "not_first = 0\n",
279
+ "for sample in range(len(track_audio) // stride):\n",
280
+ " generator.manual_seed(seed)\n",
281
+ " audio = np.array(track_audio[sample * stride:sample * stride + slice_size])\n",
282
+ " if not_first:\n",
283
+ " # Normalize and re-insert generated audio\n",
284
+ " audio[:overlap_samples] = audio2[-overlap_samples:] * np.max(\n",
285
+ " audio[:overlap_samples]) / np.max(audio2[-overlap_samples:])\n",
286
+ " _, (sample_rate,\n",
287
+ " audio2) = audio_diffusion.generate_spectrogram_and_audio_from_audio(\n",
288
+ " raw_audio=audio,\n",
289
+ " start_step=start_step,\n",
290
+ " generator=generator,\n",
291
+ " mask_start_secs=overlap_secs * not_first)\n",
292
+ " track = np.concatenate([track, audio2[overlap_samples * not_first:]])\n",
293
+ " not_first = 1\n",
294
+ " display(Audio(track, rate=sample_rate))"
295
+ ]
296
+ },
297
+ {
298
+ "cell_type": "markdown",
299
+ "id": "924ff9d5",
300
+ "metadata": {},
301
+ "source": [
302
+ "### Fill the gap (\"in-painting\")"
303
+ ]
304
+ },
305
+ {
306
+ "cell_type": "code",
307
+ "execution_count": null,
308
+ "id": "0200264c",
309
+ "metadata": {},
310
+ "outputs": [],
311
+ "source": [
312
+ "slice = 3 #@param {type:\"integer\"}\n",
313
+ "raw_audio = track_audio[sample * stride:sample * stride + slice_size]\n",
314
+ "_, (sample_rate,\n",
315
+ " audio2) = audio_diffusion.generate_spectrogram_and_audio_from_audio(\n",
316
+ " raw_audio=raw_audio,\n",
317
+ " mask_start_secs=1,\n",
318
+ " mask_end_secs=1,\n",
319
+ " step_generator=torch.Generator(device=device))\n",
320
+ "display(Audio(audio, rate=sample_rate))\n",
321
+ "display(Audio(audio2, rate=sample_rate))"
322
+ ]
323
+ },
324
+ {
325
+ "cell_type": "markdown",
326
+ "id": "efc32dae",
327
+ "metadata": {},
328
+ "source": [
329
+ "## DDIM (De-noising Diffusion Implicit Models)"
330
+ ]
331
+ },
332
+ {
333
+ "cell_type": "code",
334
+ "execution_count": null,
335
+ "id": "a021f78a",
336
+ "metadata": {},
337
+ "outputs": [],
338
+ "source": [
339
+ "audio_diffusion = AudioDiffusion(model_id='teticio/audio-diffusion-ddim-256')\n",
340
+ "mel = audio_diffusion.pipe.mel"
341
+ ]
342
+ },
343
+ {
344
+ "cell_type": "markdown",
345
+ "id": "deb23339",
346
+ "metadata": {},
347
+ "source": [
348
+ "### Generation can be done in many fewer steps with DDIMs"
349
+ ]
350
+ },
351
+ {
352
+ "cell_type": "code",
353
+ "execution_count": null,
354
+ "id": "c105a497",
355
+ "metadata": {},
356
+ "outputs": [],
357
+ "source": [
358
+ "for _ in range(10):\n",
359
+ " seed = generator.seed()\n",
360
+ " print(f'Seed = {seed}')\n",
361
+ " generator.manual_seed(seed)\n",
362
+ " image, (sample_rate,\n",
363
+ " audio) = audio_diffusion.generate_spectrogram_and_audio(\n",
364
+ " generator=generator)\n",
365
+ " display(image)\n",
366
+ " display(Audio(audio, rate=sample_rate))\n",
367
+ " loop = AudioDiffusion.loop_it(audio, sample_rate)\n",
368
+ " if loop is not None:\n",
369
+ " display(Audio(loop, rate=sample_rate))\n",
370
+ " else:\n",
371
+ " print(\"Unable to determine loop points\")"
372
+ ]
373
+ },
374
+ {
375
+ "cell_type": "markdown",
376
+ "id": "cab4692c",
377
+ "metadata": {},
378
+ "source": [
379
+ "The parameter eta controls the variance:\n",
380
+ "* 0 - DDIM (deterministic)\n",
381
+ "* 1 - DDPM (De-noising Diffusion Probabilistic Model)"
382
+ ]
383
+ },
384
+ {
385
+ "cell_type": "code",
386
+ "execution_count": null,
387
+ "id": "72bdd207",
388
+ "metadata": {},
389
+ "outputs": [],
390
+ "source": [
391
+ "image, (sample_rate, audio) = audio_diffusion.generate_spectrogram_and_audio(\n",
392
+ " steps=1000, generator=generator, eta=1)\n",
393
+ "display(image)\n",
394
+ "display(Audio(audio, rate=sample_rate))"
395
+ ]
396
+ },
397
+ {
398
+ "cell_type": "markdown",
399
+ "id": "b8d5442c",
400
+ "metadata": {},
401
+ "source": [
402
+ "### DDIMs can be used as encoders..."
403
+ ]
404
+ },
405
+ {
406
+ "cell_type": "code",
407
+ "execution_count": null,
408
+ "id": "269ee816",
409
+ "metadata": {},
410
+ "outputs": [],
411
+ "source": [
412
+ "# Doesn't have to be an audio from the train dataset, this is just for convenience\n",
413
+ "ds = load_dataset('teticio/audio-diffusion-256')"
414
+ ]
415
+ },
416
+ {
417
+ "cell_type": "code",
418
+ "execution_count": null,
419
+ "id": "278d1d80",
420
+ "metadata": {},
421
+ "outputs": [],
422
+ "source": [
423
+ "image = ds['train'][264]['image']\n",
424
+ "display(Audio(mel.image_to_audio(image), rate=sample_rate))"
425
+ ]
426
+ },
427
+ {
428
+ "cell_type": "code",
429
+ "execution_count": null,
430
+ "id": "912b54e4",
431
+ "metadata": {},
432
+ "outputs": [],
433
+ "source": [
434
+ "noise = audio_diffusion.pipe.encode([image])"
435
+ ]
436
+ },
437
+ {
438
+ "cell_type": "code",
439
+ "execution_count": null,
440
+ "id": "c7b31f97",
441
+ "metadata": {},
442
+ "outputs": [],
443
+ "source": [
444
+ "# Reconstruct original audio from noise\n",
445
+ "_, (sample_rate, audio) = audio_diffusion.generate_spectrogram_and_audio(\n",
446
+ " noise=noise, generator=generator)\n",
447
+ "display(Audio(audio, rate=sample_rate))"
448
+ ]
449
+ },
450
+ {
451
+ "cell_type": "markdown",
452
+ "id": "998c776b",
453
+ "metadata": {},
454
+ "source": [
455
+ "### ...or to interpolate between audios"
456
+ ]
457
+ },
458
+ {
459
+ "cell_type": "code",
460
+ "execution_count": null,
461
+ "id": "33f82367",
462
+ "metadata": {},
463
+ "outputs": [],
464
+ "source": [
465
+ "image2 = ds['train'][15978]['image']\n",
466
+ "display(Audio(mel.image_to_audio(image2), rate=sample_rate))"
467
+ ]
468
+ },
469
+ {
470
+ "cell_type": "code",
471
+ "execution_count": null,
472
+ "id": "f93fb6c0",
473
+ "metadata": {},
474
+ "outputs": [],
475
+ "source": [
476
+ "noise2 = audio_diffusion.pipe.encode([image2])"
477
+ ]
478
+ },
479
+ {
480
+ "cell_type": "code",
481
+ "execution_count": null,
482
+ "id": "a4190563",
483
+ "metadata": {},
484
+ "outputs": [],
485
+ "source": [
486
+ "alpha = 0.5 #@param {type:\"slider\", min:0, max:1, step:0.1}\n",
487
+ "_, (sample_rate, audio) = audio_diffusion.generate_spectrogram_and_audio(\n",
488
+ " noise=audio_diffusion.pipe.slerp(noise, noise2, alpha),\n",
489
+ " generator=generator)\n",
490
+ "display(Audio(mel.image_to_audio(image), rate=sample_rate))\n",
491
+ "display(Audio(mel.image_to_audio(image2), rate=sample_rate))\n",
492
+ "display(Audio(audio, rate=sample_rate))"
493
+ ]
494
+ },
495
+ {
496
+ "cell_type": "markdown",
497
+ "id": "9b244547",
498
+ "metadata": {},
499
+ "source": [
500
+ "## Latent Audio Diffusion\n",
501
+ "Instead of de-noising images directly in the pixel space, we can work in the latent space of a pre-trained VAE (Variational AutoEncoder). This is much faster to train and run inference on, although the quality suffers as there are now three stages involved in encoding / decoding: mel spectrogram, VAE and de-noising."
502
+ ]
503
+ },
504
+ {
505
+ "cell_type": "code",
506
+ "execution_count": null,
507
+ "id": "a88b3fbb",
508
+ "metadata": {},
509
+ "outputs": [],
510
+ "source": [
511
+ "model_id = \"teticio/latent-audio-diffusion-ddim-256\" #@param [\"teticio/latent-audio-diffusion-256\", \"teticio/latent-audio-diffusion-ddim-256\"]"
512
+ ]
513
+ },
514
+ {
515
+ "cell_type": "code",
516
+ "execution_count": null,
517
+ "id": "15e353ee",
518
+ "metadata": {},
519
+ "outputs": [],
520
+ "source": [
521
+ "audio_diffusion = AudioDiffusion(model_id=model_id)\n",
522
+ "mel = audio_diffusion.pipe.mel"
523
+ ]
524
+ },
525
+ {
526
+ "cell_type": "code",
527
+ "execution_count": null,
528
+ "id": "fa0f0c8c",
529
+ "metadata": {},
530
+ "outputs": [],
531
+ "source": [
532
+ "seed = 3412253600050855 #@param {type:\"integer\"}\n",
533
+ "generator.manual_seed(seed)\n",
534
+ "image, (sample_rate, audio) = audio_diffusion.generate_spectrogram_and_audio(\n",
535
+ " generator=generator)\n",
536
+ "display(image)\n",
537
+ "display(Audio(audio, rate=sample_rate))"
538
+ ]
539
+ },
540
+ {
541
+ "cell_type": "code",
542
+ "execution_count": null,
543
+ "id": "73dc575d",
544
+ "metadata": {},
545
+ "outputs": [],
546
+ "source": [
547
+ "seed2 = 7016114633369557 #@param {type:\"integer\"}\n",
548
+ "generator.manual_seed(seed2)\n",
549
+ "image2, (sample_rate, audio2) = audio_diffusion.generate_spectrogram_and_audio(\n",
550
+ " generator=generator)\n",
551
+ "display(image2)\n",
552
+ "display(Audio(audio2, rate=sample_rate))"
553
+ ]
554
+ },
555
+ {
556
+ "cell_type": "markdown",
557
+ "id": "428d2d67",
558
+ "metadata": {},
559
+ "source": [
560
+ "### Interpolation in latent space\n",
561
+ "As the VAE forces a more compact, lower dimensional representation for the spectrograms, interpolation in latent space can lead to meaningful combinations of audios. In combination with the (deterministic) DDIM from the previous section, the model can be used as an encoder / decoder to a lower dimensional space."
562
+ ]
563
+ },
564
+ {
565
+ "cell_type": "code",
566
+ "execution_count": null,
567
+ "id": "72211c2b",
568
+ "metadata": {},
569
+ "outputs": [],
570
+ "source": [
571
+ "generator.manual_seed(seed)\n",
572
+ "latents = torch.randn((1, audio_diffusion.pipe.unet.in_channels,\n",
573
+ " audio_diffusion.pipe.unet.sample_size[0],\n",
574
+ " audio_diffusion.pipe.unet.sample_size[1]),\n",
575
+ " device=device,\n",
576
+ " generator=generator)\n",
577
+ "latents.shape"
578
+ ]
579
+ },
580
+ {
581
+ "cell_type": "code",
582
+ "execution_count": null,
583
+ "id": "6c732dbe",
584
+ "metadata": {},
585
+ "outputs": [],
586
+ "source": [
587
+ "generator.manual_seed(seed2)\n",
588
+ "latents2 = torch.randn((1, audio_diffusion.pipe.unet.in_channels,\n",
589
+ " audio_diffusion.pipe.unet.sample_size[0],\n",
590
+ " audio_diffusion.pipe.unet.sample_size[1]),\n",
591
+ " device=device,\n",
592
+ " generator=generator)\n",
593
+ "latents2.shape"
594
+ ]
595
+ },
596
+ {
597
+ "cell_type": "code",
598
+ "execution_count": null,
599
+ "id": "159bcfc4",
600
+ "metadata": {},
601
+ "outputs": [],
602
+ "source": [
603
+ "alpha = 0.5 #@param {type:\"slider\", min:0, max:1, step:0.1}\n",
604
+ "_, (sample_rate, audio3) = audio_diffusion.generate_spectrogram_and_audio(\n",
605
+ " noise=audio_diffusion.pipe.slerp(latents, latents2, alpha),\n",
606
+ " generator=generator)\n",
607
+ "display(Audio(audio, rate=sample_rate))\n",
608
+ "display(Audio(audio2, rate=sample_rate))\n",
609
+ "display(Audio(audio3, rate=sample_rate))"
610
+ ]
611
+ },
612
+ {
613
+ "cell_type": "code",
614
+ "execution_count": null,
615
+ "id": "ce6c9cc1",
616
+ "metadata": {},
617
+ "outputs": [],
618
+ "source": []
619
+ }
620
+ ],
621
+ "metadata": {
622
+ "accelerator": "GPU",
623
+ "colab": {
624
+ "provenance": []
625
+ },
626
+ "gpuClass": "standard",
627
+ "kernelspec": {
628
+ "display_name": "huggingface",
629
+ "language": "python",
630
+ "name": "huggingface"
631
+ },
632
+ "language_info": {
633
+ "codemirror_mode": {
634
+ "name": "ipython",
635
+ "version": 3
636
+ },
637
+ "file_extension": ".py",
638
+ "mimetype": "text/x-python",
639
+ "name": "python",
640
+ "nbconvert_exporter": "python",
641
+ "pygments_lexer": "ipython3",
642
+ "version": "3.10.6"
643
+ },
644
+ "toc": {
645
+ "base_numbering": 1,
646
+ "nav_menu": {},
647
+ "number_sections": true,
648
+ "sideBar": true,
649
+ "skip_h1_title": false,
650
+ "title_cell": "Table of Contents",
651
+ "title_sidebar": "Contents",
652
+ "toc_cell": false,
653
+ "toc_position": {},
654
+ "toc_section_display": true,
655
+ "toc_window_display": false
656
+ }
657
+ },
658
+ "nbformat": 4,
659
+ "nbformat_minor": 5
660
+ }
notebooks/test_vae.ipynb ADDED
@@ -0,0 +1,233 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "execution_count": null,
6
+ "id": "b451ab22",
7
+ "metadata": {},
8
+ "outputs": [],
9
+ "source": [
10
+ "import torch\n",
11
+ "import random\n",
12
+ "import numpy as np\n",
13
+ "from PIL import Image\n",
14
+ "from datasets import load_dataset\n",
15
+ "from IPython.display import Audio\n",
16
+ "from diffusers import AutoencoderKL, AudioDiffusionPipeline, Mel"
17
+ ]
18
+ },
19
+ {
20
+ "cell_type": "code",
21
+ "execution_count": null,
22
+ "id": "324cef44",
23
+ "metadata": {},
24
+ "outputs": [],
25
+ "source": [
26
+ "mel = Mel()\n",
27
+ "vae = AutoencoderKL.from_pretrained('../models/autoencoder-kl')"
28
+ ]
29
+ },
30
+ {
31
+ "cell_type": "code",
32
+ "execution_count": null,
33
+ "id": "da55ce79",
34
+ "metadata": {},
35
+ "outputs": [],
36
+ "source": [
37
+ "vae.config"
38
+ ]
39
+ },
40
+ {
41
+ "cell_type": "code",
42
+ "execution_count": null,
43
+ "id": "5fea99ff",
44
+ "metadata": {},
45
+ "outputs": [],
46
+ "source": [
47
+ "ds = load_dataset('teticio/audio-diffusion-256')"
48
+ ]
49
+ },
50
+ {
51
+ "cell_type": "markdown",
52
+ "id": "3a65ec4d",
53
+ "metadata": {},
54
+ "source": [
55
+ "### Reconstruct audio"
56
+ ]
57
+ },
58
+ {
59
+ "cell_type": "code",
60
+ "execution_count": null,
61
+ "id": "426c6edd",
62
+ "metadata": {},
63
+ "outputs": [],
64
+ "source": [
65
+ "image = random.choice(ds['train'])['image']\n",
66
+ "display(image)\n",
67
+ "Audio(data=mel.image_to_audio(image), rate=mel.get_sample_rate())"
68
+ ]
69
+ },
70
+ {
71
+ "cell_type": "code",
72
+ "execution_count": null,
73
+ "id": "29c9011d",
74
+ "metadata": {},
75
+ "outputs": [],
76
+ "source": [
77
+ "# encode\n",
78
+ "input_image = np.frombuffer(image.tobytes(), dtype=\"uint8\").reshape(\n",
79
+ " (image.height, image.width, 1))\n",
80
+ "input_image = ((input_image / 255) * 2 - 1).transpose(2, 0, 1)\n",
81
+ "posterior = vae.encode(torch.tensor([input_image],\n",
82
+ " dtype=torch.float32)).latent_dist\n",
83
+ "latents = posterior.sample()"
84
+ ]
85
+ },
86
+ {
87
+ "cell_type": "code",
88
+ "execution_count": null,
89
+ "id": "323ba46d",
90
+ "metadata": {},
91
+ "outputs": [],
92
+ "source": [
93
+ "# reconstruct\n",
94
+ "output_image = vae.decode(latents)['sample']\n",
95
+ "output_image = torch.clamp(output_image, -1., 1.)\n",
96
+ "output_image = (output_image + 1.0) / 2.0 # -1,1 -> 0,1; c,h,w\n",
97
+ "output_image = (output_image.detach().cpu().numpy() *\n",
98
+ " 255).round().astype(\"uint8\").transpose(0, 2, 3, 1)[0, :, :, 0]\n",
99
+ "output_image = Image.fromarray(output_image)\n",
100
+ "display(output_image)\n",
101
+ "Audio(data=mel.image_to_audio(output_image), rate=mel.get_sample_rate())"
102
+ ]
103
+ },
104
+ {
105
+ "cell_type": "markdown",
106
+ "id": "00ff2ffa",
107
+ "metadata": {},
108
+ "source": [
109
+ "### Random sample from latent space\n",
110
+ "(Don't expect interesting results!)"
111
+ ]
112
+ },
113
+ {
114
+ "cell_type": "code",
115
+ "execution_count": null,
116
+ "id": "156a06a2",
117
+ "metadata": {},
118
+ "outputs": [],
119
+ "source": [
120
+ "# sample\n",
121
+ "output_image = vae.decode(torch.randn_like(latents))['sample']\n",
122
+ "output_image = torch.clamp(output_image, -1., 1.)\n",
123
+ "output_image = (output_image + 1.0) / 2.0 # -1,1 -> 0,1; c,h,w\n",
124
+ "output_image = (output_image.detach().cpu().numpy() *\n",
125
+ " 255).round().astype(\"uint8\").transpose(0, 2, 3, 1)[0, :, :, 0]\n",
126
+ "output_image = Image.fromarray(output_image)\n",
127
+ "display(output_image)\n",
128
+ "Audio(data=mel.image_to_audio(output_image), rate=mel.get_sample_rate())"
129
+ ]
130
+ },
131
+ {
132
+ "cell_type": "markdown",
133
+ "id": "ee3997cf",
134
+ "metadata": {},
135
+ "source": [
136
+ "### Interpolate between two audios in latent space"
137
+ ]
138
+ },
139
+ {
140
+ "cell_type": "code",
141
+ "execution_count": null,
142
+ "id": "46019770",
143
+ "metadata": {},
144
+ "outputs": [],
145
+ "source": [
146
+ "image2 = random.choice(ds['train'])['image']\n",
147
+ "display(image2)\n",
148
+ "Audio(data=mel.image_to_audio(image2), rate=mel.get_sample_rate())"
149
+ ]
150
+ },
151
+ {
152
+ "cell_type": "code",
153
+ "execution_count": null,
154
+ "id": "e6552b19",
155
+ "metadata": {},
156
+ "outputs": [],
157
+ "source": [
158
+ "# encode\n",
159
+ "input_image2 = np.frombuffer(image2.tobytes(), dtype=\"uint8\").reshape(\n",
160
+ " (image2.height, image2.width, 1))\n",
161
+ "input_image2 = ((input_image2 / 255) * 2 - 1).transpose(2, 0, 1)\n",
162
+ "posterior2 = vae.encode(torch.tensor([input_image2],\n",
163
+ " dtype=torch.float32)).latent_dist\n",
164
+ "latents2 = posterior2.sample()"
165
+ ]
166
+ },
167
+ {
168
+ "cell_type": "code",
169
+ "execution_count": null,
170
+ "id": "060a0b25",
171
+ "metadata": {},
172
+ "outputs": [],
173
+ "source": [
174
+ "# interpolate\n",
175
+ "alpha = 0.5 #@param {type:\"slider\", min:0, max:1, step:0.1}\n",
176
+ "output_image = vae.decode(\n",
177
+ " AudioDiffusionPipeline.slerp(latents, latents2, alpha))['sample']\n",
178
+ "output_image = torch.clamp(output_image, -1., 1.)\n",
179
+ "output_image = (output_image + 1.0) / 2.0 # -1,1 -> 0,1; c,h,w\n",
180
+ "output_image = (output_image.detach().cpu().numpy() *\n",
181
+ " 255).round().astype(\"uint8\").transpose(0, 2, 3, 1)[0, :, :, 0]\n",
182
+ "output_image = Image.fromarray(output_image)\n",
183
+ "display(output_image)\n",
184
+ "display(Audio(data=mel.image_to_audio(image), rate=mel.get_sample_rate()))\n",
185
+ "display(Audio(data=mel.image_to_audio(image2), rate=mel.get_sample_rate()))\n",
186
+ "display(\n",
187
+ " Audio(data=mel.image_to_audio(output_image), rate=mel.get_sample_rate()))"
188
+ ]
189
+ },
190
+ {
191
+ "cell_type": "code",
192
+ "execution_count": null,
193
+ "id": "d6c74105",
194
+ "metadata": {},
195
+ "outputs": [],
196
+ "source": []
197
+ }
198
+ ],
199
+ "metadata": {
200
+ "kernelspec": {
201
+ "display_name": "huggingface",
202
+ "language": "python",
203
+ "name": "huggingface"
204
+ },
205
+ "language_info": {
206
+ "codemirror_mode": {
207
+ "name": "ipython",
208
+ "version": 3
209
+ },
210
+ "file_extension": ".py",
211
+ "mimetype": "text/x-python",
212
+ "name": "python",
213
+ "nbconvert_exporter": "python",
214
+ "pygments_lexer": "ipython3",
215
+ "version": "3.10.6"
216
+ },
217
+ "toc": {
218
+ "base_numbering": 1,
219
+ "nav_menu": {},
220
+ "number_sections": true,
221
+ "sideBar": true,
222
+ "skip_h1_title": false,
223
+ "title_cell": "Table of Contents",
224
+ "title_sidebar": "Contents",
225
+ "toc_cell": false,
226
+ "toc_position": {},
227
+ "toc_section_display": true,
228
+ "toc_window_display": false
229
+ }
230
+ },
231
+ "nbformat": 4,
232
+ "nbformat_minor": 5
233
+ }
notebooks/train_model.ipynb ADDED
@@ -0,0 +1,600 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ "import sys\n",
46
+ "from IPython.display import Audio\n",
47
+ "from audiodiffusion import AudioDiffusion"
48
+ ]
49
+ },
50
+ {
51
+ "cell_type": "markdown",
52
+ "id": "MqlpL75_mDVv",
53
+ "metadata": {
54
+ "id": "MqlpL75_mDVv"
55
+ },
56
+ "source": [
57
+ "### Upload / specify audio files to train on\n",
58
+ "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."
59
+ ]
60
+ },
61
+ {
62
+ "cell_type": "code",
63
+ "execution_count": null,
64
+ "id": "jg1zAHVsmCBG",
65
+ "metadata": {
66
+ "colab": {
67
+ "base_uri": "https://localhost:8080/",
68
+ "height": 73
69
+ },
70
+ "id": "jg1zAHVsmCBG",
71
+ "outputId": "414244c9-02b6-4ccf-cbfd-83f9022a0fc1"
72
+ },
73
+ "outputs": [],
74
+ "source": [
75
+ "try:\n",
76
+ " # are we running on Google Colab?\n",
77
+ " from google.colab import files\n",
78
+ " input_dir = '.'\n",
79
+ " files.upload();\n",
80
+ "except:\n",
81
+ " input_dir = \".\""
82
+ ]
83
+ },
84
+ {
85
+ "cell_type": "markdown",
86
+ "id": "10v0RCSUu75P",
87
+ "metadata": {
88
+ "id": "10v0RCSUu75P"
89
+ },
90
+ "source": [
91
+ "### Prepare dataset"
92
+ ]
93
+ },
94
+ {
95
+ "cell_type": "code",
96
+ "execution_count": null,
97
+ "id": "NJNeEU6ftaTM",
98
+ "metadata": {
99
+ "colab": {
100
+ "base_uri": "https://localhost:8080/"
101
+ },
102
+ "id": "NJNeEU6ftaTM",
103
+ "outputId": "6c5bed15-c821-4def-eb90-3ab1a17b3c3d"
104
+ },
105
+ "outputs": [],
106
+ "source": [
107
+ "!{sys.executable} scripts/audio_to_images.py \\\n",
108
+ " --resolution 256,256 \\\n",
109
+ " --input_dir {input_dir} \\\n",
110
+ " --output_dir data"
111
+ ]
112
+ },
113
+ {
114
+ "cell_type": "markdown",
115
+ "id": "5mGeXyJFvQCO",
116
+ "metadata": {
117
+ "id": "5mGeXyJFvQCO"
118
+ },
119
+ "source": [
120
+ "### Train model\n",
121
+ "The DDIM scheduler generates samples much faster."
122
+ ]
123
+ },
124
+ {
125
+ "cell_type": "code",
126
+ "execution_count": null,
127
+ "id": "JGnlePbLvTOH",
128
+ "metadata": {
129
+ "colab": {
130
+ "base_uri": "https://localhost:8080/"
131
+ },
132
+ "id": "JGnlePbLvTOH",
133
+ "outputId": "69b6f53e-25a3-4c59-e205-2eab42889cd8"
134
+ },
135
+ "outputs": [],
136
+ "source": [
137
+ "!{sys.executable} scripts/train_unet.py \\\n",
138
+ " --dataset_name data \\\n",
139
+ " --output_dir models/model \\\n",
140
+ " --num_epochs 10 \\\n",
141
+ " --train_batch_size 2 \\\n",
142
+ " --eval_batch_size 2 \\\n",
143
+ " --gradient_accumulation_steps 8 \\\n",
144
+ " --save_images_epochs 100 \\\n",
145
+ " --save_model_epochs 1 \\\n",
146
+ " --scheduler ddim"
147
+ ]
148
+ },
149
+ {
150
+ "cell_type": "markdown",
151
+ "id": "nTMAYEtMxtt0",
152
+ "metadata": {
153
+ "id": "nTMAYEtMxtt0"
154
+ },
155
+ "source": [
156
+ "### Generate samples with model"
157
+ ]
158
+ },
159
+ {
160
+ "cell_type": "code",
161
+ "execution_count": null,
162
+ "id": "b294a94a",
163
+ "metadata": {
164
+ "id": "b294a94a"
165
+ },
166
+ "outputs": [],
167
+ "source": [
168
+ "audio_diffusion = AudioDiffusion(\"models/model\")"
169
+ ]
170
+ },
171
+ {
172
+ "cell_type": "code",
173
+ "execution_count": null,
174
+ "id": "k2bKq3aqyAIM",
175
+ "metadata": {
176
+ "colab": {
177
+ "base_uri": "https://localhost:8080/",
178
+ "height": 363,
179
+ "referenced_widgets": [
180
+ "474d4db933d54e0497da4076a7fe135b",
181
+ "a849a3a1b46947db830a6a087411ec68",
182
+ "378f819239274ac88d913714bc27bf06",
183
+ "cc3b33e508744206955b26a417fbbdec",
184
+ "6015e5a9e6774e9abf7db273bca57363",
185
+ "629c21c68d22447185bb961e22bce4a6",
186
+ "2d5abefbc2ed4b72aed8c4f8ddc7a00c",
187
+ "11d1dbae00764a1c9dcc899c0b0f67dc",
188
+ "acdb5ddc7bda411a948689787b18b21e",
189
+ "9c4955f9d0f443a7b28ed827c5cdb37f",
190
+ "f9a1a976d82148f8961e80c357bc2764"
191
+ ]
192
+ },
193
+ "id": "k2bKq3aqyAIM",
194
+ "outputId": "d48238fe-ae36-4736-e67b-b69e3729304a"
195
+ },
196
+ "outputs": [],
197
+ "source": [
198
+ "image, (sample_rate, audio) = audio_diffusion.generate_spectrogram_and_audio()\n",
199
+ "display(image)\n",
200
+ "display(Audio(audio, rate=sample_rate))"
201
+ ]
202
+ },
203
+ {
204
+ "cell_type": "code",
205
+ "execution_count": null,
206
+ "id": "K2qAIJzg2DNK",
207
+ "metadata": {
208
+ "id": "K2qAIJzg2DNK"
209
+ },
210
+ "outputs": [],
211
+ "source": []
212
+ }
213
+ ],
214
+ "metadata": {
215
+ "accelerator": "GPU",
216
+ "colab": {
217
+ "collapsed_sections": [],
218
+ "provenance": []
219
+ },
220
+ "gpuClass": "standard",
221
+ "kernelspec": {
222
+ "display_name": "tmp",
223
+ "language": "python",
224
+ "name": "tmp"
225
+ },
226
+ "language_info": {
227
+ "codemirror_mode": {
228
+ "name": "ipython",
229
+ "version": 3
230
+ },
231
+ "file_extension": ".py",
232
+ "mimetype": "text/x-python",
233
+ "name": "python",
234
+ "nbconvert_exporter": "python",
235
+ "pygments_lexer": "ipython3",
236
+ "version": "3.10.6"
237
+ },
238
+ "toc": {
239
+ "base_numbering": 1,
240
+ "nav_menu": {},
241
+ "number_sections": true,
242
+ "sideBar": true,
243
+ "skip_h1_title": false,
244
+ "title_cell": "Table of Contents",
245
+ "title_sidebar": "Contents",
246
+ "toc_cell": false,
247
+ "toc_position": {},
248
+ "toc_section_display": true,
249
+ "toc_window_display": false
250
+ },
251
+ "widgets": {
252
+ "application/vnd.jupyter.widget-state+json": {
253
+ "11d1dbae00764a1c9dcc899c0b0f67dc": {
254
+ "model_module": "@jupyter-widgets/base",
255
+ "model_module_version": "1.2.0",
256
+ "model_name": "LayoutModel",
257
+ "state": {
258
+ "_model_module": "@jupyter-widgets/base",
259
+ "_model_module_version": "1.2.0",
260
+ "_model_name": "LayoutModel",
261
+ "_view_count": null,
262
+ "_view_module": "@jupyter-widgets/base",
263
+ "_view_module_version": "1.2.0",
264
+ "_view_name": "LayoutView",
265
+ "align_content": null,
266
+ "align_items": null,
267
+ "align_self": null,
268
+ "border": null,
269
+ "bottom": null,
270
+ "display": null,
271
+ "flex": null,
272
+ "flex_flow": null,
273
+ "grid_area": null,
274
+ "grid_auto_columns": null,
275
+ "grid_auto_flow": null,
276
+ "grid_auto_rows": null,
277
+ "grid_column": null,
278
+ "grid_gap": null,
279
+ "grid_row": null,
280
+ "grid_template_areas": null,
281
+ "grid_template_columns": null,
282
+ "grid_template_rows": null,
283
+ "height": null,
284
+ "justify_content": null,
285
+ "justify_items": null,
286
+ "left": null,
287
+ "margin": null,
288
+ "max_height": null,
289
+ "max_width": null,
290
+ "min_height": null,
291
+ "min_width": null,
292
+ "object_fit": null,
293
+ "object_position": null,
294
+ "order": null,
295
+ "overflow": null,
296
+ "overflow_x": null,
297
+ "overflow_y": null,
298
+ "padding": null,
299
+ "right": null,
300
+ "top": null,
301
+ "visibility": null,
302
+ "width": null
303
+ }
304
+ },
305
+ "2d5abefbc2ed4b72aed8c4f8ddc7a00c": {
306
+ "model_module": "@jupyter-widgets/controls",
307
+ "model_module_version": "1.5.0",
308
+ "model_name": "DescriptionStyleModel",
309
+ "state": {
310
+ "_model_module": "@jupyter-widgets/controls",
311
+ "_model_module_version": "1.5.0",
312
+ "_model_name": "DescriptionStyleModel",
313
+ "_view_count": null,
314
+ "_view_module": "@jupyter-widgets/base",
315
+ "_view_module_version": "1.2.0",
316
+ "_view_name": "StyleView",
317
+ "description_width": ""
318
+ }
319
+ },
320
+ "378f819239274ac88d913714bc27bf06": {
321
+ "model_module": "@jupyter-widgets/controls",
322
+ "model_module_version": "1.5.0",
323
+ "model_name": "FloatProgressModel",
324
+ "state": {
325
+ "_dom_classes": [],
326
+ "_model_module": "@jupyter-widgets/controls",
327
+ "_model_module_version": "1.5.0",
328
+ "_model_name": "FloatProgressModel",
329
+ "_view_count": null,
330
+ "_view_module": "@jupyter-widgets/controls",
331
+ "_view_module_version": "1.5.0",
332
+ "_view_name": "ProgressView",
333
+ "bar_style": "success",
334
+ "description": "",
335
+ "description_tooltip": null,
336
+ "layout": "IPY_MODEL_11d1dbae00764a1c9dcc899c0b0f67dc",
337
+ "max": 50,
338
+ "min": 0,
339
+ "orientation": "horizontal",
340
+ "style": "IPY_MODEL_acdb5ddc7bda411a948689787b18b21e",
341
+ "value": 50
342
+ }
343
+ },
344
+ "474d4db933d54e0497da4076a7fe135b": {
345
+ "model_module": "@jupyter-widgets/controls",
346
+ "model_module_version": "1.5.0",
347
+ "model_name": "HBoxModel",
348
+ "state": {
349
+ "_dom_classes": [],
350
+ "_model_module": "@jupyter-widgets/controls",
351
+ "_model_module_version": "1.5.0",
352
+ "_model_name": "HBoxModel",
353
+ "_view_count": null,
354
+ "_view_module": "@jupyter-widgets/controls",
355
+ "_view_module_version": "1.5.0",
356
+ "_view_name": "HBoxView",
357
+ "box_style": "",
358
+ "children": [
359
+ "IPY_MODEL_a849a3a1b46947db830a6a087411ec68",
360
+ "IPY_MODEL_378f819239274ac88d913714bc27bf06",
361
+ "IPY_MODEL_cc3b33e508744206955b26a417fbbdec"
362
+ ],
363
+ "layout": "IPY_MODEL_6015e5a9e6774e9abf7db273bca57363"
364
+ }
365
+ },
366
+ "6015e5a9e6774e9abf7db273bca57363": {
367
+ "model_module": "@jupyter-widgets/base",
368
+ "model_module_version": "1.2.0",
369
+ "model_name": "LayoutModel",
370
+ "state": {
371
+ "_model_module": "@jupyter-widgets/base",
372
+ "_model_module_version": "1.2.0",
373
+ "_model_name": "LayoutModel",
374
+ "_view_count": null,
375
+ "_view_module": "@jupyter-widgets/base",
376
+ "_view_module_version": "1.2.0",
377
+ "_view_name": "LayoutView",
378
+ "align_content": null,
379
+ "align_items": null,
380
+ "align_self": null,
381
+ "border": null,
382
+ "bottom": null,
383
+ "display": null,
384
+ "flex": null,
385
+ "flex_flow": null,
386
+ "grid_area": null,
387
+ "grid_auto_columns": null,
388
+ "grid_auto_flow": null,
389
+ "grid_auto_rows": null,
390
+ "grid_column": null,
391
+ "grid_gap": null,
392
+ "grid_row": null,
393
+ "grid_template_areas": null,
394
+ "grid_template_columns": null,
395
+ "grid_template_rows": null,
396
+ "height": null,
397
+ "justify_content": null,
398
+ "justify_items": null,
399
+ "left": null,
400
+ "margin": null,
401
+ "max_height": null,
402
+ "max_width": null,
403
+ "min_height": null,
404
+ "min_width": null,
405
+ "object_fit": null,
406
+ "object_position": null,
407
+ "order": null,
408
+ "overflow": null,
409
+ "overflow_x": null,
410
+ "overflow_y": null,
411
+ "padding": null,
412
+ "right": null,
413
+ "top": null,
414
+ "visibility": null,
415
+ "width": null
416
+ }
417
+ },
418
+ "629c21c68d22447185bb961e22bce4a6": {
419
+ "model_module": "@jupyter-widgets/base",
420
+ "model_module_version": "1.2.0",
421
+ "model_name": "LayoutModel",
422
+ "state": {
423
+ "_model_module": "@jupyter-widgets/base",
424
+ "_model_module_version": "1.2.0",
425
+ "_model_name": "LayoutModel",
426
+ "_view_count": null,
427
+ "_view_module": "@jupyter-widgets/base",
428
+ "_view_module_version": "1.2.0",
429
+ "_view_name": "LayoutView",
430
+ "align_content": null,
431
+ "align_items": null,
432
+ "align_self": null,
433
+ "border": null,
434
+ "bottom": null,
435
+ "display": null,
436
+ "flex": null,
437
+ "flex_flow": null,
438
+ "grid_area": null,
439
+ "grid_auto_columns": null,
440
+ "grid_auto_flow": null,
441
+ "grid_auto_rows": null,
442
+ "grid_column": null,
443
+ "grid_gap": null,
444
+ "grid_row": null,
445
+ "grid_template_areas": null,
446
+ "grid_template_columns": null,
447
+ "grid_template_rows": null,
448
+ "height": null,
449
+ "justify_content": null,
450
+ "justify_items": null,
451
+ "left": null,
452
+ "margin": null,
453
+ "max_height": null,
454
+ "max_width": null,
455
+ "min_height": null,
456
+ "min_width": null,
457
+ "object_fit": null,
458
+ "object_position": null,
459
+ "order": null,
460
+ "overflow": null,
461
+ "overflow_x": null,
462
+ "overflow_y": null,
463
+ "padding": null,
464
+ "right": null,
465
+ "top": null,
466
+ "visibility": null,
467
+ "width": null
468
+ }
469
+ },
470
+ "9c4955f9d0f443a7b28ed827c5cdb37f": {
471
+ "model_module": "@jupyter-widgets/base",
472
+ "model_module_version": "1.2.0",
473
+ "model_name": "LayoutModel",
474
+ "state": {
475
+ "_model_module": "@jupyter-widgets/base",
476
+ "_model_module_version": "1.2.0",
477
+ "_model_name": "LayoutModel",
478
+ "_view_count": null,
479
+ "_view_module": "@jupyter-widgets/base",
480
+ "_view_module_version": "1.2.0",
481
+ "_view_name": "LayoutView",
482
+ "align_content": null,
483
+ "align_items": null,
484
+ "align_self": null,
485
+ "border": null,
486
+ "bottom": null,
487
+ "display": null,
488
+ "flex": null,
489
+ "flex_flow": null,
490
+ "grid_area": null,
491
+ "grid_auto_columns": null,
492
+ "grid_auto_flow": null,
493
+ "grid_auto_rows": null,
494
+ "grid_column": null,
495
+ "grid_gap": null,
496
+ "grid_row": null,
497
+ "grid_template_areas": null,
498
+ "grid_template_columns": null,
499
+ "grid_template_rows": null,
500
+ "height": null,
501
+ "justify_content": null,
502
+ "justify_items": null,
503
+ "left": null,
504
+ "margin": null,
505
+ "max_height": null,
506
+ "max_width": null,
507
+ "min_height": null,
508
+ "min_width": null,
509
+ "object_fit": null,
510
+ "object_position": null,
511
+ "order": null,
512
+ "overflow": null,
513
+ "overflow_x": null,
514
+ "overflow_y": null,
515
+ "padding": null,
516
+ "right": null,
517
+ "top": null,
518
+ "visibility": null,
519
+ "width": null
520
+ }
521
+ },
522
+ "a849a3a1b46947db830a6a087411ec68": {
523
+ "model_module": "@jupyter-widgets/controls",
524
+ "model_module_version": "1.5.0",
525
+ "model_name": "HTMLModel",
526
+ "state": {
527
+ "_dom_classes": [],
528
+ "_model_module": "@jupyter-widgets/controls",
529
+ "_model_module_version": "1.5.0",
530
+ "_model_name": "HTMLModel",
531
+ "_view_count": null,
532
+ "_view_module": "@jupyter-widgets/controls",
533
+ "_view_module_version": "1.5.0",
534
+ "_view_name": "HTMLView",
535
+ "description": "",
536
+ "description_tooltip": null,
537
+ "layout": "IPY_MODEL_629c21c68d22447185bb961e22bce4a6",
538
+ "placeholder": "​",
539
+ "style": "IPY_MODEL_2d5abefbc2ed4b72aed8c4f8ddc7a00c",
540
+ "value": "100%"
541
+ }
542
+ },
543
+ "acdb5ddc7bda411a948689787b18b21e": {
544
+ "model_module": "@jupyter-widgets/controls",
545
+ "model_module_version": "1.5.0",
546
+ "model_name": "ProgressStyleModel",
547
+ "state": {
548
+ "_model_module": "@jupyter-widgets/controls",
549
+ "_model_module_version": "1.5.0",
550
+ "_model_name": "ProgressStyleModel",
551
+ "_view_count": null,
552
+ "_view_module": "@jupyter-widgets/base",
553
+ "_view_module_version": "1.2.0",
554
+ "_view_name": "StyleView",
555
+ "bar_color": null,
556
+ "description_width": ""
557
+ }
558
+ },
559
+ "cc3b33e508744206955b26a417fbbdec": {
560
+ "model_module": "@jupyter-widgets/controls",
561
+ "model_module_version": "1.5.0",
562
+ "model_name": "HTMLModel",
563
+ "state": {
564
+ "_dom_classes": [],
565
+ "_model_module": "@jupyter-widgets/controls",
566
+ "_model_module_version": "1.5.0",
567
+ "_model_name": "HTMLModel",
568
+ "_view_count": null,
569
+ "_view_module": "@jupyter-widgets/controls",
570
+ "_view_module_version": "1.5.0",
571
+ "_view_name": "HTMLView",
572
+ "description": "",
573
+ "description_tooltip": null,
574
+ "layout": "IPY_MODEL_9c4955f9d0f443a7b28ed827c5cdb37f",
575
+ "placeholder": "​",
576
+ "style": "IPY_MODEL_f9a1a976d82148f8961e80c357bc2764",
577
+ "value": " 50/50 [00:07&lt;00:00, 8.13it/s]"
578
+ }
579
+ },
580
+ "f9a1a976d82148f8961e80c357bc2764": {
581
+ "model_module": "@jupyter-widgets/controls",
582
+ "model_module_version": "1.5.0",
583
+ "model_name": "DescriptionStyleModel",
584
+ "state": {
585
+ "_model_module": "@jupyter-widgets/controls",
586
+ "_model_module_version": "1.5.0",
587
+ "_model_name": "DescriptionStyleModel",
588
+ "_view_count": null,
589
+ "_view_module": "@jupyter-widgets/base",
590
+ "_view_module_version": "1.2.0",
591
+ "_view_name": "StyleView",
592
+ "description_width": ""
593
+ }
594
+ }
595
+ }
596
+ }
597
+ },
598
+ "nbformat": 4,
599
+ "nbformat_minor": 5
600
+ }
pyproject.toml ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ [tool.black]
2
+ line-length = 119
3
+ target-version = ['py36']
requirements.txt ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ torch
2
+ numpy
3
+ Pillow
4
+ diffusers>=0.12.0
5
+ librosa
6
+ datasets>=2.9.0
7
+ gradio
8
+ streamlit
9
+ tensorboard
10
+ accelerate
11
+ torchvision
12
+ transformers
scripts/audio_to_images.py ADDED
@@ -0,0 +1,113 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import io
3
+ import logging
4
+ import os
5
+ import re
6
+
7
+ import numpy as np
8
+ import pandas as pd
9
+ from datasets import Dataset, DatasetDict, Features, Image, Value
10
+ from diffusers.pipelines.audio_diffusion import Mel
11
+ from tqdm.auto import tqdm
12
+
13
+ logging.basicConfig(level=logging.WARN)
14
+ logger = logging.getLogger("audio_to_images")
15
+
16
+
17
+ def main(args):
18
+ mel = Mel(
19
+ x_res=args.resolution[0],
20
+ y_res=args.resolution[1],
21
+ hop_length=args.hop_length,
22
+ sample_rate=args.sample_rate,
23
+ n_fft=args.n_fft,
24
+ )
25
+ os.makedirs(args.output_dir, exist_ok=True)
26
+ audio_files = [
27
+ os.path.join(root, file)
28
+ for root, _, files in os.walk(args.input_dir)
29
+ for file in files
30
+ if re.search("\.(mp3|wav|m4a)$", file, re.IGNORECASE)
31
+ ]
32
+ examples = []
33
+ try:
34
+ for audio_file in tqdm(audio_files):
35
+ try:
36
+ mel.load_audio(audio_file)
37
+ except KeyboardInterrupt:
38
+ raise
39
+ except:
40
+ continue
41
+ for slice in range(mel.get_number_of_slices()):
42
+ image = mel.audio_slice_to_image(slice)
43
+ assert image.width == args.resolution[0] and image.height == args.resolution[1], "Wrong resolution"
44
+ # skip completely silent slices
45
+ if all(np.frombuffer(image.tobytes(), dtype=np.uint8) == 255):
46
+ logger.warn("File %s slice %d is completely silent", audio_file, slice)
47
+ continue
48
+ with io.BytesIO() as output:
49
+ image.save(output, format="PNG")
50
+ bytes = output.getvalue()
51
+ examples.extend(
52
+ [
53
+ {
54
+ "image": {"bytes": bytes},
55
+ "audio_file": audio_file,
56
+ "slice": slice,
57
+ }
58
+ ]
59
+ )
60
+ except Exception as e:
61
+ print(e)
62
+ finally:
63
+ if len(examples) == 0:
64
+ logger.warn("No valid audio files were found.")
65
+ return
66
+ ds = Dataset.from_pandas(
67
+ pd.DataFrame(examples),
68
+ features=Features(
69
+ {
70
+ "image": Image(),
71
+ "audio_file": Value(dtype="string"),
72
+ "slice": Value(dtype="int16"),
73
+ }
74
+ ),
75
+ )
76
+ dsd = DatasetDict({"train": ds})
77
+ dsd.save_to_disk(os.path.join(args.output_dir))
78
+ if args.push_to_hub:
79
+ dsd.push_to_hub(args.push_to_hub)
80
+
81
+
82
+ if __name__ == "__main__":
83
+ parser = argparse.ArgumentParser(description="Create dataset of Mel spectrograms from directory of audio files.")
84
+ parser.add_argument("--input_dir", type=str)
85
+ parser.add_argument("--output_dir", type=str, default="data")
86
+ parser.add_argument(
87
+ "--resolution",
88
+ type=str,
89
+ default="256",
90
+ help="Either square resolution or width,height.",
91
+ )
92
+ parser.add_argument("--hop_length", type=int, default=512)
93
+ parser.add_argument("--push_to_hub", type=str, default=None)
94
+ parser.add_argument("--sample_rate", type=int, default=22050)
95
+ parser.add_argument("--n_fft", type=int, default=2048)
96
+ args = parser.parse_args()
97
+
98
+ if args.input_dir is None:
99
+ raise ValueError("You must specify an input directory for the audio files.")
100
+
101
+ # Handle the resolutions.
102
+ try:
103
+ args.resolution = (int(args.resolution), int(args.resolution))
104
+ except ValueError:
105
+ try:
106
+ args.resolution = tuple(int(x) for x in args.resolution.split(","))
107
+ if len(args.resolution) != 2:
108
+ raise ValueError
109
+ except ValueError:
110
+ raise ValueError("Resolution must be a tuple of two integers or a single integer.")
111
+ assert isinstance(args.resolution, tuple)
112
+
113
+ main(args)
scripts/encode_audio.py ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import os
3
+ import pickle
4
+
5
+ from datasets import load_dataset, load_from_disk
6
+ from tqdm.auto import tqdm
7
+
8
+ from audiodiffusion.audio_encoder import AudioEncoder
9
+
10
+
11
+ def main(args):
12
+ audio_encoder = AudioEncoder.from_pretrained("teticio/audio-encoder")
13
+
14
+ if args.dataset_name is not None:
15
+ if os.path.exists(args.dataset_name):
16
+ dataset = load_from_disk(args.dataset_name)["train"]
17
+ else:
18
+ dataset = load_dataset(
19
+ args.dataset_name,
20
+ args.dataset_config_name,
21
+ cache_dir=args.cache_dir,
22
+ use_auth_token=True if args.use_auth_token else None,
23
+ split="train",
24
+ )
25
+
26
+ encodings = {}
27
+ for audio_file in tqdm(dataset.to_pandas()["audio_file"].unique()):
28
+ encodings[audio_file] = audio_encoder.encode([audio_file])
29
+ pickle.dump(encodings, open(args.output_file, "wb"))
30
+
31
+
32
+ if __name__ == "__main__":
33
+ parser = argparse.ArgumentParser(description="Create pickled audio encodings for dataset of audio files.")
34
+ parser.add_argument("--dataset_name", type=str, default=None)
35
+ parser.add_argument("--output_file", type=str, default="data/encodings.p")
36
+ parser.add_argument("--use_auth_token", type=bool, default=False)
37
+ args = parser.parse_args()
38
+ main(args)
scripts/train_unet.py ADDED
@@ -0,0 +1,453 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # based on https://github.com/huggingface/diffusers/blob/main/examples/train_unconditional.py
2
+
3
+ import argparse
4
+ import os
5
+ import pickle
6
+ import random
7
+ from pathlib import Path
8
+ from typing import Optional
9
+
10
+ import numpy as np
11
+ import torch
12
+ import torch.nn.functional as F
13
+ from accelerate import Accelerator
14
+ from accelerate.logging import get_logger
15
+ from datasets import load_dataset, load_from_disk
16
+ from diffusers import (AutoencoderKL, DDIMScheduler, DDPMScheduler,
17
+ UNet2DConditionModel, UNet2DModel)
18
+ from diffusers.optimization import get_scheduler
19
+ from diffusers.pipelines.audio_diffusion import Mel
20
+ from diffusers.training_utils import EMAModel
21
+ from huggingface_hub import HfFolder, Repository, whoami
22
+ from librosa.util import normalize
23
+ from torchvision.transforms import Compose, Normalize, ToTensor
24
+ from tqdm.auto import tqdm
25
+
26
+ from audiodiffusion.pipeline_audio_diffusion import AudioDiffusionPipeline
27
+
28
+ logger = get_logger(__name__)
29
+
30
+
31
+ def get_full_repo_name(model_id: str,
32
+ organization: Optional[str] = None,
33
+ token: Optional[str] = None):
34
+ if token is None:
35
+ token = HfFolder.get_token()
36
+ if organization is None:
37
+ username = whoami(token)["name"]
38
+ return f"{username}/{model_id}"
39
+ else:
40
+ return f"{organization}/{model_id}"
41
+
42
+
43
+ def main(args):
44
+ output_dir = os.environ.get("SM_MODEL_DIR", None) or args.output_dir
45
+ logging_dir = os.path.join(output_dir, args.logging_dir)
46
+ accelerator = Accelerator(
47
+ gradient_accumulation_steps=args.gradient_accumulation_steps,
48
+ mixed_precision=args.mixed_precision,
49
+ log_with="tensorboard",
50
+ logging_dir=logging_dir,
51
+ )
52
+
53
+ if args.dataset_name is not None:
54
+ if os.path.exists(args.dataset_name):
55
+ dataset = load_from_disk(
56
+ args.dataset_name,
57
+ storage_options=args.dataset_config_name)["train"]
58
+ else:
59
+ dataset = load_dataset(
60
+ args.dataset_name,
61
+ args.dataset_config_name,
62
+ cache_dir=args.cache_dir,
63
+ use_auth_token=True if args.use_auth_token else None,
64
+ split="train",
65
+ )
66
+ else:
67
+ dataset = load_dataset(
68
+ "imagefolder",
69
+ data_dir=args.train_data_dir,
70
+ cache_dir=args.cache_dir,
71
+ split="train",
72
+ )
73
+ # Determine image resolution
74
+ resolution = dataset[0]["image"].height, dataset[0]["image"].width
75
+
76
+ augmentations = Compose([
77
+ ToTensor(),
78
+ Normalize([0.5], [0.5]),
79
+ ])
80
+
81
+ def transforms(examples):
82
+ if args.vae is not None and vqvae.config["in_channels"] == 3:
83
+ images = [
84
+ augmentations(image.convert("RGB"))
85
+ for image in examples["image"]
86
+ ]
87
+ else:
88
+ images = [augmentations(image) for image in examples["image"]]
89
+ if args.encodings is not None:
90
+ encoding = [encodings[file] for file in examples["audio_file"]]
91
+ return {"input": images, "encoding": encoding}
92
+ return {"input": images}
93
+
94
+ dataset.set_transform(transforms)
95
+ train_dataloader = torch.utils.data.DataLoader(
96
+ dataset, batch_size=args.train_batch_size, shuffle=True)
97
+
98
+ if args.encodings is not None:
99
+ encodings = pickle.load(open(args.encodings, "rb"))
100
+
101
+ vqvae = None
102
+ if args.vae is not None:
103
+ try:
104
+ vqvae = AutoencoderKL.from_pretrained(args.vae)
105
+ except EnvironmentError:
106
+ vqvae = AudioDiffusionPipeline.from_pretrained(args.vae).vqvae
107
+ # Determine latent resolution
108
+ with torch.no_grad():
109
+ latent_resolution = vqvae.encode(
110
+ torch.zeros((1, 1) +
111
+ resolution)).latent_dist.sample().shape[2:]
112
+
113
+ if args.from_pretrained is not None:
114
+ pipeline = AudioDiffusionPipeline.from_pretrained(args.from_pretrained)
115
+ mel = pipeline.mel
116
+ model = pipeline.unet
117
+ if hasattr(pipeline, "vqvae"):
118
+ vqvae = pipeline.vqvae
119
+
120
+ else:
121
+ if args.encodings is None:
122
+ model = UNet2DModel(
123
+ sample_size=resolution if vqvae is None else latent_resolution,
124
+ in_channels=1
125
+ if vqvae is None else vqvae.config["latent_channels"],
126
+ out_channels=1
127
+ if vqvae is None else vqvae.config["latent_channels"],
128
+ layers_per_block=2,
129
+ block_out_channels=(128, 128, 256, 256, 512, 512),
130
+ down_block_types=(
131
+ "DownBlock2D",
132
+ "DownBlock2D",
133
+ "DownBlock2D",
134
+ "DownBlock2D",
135
+ "AttnDownBlock2D",
136
+ "DownBlock2D",
137
+ ),
138
+ up_block_types=(
139
+ "UpBlock2D",
140
+ "AttnUpBlock2D",
141
+ "UpBlock2D",
142
+ "UpBlock2D",
143
+ "UpBlock2D",
144
+ "UpBlock2D",
145
+ ),
146
+ )
147
+
148
+ else:
149
+ model = UNet2DConditionModel(
150
+ sample_size=resolution if vqvae is None else latent_resolution,
151
+ in_channels=1
152
+ if vqvae is None else vqvae.config["latent_channels"],
153
+ out_channels=1
154
+ if vqvae is None else vqvae.config["latent_channels"],
155
+ layers_per_block=2,
156
+ block_out_channels=(128, 256, 512, 512),
157
+ down_block_types=(
158
+ "CrossAttnDownBlock2D",
159
+ "CrossAttnDownBlock2D",
160
+ "CrossAttnDownBlock2D",
161
+ "DownBlock2D",
162
+ ),
163
+ up_block_types=(
164
+ "UpBlock2D",
165
+ "CrossAttnUpBlock2D",
166
+ "CrossAttnUpBlock2D",
167
+ "CrossAttnUpBlock2D",
168
+ ),
169
+ cross_attention_dim=list(encodings.values())[0].shape[-1],
170
+ )
171
+
172
+ if args.scheduler == "ddpm":
173
+ noise_scheduler = DDPMScheduler(
174
+ num_train_timesteps=args.num_train_steps)
175
+ else:
176
+ noise_scheduler = DDIMScheduler(
177
+ num_train_timesteps=args.num_train_steps)
178
+
179
+ optimizer = torch.optim.AdamW(
180
+ model.parameters(),
181
+ lr=args.learning_rate,
182
+ betas=(args.adam_beta1, args.adam_beta2),
183
+ weight_decay=args.adam_weight_decay,
184
+ eps=args.adam_epsilon,
185
+ )
186
+
187
+ lr_scheduler = get_scheduler(
188
+ args.lr_scheduler,
189
+ optimizer=optimizer,
190
+ num_warmup_steps=args.lr_warmup_steps,
191
+ num_training_steps=(len(train_dataloader) * args.num_epochs) //
192
+ args.gradient_accumulation_steps,
193
+ )
194
+
195
+ model, optimizer, train_dataloader, lr_scheduler = accelerator.prepare(
196
+ model, optimizer, train_dataloader, lr_scheduler)
197
+
198
+ ema_model = EMAModel(
199
+ getattr(model, "module", model),
200
+ inv_gamma=args.ema_inv_gamma,
201
+ power=args.ema_power,
202
+ max_value=args.ema_max_decay,
203
+ )
204
+
205
+ if args.push_to_hub:
206
+ if args.hub_model_id is None:
207
+ repo_name = get_full_repo_name(Path(output_dir).name,
208
+ token=args.hub_token)
209
+ else:
210
+ repo_name = args.hub_model_id
211
+ repo = Repository(output_dir, clone_from=repo_name)
212
+
213
+ if accelerator.is_main_process:
214
+ run = os.path.split(__file__)[-1].split(".")[0]
215
+ accelerator.init_trackers(run)
216
+
217
+ mel = Mel(
218
+ x_res=resolution[1],
219
+ y_res=resolution[0],
220
+ hop_length=args.hop_length,
221
+ sample_rate=args.sample_rate,
222
+ n_fft=args.n_fft,
223
+ )
224
+
225
+ global_step = 0
226
+ for epoch in range(args.num_epochs):
227
+ progress_bar = tqdm(total=len(train_dataloader),
228
+ disable=not accelerator.is_local_main_process)
229
+ progress_bar.set_description(f"Epoch {epoch}")
230
+
231
+ if epoch < args.start_epoch:
232
+ for step in range(len(train_dataloader)):
233
+ optimizer.step()
234
+ lr_scheduler.step()
235
+ progress_bar.update(1)
236
+ global_step += 1
237
+ if epoch == args.start_epoch - 1 and args.use_ema:
238
+ ema_model.optimization_step = global_step
239
+ continue
240
+
241
+ model.train()
242
+ for step, batch in enumerate(train_dataloader):
243
+ clean_images = batch["input"]
244
+
245
+ if vqvae is not None:
246
+ vqvae.to(clean_images.device)
247
+ with torch.no_grad():
248
+ clean_images = vqvae.encode(
249
+ clean_images).latent_dist.sample()
250
+ # Scale latent images to ensure approximately unit variance
251
+ clean_images = clean_images * 0.18215
252
+
253
+ # Sample noise that we'll add to the images
254
+ noise = torch.randn(clean_images.shape).to(clean_images.device)
255
+ bsz = clean_images.shape[0]
256
+ # Sample a random timestep for each image
257
+ timesteps = torch.randint(
258
+ 0,
259
+ noise_scheduler.config.num_train_timesteps,
260
+ (bsz, ),
261
+ device=clean_images.device,
262
+ ).long()
263
+
264
+ # Add noise to the clean images according to the noise magnitude at each timestep
265
+ # (this is the forward diffusion process)
266
+ noisy_images = noise_scheduler.add_noise(clean_images, noise,
267
+ timesteps)
268
+
269
+ with accelerator.accumulate(model):
270
+ # Predict the noise residual
271
+ if args.encodings is not None:
272
+ noise_pred = model(noisy_images, timesteps,
273
+ batch["encoding"])["sample"]
274
+ else:
275
+ noise_pred = model(noisy_images, timesteps)["sample"]
276
+ loss = F.mse_loss(noise_pred, noise)
277
+ accelerator.backward(loss)
278
+
279
+ if accelerator.sync_gradients:
280
+ accelerator.clip_grad_norm_(model.parameters(), 1.0)
281
+ optimizer.step()
282
+ lr_scheduler.step()
283
+ if args.use_ema:
284
+ ema_model.step(model)
285
+ optimizer.zero_grad()
286
+
287
+ progress_bar.update(1)
288
+ global_step += 1
289
+
290
+ logs = {
291
+ "loss": loss.detach().item(),
292
+ "lr": lr_scheduler.get_last_lr()[0],
293
+ "step": global_step,
294
+ }
295
+ if args.use_ema:
296
+ logs["ema_decay"] = ema_model.decay
297
+ progress_bar.set_postfix(**logs)
298
+ accelerator.log(logs, step=global_step)
299
+ progress_bar.close()
300
+
301
+ accelerator.wait_for_everyone()
302
+
303
+ # Generate sample images for visual inspection
304
+ if accelerator.is_main_process:
305
+ if ((epoch + 1) % args.save_model_epochs == 0
306
+ or (epoch + 1) % args.save_images_epochs == 0
307
+ or epoch == args.num_epochs - 1):
308
+ unet = accelerator.unwrap_model(model)
309
+ if args.use_ema:
310
+ ema_model.copy_to(unet.parameters())
311
+ pipeline = AudioDiffusionPipeline(
312
+ vqvae=vqvae,
313
+ unet=unet,
314
+ mel=mel,
315
+ scheduler=noise_scheduler,
316
+ )
317
+
318
+ if (
319
+ epoch + 1
320
+ ) % args.save_model_epochs == 0 or epoch == args.num_epochs - 1:
321
+ pipeline.save_pretrained(output_dir)
322
+
323
+ # save the model
324
+ if args.push_to_hub:
325
+ repo.push_to_hub(
326
+ commit_message=f"Epoch {epoch}",
327
+ blocking=False,
328
+ auto_lfs_prune=True,
329
+ )
330
+
331
+ if (epoch + 1) % args.save_images_epochs == 0:
332
+ generator = torch.Generator(
333
+ device=clean_images.device).manual_seed(42)
334
+
335
+ if args.encodings is not None:
336
+ random.seed(42)
337
+ encoding = torch.stack(
338
+ random.sample(list(encodings.values()),
339
+ args.eval_batch_size)).to(
340
+ clean_images.device)
341
+ else:
342
+ encoding = None
343
+
344
+ # run pipeline in inference (sample random noise and denoise)
345
+ images, (sample_rate, audios) = pipeline(
346
+ generator=generator,
347
+ batch_size=args.eval_batch_size,
348
+ return_dict=False,
349
+ encoding=encoding,
350
+ )
351
+
352
+ # denormalize the images and save to tensorboard
353
+ images = np.array([
354
+ np.frombuffer(image.tobytes(), dtype="uint8").reshape(
355
+ (len(image.getbands()), image.height, image.width))
356
+ for image in images
357
+ ])
358
+ accelerator.trackers[0].writer.add_images(
359
+ "test_samples", images, epoch)
360
+ for _, audio in enumerate(audios):
361
+ accelerator.trackers[0].writer.add_audio(
362
+ f"test_audio_{_}",
363
+ normalize(audio),
364
+ epoch,
365
+ sample_rate=sample_rate,
366
+ )
367
+ accelerator.wait_for_everyone()
368
+
369
+ accelerator.end_training()
370
+
371
+
372
+ if __name__ == "__main__":
373
+ parser = argparse.ArgumentParser(
374
+ description="Simple example of a training script.")
375
+ parser.add_argument("--local_rank", type=int, default=-1)
376
+ parser.add_argument("--dataset_name", type=str, default=None)
377
+ parser.add_argument("--dataset_config_name", type=str, default=None)
378
+ parser.add_argument(
379
+ "--train_data_dir",
380
+ type=str,
381
+ default=None,
382
+ help="A folder containing the training data.",
383
+ )
384
+ parser.add_argument("--output_dir", type=str, default="ddpm-model-64")
385
+ parser.add_argument("--overwrite_output_dir", type=bool, default=False)
386
+ parser.add_argument("--cache_dir", type=str, default=None)
387
+ parser.add_argument("--train_batch_size", type=int, default=16)
388
+ parser.add_argument("--eval_batch_size", type=int, default=16)
389
+ parser.add_argument("--num_epochs", type=int, default=100)
390
+ parser.add_argument("--save_images_epochs", type=int, default=10)
391
+ parser.add_argument("--save_model_epochs", type=int, default=10)
392
+ parser.add_argument("--gradient_accumulation_steps", type=int, default=1)
393
+ parser.add_argument("--learning_rate", type=float, default=1e-4)
394
+ parser.add_argument("--lr_scheduler", type=str, default="cosine")
395
+ parser.add_argument("--lr_warmup_steps", type=int, default=500)
396
+ parser.add_argument("--adam_beta1", type=float, default=0.95)
397
+ parser.add_argument("--adam_beta2", type=float, default=0.999)
398
+ parser.add_argument("--adam_weight_decay", type=float, default=1e-6)
399
+ parser.add_argument("--adam_epsilon", type=float, default=1e-08)
400
+ parser.add_argument("--use_ema", type=bool, default=True)
401
+ parser.add_argument("--ema_inv_gamma", type=float, default=1.0)
402
+ parser.add_argument("--ema_power", type=float, default=3 / 4)
403
+ parser.add_argument("--ema_max_decay", type=float, default=0.9999)
404
+ parser.add_argument("--push_to_hub", type=bool, default=False)
405
+ parser.add_argument("--use_auth_token", type=bool, default=False)
406
+ parser.add_argument("--hub_token", type=str, default=None)
407
+ parser.add_argument("--hub_model_id", type=str, default=None)
408
+ parser.add_argument("--hub_private_repo", type=bool, default=False)
409
+ parser.add_argument("--logging_dir", type=str, default="logs")
410
+ parser.add_argument(
411
+ "--mixed_precision",
412
+ type=str,
413
+ default="no",
414
+ choices=["no", "fp16", "bf16"],
415
+ help=(
416
+ "Whether to use mixed precision. Choose"
417
+ "between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10."
418
+ "and an Nvidia Ampere GPU."),
419
+ )
420
+ parser.add_argument("--hop_length", type=int, default=512)
421
+ parser.add_argument("--sample_rate", type=int, default=22050)
422
+ parser.add_argument("--n_fft", type=int, default=2048)
423
+ parser.add_argument("--from_pretrained", type=str, default=None)
424
+ parser.add_argument("--start_epoch", type=int, default=0)
425
+ parser.add_argument("--num_train_steps", type=int, default=1000)
426
+ parser.add_argument("--scheduler",
427
+ type=str,
428
+ default="ddpm",
429
+ help="ddpm or ddim")
430
+ parser.add_argument(
431
+ "--vae",
432
+ type=str,
433
+ default=None,
434
+ help="pretrained VAE model for latent diffusion",
435
+ )
436
+ parser.add_argument(
437
+ "--encodings",
438
+ type=str,
439
+ default=None,
440
+ help="picked dictionary mapping audio_file to encoding",
441
+ )
442
+
443
+ args = parser.parse_args()
444
+ env_local_rank = int(os.environ.get("LOCAL_RANK", -1))
445
+ if env_local_rank != -1 and env_local_rank != args.local_rank:
446
+ args.local_rank = env_local_rank
447
+
448
+ if args.dataset_name is None and args.train_data_dir is None:
449
+ raise ValueError(
450
+ "You must specify either a dataset name from the hub or a train data directory."
451
+ )
452
+
453
+ 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 argparse
4
+ import os
5
+
6
+ import numpy as np
7
+ import pytorch_lightning as pl
8
+ import torch
9
+ import torchvision
10
+ from datasets import load_dataset, load_from_disk
11
+ from diffusers.pipelines.audio_diffusion import Mel
12
+ from ldm.util import instantiate_from_config
13
+ from librosa.util import normalize
14
+ from omegaconf import OmegaConf
15
+ from PIL import Image
16
+ from pytorch_lightning.callbacks import Callback, ModelCheckpoint
17
+ from pytorch_lightning.trainer import Trainer
18
+ from pytorch_lightning.utilities.distributed import rank_zero_only
19
+ from torch.utils.data import DataLoader, Dataset
20
+
21
+ from audiodiffusion.utils import convert_ldm_to_hf_vae
22
+
23
+
24
+ class AudioDiffusion(Dataset):
25
+ def __init__(self, model_id, channels=3):
26
+ super().__init__()
27
+ self.channels = channels
28
+ if os.path.exists(model_id):
29
+ self.hf_dataset = load_from_disk(model_id)["train"]
30
+ else:
31
+ self.hf_dataset = load_dataset(model_id)["train"]
32
+
33
+ def __len__(self):
34
+ return len(self.hf_dataset)
35
+
36
+ def __getitem__(self, idx):
37
+ image = self.hf_dataset[idx]["image"]
38
+ if self.channels == 3:
39
+ image = image.convert("RGB")
40
+ image = np.frombuffer(image.tobytes(), dtype="uint8").reshape((image.height, image.width, self.channels))
41
+ image = (image / 255) * 2 - 1
42
+ return {"image": image}
43
+
44
+
45
+ class AudioDiffusionDataModule(pl.LightningDataModule):
46
+ def __init__(self, model_id, batch_size, channels):
47
+ super().__init__()
48
+ self.batch_size = batch_size
49
+ self.dataset = AudioDiffusion(model_id=model_id, channels=channels)
50
+ self.num_workers = 1
51
+
52
+ def train_dataloader(self):
53
+ return DataLoader(self.dataset, batch_size=self.batch_size, num_workers=self.num_workers)
54
+
55
+
56
+ class ImageLogger(Callback):
57
+ def __init__(self, every=1000, hop_length=512, sample_rate=22050, n_fft=2048):
58
+ super().__init__()
59
+ self.every = every
60
+ self.hop_length = hop_length
61
+ self.sample_rate = sample_rate
62
+ self.n_fft = n_fft
63
+
64
+ @rank_zero_only
65
+ def log_images_and_audios(self, pl_module, batch):
66
+ pl_module.eval()
67
+ with torch.no_grad():
68
+ images = pl_module.log_images(batch, split="train")
69
+ pl_module.train()
70
+
71
+ image_shape = next(iter(images.values())).shape
72
+ channels = image_shape[1]
73
+ mel = Mel(
74
+ x_res=image_shape[2],
75
+ y_res=image_shape[3],
76
+ hop_length=self.hop_length,
77
+ sample_rate=self.sample_rate,
78
+ n_fft=self.n_fft,
79
+ )
80
+
81
+ for k in images:
82
+ images[k] = images[k].detach().cpu()
83
+ images[k] = torch.clamp(images[k], -1.0, 1.0)
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(tag, grid, global_step=pl_module.global_step)
89
+
90
+ images[k] = (images[k].numpy() * 255).round().astype("uint8").transpose(0, 2, 3, 1)
91
+ for _, image in enumerate(images[k]):
92
+ audio = mel.image_to_audio(
93
+ Image.fromarray(image, mode="RGB").convert("L")
94
+ if channels == 3
95
+ else Image.fromarray(image[:, :, 0])
96
+ )
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
+
104
+ def on_train_batch_end(self, trainer, pl_module, outputs, batch, 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
+ def __init__(self, ldm_config, hf_checkpoint, *args, **kwargs):
112
+ super().__init__(*args, **kwargs)
113
+ self.ldm_config = ldm_config
114
+ self.hf_checkpoint = hf_checkpoint
115
+ self.sample_size = None
116
+
117
+ def on_train_batch_start(self, trainer, pl_module, batch, batch_idx):
118
+ if self.sample_size is None:
119
+ self.sample_size = list(batch["image"].shape[1:3])
120
+
121
+ def on_train_epoch_end(self, trainer, pl_module):
122
+ ldm_checkpoint = self._get_metric_interpolated_filepath_name({"epoch": trainer.current_epoch}, trainer)
123
+ super().on_train_epoch_end(trainer, pl_module)
124
+ self.ldm_config.model.params.ddconfig.resolution = self.sample_size
125
+ convert_ldm_to_hf_vae(ldm_checkpoint, self.ldm_config, self.hf_checkpoint, self.sample_size)
126
+
127
+
128
+ if __name__ == "__main__":
129
+ parser = argparse.ArgumentParser(description="Train VAE using ldm.")
130
+ parser.add_argument("-d", "--dataset_name", type=str, default=None)
131
+ parser.add_argument("-b", "--batch_size", type=int, default=1)
132
+ parser.add_argument("-c", "--ldm_config_file", type=str, default="config/ldm_autoencoder_kl.yaml")
133
+ parser.add_argument("--ldm_checkpoint_dir", type=str, default="models/ldm-autoencoder-kl")
134
+ parser.add_argument("--hf_checkpoint_dir", type=str, default="models/autoencoder-kl")
135
+ parser.add_argument("-r", "--resume_from_checkpoint", type=str, default=None)
136
+ parser.add_argument("-g", "--gradient_accumulation_steps", type=int, default=1)
137
+ parser.add_argument("--hop_length", type=int, default=512)
138
+ parser.add_argument("--sample_rate", type=int, default=22050)
139
+ parser.add_argument("--n_fft", type=int, default=2048)
140
+ parser.add_argument("--save_images_batches", type=int, default=1000)
141
+ parser.add_argument("--max_epochs", type=int, default=100)
142
+ args = parser.parse_args()
143
+
144
+ config = OmegaConf.load(args.ldm_config_file)
145
+ model = instantiate_from_config(config.model)
146
+ model.learning_rate = config.model.base_learning_rate
147
+ data = AudioDiffusionDataModule(
148
+ model_id=args.dataset_name,
149
+ batch_size=args.batch_size,
150
+ channels=config.model.params.ddconfig.in_channels,
151
+ )
152
+ lightning_config = config.pop("lightning", OmegaConf.create())
153
+ trainer_config = lightning_config.get("trainer", OmegaConf.create())
154
+ trainer_config.accumulate_grad_batches = args.gradient_accumulation_steps
155
+ trainer_opt = argparse.Namespace(**trainer_config)
156
+ trainer = Trainer.from_argparse_args(
157
+ trainer_opt,
158
+ max_epochs=args.max_epochs,
159
+ resume_from_checkpoint=args.resume_from_checkpoint,
160
+ callbacks=[
161
+ ImageLogger(
162
+ every=args.save_images_batches,
163
+ hop_length=args.hop_length,
164
+ sample_rate=args.sample_rate,
165
+ n_fft=args.n_fft,
166
+ ),
167
+ HFModelCheckpoint(
168
+ ldm_config=config,
169
+ hf_checkpoint=args.hf_checkpoint_dir,
170
+ dirpath=args.ldm_checkpoint_dir,
171
+ filename="{epoch:06}",
172
+ verbose=True,
173
+ save_last=True,
174
+ ),
175
+ ],
176
+ )
177
+ trainer.fit(model, data)
setup.cfg ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ long_description_content_type = text/markdown
7
+ license = GPL3
8
+ classifiers =
9
+ Programming Language :: Python :: 3
10
+
11
+ [options]
12
+ zip_safe = False
13
+ packages = audiodiffusion
14
+ install_requires =
15
+ torch
16
+ numpy
17
+ Pillow
18
+ diffusers>=0.12.0
19
+ librosa
20
+ datasets>=2.9.0
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()