{ "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" } } ] }