-
Notifications
You must be signed in to change notification settings - Fork 6
/
giant_music_transformer_bulk_generator.py
988 lines (674 loc) · 27.9 KB
/
giant_music_transformer_bulk_generator.py
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
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
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
# -*- coding: utf-8 -*-
"""Giant_Music_Transformer_Bulk_Generator.ipynb
Automatically generated by Colab.
Original file is located at
https://colab.research.google.com/github/asigalov61/Giant-Music-Transformer/blob/main/Giant_Music_Transformer_Bulk_Generator.ipynb
# Giant Music Transformer Bulk Generator (ver. 4.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
***
# (GPU CHECK)
"""
#@title NVIDIA GPU check
!nvidia-smi
"""# (SETUP ENVIRONMENT)"""
#@title Install dependencies
!git clone --depth 1 https://github.com/asigalov61/Giant-Music-Transformer
!pip install -U torch
!pip install einops
!pip install torch-summary
!apt install fluidsynth #Pip does not work for some reason. Only apt works
# Commented out IPython magic to ensure Python compatibility.
#@title Import modules
print('=' * 70)
print('Loading core Giant Music Transformer modules...')
import os
import pickle
import secrets
import statistics
from time import time
import datetime
import tqdm
import locale
locale.getpreferredencoding = lambda: "UTF-8"
print('=' * 70)
print('Creating I/O dirs...')
if not os.path.exists('/content/Output/Improvs'):
os.makedirs('/content/Output/Improvs')
if not os.path.exists('/content/Output/Continuations'):
os.makedirs('/content/Output/Continuations')
print('=' * 70)
print('Loading main Giant Music Transformer modules...')
os.environ['USE_FLASH_ATTENTION'] = '1'
import torch
torch.set_float32_matmul_precision('high')
torch.backends.cuda.matmul.allow_tf32 = True # allow tf32 on matmul
torch.backends.cudnn.allow_tf32 = True # allow tf32 on cudnn
torch.backends.cuda.enable_mem_efficient_sdp(True)
torch.backends.cuda.enable_math_sdp(True)
torch.backends.cuda.enable_flash_sdp(True)
torch.backends.cuda.enable_cudnn_sdp(True)
# %cd /content/Giant-Music-Transformer
import TMIDIX
from midi_to_colab_audio import midi_to_colab_audio
from x_transformer_1_23_2 import *
import random
# %cd /content/
print('=' * 70)
print('Loading aux Giant Music Transformer modules...')
import matplotlib.pyplot as plt
from torchsummary import summary
from sklearn import metrics
from IPython.display import Audio, display
from huggingface_hub import hf_hub_download
from google.colab import files
print('=' * 70)
print('PyTorch version:', torch.__version__)
print('=' * 70)
print('Done!')
print('Enjoy! :)')
print('=' * 70)
"""# (LOAD MODEL)"""
#@title Load Giant Music Transformer Pre-Trained Model
#@markdown Choose model
select_model_to_load = "482M-8L-Ultra-Fast-Medium" # @param ["482M-8L-Ultra-Fast-Medium","585M-32L-Very-Fast-Large","786M-44L-Fast-Extra-Large"]
#@markdown Model precision option
model_precision = "bfloat16" # @param ["bfloat16", "float16"]
#@markdown bfloat16 == Half precision/faster speed (if supported, otherwise the model will default to float16)
#@markdown float16 == Full precision/fast speed
plot_tokens_embeddings = "None" # @param ["None", "Start Times", "Durations Velocities", "Piano Pitches", "Drums Pitches", "Aux"]
print('=' * 70)
print('Loading Giant Music Transformer', select_model_to_load,'Pre-Trained Model...')
print('Please wait...')
print('=' * 70)
full_path_to_models_dir = "/content/Giant-Music-Transformer/Models"
if select_model_to_load == '786M-44L-Fast-Extra-Large':
model_checkpoint_file_name = 'Giant_Music_Transformer_Extra_Large_Trained_Model_18001_steps_0.2657_loss_0.9272_acc.pth'
model_path = full_path_to_models_dir+'/Extra Large/'+model_checkpoint_file_name
mdim = 1024
num_layers = 44
mrpe = False
if os.path.isfile(model_path):
print('Model already exists...')
else:
hf_hub_download(repo_id='asigalov61/Giant-Music-Transformer',
filename=model_checkpoint_file_name,
local_dir='/content/Giant-Music-Transformer/Models/Extra Large',
)
elif select_model_to_load == '585M-32L-Very-Fast-Large':
model_checkpoint_file_name = 'Giant_Music_Transformer_Large_Trained_Model_36074_steps_0.3067_loss_0.927_acc.pth'
model_path = full_path_to_models_dir+'/Large/'+model_checkpoint_file_name
mdim = 1024
num_layers = 32
mrpe = False
if os.path.isfile(model_path):
print('Model already exists...')
else:
hf_hub_download(repo_id='asigalov61/Giant-Music-Transformer',
filename=model_checkpoint_file_name,
local_dir='/content/Giant-Music-Transformer/Models/Large',
)
elif select_model_to_load == '482M-8L-Ultra-Fast-Medium':
model_checkpoint_file_name = 'Giant_Music_Transformer_Medium_Trained_Model_42174_steps_0.5211_loss_0.8542_acc.pth'
model_path = full_path_to_models_dir+'/Medium/'+model_checkpoint_file_name
mdim = 2048
num_layers = 8
mrpe = True
if os.path.isfile(model_path):
print('Model already exists...')
else:
hf_hub_download(repo_id='asigalov61/Giant-Music-Transformer',
filename=model_checkpoint_file_name,
local_dir='/content/Giant-Music-Transformer/Models/Medium',
)
print('=' * 70)
print('Instantiating model...')
device_type = 'cuda'
if model_precision == 'bfloat16' and torch.cuda.is_bf16_supported():
dtype = 'bfloat16'
else:
dtype = 'float16'
if model_precision == 'float16':
dtype = 'float16'
ptdtype = {'bfloat16': torch.bfloat16, 'float16': torch.float16}[dtype]
ctx = torch.amp.autocast(device_type=device_type, dtype=ptdtype)
SEQ_LEN = 8192
PAD_IDX = 19463
model = TransformerWrapper(
num_tokens = PAD_IDX+1,
max_seq_len = SEQ_LEN,
attn_layers = Decoder(dim = mdim,
depth = num_layers,
heads = 32,
rotary_pos_emb = mrpe,
attn_flash = True
)
)
model = AutoregressiveWrapper(model, ignore_index=PAD_IDX, pad_value=PAD_IDX)
print('=' * 70)
print('Loading model checkpoint...')
model.load_state_dict(torch.load(model_path))
print('=' * 70)
model.cuda()
model.eval()
print('Done!')
print('=' * 70)
print('Model will use', dtype, 'precision...')
print('=' * 70)
# Model stats
print('Model summary...')
summary(model)
# Plot Token Embeddings
if plot_tokens_embeddings != 'None':
tok_emb = model.net.token_emb.emb.weight.detach().cpu().tolist()
if plot_tokens_embeddings == 'Start Times':
tok_range = [0, 256]
elif plot_tokens_embeddings == 'Durations Velocities':
tok_range = [256, 2304]
elif plot_tokens_embeddings == 'Piano Pitches':
tok_range = [2304, 2304+128]
elif plot_tokens_embeddings == 'Drums Pitches':
tok_range = [18945-128, 18945]
elif plot_tokens_embeddings == 'Aux':
tok_range = [18945, 19465]
if plot_tokens_embeddings != 'None':
tok_emb1 = []
for t in tok_emb[tok_range[0]:tok_range[1]]:
tok_emb1.append(t)
cos_sim = metrics.pairwise_distances(
tok_emb1, metric='cosine'
)
plt.figure(figsize=(7, 7))
plt.imshow(cos_sim, cmap="inferno", interpolation="nearest")
im_ratio = cos_sim.shape[0] / cos_sim.shape[1]
plt.colorbar(fraction=0.046 * im_ratio, pad=0.04)
plt.xlabel("Position")
plt.ylabel("Position")
plt.tight_layout()
plt.plot()
plt.savefig("/content/Giant-Music-Transformer-Tokens-Embeddings-Plot.png", bbox_inches="tight")
"""# (GENERATE)
# (BULK IMPROV)
"""
#@title Bulk Improv Generator
#@markdown NOTE: You can stop bulk generation at any time
#@markdown Improv type
improv_type = "Random Freestyle" # @param ["Random Freestyle", "Freestyle without Drums", "Freestyle with Drums", "Custom"]
#@markdown Custom Improv settings
first_note_MIDI_patch_number = 0 # @param {type:"slider", min:0, max:128, step:1}
add_drums = False #@param {type:"boolean"}
#@markdown Generation settings
number_of_generation_cycles = 10 # @param {type:"slider", min:1, max:256, step:1}
number_of_tokens_to_generate = 2046 # @param {type:"slider", min:30, max:8190, step:3}
number_of_batches_to_generate = 8 #@param {type:"slider", min:1, max:16, step:1}
temperature = 0.9 # @param {type:"slider", min:0.1, max:1, step:0.05}
model_sampling_top_p_value = 0.96 # @param {type:"slider", min:0.1, max:1, step:0.01}
#@markdown Other settings
verbose = False # @param {type:"boolean"}
date_time = datetime.datetime.strftime(datetime.datetime.now(), '%Y-%m-%d_%H-%M-%S')
if improv_type == 'Random Freestyle':
outy = [19461]
improv_type = 'Random_Freestyle'
if improv_type == 'Freestyle without Drums':
outy = [19461, 19330]
improv_type = 'Freestyle_without_Drums'
if improv_type == 'Freestyle with Drums':
outy = [19461, 19331]
improv_type = 'Freestyle_with_Drums'
if improv_type == 'Custom':
if add_drums:
drumsp = 19331 # Yes
dr = 1
else:
drumsp = 19330 # No
dr = 0
outy = [19461, drumsp, 19332+first_note_MIDI_patch_number, 0]
improv_type += '_P'+str(first_note_MIDI_patch_number)+'_D'+str(dr)
output_dir = '/content/Output/Improvs/'+improv_type+'_'+str(date_time) + '/'
if not os.path.exists(output_dir):
os.makedirs(output_dir)
print('=' * 70)
print('Giant Music Transformer Bulk Improv Model Generator')
print('=' * 70)
print('Generating', number_of_generation_cycles * number_of_batches_to_generate, 'compositions', number_of_tokens_to_generate, 'tokens each')
print('=' * 70)
print('Total number of tokens to generate:', number_of_generation_cycles*number_of_batches_to_generate * number_of_tokens_to_generate)
print('=' * 70)
print('Output directory:', output_dir)
print('=' * 70)
print('Generating...Please wait...')
print('=' * 70)
try:
for gc in tqdm.tqdm(range(number_of_generation_cycles)):
if verbose:
print('Selected Improv sequence:')
print(outy)
print('=' * 70)
torch.cuda.empty_cache()
inp = [outy] * number_of_batches_to_generate
inp = torch.LongTensor(inp).cuda()
with ctx:
with torch.inference_mode():
out = model.generate(inp,
number_of_tokens_to_generate,
filter_logits_fn=top_p,
filter_kwargs={'thres': model_sampling_top_p_value},
temperature=temperature,
return_prime=True,
verbose=verbose)
out0 = out.tolist()
if verbose:
print('=' * 70)
print('Done!')
print('=' * 70)
torch.cuda.empty_cache()
#======================================================================
if verbose:
print('Rendering results...')
for i in range(number_of_batches_to_generate):
if verbose:
print('=' * 70)
print('Batch #', i)
print('=' * 70)
out1 = out0[i]
if verbose:
print('Sample INTs', out1[:12])
print('=' * 70)
if len(out1) != 0:
song = out1
song_f = []
time = 0
dur = 0
vel = 90
pitch = 0
channel = 0
patches = [-1] * 16
channels = [0] * 16
channels[9] = 1
for ss in song:
if 0 <= ss < 256:
time += ss * 16
if 256 <= ss < 2304:
dur = ((ss-256) // 8) * 16
vel = (((ss-256) % 8)+1) * 15
if 2304 <= ss < 18945:
patch = (ss-2304) // 129
if patch < 128:
if patch not in patches:
if 0 in channels:
cha = channels.index(0)
channels[cha] = 1
else:
cha = 15
patches[cha] = patch
channel = patches.index(patch)
else:
channel = patches.index(patch)
if patch == 128:
channel = 9
pitch = (ss-2304) % 129
song_f.append(['note', time, dur, channel, pitch, vel ])
patches = [0 if x==-1 else x for x in patches]
data = TMIDIX.Tegridy_ms_SONG_to_MIDI_Converter(song_f,
output_signature = 'Giant Music Transformer',
output_file_name = output_dir + 'Giant-Music-Transformer-Music-Composition_'+str(i+(gc*number_of_batches_to_generate)).zfill(5),
track_name='Project Los Angeles',
list_of_MIDI_patches=patches,
verbose=verbose)
if verbose:
print('=' * 70)
except KeyboardInterrupt:
print('STOP!!!')
print('=' * 70)
print('Stopping generation...')
print('Done!')
print('=' * 70)
"""# (BULK CUSTOM MIDI CONTINUATIONS)"""
#@title Load Seed MIDI
#@markdown Press play button to to upload your own seed MIDI or to load one of the provided sample seed MIDIs from the dropdown list below
select_seed_MIDI = "Upload your own custom MIDI" # @param ["Upload your own custom MIDI", "Giant-Music-Transformer-Piano-Seed-1", "Giant-Music-Transformer-Piano-Seed-2", "Giant-Music-Transformer-Piano-Seed-3", "Giant-Music-Transformer-Piano-Seed-4", "Giant-Music-Transformer-Piano-Seed-5", "Giant-Music-Transformer-Piano-Seed-6", "Giant-Music-Transformer-MI-Seed-1", "Giant-Music-Transformer-MI-Seed-2", "Giant-Music-Transformer-MI-Seed-3", "Giant-Music-Transformer-MI-Seed-4", "Giant-Music-Transformer-MI-Seed-5", "Giant-Music-Transformer-MI-Seed-6"]
render_MIDI_to_audio = False # @param {type:"boolean"}
print('=' * 70)
print('Giant Music Transformer Seed MIDI Loader')
print('=' * 70)
f = ''
if select_seed_MIDI != "Upload your own custom MIDI":
print('Loading seed MIDI...')
f = '/content/Giant-Music-Transformer/Seeds/'+select_seed_MIDI+'.mid'
else:
print('Upload your own custom MIDI...')
print('=' * 70)
uploaded_MIDI = files.upload()
if list(uploaded_MIDI.keys()):
f = list(uploaded_MIDI.keys())[0]
if f != '':
fn = f.split('/')[-1]
custom_midi_file_name = fn.split('.mid')[0]
print('=' * 70)
print('File:', f)
print('=' * 70)
#=======================================================
# START PROCESSING
# Convering MIDI to ms score with MIDI.py module
score = TMIDIX.midi2single_track_ms_score(open(f, 'rb').read(), recalculate_channels=False)
# INSTRUMENTS CONVERSION CYCLE
events_matrix = []
itrack = 1
patches = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
while itrack < len(score):
for event in score[itrack]:
if event[0] == 'note' or event[0] == 'patch_change':
events_matrix.append(event)
itrack += 1
events_matrix.sort(key=lambda x: x[1])
events_matrix1 = []
for event in events_matrix:
if event[0] == 'patch_change':
patches[event[2]] = event[3]
if event[0] == 'note':
event.extend([patches[event[3]]])
if events_matrix1:
if (event[1] == events_matrix1[-1][1]):
if ([event[3], event[4]] != events_matrix1[-1][3:5]):
events_matrix1.append(event)
else:
events_matrix1.append(event)
else:
events_matrix1.append(event)
if len(events_matrix1) > 0:
if min([e[1] for e in events_matrix1]) >= 0 and min([e[2] for e in events_matrix1]) >= 0:
#=======================================================
# PRE-PROCESSING
# checking number of instruments in a composition
instruments_list_without_drums = list(set([y[3] for y in events_matrix1 if y[3] != 9]))
instruments_list = list(set([y[3] for y in events_matrix1]))
if len(events_matrix1) > 0 and len(instruments_list_without_drums) > 0:
#======================================
events_matrix2 = []
# Recalculating timings
for e in events_matrix1:
# Original timings
e[1] = int(e[1] / 16)
e[2] = int(e[2] / 16)
#===================================
# ORIGINAL COMPOSITION
#===================================
# Sorting by patch, pitch, then by start-time
events_matrix1.sort(key=lambda x: x[6])
events_matrix1.sort(key=lambda x: x[4], reverse=True)
events_matrix1.sort(key=lambda x: x[1])
#=======================================================
# FINAL PROCESSING
melody_chords = []
melody_chords2 = []
# Break between compositions / Intro seq
if 9 in instruments_list:
drums_present = 19331 # Yes
else:
drums_present = 19330 # No
if events_matrix1[0][3] != 9:
pat = events_matrix1[0][6]
else:
pat = 128
melody_chords.extend([19461, drums_present, 19332+pat]) # Intro seq
#=======================================================
# MAIN PROCESSING CYCLE
#=======================================================
abs_time = 0
pbar_time = 0
pe = events_matrix1[0]
chords_counter = 1
comp_chords_len = len(list(set([y[1] for y in events_matrix1])))
for e in events_matrix1:
#=======================================================
# Timings...
# Cliping all values...
delta_time = max(0, min(255, e[1]-pe[1]))
# Durations and channels
dur = max(0, min(255, e[2]))
cha = max(0, min(15, e[3]))
# Patches
if cha == 9: # Drums patch will be == 128
pat = 128
else:
pat = e[6]
# Pitches
ptc = max(1, min(127, e[4]))
# Velocities
# Calculating octo-velocity
vel = max(8, min(127, e[5]))
velocity = round(vel / 15)-1
#=======================================================
# Outro seq
# if ((comp_chords_len - chords_counter) == 50) and (delta_time != 0):
# out_t = 18946+delta_time
# out_p = 19202+ptc
# melody_chords.extend([18945, out_t, out_p]) # outro seq
# if delta_time != 0:
# chords_counter += 1
#=======================================================
# FINAL NOTE SEQ
# Writing final note asynchronously
dur_vel = (8 * dur) + velocity
pat_ptc = (129 * pat) + ptc
melody_chords.extend([delta_time, dur_vel+256, pat_ptc+2304])
melody_chords2.append([delta_time, dur_vel+256, pat_ptc+2304])
pe = e
#=======================================================
# melody_chords.extend([19462, 19462, 19462]) # EOS
#=======================================================
# TOTAL DICTIONARY SIZE 19462+1=19463
#=======================================================
#=======================================================
song = melody_chords
song_f = []
time = 0
dur = 0
vel = 90
pitch = 0
channel = 0
patches = [-1] * 16
channels = [0] * 16
channels[9] = 1
for ss in song:
if 0 <= ss < 256:
time += ss * 16
if 256 <= ss < 2304:
dur = ((ss-256) // 8) * 16
vel = (((ss-256) % 8)+1) * 15
if 2304 <= ss < 18945:
patch = (ss-2304) // 129
if patch < 128:
if patch not in patches:
if 0 in channels:
cha = channels.index(0)
channels[cha] = 1
else:
cha = 15
patches[cha] = patch
channel = patches.index(patch)
else:
channel = patches.index(patch)
if patch == 128:
channel = 9
pitch = (ss-2304) % 129
song_f.append(['note', time, dur, channel, pitch, vel, patch ])
patches = [0 if x==-1 else x for x in patches]
detailed_stats = TMIDIX.Tegridy_ms_SONG_to_MIDI_Converter(song_f,
output_signature = 'Giant Music Transformer',
output_file_name = '/content/Giant-Music-Transformer-Seed-Composition',
track_name='Project Los Angeles',
list_of_MIDI_patches=patches
)
#=======================================================
print('=' * 70)
print('Composition stats:')
print('Composition has', len(melody_chords2), 'notes')
print('Composition has', len(melody_chords), 'tokens')
print('Composition MIDI patches:', sorted(list(set([((y-2304) // 129) for y in melody_chords if 2304 <= y < 18945]))))
print('=' * 70)
print('Displaying resulting composition...')
print('=' * 70)
fname = '/content/Giant-Music-Transformer-Seed-Composition'
if render_MIDI_to_audio:
midi_audio = midi_to_colab_audio(fname + '.mid')
display(Audio(midi_audio, rate=16000, normalize=False))
TMIDIX.plot_ms_SONG(song_f, plot_title=fname)
else:
print('=' * 70)
"""# (BULK CONTINUATIONS)"""
#@title Bulk Continuations
#@markdown NOTE: You can stop bulk generation at any time
#@markdown Generation settings
try_to_generate_outro = False #@param {type:"boolean"}
number_of_prime_tokens = 1020 # @param {type:"slider", min:3, max:8190, step:3}
number_of_tokens_to_generate = 1041 # @param {type:"slider", min:30, max:8190, step:3}
number_of_generation_cycles = 10 # @param {type:"slider", min:1, max:256, step:1}
number_of_batches_to_generate = 4 #@param {type:"slider", min:1, max:16, step:1}
temperature = 0.9 # @param {type:"slider", min:0.1, max:1, step:0.05}
model_sampling_top_p_value = 0.96 # @param {type:"slider", min:0.1, max:1, step:0.01}
#@markdown Other settings
include_prime_tokens_in_generated_output = True #@param {type:"boolean"}
allow_model_to_stop_generation_if_needed = False #@param {type:"boolean"}
verbose = False # @param {type:"boolean"}
if allow_model_to_stop_generation_if_needed:
min_stop_token = 19462
else:
min_stop_token = None
outy = melody_chords[:number_of_prime_tokens]
if try_to_generate_outro:
outy.extend([18945])
num_gen_toks = min(8190, number_of_tokens_to_generate)
date_time = datetime.datetime.strftime(datetime.datetime.now(), '%Y-%m-%d_%H-%M-%S')
output_dir = '/content/Output/Continuations/'+custom_midi_file_name+'_'+str(date_time) + '/'
if not os.path.exists(output_dir):
os.makedirs(output_dir)
print('=' * 70)
print('Giant Music Transformer Bulk Continuations Model Generator')
print('=' * 70)
print('Generating', number_of_generation_cycles * number_of_batches_to_generate, 'continuations blocks', number_of_tokens_to_generate, 'tokens each')
print('=' * 70)
print('Total number of tokens to generate:', number_of_generation_cycles * number_of_batches_to_generate * number_of_tokens_to_generate)
print('=' * 70)
print('Output directory:', output_dir)
print('=' * 70)
print('Generating...Please wait...')
print('=' * 70)
try:
for gc in tqdm.tqdm(range(number_of_generation_cycles)):
torch.cuda.empty_cache()
inp = [outy] * number_of_batches_to_generate
inp = torch.LongTensor(inp).cuda()
with ctx:
with torch.inference_mode():
out = model.generate(inp,
num_gen_toks,
filter_logits_fn=top_p,
filter_kwargs={'thres': model_sampling_top_p_value},
temperature=temperature,
return_prime=include_prime_tokens_in_generated_output,
eos_token=min_stop_token,
verbose=verbose)
out0 = out.tolist()
torch.cuda.empty_cache()
if verbose:
print('=' * 70)
print('Done!')
print('=' * 70)
#======================================================================
if verbose:
print('Rendering results...')
for i in range(number_of_batches_to_generate):
if verbose:
print('=' * 70)
print('Batch #', i)
print('=' * 70)
out1 = out0[i]
if verbose:
print('Sample INTs', out1[:12])
print('=' * 70)
if len(out) != 0:
song = out1
song_f = []
time = 0
dur = 0
vel = 90
pitch = 0
channel = 0
patches = [-1] * 16
channels = [0] * 16
channels[9] = 1
for ss in song:
if 0 <= ss < 256:
time += ss * 16
if 256 <= ss < 2304:
dur = ((ss-256) // 8) * 16
vel = (((ss-256) % 8)+1) * 15
if 2304 <= ss < 18945:
patch = (ss-2304) // 129
if patch < 128:
if patch not in patches:
if 0 in channels:
cha = channels.index(0)
channels[cha] = 1
else:
cha = 15
patches[cha] = patch
channel = patches.index(patch)
else:
channel = patches.index(patch)
if patch == 128:
channel = 9
pitch = (ss-2304) % 129
song_f.append(['note', time, dur, channel, pitch, vel ])
patches = [0 if x==-1 else x for x in patches]
detailed_stats = TMIDIX.Tegridy_ms_SONG_to_MIDI_Converter(song_f,
output_signature = 'Giant Music Transformer',
output_file_name = output_dir + 'Giant-Music-Transformer-Music-Composition_'+str(i + (gc * number_of_batches_to_generate)).zfill(5),
track_name='Project Los Angeles',
list_of_MIDI_patches=patches,
verbose=verbose
)
if verbose:
print('=' * 70)
except KeyboardInterrupt:
print('STOP!!!')
print('=' * 70)
print('Stopping generation...')
print('Done!')
print('=' * 70)
"""# (ZIP AND DOWNLOAD RESULTS)"""
# Commented out IPython magic to ensure Python compatibility.
#@title Zip and download all bulk generations results
print('=' * 70)
try:
os.remove('Giant_Music_Transformer_Bulk_Generator_Output.zip')
except OSError:
pass
print('Zipping... Please wait...')
print('=' * 70)
# %cd /content/Output/
!zip -r Giant_Music_Transformer_Bulk_Generator_Output.zip *
# %cd /content/
print('=' * 70)
print('Done!')
print('=' * 70)
print('Downloading final zip file...')
print('=' * 70)
files.download('/content/Output/Giant_Music_Transformer_Bulk_Generator_Output.zip')
print('Done!')
print('=' * 70)
# @title Delete results directory and files
#@markdown WARNING: This can't be undone so make sure you downloaded the results first
print('=' * 70)
print('Deleting... Please wait...')
print('=' * 70)
!rm -rf /content/Output
print('Done!')
print('=' * 70)
"""# Congrats! You did it! :)"""