├── CITATION.cff
├── LICENSE
├── README.md
├── part-1-py-training
├── Train.colab.ipynb
├── data
│ ├── README.md
│ └── maestro-v2.0.0-simple.json.gz
├── figures
│ ├── README.md
│ ├── decoder.png
│ ├── encoder.png
│ ├── overview.png
│ └── quantization.png
└── pretrained
│ ├── cfg.json
│ ├── model.pt
│ └── run.txt
└── part-2-js-interaction
├── assets
└── favicon-32x32.png
├── index.html
├── modules.js
├── piano-genie.js
├── pretrained
├── cfg.json
├── group1-shard1of1.bin
└── weights_manifest.json
├── script.js
├── style.css
└── test
└── test.json
/CITATION.cff:
--------------------------------------------------------------------------------
1 | cff-version: 1.2.0
2 | message: "If you found this tutorial helpful, please consider citing it as below."
3 | authors:
4 | - family-names: "Donahue"
5 | given-names: "Chris"
6 | - family-names: "Huang"
7 | given-names: "Cheng-Zhi Anna"
8 | - family-names: "Gillick"
9 | given-names: "Jon"
10 | title: "Interactive music co-creation with PyTorch and Tensorflow.js"
11 | date-released: 2021-11-07
12 | url: "https://github.com/chrisdonahue/music-cocreation-tutorial"
13 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Attribution-NonCommercial-ShareAlike 4.0 International
2 |
3 | =======================================================================
4 |
5 | Creative Commons Corporation ("Creative Commons") is not a law firm and
6 | does not provide legal services or legal advice. Distribution of
7 | Creative Commons public licenses does not create a lawyer-client or
8 | other relationship. Creative Commons makes its licenses and related
9 | information available on an "as-is" basis. Creative Commons gives no
10 | warranties regarding its licenses, any material licensed under their
11 | terms and conditions, or any related information. Creative Commons
12 | disclaims all liability for damages resulting from their use to the
13 | fullest extent possible.
14 |
15 | Using Creative Commons Public Licenses
16 |
17 | Creative Commons public licenses provide a standard set of terms and
18 | conditions that creators and other rights holders may use to share
19 | original works of authorship and other material subject to copyright
20 | and certain other rights specified in the public license below. The
21 | following considerations are for informational purposes only, are not
22 | exhaustive, and do not form part of our licenses.
23 |
24 | Considerations for licensors: Our public licenses are
25 | intended for use by those authorized to give the public
26 | permission to use material in ways otherwise restricted by
27 | copyright and certain other rights. Our licenses are
28 | irrevocable. Licensors should read and understand the terms
29 | and conditions of the license they choose before applying it.
30 | Licensors should also secure all rights necessary before
31 | applying our licenses so that the public can reuse the
32 | material as expected. Licensors should clearly mark any
33 | material not subject to the license. This includes other CC-
34 | licensed material, or material used under an exception or
35 | limitation to copyright. More considerations for licensors:
36 | wiki.creativecommons.org/Considerations_for_licensors
37 |
38 | Considerations for the public: By using one of our public
39 | licenses, a licensor grants the public permission to use the
40 | licensed material under specified terms and conditions. If
41 | the licensor's permission is not necessary for any reason--for
42 | example, because of any applicable exception or limitation to
43 | copyright--then that use is not regulated by the license. Our
44 | licenses grant only permissions under copyright and certain
45 | other rights that a licensor has authority to grant. Use of
46 | the licensed material may still be restricted for other
47 | reasons, including because others have copyright or other
48 | rights in the material. A licensor may make special requests,
49 | such as asking that all changes be marked or described.
50 | Although not required by our licenses, you are encouraged to
51 | respect those requests where reasonable. More considerations
52 | for the public:
53 | wiki.creativecommons.org/Considerations_for_licensees
54 |
55 | =======================================================================
56 |
57 | Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International
58 | Public License
59 |
60 | By exercising the Licensed Rights (defined below), You accept and agree
61 | to be bound by the terms and conditions of this Creative Commons
62 | Attribution-NonCommercial-ShareAlike 4.0 International Public License
63 | ("Public License"). To the extent this Public License may be
64 | interpreted as a contract, You are granted the Licensed Rights in
65 | consideration of Your acceptance of these terms and conditions, and the
66 | Licensor grants You such rights in consideration of benefits the
67 | Licensor receives from making the Licensed Material available under
68 | these terms and conditions.
69 |
70 |
71 | Section 1 -- Definitions.
72 |
73 | a. Adapted Material means material subject to Copyright and Similar
74 | Rights that is derived from or based upon the Licensed Material
75 | and in which the Licensed Material is translated, altered,
76 | arranged, transformed, or otherwise modified in a manner requiring
77 | permission under the Copyright and Similar Rights held by the
78 | Licensor. For purposes of this Public License, where the Licensed
79 | Material is a musical work, performance, or sound recording,
80 | Adapted Material is always produced where the Licensed Material is
81 | synched in timed relation with a moving image.
82 |
83 | b. Adapter's License means the license You apply to Your Copyright
84 | and Similar Rights in Your contributions to Adapted Material in
85 | accordance with the terms and conditions of this Public License.
86 |
87 | c. BY-NC-SA Compatible License means a license listed at
88 | creativecommons.org/compatiblelicenses, approved by Creative
89 | Commons as essentially the equivalent of this Public License.
90 |
91 | d. Copyright and Similar Rights means copyright and/or similar rights
92 | closely related to copyright including, without limitation,
93 | performance, broadcast, sound recording, and Sui Generis Database
94 | Rights, without regard to how the rights are labeled or
95 | categorized. For purposes of this Public License, the rights
96 | specified in Section 2(b)(1)-(2) are not Copyright and Similar
97 | Rights.
98 |
99 | e. Effective Technological Measures means those measures that, in the
100 | absence of proper authority, may not be circumvented under laws
101 | fulfilling obligations under Article 11 of the WIPO Copyright
102 | Treaty adopted on December 20, 1996, and/or similar international
103 | agreements.
104 |
105 | f. Exceptions and Limitations means fair use, fair dealing, and/or
106 | any other exception or limitation to Copyright and Similar Rights
107 | that applies to Your use of the Licensed Material.
108 |
109 | g. License Elements means the license attributes listed in the name
110 | of a Creative Commons Public License. The License Elements of this
111 | Public License are Attribution, NonCommercial, and ShareAlike.
112 |
113 | h. Licensed Material means the artistic or literary work, database,
114 | or other material to which the Licensor applied this Public
115 | License.
116 |
117 | i. Licensed Rights means the rights granted to You subject to the
118 | terms and conditions of this Public License, which are limited to
119 | all Copyright and Similar Rights that apply to Your use of the
120 | Licensed Material and that the Licensor has authority to license.
121 |
122 | j. Licensor means the individual(s) or entity(ies) granting rights
123 | under this Public License.
124 |
125 | k. NonCommercial means not primarily intended for or directed towards
126 | commercial advantage or monetary compensation. For purposes of
127 | this Public License, the exchange of the Licensed Material for
128 | other material subject to Copyright and Similar Rights by digital
129 | file-sharing or similar means is NonCommercial provided there is
130 | no payment of monetary compensation in connection with the
131 | exchange.
132 |
133 | l. Share means to provide material to the public by any means or
134 | process that requires permission under the Licensed Rights, such
135 | as reproduction, public display, public performance, distribution,
136 | dissemination, communication, or importation, and to make material
137 | available to the public including in ways that members of the
138 | public may access the material from a place and at a time
139 | individually chosen by them.
140 |
141 | m. Sui Generis Database Rights means rights other than copyright
142 | resulting from Directive 96/9/EC of the European Parliament and of
143 | the Council of 11 March 1996 on the legal protection of databases,
144 | as amended and/or succeeded, as well as other essentially
145 | equivalent rights anywhere in the world.
146 |
147 | n. You means the individual or entity exercising the Licensed Rights
148 | under this Public License. Your has a corresponding meaning.
149 |
150 |
151 | Section 2 -- Scope.
152 |
153 | a. License grant.
154 |
155 | 1. Subject to the terms and conditions of this Public License,
156 | the Licensor hereby grants You a worldwide, royalty-free,
157 | non-sublicensable, non-exclusive, irrevocable license to
158 | exercise the Licensed Rights in the Licensed Material to:
159 |
160 | a. reproduce and Share the Licensed Material, in whole or
161 | in part, for NonCommercial purposes only; and
162 |
163 | b. produce, reproduce, and Share Adapted Material for
164 | NonCommercial purposes only.
165 |
166 | 2. Exceptions and Limitations. For the avoidance of doubt, where
167 | Exceptions and Limitations apply to Your use, this Public
168 | License does not apply, and You do not need to comply with
169 | its terms and conditions.
170 |
171 | 3. Term. The term of this Public License is specified in Section
172 | 6(a).
173 |
174 | 4. Media and formats; technical modifications allowed. The
175 | Licensor authorizes You to exercise the Licensed Rights in
176 | all media and formats whether now known or hereafter created,
177 | and to make technical modifications necessary to do so. The
178 | Licensor waives and/or agrees not to assert any right or
179 | authority to forbid You from making technical modifications
180 | necessary to exercise the Licensed Rights, including
181 | technical modifications necessary to circumvent Effective
182 | Technological Measures. For purposes of this Public License,
183 | simply making modifications authorized by this Section 2(a)
184 | (4) never produces Adapted Material.
185 |
186 | 5. Downstream recipients.
187 |
188 | a. Offer from the Licensor -- Licensed Material. Every
189 | recipient of the Licensed Material automatically
190 | receives an offer from the Licensor to exercise the
191 | Licensed Rights under the terms and conditions of this
192 | Public License.
193 |
194 | b. Additional offer from the Licensor -- Adapted Material.
195 | Every recipient of Adapted Material from You
196 | automatically receives an offer from the Licensor to
197 | exercise the Licensed Rights in the Adapted Material
198 | under the conditions of the Adapter's License You apply.
199 |
200 | c. No downstream restrictions. You may not offer or impose
201 | any additional or different terms or conditions on, or
202 | apply any Effective Technological Measures to, the
203 | Licensed Material if doing so restricts exercise of the
204 | Licensed Rights by any recipient of the Licensed
205 | Material.
206 |
207 | 6. No endorsement. Nothing in this Public License constitutes or
208 | may be construed as permission to assert or imply that You
209 | are, or that Your use of the Licensed Material is, connected
210 | with, or sponsored, endorsed, or granted official status by,
211 | the Licensor or others designated to receive attribution as
212 | provided in Section 3(a)(1)(A)(i).
213 |
214 | b. Other rights.
215 |
216 | 1. Moral rights, such as the right of integrity, are not
217 | licensed under this Public License, nor are publicity,
218 | privacy, and/or other similar personality rights; however, to
219 | the extent possible, the Licensor waives and/or agrees not to
220 | assert any such rights held by the Licensor to the limited
221 | extent necessary to allow You to exercise the Licensed
222 | Rights, but not otherwise.
223 |
224 | 2. Patent and trademark rights are not licensed under this
225 | Public License.
226 |
227 | 3. To the extent possible, the Licensor waives any right to
228 | collect royalties from You for the exercise of the Licensed
229 | Rights, whether directly or through a collecting society
230 | under any voluntary or waivable statutory or compulsory
231 | licensing scheme. In all other cases the Licensor expressly
232 | reserves any right to collect such royalties, including when
233 | the Licensed Material is used other than for NonCommercial
234 | purposes.
235 |
236 |
237 | Section 3 -- License Conditions.
238 |
239 | Your exercise of the Licensed Rights is expressly made subject to the
240 | following conditions.
241 |
242 | a. Attribution.
243 |
244 | 1. If You Share the Licensed Material (including in modified
245 | form), You must:
246 |
247 | a. retain the following if it is supplied by the Licensor
248 | with the Licensed Material:
249 |
250 | i. identification of the creator(s) of the Licensed
251 | Material and any others designated to receive
252 | attribution, in any reasonable manner requested by
253 | the Licensor (including by pseudonym if
254 | designated);
255 |
256 | ii. a copyright notice;
257 |
258 | iii. a notice that refers to this Public License;
259 |
260 | iv. a notice that refers to the disclaimer of
261 | warranties;
262 |
263 | v. a URI or hyperlink to the Licensed Material to the
264 | extent reasonably practicable;
265 |
266 | b. indicate if You modified the Licensed Material and
267 | retain an indication of any previous modifications; and
268 |
269 | c. indicate the Licensed Material is licensed under this
270 | Public License, and include the text of, or the URI or
271 | hyperlink to, this Public License.
272 |
273 | 2. You may satisfy the conditions in Section 3(a)(1) in any
274 | reasonable manner based on the medium, means, and context in
275 | which You Share the Licensed Material. For example, it may be
276 | reasonable to satisfy the conditions by providing a URI or
277 | hyperlink to a resource that includes the required
278 | information.
279 | 3. If requested by the Licensor, You must remove any of the
280 | information required by Section 3(a)(1)(A) to the extent
281 | reasonably practicable.
282 |
283 | b. ShareAlike.
284 |
285 | In addition to the conditions in Section 3(a), if You Share
286 | Adapted Material You produce, the following conditions also apply.
287 |
288 | 1. The Adapter's License You apply must be a Creative Commons
289 | license with the same License Elements, this version or
290 | later, or a BY-NC-SA Compatible License.
291 |
292 | 2. You must include the text of, or the URI or hyperlink to, the
293 | Adapter's License You apply. You may satisfy this condition
294 | in any reasonable manner based on the medium, means, and
295 | context in which You Share Adapted Material.
296 |
297 | 3. You may not offer or impose any additional or different terms
298 | or conditions on, or apply any Effective Technological
299 | Measures to, Adapted Material that restrict exercise of the
300 | rights granted under the Adapter's License You apply.
301 |
302 |
303 | Section 4 -- Sui Generis Database Rights.
304 |
305 | Where the Licensed Rights include Sui Generis Database Rights that
306 | apply to Your use of the Licensed Material:
307 |
308 | a. for the avoidance of doubt, Section 2(a)(1) grants You the right
309 | to extract, reuse, reproduce, and Share all or a substantial
310 | portion of the contents of the database for NonCommercial purposes
311 | only;
312 |
313 | b. if You include all or a substantial portion of the database
314 | contents in a database in which You have Sui Generis Database
315 | Rights, then the database in which You have Sui Generis Database
316 | Rights (but not its individual contents) is Adapted Material,
317 | including for purposes of Section 3(b); and
318 |
319 | c. You must comply with the conditions in Section 3(a) if You Share
320 | all or a substantial portion of the contents of the database.
321 |
322 | For the avoidance of doubt, this Section 4 supplements and does not
323 | replace Your obligations under this Public License where the Licensed
324 | Rights include other Copyright and Similar Rights.
325 |
326 |
327 | Section 5 -- Disclaimer of Warranties and Limitation of Liability.
328 |
329 | a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE
330 | EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS
331 | AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF
332 | ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS,
333 | IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION,
334 | WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR
335 | PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS,
336 | ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT
337 | KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT
338 | ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU.
339 |
340 | b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE
341 | TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION,
342 | NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT,
343 | INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES,
344 | COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR
345 | USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN
346 | ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR
347 | DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR
348 | IN PART, THIS LIMITATION MAY NOT APPLY TO YOU.
349 |
350 | c. The disclaimer of warranties and limitation of liability provided
351 | above shall be interpreted in a manner that, to the extent
352 | possible, most closely approximates an absolute disclaimer and
353 | waiver of all liability.
354 |
355 |
356 | Section 6 -- Term and Termination.
357 |
358 | a. This Public License applies for the term of the Copyright and
359 | Similar Rights licensed here. However, if You fail to comply with
360 | this Public License, then Your rights under this Public License
361 | terminate automatically.
362 |
363 | b. Where Your right to use the Licensed Material has terminated under
364 | Section 6(a), it reinstates:
365 |
366 | 1. automatically as of the date the violation is cured, provided
367 | it is cured within 30 days of Your discovery of the
368 | violation; or
369 |
370 | 2. upon express reinstatement by the Licensor.
371 |
372 | For the avoidance of doubt, this Section 6(b) does not affect any
373 | right the Licensor may have to seek remedies for Your violations
374 | of this Public License.
375 |
376 | c. For the avoidance of doubt, the Licensor may also offer the
377 | Licensed Material under separate terms or conditions or stop
378 | distributing the Licensed Material at any time; however, doing so
379 | will not terminate this Public License.
380 |
381 | d. Sections 1, 5, 6, 7, and 8 survive termination of this Public
382 | License.
383 |
384 |
385 | Section 7 -- Other Terms and Conditions.
386 |
387 | a. The Licensor shall not be bound by any additional or different
388 | terms or conditions communicated by You unless expressly agreed.
389 |
390 | b. Any arrangements, understandings, or agreements regarding the
391 | Licensed Material not stated herein are separate from and
392 | independent of the terms and conditions of this Public License.
393 |
394 |
395 | Section 8 -- Interpretation.
396 |
397 | a. For the avoidance of doubt, this Public License does not, and
398 | shall not be interpreted to, reduce, limit, restrict, or impose
399 | conditions on any use of the Licensed Material that could lawfully
400 | be made without permission under this Public License.
401 |
402 | b. To the extent possible, if any provision of this Public License is
403 | deemed unenforceable, it shall be automatically reformed to the
404 | minimum extent necessary to make it enforceable. If the provision
405 | cannot be reformed, it shall be severed from this Public License
406 | without affecting the enforceability of the remaining terms and
407 | conditions.
408 |
409 | c. No term or condition of this Public License will be waived and no
410 | failure to comply consented to unless expressly agreed to by the
411 | Licensor.
412 |
413 | d. Nothing in this Public License constitutes or may be interpreted
414 | as a limitation upon, or waiver of, any privileges and immunities
415 | that apply to the Licensor or You, including from the legal
416 | processes of any jurisdiction or authority.
417 |
418 | =======================================================================
419 |
420 | Creative Commons is not a party to its public
421 | licenses. Notwithstanding, Creative Commons may elect to apply one of
422 | its public licenses to material it publishes and in those instances
423 | will be considered the “Licensor.” The text of the Creative Commons
424 | public licenses is dedicated to the public domain under the CC0 Public
425 | Domain Dedication. Except for the limited purpose of indicating that
426 | material is shared under a Creative Commons public license or as
427 | otherwise permitted by the Creative Commons policies published at
428 | creativecommons.org/policies, Creative Commons does not authorize the
429 | use of the trademark "Creative Commons" or any other trademark or logo
430 | of Creative Commons without its prior written consent including,
431 | without limitation, in connection with any unauthorized modifications
432 | to any of its public licenses or any other arrangements,
433 | understandings, or agreements concerning use of licensed material. For
434 | the avoidance of doubt, this paragraph does not form part of the
435 | public licenses.
436 |
437 | Creative Commons may be contacted at creativecommons.org.
438 |
439 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | ## Interactive music co-creation with PyTorch and TensorFlow.js
2 |
3 | This tutorial is a start-to-finish demonstration ([click here for result](https://chrisdonahue.com/music-cocreation-tutorial)) of building an interactive music co-creation system in two parts:
4 |
5 | 1. **[Training a generative model of music in Python](#part-1-training-in-python)** (via PyTorch)
6 | 2. **[Deploying it in JavaScript for interaction](#part-2-deploying-in-javascript)** (via TensorFlow.js)
7 |
8 | This demonstration was prepared by [Chris Donahue](https://chrisdonahue.com) as part of an [ISMIR 2021 tutorial](https://ismir2021.ismir.net/tutorials/) on *Designing generative models for interactive co-creation*, co-organized by [Anna Huang](https://research.google/people/105787/) and [Jon Gillick](https://www.jongillick.com).
9 |
10 | The example generative model we will train and deploy is [Piano Genie](https://magenta.tensorflow.org/pianogenie) (Donahue et al. 2019). Piano Genie allows anyone to improvise on the piano by mapping performances on a miniature 8-button keyboard to realistic performances on a full 88-key piano in real time. We train Piano Genie by autoencoding expert piano performances: an encoder maps 88-key piano performances into 8-button "button performances", and a decoder attempts to reconstruct the piano performance from the button performance. At interaction time, we replace the encoder with a user performing on the buttons. At a low-level, the decoder is an LSTM that operates on symbolic music data (i.e., MIDI), and is lightweight enough for real-time performance on mobile CPUs.
11 |
12 |
13 |
14 | ### Part 1: Training in Python
15 |
16 |
17 |
18 | This part of the tutorial involves training a music generative model (Piano Genie) from scratch in PyTorch, which comes in the form of a self-contained [Google Colab notebook](https://colab.research.google.com/drive/124pk1yehPx1y-K3hBG6-SoUSVqQ-RWnM?usp=sharing). The instructions for this part are embedded in the Colab, and the model takes about an hour to train on Colab's free GPUs. The outputs of this part are: (1) a [model checkpoint](part-2-js-interaction/pretrained), and (2) [serialized inputs and outputs for a test case](part-2-js-interaction/test/test.json), which we will use to check correctness of our JavaScript port in the next part.
19 |
20 | ### Part 2: Deploying in JavaScript
21 |
22 |
23 |
24 | This part of the tutorial involves porting the trained generative model from PyTorch to TensorFlow.js, and hooking the model up to a simple UI to allow users to interact with the model. The final result is this [simple web demo](https://chrisdonahue.com/music-cocreation-tutorial). The static files for this demo are located in the [`part-2-js-interaction`](part-2-js-interaction) directory.
25 |
26 | We use JavaScript as the target language for interaction because, unlike Python, it allows for straightforward prototyping and sharing of interactive UIs. However, note that JavaScript is likely not the best target when building tools that musicians can integrate into their workflows. For this, you probably want to integrate with digital audio workstations through C++ plugin frameworks like [VSTs](https://en.wikipedia.org/wiki/Virtual_Studio_Technology) or visual programming environments like [Max/MSP](https://en.wikipedia.org/wiki/Max_(software)).
27 |
28 | At time of writing, [TensorFlow.js](https://www.tensorflow.org/js) is the most mature JavaScript framework for client-side inference of machine learning models. If your Python model is written in TensorFlow, porting it to TensorFlow.js will be much easier, or perhaps even [automatic](https://www.tensorflow.org/js/tutorials/conversion/import_saved_model). However, if you prefer to use a different Python framework like PyTorch or JAX, porting to TensorFlow.js can be a bit tricky, but not insurmountable!
29 |
30 | #### Porting weights from PyTorch to TensorFlow.js
31 |
32 | At the end of Part 1, we exported our model parameters from PyTorch to a format that TensorFlow.js can recognize. For convenience, we've also included a relevant snippet here:
33 |
34 | ```py
35 | import pathlib
36 | from tensorflowjs.write_weights import write_weights
37 | import torch
38 |
39 | # Load saved model params
40 | d = torch.load("model.pt", map_location=torch.device("cpu"))
41 |
42 | # Convert to simple dictionary of named numpy arrays
43 | d = {k: v.numpy() for k, v in d.items()}
44 |
45 | # Save in TensorFlow.js format
46 | pathlib.Path("output").mkdir(exist_ok=True)
47 | write_weights([[{"name": k, "data": v} for k, v in d.items()]], "output")
48 | ```
49 |
50 | This snippet will produce `output/group1-shard1of1.bin`, a binary file containing the model parameters, and `output/weights_manifest.json` a JSON spec which informs TensorFlow.js how to unpack the binary file into a JavaScript `Object`. Both of these files must be hosted in the same directory when loading the weights with TensorFlow.js
51 |
52 | #### Creating a test case
53 |
54 | At the end of Part 1, we also created a test case—a pair of raw inputs to and outputs from our trained model. For convenience, we've also included a relevant snippet here:
55 |
56 | ```py
57 | import json
58 | import torch
59 |
60 | # Restore model from saved checkpoint
61 | model = Model()
62 | model.load_state_dict(torch.load("model.pt", map_location=device))
63 | model.eval()
64 |
65 | # Serialize a batch of inputs/outputs as JSON
66 | with torch.no_grad():
67 | inputs = get_batch()
68 | outputs = model(inputs)
69 | test = {
70 | "inputs": inputs.cpu().numpy().tolist(),
71 | "outputs": outputs.cpu().numpy().tolist(),
72 | }
73 | with open("test.json", "w") as f:
74 | f.write(json.dumps(test))
75 | ```
76 |
77 | This snippet will produce `test.json`, a JSON-encoded file containing serialized inputs and outputs for our model. We can use this later to check our ported model for correctness.
78 |
79 | #### Redefining the model in TensorFlow.js
80 |
81 | Next, we will write equivalent TensorFlow.js code to reimplement our PyTorch model. This is tricky, and will likely require unit testing (I have ported several models from Python to JavaScript and have yet to get it right on the first try) as well as a lot of poking around in the [documentation](https://js.tensorflow.org/api/latest/).
82 |
83 | One tip is to try to make the APIs for the Python and JavaScript models as similar as possible. Here is a side-by-side comparison between the reference PyTorch model (from the [Colab notebook](part-1-py-training/Train.colab.ipynb)) and the TensorFlow.js equivalent (from [`part-2-js-interaction/modules.js`](part2-js-interaction/modules.js)):
84 |
85 |
198 |
199 | While these models have similar APIs, note that the PyTorch model takes as input entire sequences, i.e., tensors of shape `[batch_size, seq_len]`, while the TensorFlow.js equivalent takes an individual timestep as input, i.e., tensors of shape `[batch_size]`. This is because in Python, we are passing as input full sequences of training data, while in JavaScript, we will be using the model in an on-demand fashion, passing in user inputs as they become available.
200 |
201 | Note that this implementation makes use of several helpers, such as a `Module` class which mocks behavior in `torch.nn.Module`, and a factory method `pyTorchLSTMCellFactory` which handles subtle differences in the LSTM implementations between PyTorch and TensorFlow.js. See [`part-2-js-interaction/modules.js`](part-2-js-interaction/modules.js) for full implementation.
202 |
203 | #### Testing for correctness
204 |
205 | Now that we have our model redefined in JavaScript, it is critical that we test it to ensure the behavior is identical to that of the original Python version. The easiest way to do this is to serialize a batch of inputs to and outputs from your Python model as JSON. Then, you can run those inputs through your JavaScript model and check if the outputs are identical (modulo some inevitable numerical precision error). Such a test case might look like this (from [`part-2-js-interaction/modules.js`](part-2-js-interaction/modules.js)):
206 |
207 | ```js
208 | async function testPianoGenieDecoder() {
209 | const numBytesBefore = tf.memory().numBytes;
210 |
211 | // Create model
212 | const quantizer = new IntegerQuantizer();
213 | const decoder = new PianoGenieDecoder();
214 | await decoder.init();
215 |
216 | // Fetch test case
217 | const t = await fetch(TEST_CASE_URI).then(r => r.json());
218 |
219 | // Run test
220 | let totalErr = 0;
221 | let him1 = null;
222 | for (let i = 0; i < 128; ++i) {
223 | him1 = tf.tidy(() => {
224 | const kim1 = tf.tensor(t["input_keys"][i], [1], "int32");
225 | const ti = tf.tensor(t["input_dts"][i], [1], "float32");
226 | let bi = tf.tensor(t["input_buttons"][i], [1], "float32");
227 | bi = quantizer.discreteToReal(bi);
228 | const [khati, hi] = decoder.forward(kim1, ti, bi, him1);
229 |
230 | const expectedLogits = tf.tensor(
231 | t["output_logits"][i],
232 | [1, 88],
233 | "float32"
234 | );
235 | const err = tf.sum(tf.abs(tf.sub(khati, expectedLogits))).arraySync();
236 | totalErr += err;
237 |
238 | if (him1 !== null) him1.dispose();
239 | return hi;
240 | });
241 | }
242 |
243 | // Check equivalence to expected outputs
244 | if (isNaN(totalErr) || totalErr > 0.015) {
245 | console.log(totalErr);
246 | throw "Failed test";
247 | }
248 |
249 | // Check for memory leaks
250 | him1.dispose();
251 | decoder.dispose();
252 | if (tf.memory().numBytes !== numBytesBefore) {
253 | throw "Memory leak";
254 | }
255 | quantizer.dispose();
256 |
257 | console.log("Passed test");
258 | }
259 | ```
260 |
261 | Note that this function makes use of the [`tf.tidy`](https://js.tensorflow.org/api/latest/#tidy) wrapper. TensorFlow.js is [unable to automatically manage memory](https://www.tensorflow.org/js/guide/tensors_operations#memory) when running on GPUs via WebGL, so best practices for writing TensorFlow.js code involve some amount of manual memory management. The `tf.tidy` wrapper makes this easy—any tensor that is allocated during (but not returned by) the wrapped function will be automatically freed when the wrapped function finishes. However, in this case we have two sets of tensors that must persist across model calls: the model's parameters and the RNN memory. Unfortunately, we will have to carefully and manually dispose of these to prevent memory leaks.
262 |
263 | #### Hooking model up to simple UI
264 |
265 | Now that we have ported and tested our model, we can finally have some fun and start building out the interactive elements! Our demo includes a [simple HTML UI](part-2-js-interaction/index.html) with 8 buttons, and a [script](part-2-js-interaction/script.js) which hooks the frontend up to the model. Our script makes use of the wonderful [Tone.js](https://tonejs.github.io/) library to quickly build out a polyphonic FM synthesizer. We also [build a higher-level API](part-2-js-interaction/piano-genie.js) around our low-level model port, to handle things like keeping track of state and sampling from a model's distribution.
266 |
267 | While this is the stopping point of the tutorial, I would encourage you to experiment further. You're now at the point where the benefits of porting the model to JavaScript are clear: JavaScript makes it fairly straightforward to add additional functionality to enrich the interaction. For example, you could add an piano keyboard display to visualize Piano Genie's outputs, bind the space bar to act as a sustain pedal to Piano Genie, or you could use the WebMIDI API to output notes to a hardware synthesizer (hint: all of this functionality is built into [Monica Dinculescu](https://meowni.ca/)'s official [Piano Genie demo](https://www.w3.org/TR/webmidi/)). The possibilities are endless!
268 |
269 | ### End matter
270 |
271 | #### Licensing info
272 |
273 | This tutorial uses the [MAESTRO dataset](https://magenta.tensorflow.org/datasets/maestro) (Hawthorne et al. 2018), which is distributed under a [CC BY-NC-SA 4.0 license](https://creativecommons.org/licenses/by-nc-sa/4.0/). Because of the ShareAlike clause, the material in this tutorial is also distributed under that same license.
274 |
275 | #### Acknowledgements
276 |
277 | Thanks to Ian Simon and Sander Dieleman, co-authors on Piano Genie, and to Monica Dinculescu for creating the original [Piano Genie demo](https://piano-genie.glitch.me).
278 |
279 | #### Attribution
280 |
281 | If this tutorial was useful to you, please consider citing this repository.
282 |
283 | ```
284 | @software{donahue2021tutorial,
285 | author={Donahue, Chris and Huang, Cheng-Zhi Anna and Gillick, Jon},
286 | title={Interactive music co-creation with {PyTorch} and {TensorFlow.js}},
287 | url={https://github.com/chrisdonahue/music-cocreation-tutorial},
288 | year={2021}
289 | }
290 | ```
291 |
292 | If Piano Genie was useful to you, please consider citing our original paper.
293 |
294 | ```
295 | @inproceedings{donahue2019genie,
296 | title={Piano Genie},
297 | author={Donahue, Chris and Simon, Ian and Dieleman, Sander},
298 | booktitle={Proceedings of the 24th ACM Conference on Intelligent User Interfaces},
299 | year={2019}
300 | }
301 | ```
302 |
--------------------------------------------------------------------------------
/part-1-py-training/Train.colab.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "nbformat": 4,
3 | "nbformat_minor": 0,
4 | "metadata": {
5 | "colab": {
6 | "name": "Music Co-creation Tutorial Part 1 (Training).ipynb",
7 | "private_outputs": true,
8 | "provenance": [],
9 | "collapsed_sections": []
10 | },
11 | "kernelspec": {
12 | "name": "python3",
13 | "display_name": "Python 3"
14 | },
15 | "language_info": {
16 | "name": "python"
17 | },
18 | "accelerator": "GPU"
19 | },
20 | "cells": [
21 | {
22 | "cell_type": "markdown",
23 | "metadata": {
24 | "id": "PK41YT0yH3vs"
25 | },
26 | "source": [
27 | "# Music Co-creation Tutorial Part 1: Training a generative model of music\n",
28 | "### [Chris Donahue](https://chrisdonahue.com), [Anna Huang](https://research.google/people/105787/), [Jon Gillick](https://www.jongillick.com/)\n",
29 | "\n",
30 | "This is the first part of a two-part tutorial entitled [*Interactive music co-creation with PyTorch and TensorFlow.js*](https://github.com/chrisdonahue/music-cocreation-tutorial/), prepared as part of the ISMIR 2021 tutorial *Designing generative models for interactive co-creation*. This part of the tutorial will demonstrate how to **train a generative model of music in PyTorch**, and **port its weights to TensorFlow.js** format for interaction. The [final result is here](https://chrisdonahue.com/music-cocreation-tutorial)—see our [GitHub repo](https://github.com/chrisdonahue/music-cocreation-tutorial/) for part 2.\n",
31 | "\n",
32 | "## Primer on Piano Genie\n",
33 | "\n",
34 | "The generative model we will train is called [Piano Genie](https://magenta.tensorflow.org/pianogenie) (Donahue et al. 2019). Piano Genie is a system which maps amateur improvisations on a miniature 8-button keyboard ([video](https://www.youtube.com/watch?v=YRb0XAnUpIk), [demo](https://piano-genie.glitch.me)) into realistic performances on a full 88-key piano.\n",
35 | "\n",
36 | "To achieve this, Piano Genie adopts an _autoencoder_ approach. First, an _encoder_ maps professional piano performances into this 8-button space. Then, a _decoder_ attempts to reconstruct the original piano performance from the 8-button version. The entire system is trained end-to-end to minimize the decoder's reconstruction error. At performance time, we replace the encoder with a user improvising on an 8-button controller, and use the pre-trained decoder to generate a corresponding piano performance.\n",
37 | "\n",
38 | "
\n",
39 | "\n",
40 | "At a low-level, both the encoder and the decoder for Piano Genie are lightweight recurrent neural networks, which are suitable for real-time performance even on mobile CPUs. The discrete bottleneck is achieved using a technique called _integer-quantized autoencoding_ (IQAE), which was also proposed in the Piano Genie paper."
41 | ]
42 | },
43 | {
44 | "cell_type": "code",
45 | "metadata": {
46 | "id": "an946C19rSVJ"
47 | },
48 | "source": [
49 | "#@title **(Step 1)** Parse MIDI piano performances into simple lists of notes\n",
50 | "\n",
51 | "# @markdown *Note*: Check this box to rebuild the dataset from scratch.\n",
52 | "REBUILD_DATASET = False # @param{type:\"boolean\"}\n",
53 | "\n",
54 | "# @markdown To train Piano Genie, we will use a dataset of professional piano performances called [MAESTRO](https://magenta.tensorflow.org/datasets/maestro) (Hawthorne et al. 2019).\n",
55 | "# @markdown Each performance in this dataset was captured by a Disklavier, a computerized piano which can record human performances in MIDI format, i.e., as timestamped sequences of notes.\n",
56 | "\n",
57 | "PIANO_LOWEST_KEY_MIDI_PITCH = 21\n",
58 | "PIANO_NUM_KEYS = 88\n",
59 | "\n",
60 | "import gzip\n",
61 | "import json\n",
62 | "from collections import defaultdict\n",
63 | "\n",
64 | "from tqdm.notebook import tqdm\n",
65 | "\n",
66 | "\n",
67 | "def download_and_parse_maestro():\n",
68 | " # Install pretty_midi\n",
69 | " !!pip install pretty_midi\n",
70 | " import pretty_midi\n",
71 | "\n",
72 | " # Download MAESTRO dataset (Hawthorne+ 2018)\n",
73 | " !!wget -nc https://storage.googleapis.com/magentadata/datasets/maestro/v2.0.0/maestro-v2.0.0-midi.zip\n",
74 | " !!unzip maestro-v2.0.0-midi.zip\n",
75 | "\n",
76 | " # Parse MAESTRO dataset\n",
77 | " dataset = defaultdict(list)\n",
78 | " with open(\"maestro-v2.0.0/maestro-v2.0.0.json\", \"r\") as f:\n",
79 | " for attrs in tqdm(json.load(f)):\n",
80 | " split = attrs[\"split\"]\n",
81 | " midi = pretty_midi.PrettyMIDI(\"maestro-v2.0.0/\" + attrs[\"midi_filename\"])\n",
82 | " assert len(midi.instruments) == 1\n",
83 | " # @markdown Formally, a piano performance is a sequence of notes: $\\mathbf{x} = (x_1, \\ldots, x_N)$, where each $x_i = (t_i, d_i, k_i, v_i)$, signifying:\n",
84 | " notes = [\n",
85 | " (\n",
86 | " # @markdown 1. (When the key was pressed) An _onset_ time $t_i \\in \\mathbb{T}$, where $\\mathbb{T} = \\{ t \\in \\mathbb{R} \\mid 0 \\leq t \\leq T \\}$ \n",
87 | " float(n.start),\n",
88 | " # @markdown 2. (How long the key was held) A _duration_ $d_i \\in \\mathbb{R}_{>0}$\n",
89 | " float(n.end) - float(n.start),\n",
90 | " # @markdown 3. (Which key was pressed) A _key_ index $k_i \\in \\mathbb{K}$, where $\\mathbb{K} = \\{\\text{A0}, \\ldots, \\text{C8}\\}$ and $|\\mathbb{K}| = 88$\n",
91 | " int(n.pitch - PIANO_LOWEST_KEY_MIDI_PITCH),\n",
92 | " # @markdown 4. (How hard the key was pressed) A _velocity_ $v_i \\in \\mathbb{V}$, where $\\mathbb{V} = \\{1, \\ldots, 127\\}$\n",
93 | " int(n.velocity),\n",
94 | " )\n",
95 | " for n in midi.instruments[0].notes\n",
96 | " ]\n",
97 | "\n",
98 | " # This list is in sorted order of onset time, i.e., $t_{i-1} \\leq t_i ~\\forall~i \\in \\{2, \\ldots, N\\}$.\n",
99 | " notes = sorted(notes, key=lambda n: (n[0], n[2]))\n",
100 | " assert all(\n",
101 | " [\n",
102 | " all(\n",
103 | " [\n",
104 | " # Start times should be non-negative\n",
105 | " n[0] >= 0,\n",
106 | " # Note durations should be strictly positive, i.e., $d_i > 0$\n",
107 | " n[1] > 0,\n",
108 | " # Key index should be in range of the piano\n",
109 | " 0 <= n[2] and n[2] < PIANO_NUM_KEYS,\n",
110 | " # Velocity should be valid\n",
111 | " 1 <= n[3] and n[3] < 128,\n",
112 | " ]\n",
113 | " )\n",
114 | " for n in notes\n",
115 | " ]\n",
116 | " )\n",
117 | " dataset[split].append(notes)\n",
118 | "\n",
119 | " return dataset\n",
120 | "\n",
121 | "\n",
122 | "if REBUILD_DATASET:\n",
123 | " DATASET = download_and_parse_maestro()\n",
124 | " with gzip.open(\"maestro-v2.0.0-simple.json.gz\", \"w\") as f:\n",
125 | " f.write(json.dumps(DATASET).encode(\"utf-8\"))\n",
126 | "else:\n",
127 | " !!wget -nc https://github.com/chrisdonahue/music-cocreation-tutorial/raw/main/part-1-py-training/data/maestro-v2.0.0-simple.json.gz\n",
128 | " with gzip.open(\"maestro-v2.0.0-simple.json.gz\", \"rb\") as f:\n",
129 | " DATASET = json.load(f)\n",
130 | "\n",
131 | "print([(s, len(DATASET[s])) for s in [\"train\", \"validation\", \"test\"]])"
132 | ],
133 | "execution_count": null,
134 | "outputs": []
135 | },
136 | {
137 | "cell_type": "code",
138 | "metadata": {
139 | "id": "9UQ9PAvMCwd2"
140 | },
141 | "source": [
142 | "# @title **(Step 2)** Define Piano Genie autoencoder\n",
143 | "\n",
144 | "# @markdown Our intended interaction for Piano Genie is to have users perform on a miniature 8-button keyboard and automatically map each of their button presses to a key on a piano. \n",
145 | "# @markdown Similarly to our formalization of piano performances, we will formalize a \"button performance\" as a sequence of \"notes\", where piano keys $k_i$ are replaced with buttons $b_i$, and we remove velocity since our button controller is not velocity sensitive. \n",
146 | "# @markdown So a button performance $\\mathbf{c}$ is:\n",
147 | "\n",
148 | "# @markdown - $\\mathbf{c} = (c_1, \\ldots, c_N)$, where $c_i = (t_i, d_i, b_i \\in \\mathbb{B})$, i.e., (onsets, durations, buttons), and $\\mathbb{B} = \\{ \\color{#EE2B29}\\blacksquare, \\color{#ff9800}\\blacksquare, \\color{#ffff00}\\blacksquare, \\color{#c6ff00}\\blacksquare, \\color{#00e5ff}\\blacksquare, \\color{#2979ff}\\blacksquare, \\color{#651fff}\\blacksquare, \\color{#d500f9}\\blacksquare \\}$\n",
149 | "\n",
150 | "# @markdown And a corresponding piano performance is:\n",
151 | "\n",
152 | "# @markdown - $\\mathbf{x} = (x_1, \\ldots, x_N)$, where $x_i = (t_i, d_i, k_i, v_i)$, i.e., (onsets, durations, keys, velocities)\n",
153 | "\n",
154 | "# @markdown To map button performances into piano performances, we will train a generative model $P(\\mathbf{x} \\mid \\mathbf{c})$.\n",
155 | "# @markdown In practice, we will factorize this joint distribution over note sequences $\\mathbf{x}$ into the product of conditional probabilities of individual notes: $P(\\mathbf{x} \\mid \\mathbf{c}) = \\prod_{i=1}^{N} P(x_i \\mid \\mathbf{x}_{< i}, \\mathbf{c})$. \n",
156 | "\n",
157 | "# @markdown Hence, our **overall goal is to learn** $P(x_i \\mid \\mathbf{x}_{< i}, \\mathbf{c})$, \n",
158 | "# @markdown which we will **approximate by modeling**:\n",
159 | "\n",
160 | "# @markdown
$P(k_i \\mid \\mathbf{k}_{\n",
161 | "\n",
162 | "# @markdown We arrived at this approximation by working through constraints imposed by the interaction (details at the end).\n",
163 | "\n",
164 | "import torch\n",
165 | "import torch.nn as nn\n",
166 | "import torch.nn.functional as F\n",
167 | "\n",
168 | "# @markdown #### **Decoder**\n",
169 | "\n",
170 | "# @markdown
\n",
240 | "\n",
241 | "# @markdown Because we lack examples of human button performances, we use an encoder to automatically learn to map piano performances into synthetic button performances.\n",
242 | "# @markdown The encoder takes as input a sequence of keys and onset times and produces an equal-length sequence of buttons. \n",
243 | "# @markdown Formally, the encoder is a function: $E_{\\varphi} : \\mathbf{k}, \\mathbf{t} \\mapsto \\mathbf{b}$.\n",
244 | "\n",
245 | "# @markdown Note the conceptual difference between the decoder and the encoder: the decoder process one sequence item at a time, while the encoder maps an entire input sequence to an output sequence.\n",
246 | "# @markdown This is because the decoder (which we will use during inference) needs to process information as it becomes available in real time, whereas the encoder (which we only use during training) can observe the entire piano sequence before translating it into buttons.\n",
247 | "# @markdown Despite this conceptual difference, in practice the encoder is also an RNN (though a bidirectional one) under the hood.\n",
248 | "\n",
249 | "class PianoGenieEncoder(nn.Module):\n",
250 | " def __init__(self, rnn_dim=128, rnn_num_layers=2):\n",
251 | " super().__init__()\n",
252 | " self.rnn_dim = rnn_dim\n",
253 | " self.rnn_num_layers = rnn_num_layers\n",
254 | " self.input = nn.Linear(PIANO_NUM_KEYS + 1, rnn_dim)\n",
255 | " self.lstm = nn.LSTM(\n",
256 | " rnn_dim,\n",
257 | " rnn_dim,\n",
258 | " rnn_num_layers,\n",
259 | " batch_first=True,\n",
260 | " bidirectional=True,\n",
261 | " )\n",
262 | " self.output = nn.Linear(rnn_dim * 2, 1)\n",
263 | "\n",
264 | " def forward(self, k, t):\n",
265 | " inputs = [\n",
266 | " F.one_hot(k, PIANO_NUM_KEYS),\n",
267 | " t.unsqueeze(dim=2),\n",
268 | " ]\n",
269 | " x = self.input(torch.cat(inputs, dim=2))\n",
270 | " # NOTE: PyTorch uses zeros automatically if h is None\n",
271 | " x, _ = self.lstm(x, None)\n",
272 | " x = self.output(x)\n",
273 | " return x[:, :, 0]\n",
274 | "\n",
275 | "\n",
276 | "# @markdown #### **Quantizing encoder output to discrete buttons**\n",
277 | "\n",
278 | "# @markdown
\n",
279 | "# @markdown
Quantizing continuous encoder output (grey line) to eight discrete values (colorful line segments)
\n",
280 | "\n",
281 | "# @markdown You may have noticed in the code that the encoder outputs a real-valued scalar (let's call it $e_i \\in \\mathbb{R}$) at each timestep, but our goal is to output one of eight discrete buttons, i.e., $b_i \\in \\mathbb{B}$. \n",
282 | "# @markdown To achieve this, we will quantize this real-valued scalar as the centroid of the nearest of eight bins between $[-1, 1]$ (see figure above):\n",
283 | "\n",
284 | "# @markdown
\n",
285 | "\n",
286 | "class IntegerQuantizer(nn.Module):\n",
287 | " def __init__(self, num_bins):\n",
288 | " super().__init__()\n",
289 | " self.num_bins = num_bins\n",
290 | "\n",
291 | " def real_to_discrete(self, x, eps=1e-6):\n",
292 | " x = (x + 1) / 2\n",
293 | " x = torch.clamp(x, 0, 1)\n",
294 | " x *= self.num_bins - 1\n",
295 | " x = (torch.round(x) + eps).long()\n",
296 | " return x\n",
297 | "\n",
298 | " def discrete_to_real(self, x):\n",
299 | " x = x.float()\n",
300 | " x /= self.num_bins - 1\n",
301 | " x = (x * 2) - 1\n",
302 | " return x\n",
303 | "\n",
304 | " def forward(self, x):\n",
305 | " # Quantize and compute delta (used for straight-through estimator)\n",
306 | " with torch.no_grad():\n",
307 | " x_disc = self.real_to_discrete(x)\n",
308 | " x_quant = self.discrete_to_real(x_disc)\n",
309 | " x_quant_delta = x_quant - x\n",
310 | "\n",
311 | " # @markdown In the backwards pass, we will use the straight-through estimator (Bengio et al. 2013), i.e., pretend that this discretization did not happen when computing gradients.\n",
312 | " # Quantize w/ straight-through estimator\n",
313 | " x = x + x_quant_delta\n",
314 | "\n",
315 | " return x\n",
316 | "\n",
317 | "\n",
318 | "# @markdown #### **Defining the autoencoder**\n",
319 | "\n",
320 | "# @markdown Finally, the Piano Genie autoencoder is simply the composition of the encoder, quantizer, and decoder.\n",
321 | "\n",
322 | "class PianoGenieAutoencoder(nn.Module):\n",
323 | " def __init__(self, cfg):\n",
324 | " super().__init__()\n",
325 | " self.enc = PianoGenieEncoder(\n",
326 | " rnn_dim=cfg[\"model_rnn_dim\"],\n",
327 | " rnn_num_layers=cfg[\"model_rnn_num_layers\"],\n",
328 | " )\n",
329 | " self.quant = IntegerQuantizer(cfg[\"num_buttons\"])\n",
330 | " self.dec = PianoGenieDecoder(\n",
331 | " rnn_dim=cfg[\"model_rnn_dim\"],\n",
332 | " rnn_num_layers=cfg[\"model_rnn_num_layers\"],\n",
333 | " )\n",
334 | "\n",
335 | " def forward(self, k, t):\n",
336 | " e = self.enc(k, t)\n",
337 | " b = self.quant(e)\n",
338 | " hat_k, _ = self.dec(k, t, b)\n",
339 | " return hat_k, e\n",
340 | "\n",
341 | "\n",
342 | "# @markdown #### **Approximating $P(x_i \\mid \\mathbf{x}_{< i}, \\mathbf{c})$**\n",
343 | "\n",
344 | "# @markdown This section walks through how we designed an approximation to $P(x_i \\mid \\mathbf{x}_{< i}, \\mathbf{c})$ which would be appropriate for our intended interaction. You probably don't need to understand this, but some may find it helpful as an illustration of how to design a generative model around constraints imposed by interaction.\n",
345 | "\n",
346 | "# @markdown First, we expand the terms, treating the onsets $\\mathbf{t}$ and durations $\\mathbf{d}$ as part of the button performance $\\mathbf{c}$:\n",
347 | "\n",
348 | "# @markdown
$P(x_i \\mid \\mathbf{x}_{< i}, \\mathbf{c}) = P(k_i, v_i \\mid \\mathbf{k}_{\n",
349 | "\n",
350 | "# @markdown Because we want this interaction to be real-time, we must remove any information that might not be available at time $t_i$ (the moment the user presses a button), which includes future onsets $\\mathbf{t}_{>i}$, future buttons $\\mathbf{b}_{>i}$, and all durations $\\mathbf{d}$, since notes can be held indefinitely:\n",
351 | "\n",
352 | "# @markdown
$\\approx P(k_i, v_i \\mid \\mathbf{k}_{\n",
353 | "\n",
354 | "# @markdown Finally, we anticipate that it will be frustrating for users if the model predicts dynamics on their behalf, so we remove velocity terms $\\mathbf{v}$:\n",
355 | "\n",
356 | "# @markdown
$\\approx P(k_i, \\mid \\mathbf{k}_{"
357 | ],
358 | "execution_count": null,
359 | "outputs": []
360 | },
361 | {
362 | "cell_type": "code",
363 | "metadata": {
364 | "id": "A_fReq-uCfoy"
365 | },
366 | "source": [
367 | "# @title **(Step 3)** Train Piano Genie\n",
368 | "\n",
369 | "# @markdown *Note*: Check this box to log training curves to [Weights & Biases](https://wandb.ai/) (which will prompt you to log in).\n",
370 | "USE_WANDB = False # @param{type:\"boolean\"}\n",
371 | "\n",
372 | "# @markdown Now that we've defined the autoencoder, we need to train it.\n",
373 | "# @markdown We will train the entire autoencoder end-to-end to minimize the reconstruction loss of the decoder.\n",
374 | "\n",
375 | "# @markdown
\n",
376 | "\n",
377 | "# @markdown This loss alone does not encourage the encoder to produce button sequences with any particular structure, so the behavior of the decoder will likely be fairly unpredictable at interaction time.\n",
378 | "# @markdown We think it might be intuitive to users if the decoder respected the _contour_ of their performance, i.e., if higher buttons produced higher notes and lower buttons produced lower notes.\n",
379 | "# @markdown Hence, we include a loss term which encourages the encoder to produces button sequences which align with the contour of the piano key sequences.\n",
380 | "\n",
381 | "# @markdown
\n",
382 | "\n",
383 | "# @markdown Finally, we find empirically that the encoder often outputs values outside of the $[-1, 1]$ range used for discretization. \n",
384 | "# @markdown Hence, we add a loss term which explicitly encourages this behavior\n",
385 | "\n",
386 | "# @markdown
\n",
390 | "\n",
391 | "\n",
392 | "CFG = {\n",
393 | " \"seed\": 0,\n",
394 | " # Number of buttons in interface\n",
395 | " \"num_buttons\": 8,\n",
396 | " # Onset delta times will be clipped to this maximum\n",
397 | " \"data_delta_time_max\": 1.0,\n",
398 | " # Max time stretch for data augmentation (+- 5%)\n",
399 | " \"data_augment_time_stretch_max\": 0.05,\n",
400 | " # Max transposition for data augmentation (+- tritone)\n",
401 | " \"data_augment_transpose_max\": 6,\n",
402 | " # RNN dimensionality\n",
403 | " \"model_rnn_dim\": 128,\n",
404 | " # RNN num layers\n",
405 | " \"model_rnn_num_layers\": 2,\n",
406 | " # Training hyperparameters\n",
407 | " \"batch_size\": 32,\n",
408 | " \"seq_len\": 128,\n",
409 | " \"lr\": 3e-4,\n",
410 | " \"loss_margin_multiplier\": 1.0,\n",
411 | " \"loss_contour_multiplier\": 1.0,\n",
412 | " \"summarize_frequency\": 128,\n",
413 | " \"eval_frequency\": 128,\n",
414 | " \"max_num_steps\": 50000\n",
415 | "}\n",
416 | "\n",
417 | "import pathlib\n",
418 | "import random\n",
419 | "\n",
420 | "import numpy as np\n",
421 | "\n",
422 | "if USE_WANDB:\n",
423 | " try:\n",
424 | " import wandb\n",
425 | " except ModuleNotFoundError:\n",
426 | " !!pip install wandb\n",
427 | " import wandb\n",
428 | "\n",
429 | "# Init\n",
430 | "run_dir = pathlib.Path(\"piano_genie\")\n",
431 | "run_dir.mkdir(exist_ok=True)\n",
432 | "with open(pathlib.Path(run_dir, \"cfg.json\"), \"w\") as f:\n",
433 | " f.write(json.dumps(CFG, indent=2))\n",
434 | "if USE_WANDB:\n",
435 | " wandb.init(project=\"music-cocreation-tutorial\", config=CFG, reinit=True)\n",
436 | "\n",
437 | "# Set seed\n",
438 | "if CFG[\"seed\"] is not None:\n",
439 | " random.seed(CFG[\"seed\"])\n",
440 | " np.random.seed(CFG[\"seed\"])\n",
441 | " torch.manual_seed(CFG[\"seed\"])\n",
442 | " torch.cuda.manual_seed_all(CFG[\"seed\"])\n",
443 | "\n",
444 | "# Create model\n",
445 | "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n",
446 | "model = PianoGenieAutoencoder(CFG)\n",
447 | "model.train()\n",
448 | "model.to(device)\n",
449 | "print(\"-\" * 80)\n",
450 | "for n, p in model.named_parameters():\n",
451 | " print(f\"{n}, {p.shape}\")\n",
452 | "\n",
453 | "# Create optimizer\n",
454 | "optimizer = torch.optim.Adam(model.parameters(), lr=CFG[\"lr\"])\n",
455 | "\n",
456 | "# Subsamples performances to create a minibatch\n",
457 | "def performances_to_batch(performances, device, train=True):\n",
458 | " batch_k = []\n",
459 | " batch_t = []\n",
460 | " for p in performances:\n",
461 | " # Subsample seq_len notes from performance\n",
462 | " assert len(p) >= CFG[\"seq_len\"]\n",
463 | " if train:\n",
464 | " subsample_offset = random.randrange(0, len(p) - CFG[\"seq_len\"])\n",
465 | " else:\n",
466 | " subsample_offset = 0\n",
467 | " subsample = p[subsample_offset : subsample_offset + CFG[\"seq_len\"]]\n",
468 | " assert len(subsample) == CFG[\"seq_len\"]\n",
469 | "\n",
470 | " # Data augmentation\n",
471 | " if train:\n",
472 | " stretch_factor = random.random() * CFG[\"data_augment_time_stretch_max\"] * 2\n",
473 | " stretch_factor += 1 - CFG[\"data_augment_time_stretch_max\"]\n",
474 | " transposition_factor = random.randint(\n",
475 | " -CFG[\"data_augment_transpose_max\"], CFG[\"data_augment_transpose_max\"]\n",
476 | " )\n",
477 | " subsample = [\n",
478 | " (\n",
479 | " n[0] * stretch_factor,\n",
480 | " n[1] * stretch_factor,\n",
481 | " max(0, min(n[2] + transposition_factor, PIANO_NUM_KEYS - 1)),\n",
482 | " n[3],\n",
483 | " )\n",
484 | " for n in subsample\n",
485 | " ]\n",
486 | " \n",
487 | " # Key features\n",
488 | " batch_k.append([n[2] for n in subsample])\n",
489 | "\n",
490 | " # Onset features\n",
491 | " # NOTE: For stability, we pass delta time to Piano Genie instead of time.\n",
492 | " t = np.diff([n[0] for n in subsample])\n",
493 | " t = np.concatenate([[1e8], t])\n",
494 | " t = np.clip(t, 0, CFG[\"data_delta_time_max\"])\n",
495 | " batch_t.append(t)\n",
496 | "\n",
497 | " return (torch.tensor(batch_k).long(), torch.tensor(batch_t).float())\n",
498 | "\n",
499 | "\n",
500 | "# Train\n",
501 | "step = 0\n",
502 | "best_eval_loss = float(\"inf\")\n",
503 | "while CFG[\"max_num_steps\"] is None or step < CFG[\"max_num_steps\"]:\n",
504 | " if step % CFG[\"eval_frequency\"] == 0:\n",
505 | " model.eval()\n",
506 | "\n",
507 | " with torch.no_grad():\n",
508 | " eval_losses_recons = []\n",
509 | " eval_violates_contour = []\n",
510 | " for i in range(0, len(DATASET[\"validation\"]), CFG[\"batch_size\"]):\n",
511 | " eval_batch = performances_to_batch(\n",
512 | " DATASET[\"validation\"][i : i + CFG[\"batch_size\"]],\n",
513 | " device,\n",
514 | " train=False,\n",
515 | " )\n",
516 | " eval_k, eval_t = tuple(t.to(device) for t in eval_batch)\n",
517 | " eval_hat_k, eval_e = model(eval_k, eval_t)\n",
518 | " eval_b = model.quant.real_to_discrete(eval_e)\n",
519 | " eval_loss_recons = F.cross_entropy(\n",
520 | " eval_hat_k.view(-1, PIANO_NUM_KEYS),\n",
521 | " eval_k.view(-1),\n",
522 | " reduction=\"none\",\n",
523 | " )\n",
524 | " eval_violates = torch.logical_not(\n",
525 | " torch.sign(torch.diff(eval_k, dim=1))\n",
526 | " == torch.sign(torch.diff(eval_b, dim=1)),\n",
527 | " ).float()\n",
528 | " eval_violates_contour.extend(eval_violates.cpu().numpy().tolist())\n",
529 | " eval_losses_recons.extend(eval_loss_recons.cpu().numpy().tolist())\n",
530 | "\n",
531 | " eval_loss_recons = np.mean(eval_losses_recons)\n",
532 | " if eval_loss_recons < best_eval_loss:\n",
533 | " torch.save(model.state_dict(), pathlib.Path(run_dir, \"model.pt\"))\n",
534 | " best_eval_loss = eval_loss_recons\n",
535 | "\n",
536 | " eval_metrics = {\n",
537 | " \"eval_loss_recons\": eval_loss_recons,\n",
538 | " \"eval_contour_violation_ratio\": np.mean(eval_violates_contour),\n",
539 | " }\n",
540 | " if USE_WANDB:\n",
541 | " wandb.log(eval_metrics, step=step)\n",
542 | " print(step, \"eval\", eval_metrics)\n",
543 | "\n",
544 | " model.train()\n",
545 | "\n",
546 | " # Create minibatch\n",
547 | " batch = performances_to_batch(\n",
548 | " random.sample(DATASET[\"train\"], CFG[\"batch_size\"]), device, train=True\n",
549 | " )\n",
550 | " k, t = tuple(t.to(device) for t in batch)\n",
551 | "\n",
552 | " # Run model\n",
553 | " optimizer.zero_grad()\n",
554 | " k_hat, e = model(k, t)\n",
555 | "\n",
556 | " # Compute losses and update params\n",
557 | " loss_recons = F.cross_entropy(k_hat.view(-1, PIANO_NUM_KEYS), k.view(-1))\n",
558 | " loss_margin = torch.square(\n",
559 | " torch.maximum(torch.abs(e) - 1, torch.zeros_like(e))\n",
560 | " ).mean()\n",
561 | " loss_contour = torch.square(\n",
562 | " torch.maximum(\n",
563 | " 1 - torch.diff(k, dim=1) * torch.diff(e, dim=1),\n",
564 | " torch.zeros_like(e[:, 1:]),\n",
565 | " )\n",
566 | " ).mean()\n",
567 | " loss = torch.zeros_like(loss_recons)\n",
568 | " loss += loss_recons\n",
569 | " if CFG[\"loss_margin_multiplier\"] > 0:\n",
570 | " loss += CFG[\"loss_margin_multiplier\"] * loss_margin\n",
571 | " if CFG[\"loss_contour_multiplier\"] > 0:\n",
572 | " loss += CFG[\"loss_contour_multiplier\"] * loss_contour\n",
573 | " loss.backward()\n",
574 | " optimizer.step()\n",
575 | " step += 1\n",
576 | "\n",
577 | " if step % CFG[\"summarize_frequency\"] == 0:\n",
578 | " metrics = {\n",
579 | " \"loss_recons\": loss_recons.item(),\n",
580 | " \"loss_margin\": loss_margin.item(),\n",
581 | " \"loss_contour\": loss_contour.item(),\n",
582 | " \"loss\": loss.item(),\n",
583 | " }\n",
584 | " if USE_WANDB:\n",
585 | " wandb.log(metrics, step=step)\n",
586 | " print(step, \"train\", metrics)\n",
587 | "\n",
588 | "# Download the trained model so we don't lose it!\n",
589 | "from google.colab import files\n",
590 | "\n",
591 | "files.download('piano_genie/model.pt')\n",
592 | "files.download('piano_genie/cfg.json')"
593 | ],
594 | "execution_count": null,
595 | "outputs": []
596 | },
597 | {
598 | "cell_type": "code",
599 | "metadata": {
600 | "id": "aj49WCPSAlyf"
601 | },
602 | "source": [
603 | "# @title **(Step 4)** Port trained decoder parameters to Tensorflow.js format\n",
604 | "\n",
605 | "# @markdown In this step, we will use the TensorFlow.js Python library to export our model's parameters in a binary format, to be loaded later by the JavaScript client.\n",
606 | "\n",
607 | "!!pip install tensorflowjs\n",
608 | "\n",
609 | "from tensorflowjs.write_weights import write_weights\n",
610 | "\n",
611 | "# Load saved model dict\n",
612 | "d = torch.load(\"piano_genie/model.pt\", map_location=torch.device(\"cpu\"))\n",
613 | "d = {k: v.numpy() for k, v in d.items()}\n",
614 | "\n",
615 | "# Convert to tensorflow-js format\n",
616 | "pathlib.Path(\"piano_genie/dec_tfjs\").mkdir(exist_ok=True)\n",
617 | "write_weights(\n",
618 | " [[{\"name\": k, \"data\": v} for k, v in d.items() if k.startswith(\"dec\")]],\n",
619 | " \"piano_genie/dec_tfjs\",\n",
620 | ")"
621 | ],
622 | "execution_count": null,
623 | "outputs": []
624 | },
625 | {
626 | "cell_type": "code",
627 | "metadata": {
628 | "id": "OBuHu2Hohc5f"
629 | },
630 | "source": [
631 | "# @title **(Step 5)** Create test case to check correctness of JavaScript port\n",
632 | "\n",
633 | "# @markdown Finally, we will serialize a sequence of inputs to and outputs from our trained model to create a test case for our JavaScript reimplementation.\n",
634 | "# @markdown This is critically important—I have ported many models from Python to JavaScript and have yet to get it right on the first try.\n",
635 | "# @markdown Porting models from PyTorch to TensorFlow.js is additionally tricky because parameters of the same shape are often used differently by the two APIs.\n",
636 | "\n",
637 | "# Restore model from saved checkpoint\n",
638 | "device = torch.device(\"cpu\")\n",
639 | "with open(\"piano_genie/cfg.json\", \"r\") as f:\n",
640 | " cfg = json.load(f)\n",
641 | "model = PianoGenieAutoencoder(cfg)\n",
642 | "model.load_state_dict(torch.load(\"piano_genie/model.pt\", map_location=device))\n",
643 | "model.eval()\n",
644 | "model.to(device)\n",
645 | "\n",
646 | "# Serialize a batch of inputs/outputs as JSON\n",
647 | "with torch.no_grad():\n",
648 | " ground_truth_keys, input_dts = performances_to_batch(\n",
649 | " [DATASET[\"validation\"][0]], device, train=False\n",
650 | " )\n",
651 | " output_logits, input_buttons = model(ground_truth_keys, input_dts)\n",
652 | " input_buttons = model.quant.real_to_discrete(input_buttons)\n",
653 | "\n",
654 | " input_dts = input_dts[0].cpu().numpy().tolist()\n",
655 | " ground_truth_keys = ground_truth_keys[0].cpu().numpy().tolist()\n",
656 | " input_keys = [PIANO_NUM_KEYS] + ground_truth_keys[:-1]\n",
657 | " input_buttons = input_buttons[0].cpu().numpy().tolist()\n",
658 | " output_logits = output_logits[0].cpu().numpy().tolist()\n",
659 | "\n",
660 | " test = {\n",
661 | " n: eval(n)\n",
662 | " for n in [\"input_dts\", \"input_keys\", \"input_buttons\", \"output_logits\"]\n",
663 | " }\n",
664 | " with open(pathlib.Path(\"piano_genie\", \"test.json\"), \"w\") as f:\n",
665 | " f.write(json.dumps(test))"
666 | ],
667 | "execution_count": null,
668 | "outputs": []
669 | }
670 | ]
671 | }
--------------------------------------------------------------------------------
/part-1-py-training/data/README.md:
--------------------------------------------------------------------------------
1 | ## Licensing info
2 |
3 | `maestro-v2.0.0-simple.json.gz` is a remix of the [MAESTRO v2 dataset](https://magenta.tensorflow.org/datasets/maestro#v200) from Hawthorne et al. 2018, which is distributed under a [CC BY-NC-SA 4.0 license](https://creativecommons.org/licenses/by-nc-sa/4.0/). This remix inherits the same license.
4 |
--------------------------------------------------------------------------------
/part-1-py-training/data/maestro-v2.0.0-simple.json.gz:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/chrisdonahue/music-cocreation-tutorial/8010aa0c8a4715e71ba932bd86e8ecb419535dd4/part-1-py-training/data/maestro-v2.0.0-simple.json.gz
--------------------------------------------------------------------------------
/part-1-py-training/figures/README.md:
--------------------------------------------------------------------------------
1 | Sources:
2 | - [`overview.png`](https://docs.google.com/drawings/d/1MI-bmQa4-1aZntbChtUuGUejTixqw-UYHrLMGUZIDz8/edit?usp=sharing)
3 | - [`encoder.png`](https://docs.google.com/drawings/d/1_zMUX5qK1S0oscoBLt-UliAqmNw9TUuZ1SpTi6krwFA/edit?usp=sharing)
4 | - [`decoder.png`](https://docs.google.com/drawings/d/19O4LtLmzTw9p8QogLnhEzajgFkY5YmlUmzL23lFB97k/edit?usp=sharing)
5 | - [`quantization.png`](https://colab.research.google.com/drive/110T3HfMNaJuLHimtN-caDXeu30OeR8qt?usp=sharing)
6 |
--------------------------------------------------------------------------------
/part-1-py-training/figures/decoder.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/chrisdonahue/music-cocreation-tutorial/8010aa0c8a4715e71ba932bd86e8ecb419535dd4/part-1-py-training/figures/decoder.png
--------------------------------------------------------------------------------
/part-1-py-training/figures/encoder.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/chrisdonahue/music-cocreation-tutorial/8010aa0c8a4715e71ba932bd86e8ecb419535dd4/part-1-py-training/figures/encoder.png
--------------------------------------------------------------------------------
/part-1-py-training/figures/overview.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/chrisdonahue/music-cocreation-tutorial/8010aa0c8a4715e71ba932bd86e8ecb419535dd4/part-1-py-training/figures/overview.png
--------------------------------------------------------------------------------
/part-1-py-training/figures/quantization.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/chrisdonahue/music-cocreation-tutorial/8010aa0c8a4715e71ba932bd86e8ecb419535dd4/part-1-py-training/figures/quantization.png
--------------------------------------------------------------------------------
/part-1-py-training/pretrained/cfg.json:
--------------------------------------------------------------------------------
1 | {
2 | "seed": 0,
3 | "num_buttons": 8,
4 | "data_delta_time_max": 1.0,
5 | "data_augment_time_stretch_max": 0.05,
6 | "data_augment_transpose_max": 6,
7 | "model_rnn_dim": 128,
8 | "model_rnn_num_layers": 2,
9 | "batch_size": 32,
10 | "seq_len": 128,
11 | "lr": 0.0003,
12 | "loss_margin_multiplier": 1.0,
13 | "loss_contour_multiplier": 1.0,
14 | "summarize_frequency": 128,
15 | "eval_frequency": 128,
16 | "max_num_steps": 50000
17 | }
--------------------------------------------------------------------------------
/part-1-py-training/pretrained/model.pt:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/chrisdonahue/music-cocreation-tutorial/8010aa0c8a4715e71ba932bd86e8ecb419535dd4/part-1-py-training/pretrained/model.pt
--------------------------------------------------------------------------------
/part-1-py-training/pretrained/run.txt:
--------------------------------------------------------------------------------
1 | Equivalent w/ updated training curves: https://wandb.ai/cdonahue/music-cocreation-tutorial/runs/23m56lvb?workspace=user-cdonahue
2 | Actual: https://wandb.ai/cdonahue/music-cocreation-tutorial/runs/vkm9t7h6?workspace=user-cdonahue
3 |
--------------------------------------------------------------------------------
/part-2-js-interaction/assets/favicon-32x32.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/chrisdonahue/music-cocreation-tutorial/8010aa0c8a4715e71ba932bd86e8ecb419535dd4/part-2-js-interaction/assets/favicon-32x32.png
--------------------------------------------------------------------------------
/part-2-js-interaction/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 | Music Co-creation Tutorial Part 2 (Interaction)
8 |
9 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
Piano Genie
28 |
29 |
30 |
31 |
Loading...
32 |
33 |
34 |
35 | Sound on 🔊! To play Piano Genie, use the 1️⃣-8️⃣ numbered keys on
36 | your keyboard or press the buttons below. See your developer
37 | console for latency information.
38 |
39 |
40 |
41 |
44 |
47 |
50 |
53 |
56 |
59 |
62 |
65 |
66 |
67 |
68 |
69 | About
70 |
71 |
72 | This is a barebones demo of
73 | Piano Genie
76 | prepared by
77 | Chris Donahue
78 | for the ISMIR 2021 tutorial
79 | Designing Generative Models for Interactive Co-creation. It
80 | is the second part of a two-part tutorial on training a model in
81 | Python and porting it to Javascript for interaction (see
82 | this Colab Notebook
87 | for part one). All code for this tutorial is available via our
88 | GitHub repository.
93 |
94 |
95 | This demo is aimed at developers and optimized for simplicity—please
96 | see the
97 | official demo
100 | by
101 | Monica Dinculescu
102 | for a user-friendly experience. For more about Piano Genie, please
103 | also see the original
104 | blog post,
107 | IUI 2019 paper, and
110 | codebase.
115 |