MIDI-Images / imagen_midi_images_solo_piano_model_maker.py
asigalov61's picture
Upload 2 files
10c9409 verified
raw
history blame
7.6 kB
# -*- coding: utf-8 -*-
"""Imagen_MIDI_Images_Solo_Piano_Model_Maker.ipynb
Automatically generated by Colab.
Original file is located at
https://colab.research.google.com/drive/189FJfPRxZ8zrwi44fAR_ywKnMeb73XJJ
# Imagen MIDI Images Solo Piano Model Maker (ver. 1.0)
***
Powered by tegridy-tools: https://github.com/asigalov61/tegridy-tools
***
WARNING: This complete implementation is a functioning model of the Artificial Intelligence. Please excercise great humility, care, and respect. https://www.nscai.gov/
***
#### Project Los Angeles
#### Tegridy Code 2024
***
# (SETUP ENVIRONMENT)
"""
# @title Install dependecies
!git clone --depth 1 https://github.com/asigalov61/tegridy-tools
!pip install -U imagen-pytorch
!pip install -U huggingface_hub
# Commented out IPython magic to ensure Python compatibility.
#@title Import all needed modules
print('=' * 70)
print('Loading core modules...')
import os
import numpy as np
from tqdm import tqdm
from huggingface_hub import snapshot_download
print('Done!')
print('=' * 70)
print('Creating I/O dirs...')
if not os.path.exists('/content/Dataset'):
os.makedirs('/content/Dataset')
print('Done!')
print('=' * 70)
print('Loading tegridy-tools modules...')
print('=' * 70)
# %cd /content/tegridy-tools/tegridy-tools
import TMIDIX
import TPLOTS
# %cd /content/
print('=' * 70)
print('Done!')
print('=' * 70)
print('Loading Imagen...')
import torch
from imagen_pytorch import Unet, Imagen, ImagenTrainer
from imagen_pytorch.data import Dataset
print('Done!')
print('=' * 70)
print('Torch version:', torch.__version__)
print('=' * 70)
print('Done!')
print('=' * 70)
"""# (DOWNLOAD DATASET)"""
# Commented out IPython magic to ensure Python compatibility.
# @title Download and unzip MIDI Images POP909 Solo Piano dataset
print('=' * 70)
print('Downloading MIDI Images dataset repo...')
print('=' * 70)
repo_id = "asigalov61/MIDI-Images"
repo_type = 'dataset'
local_dir = "./MIDI-Images"
snapshot_download(repo_id, repo_type=repo_type, local_dir=local_dir)
print('=' * 70)
print('Done!')
print('=' * 70)
print('Unzipping POP909 MIDI Images dataset...')
print('=' * 70)
# %cd /content/Dataset/
!unzip /content/MIDI-Images/POP909_MIDI_Dataset_Solo_Piano_MIDI_Images_128_128_32_BW_Ver_1_CC_BY_NC_SA.zip > /dev/null
# %cd /content/
print('=' * 70)
print('Done!')
print('=' * 70)
"""# (INIT MODEL)"""
# @title Init Imagen model
print('=' * 70)
print('Instantiating Imagen model...')
print('=' * 70)
# unets for unconditional imagen
unet = Unet(
dim = 64,
dim_mults = (1, 2, 4, 8),
num_resnet_blocks = 1,
channels=1,
layer_attns = (False, False, False, True),
layer_cross_attns = False
)
# imagen, which contains the unet above
imagen = Imagen(
condition_on_text = False, # this must be set to False for unconditional Imagen
unets = unet,
channels=1,
image_sizes = 128,
timesteps = 1000
)
trainer = ImagenTrainer(
imagen = imagen,
split_valid_from_train = True # whether to split the validation dataset from the training
).cuda()
print('=' * 70)
print('Done!')
print('=' * 70)
"""# (INIT DATASET)"""
# @title Prep and init dataset
batch_size = 16 # @param {"type":"slider","min":4,"max":64,"step":4}
print('=' * 70)
print('Instantiating dataloader...')
print('=' * 70)
# 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
dataset = Dataset('/content/Dataset', image_size = 128)
try:
trainer.add_train_dataset(dataset, batch_size = batch_size)
except:
print('Dataset is ready!')
pass
print('=' * 70)
print('Done!')
print('=' * 70)
"""# (TRAIN MODEL)"""
# @title Train Imagen model
NUM_EPOCHS = 10
print('=' * 70)
print('Training...')
print('=' * 70)
NUM_STEPS = NUM_EPOCHS * len(dataset)
# working training loop
epoch = 1
print('=' * 70)
print('Epoch #', epoch)
print('=' * 70)
for i in range(NUM_STEPS):
try:
loss = trainer.train_step(unet_number = 1, max_batch_size = batch_size)
print(f'loss: {loss}', '===', i)
if not (i % 50):
valid_loss = trainer.valid_step(unet_number = 1, max_batch_size = batch_size)
print('=' * 70)
print(f'valid loss: {valid_loss}')
print('=' * 70)
if not (i % 1000) and trainer.is_main: # is_main makes sure this can run in distributed
print('=' * 70)
images = trainer.sample(batch_size = batch_size // 4, return_pil_images = True) # returns List[Image]
images[0].save(f'./sample-{i // 100}.png')
print('=' * 70)
if not (i % len(dataset)):
print('=' * 70)
print('Epoch #', epoch)
print('=' * 70)
except KeyboardInterrupt:
print('=' * 70)
print('Stopping training...')
break
print('=' * 70)
print('Done!')
print('=' * 70)
"""# (SAVE/LOAD MODEL)"""
# @title Save trained model
print('=' * 70)
print('Saving model...')
print('=' * 70)
trainer.save('./Imagen_POP909_64_dim_'+str(i)+'_steps_'+str(loss)+'_loss.ckpt')
print('=' * 70)
print('Done!')
print('=' * 70)
# @title Load/reload trained model
full_path_to_model_checkpoint = "./Imagen_POP909_64_dim_10000_steps_0.01_loss.ckpt" # @param {"type":"string"}
print('=' * 70)
print('Loading model...')
print('=' * 70)
unet = Unet(
dim = 64,
dim_mults = (1, 2, 4, 8),
num_resnet_blocks = 1,
channels=1,
layer_attns = (False, False, False, True),
layer_cross_attns = False
)
imagen = Imagen(
condition_on_text = False, # this must be set to False for unconditional Imagen
unets = unet,
channels=1,
image_sizes = 128,
timesteps = 1000
)
trainer = ImagenTrainer(
imagen = imagen,
split_valid_from_train = True # whether to split the validation dataset from the training
).cuda()
trainer.load(full_path_to_model_checkpoint)
print('=' * 70)
print('Done!')
print('=' * 70)
"""# (GENERATE)"""
# @title Generate music
number_of_compositions_to_generate = 8 # @param {"type":"slider","min":1,"max":64,"step":1}
noise_threshold = 128 # @param {"type":"slider","min":0,"max":255,"step":1}
print('=' * 70)
print('Imagen Model Generator')
print('=' * 70)
print('Generating', number_of_compositions_to_generate, 'compositions...')
print('=' * 70)
images = trainer.sample(batch_size = number_of_compositions_to_generate, return_pil_images = True)
print('Done!')
print('=' * 70)
print('Converting to MIDIs...')
imgs_array = []
for idx, image in enumerate(images):
print('=' * 70)
print('Converting image #', idx)
print('=' * 70)
arr = np.array(image)
farr = np.where(arr < noise_threshold, 0, 1)
bmatrix = TPLOTS.images_to_binary_matrix([farr])
score = TMIDIX.binary_matrix_to_original_escore_notes(bmatrix)
output_score, patches, overflow_patches = TMIDIX.patch_enhanced_score_notes(score)
detailed_stats = TMIDIX.Tegridy_ms_SONG_to_MIDI_Converter(output_score,
output_signature = 'MIDI Images',
output_file_name = '/content/MIDI-Images-Composition_'+str(idx),
track_name='Project Los Angeles',
list_of_MIDI_patches=patches,
timings_multiplier=256
)
print('=' * 70)
print('Done!')
print('=' * 70)
"""# Congrats! You did it! :)"""