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15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
{
  "nbformat": 4,
  "nbformat_minor": 0,
  "metadata": {
    "colab": {
      "private_outputs": true,
      "provenance": [],
      "gpuType": "T4"
    },
    "kernelspec": {
      "name": "python3",
      "display_name": "Python 3"
    },
    "language_info": {
      "name": "python"
    },
    "accelerator": "GPU"
  },
  "cells": [
    {
      "cell_type": "markdown",
      "source": [
        "# Imagen MIDI Images Solo Piano Model Maker (ver. 1.0)\n",
        "\n",
        "***\n",
        "\n",
        "Powered by tegridy-tools: https://github.com/asigalov61/tegridy-tools\n",
        "\n",
        "***\n",
        "\n",
        "WARNING: This complete implementation is a functioning model of the Artificial Intelligence. Please excercise great humility, care, and respect. https://www.nscai.gov/\n",
        "\n",
        "***\n",
        "\n",
        "#### Project Los Angeles\n",
        "\n",
        "#### Tegridy Code 2024\n",
        "\n",
        "***"
      ],
      "metadata": {
        "id": "ipXP5fe65oQQ"
      }
    },
    {
      "cell_type": "markdown",
      "source": [
        "# (SETUP ENVIRONMENT)"
      ],
      "metadata": {
        "id": "ZLJbLL226y2m"
      }
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "pxNxlyfZ8hCg",
        "cellView": "form"
      },
      "outputs": [],
      "source": [
        "# @title Install dependecies\n",
        "!git clone --depth 1 https://github.com/asigalov61/tegridy-tools\n",
        "\n",
        "!pip install -U imagen-pytorch\n",
        "\n",
        "!pip install -U huggingface_hub"
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "#@title Import all needed modules\n",
        "\n",
        "print('=' * 70)\n",
        "print('Loading core modules...')\n",
        "\n",
        "import os\n",
        "\n",
        "import numpy as np\n",
        "from tqdm import tqdm\n",
        "\n",
        "from huggingface_hub import snapshot_download\n",
        "\n",
        "print('Done!')\n",
        "print('=' * 70)\n",
        "print('Creating I/O dirs...')\n",
        "\n",
        "if not os.path.exists('/content/Dataset'):\n",
        "    os.makedirs('/content/Dataset')\n",
        "\n",
        "print('Done!')\n",
        "print('=' * 70)\n",
        "print('Loading tegridy-tools modules...')\n",
        "print('=' * 70)\n",
        "\n",
        "%cd /content/tegridy-tools/tegridy-tools\n",
        "\n",
        "import TMIDIX\n",
        "import TPLOTS\n",
        "\n",
        "%cd /content/\n",
        "\n",
        "print('=' * 70)\n",
        "print('Done!')\n",
        "print('=' * 70)\n",
        "print('Loading Imagen...')\n",
        "\n",
        "import torch\n",
        "from imagen_pytorch import Unet, Imagen, ImagenTrainer\n",
        "from imagen_pytorch.data import Dataset\n",
        "\n",
        "print('Done!')\n",
        "print('=' * 70)\n",
        "print('Torch version:', torch.__version__)\n",
        "print('=' * 70)\n",
        "print('Done!')\n",
        "print('=' * 70)"
      ],
      "metadata": {
        "id": "OblKfMMT8rfM",
        "cellView": "form"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "# (DOWNLOAD DATASET)"
      ],
      "metadata": {
        "id": "iDdMYg4haGFn"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "# @title Download and unzip MIDI Images POP909 Solo Piano dataset\n",
        "\n",
        "print('=' * 70)\n",
        "print('Downloading MIDI Images dataset repo...')\n",
        "print('=' * 70)\n",
        "\n",
        "repo_id = \"asigalov61/MIDI-Images\"\n",
        "repo_type = 'dataset'\n",
        "\n",
        "local_dir = \"./MIDI-Images\"\n",
        "\n",
        "snapshot_download(repo_id, repo_type=repo_type, local_dir=local_dir)\n",
        "\n",
        "print('=' * 70)\n",
        "print('Done!')\n",
        "print('=' * 70)\n",
        "\n",
        "print('Unzipping POP909 MIDI Images dataset...')\n",
        "print('=' * 70)\n",
        "%cd /content/Dataset/\n",
        "!unzip /content/MIDI-Images/POP909_MIDI_Dataset_Solo_Piano_MIDI_Images_128_128_32_BW_Ver_1_CC_BY_NC_SA.zip > /dev/null\n",
        "%cd /content/\n",
        "print('=' * 70)\n",
        "print('Done!')\n",
        "print('=' * 70)"
      ],
      "metadata": {
        "cellView": "form",
        "id": "ydi1B-KD7oCC"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "# (INIT MODEL)"
      ],
      "metadata": {
        "id": "llSBItTq9LaP"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "# @title Init Imagen model\n",
        "\n",
        "print('=' * 70)\n",
        "print('Instantiating Imagen model...')\n",
        "print('=' * 70)\n",
        "\n",
        "# unets for unconditional imagen\n",
        "\n",
        "unet = Unet(\n",
        "    dim = 64,\n",
        "    dim_mults = (1, 2, 4, 8),\n",
        "    num_resnet_blocks = 1,\n",
        "    channels=1,\n",
        "    layer_attns = (False, False, False, True),\n",
        "    layer_cross_attns = False\n",
        ")\n",
        "\n",
        "# imagen, which contains the unet above\n",
        "\n",
        "imagen = Imagen(\n",
        "    condition_on_text = False,  # this must be set to False for unconditional Imagen\n",
        "    unets = unet,\n",
        "    channels=1,\n",
        "    image_sizes = 128,\n",
        "    timesteps = 1000\n",
        ")\n",
        "\n",
        "trainer = ImagenTrainer(\n",
        "    imagen = imagen,\n",
        "    split_valid_from_train = True # whether to split the validation dataset from the training\n",
        ").cuda()\n",
        "\n",
        "print('=' * 70)\n",
        "print('Done!')\n",
        "print('=' * 70)"
      ],
      "metadata": {
        "id": "m_1uKB_I5ctR",
        "cellView": "form"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "# (INIT DATASET)"
      ],
      "metadata": {
        "id": "vAJkOmUD-Bzb"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "# @title Prep and init dataset\n",
        "batch_size = 16 # @param {\"type\":\"slider\",\"min\":4,\"max\":64,\"step\":4}\n",
        "\n",
        "print('=' * 70)\n",
        "print('Instantiating dataloader...')\n",
        "print('=' * 70)\n",
        "\n",
        "# instantiate your dataloader, which returns the necessary inputs to the DDPM as tuple in the order of images, text embeddings, then text masks. in this case, only images is returned as it is unconditional training\n",
        "\n",
        "dataset = Dataset('/content/Dataset', image_size = 128)\n",
        "\n",
        "try:\n",
        "  trainer.add_train_dataset(dataset, batch_size = batch_size)\n",
        "\n",
        "except:\n",
        "  print('Dataset is ready!')\n",
        "  pass\n",
        "\n",
        "print('=' * 70)\n",
        "print('Done!')\n",
        "print('=' * 70)"
      ],
      "metadata": {
        "cellView": "form",
        "id": "nC4H4bKE-GuQ"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "# (TRAIN MODEL)"
      ],
      "metadata": {
        "id": "9-R2bCz1_M4Z"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "# @title Train Imagen model\n",
        "\n",
        "NUM_EPOCHS = 10\n",
        "\n",
        "print('=' * 70)\n",
        "print('Training...')\n",
        "print('=' * 70)\n",
        "\n",
        "NUM_STEPS = NUM_EPOCHS * len(dataset)\n",
        "\n",
        "# working training loop\n",
        "\n",
        "epoch = 1\n",
        "\n",
        "print('=' * 70)\n",
        "print('Epoch #', epoch)\n",
        "print('=' * 70)\n",
        "\n",
        "for i in range(NUM_STEPS):\n",
        "\n",
        "  try:\n",
        "\n",
        "    loss = trainer.train_step(unet_number = 1, max_batch_size = batch_size)\n",
        "    print(f'loss: {loss}', '===', i)\n",
        "\n",
        "    if not (i % 50):\n",
        "        valid_loss = trainer.valid_step(unet_number = 1, max_batch_size = batch_size)\n",
        "        print('=' * 70)\n",
        "        print(f'valid loss: {valid_loss}')\n",
        "        print('=' * 70)\n",
        "\n",
        "    if not (i % 1000) and trainer.is_main: # is_main makes sure this can run in distributed\n",
        "        print('=' * 70)\n",
        "        images = trainer.sample(batch_size = batch_size // 4, return_pil_images = True) # returns List[Image]\n",
        "        images[0].save(f'./sample-{i // 100}.png')\n",
        "        print('=' * 70)\n",
        "\n",
        "    if not (i % len(dataset)):\n",
        "      print('=' * 70)\n",
        "      print('Epoch #', epoch)\n",
        "      print('=' * 70)\n",
        "\n",
        "  except KeyboardInterrupt:\n",
        "    print('=' * 70)\n",
        "    print('Stopping training...')\n",
        "    break\n",
        "\n",
        "print('=' * 70)\n",
        "print('Done!')\n",
        "print('=' * 70)"
      ],
      "metadata": {
        "cellView": "form",
        "id": "PPH5xRwl9kB7"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "# (SAVE/LOAD MODEL)"
      ],
      "metadata": {
        "id": "mA-Of_2-BF7n"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "# @title Save trained model\n",
        "\n",
        "print('=' * 70)\n",
        "print('Saving model...')\n",
        "print('=' * 70)\n",
        "\n",
        "trainer.save('./Imagen_POP909_64_dim_'+str(i)+'_steps_'+str(loss)+'_loss.ckpt')\n",
        "\n",
        "print('=' * 70)\n",
        "print('Done!')\n",
        "print('=' * 70)"
      ],
      "metadata": {
        "id": "3GmoHTGW2_h0",
        "cellView": "form"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "# @title Load/reload trained model\n",
        "full_path_to_model_checkpoint = \"./Imagen_POP909_64_dim_10000_steps_0.01_loss.ckpt\" # @param {\"type\":\"string\"}\n",
        "\n",
        "print('=' * 70)\n",
        "print('Loading model...')\n",
        "print('=' * 70)\n",
        "\n",
        "unet = Unet(\n",
        "    dim = 64,\n",
        "    dim_mults = (1, 2, 4, 8),\n",
        "    num_resnet_blocks = 1,\n",
        "    channels=1,\n",
        "    layer_attns = (False, False, False, True),\n",
        "    layer_cross_attns = False\n",
        ")\n",
        "\n",
        "imagen = Imagen(\n",
        "    condition_on_text = False,  # this must be set to False for unconditional Imagen\n",
        "    unets = unet,\n",
        "    channels=1,\n",
        "    image_sizes = 128,\n",
        "    timesteps = 1000\n",
        ")\n",
        "\n",
        "trainer = ImagenTrainer(\n",
        "    imagen = imagen,\n",
        "    split_valid_from_train = True # whether to split the validation dataset from the training\n",
        ").cuda()\n",
        "\n",
        "trainer.load(full_path_to_model_checkpoint)\n",
        "\n",
        "print('=' * 70)\n",
        "print('Done!')\n",
        "print('=' * 70)"
      ],
      "metadata": {
        "id": "lBK05tTeBCIz",
        "cellView": "form"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "# (GENERATE)"
      ],
      "metadata": {
        "id": "uBB8c3sGFQ78"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "# @title Generate music\n",
        "\n",
        "number_of_compositions_to_generate = 8 # @param {\"type\":\"slider\",\"min\":1,\"max\":64,\"step\":1}\n",
        "noise_threshold = 128 # @param {\"type\":\"slider\",\"min\":0,\"max\":255,\"step\":1}\n",
        "\n",
        "print('=' * 70)\n",
        "print('Imagen Model Generator')\n",
        "print('=' * 70)\n",
        "print('Generating', number_of_compositions_to_generate, 'compositions...')\n",
        "print('=' * 70)\n",
        "\n",
        "images = trainer.sample(batch_size = number_of_compositions_to_generate, return_pil_images = True)\n",
        "\n",
        "print('Done!')\n",
        "print('=' * 70)\n",
        "print('Converting to MIDIs...')\n",
        "\n",
        "imgs_array = []\n",
        "\n",
        "for idx, image in enumerate(images):\n",
        "\n",
        "  print('=' * 70)\n",
        "  print('Converting image #', idx)\n",
        "  print('=' * 70)\n",
        "\n",
        "  arr = np.array(image)\n",
        "  farr = np.where(arr < noise_threshold, 0, 1)\n",
        "\n",
        "  bmatrix = TPLOTS.images_to_binary_matrix([farr])\n",
        "\n",
        "  score = TMIDIX.binary_matrix_to_original_escore_notes(bmatrix)\n",
        "\n",
        "  output_score, patches, overflow_patches = TMIDIX.patch_enhanced_score_notes(score)\n",
        "\n",
        "  detailed_stats = TMIDIX.Tegridy_ms_SONG_to_MIDI_Converter(output_score,\n",
        "                                                            output_signature = 'MIDI Images',\n",
        "                                                            output_file_name = '/content/MIDI-Images-Composition_'+str(idx),\n",
        "                                                            track_name='Project Los Angeles',\n",
        "                                                            list_of_MIDI_patches=patches,\n",
        "                                                            timings_multiplier=256\n",
        "                                                            )\n",
        "\n",
        "print('=' * 70)\n",
        "print('Done!')\n",
        "print('=' * 70)"
      ],
      "metadata": {
        "id": "c-WFUfLvE_lm",
        "cellView": "form"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "# Congrats! You did it! :)"
      ],
      "metadata": {
        "id": "F9_DkzNzHWZq"
      }
    }
  ]
}