File size: 7,597 Bytes
10c9409
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
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
# -*- 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! :)"""