-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
executable file
·2919 lines (2286 loc) · 107 KB
/
main.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
989
990
991
992
993
994
995
996
997
998
999
1000
"""
1. This is the all-in-one file for training and inferencing.
2. All results including:
the loss,
the best voicing threshold,
overall accuracy (OA),
and other detailed performance measures, like raw pitch accuracy, raw chroma accuracy, voicing accuracy, and more,
are written to tensorboard, so you can view easily.
3. All Parameters can be set in the __init__ function of class Config. These parameters include:
the checkpoint for inferencing,
the checkpoint used for resuming the training,
the prefix used when storing a checkpoint,
the directory where the tensorboard is stored,
the number of frames for each example,
the learning rate,
the number of patience epochs,
the dataset to use for inferencing.
4. Flow for training or inference:
1) Call Config() to create the configuration and the acoustic model
2) Call TFDatasetXXX to create tf dataset
3) Call MetricsXXX to create something that can gather the metrics
4) Call TBSummary to create something that can write metrics to tensorboard
5) train or inference
"""
DEBUG = True # set to True to run in debug mode for debugging
GPU_ID = 0 # which GPU to use
import logging
logging.basicConfig(
level=logging.DEBUG if DEBUG else logging.INFO,
format='[%(levelname)s] %(message)s'
)
import tensorflow as tf
tf.random.set_seed(2022)
from argparse import Namespace
import glob
import os
import numpy as np
import librosa
from self_defined import ArrayToTableTFFn # output tables to tensorboard
import pitch_local as acoustic_model_module
import nsgt as nsgt_module
assert not nsgt_module.USE_DOUBLE
import soundfile
import mir_eval
from self_defined import load_np_array_from_file_fn
if DEBUG:
for name in logging.root.manager.loggerDict:
if name.startswith('numba'):
logger = logging.getLogger(name)
logger.setLevel(logging.WARNING)
if name.startswith('matplotlib'):
logger = logging.getLogger(name)
logger.setLevel(logging.WARNING)
if name.startswith('numpy'):
logger = logging.getLogger(name)
logger.setLevel(logging.WARNING)
# configurable parameters are set in the __init__ function of the class below
class Config:
def __init__(self):
self.debug_mode = DEBUG
Config.set_gpu_fn() # select gpu
self.train_or_inference = Namespace(
inference='d0-24', # which checkpoint to use for inferencing
from_ckpt=None, # specify a checkpoint to resume the training if you have one
ckpt_prefix=None # prefix used when saving the best checkpoint
)
self.tb_dir = 'tb_inf' # folder for tensorboard
if self.train_or_inference.inference is None:
self.model_names = ('training', 'validation') # in training mode, 'test' is not allowed
else:
self.model_names = ('training', 'validation', 'test')
# check if tb_dir and checkpoints with the same prefix already exist
if not self.debug_mode:
self.chk_if_tb_dir_and_model_with_same_prefix_exist_fn()
self.snippet_len = 1200 # the number of spectral frames for each example
self.initial_learning_rate = 1e-3 # the learning rate
self.batches_per_epoch = None # automatically set, do not change it.
self.patience_epochs = 10 if self.debug_mode else 20 # number of patience epochs
self.tvt_split_dict = Config.get_dataset_split_fn() # get dataset partition of MDB
if self.debug_mode: # in debug mode, we use fewer recordings to save time.
self.tvt_split_dict['training'] = self.tvt_split_dict['training'][:3]
self.tvt_split_dict['validation'] = self.tvt_split_dict['validation'][:3]
self.tvt_split_dict['test'] = self.tvt_split_dict['test'][:3]
self.acoustic_model_ins = AcousticModel(self) # construct acoustic model
note_range = TFDataset.note_range
# build optimizer so as to create relevant optimizer weights
if self.train_or_inference.inference is None:
# self.learning_rate = tf.Variable(
# self.initial_learning_rate, dtype=tf.float32, name='learning_rate', trainable=False)
self.optimizer = tf.keras.optimizers.Adam(learning_rate=self.initial_learning_rate)
trainable_variables = self.acoustic_model_ins.trainable_variables
spec = tf.random.uniform([1, self.snippet_len, 500])
lower_note = note_range[0]
upper_note = note_range[-1]
labels = np.random.uniform(lower_note, upper_note, [self.snippet_len])
with tf.GradientTape(watch_accessed_variables=False) as tape:
tape.watch(trainable_variables)
logits = self.acoustic_model_ins(spec, training=False)
loss = self.acoustic_model_ins.loss_tf_fn(ref_notes=labels, logits=logits)
grads = tape.gradient(loss, trainable_variables)
assert all(g is not None for g in grads)
self.optimizer.apply_gradients(zip(grads, trainable_variables))
assert len(self.optimizer.variables) > 0
logging.debug('\n\noptimizer variables:')
for idx, w in enumerate(self.optimizer.variables):
logging.info('{}, {}, {}'.format(idx, w.name, w.shape))
@staticmethod
def set_gpu_fn():
gpus = tf.config.list_physical_devices('GPU')
num_gpus = len(gpus)
assert num_gpus > 0
gpu_id = min(num_gpus - 1, GPU_ID)
tf.config.set_visible_devices(gpus[gpu_id], 'GPU')
tf.config.experimental.set_memory_growth(gpus[gpu_id], True)
def chk_if_tb_dir_and_model_with_same_prefix_exist_fn(self):
# check if tb_dir exists
assert self.tb_dir is not None
is_tb_dir_exist = glob.glob('{}/'.format(self.tb_dir))
if is_tb_dir_exist:
assert False, 'directory {} already exists'.format(self.tb_dir)
# check if model exists
if self.train_or_inference.inference is None and self.train_or_inference.ckpt_prefix is not None:
ckpt_dir, ckpt_prefix = os.path.split(self.train_or_inference.ckpt_prefix)
assert ckpt_prefix != ''
if ckpt_dir == '':
ckpt_dir = 'ckpts'
is_exist = glob.glob('{}/{}*'.format(ckpt_dir, ckpt_prefix))
if is_exist:
assert False, 'checkpoints with prefix {} already exist'.format(ckpt_prefix)
@staticmethod
def get_dataset_split_fn():
train_songlist = ["AimeeNorwich_Child", "AlexanderRoss_GoodbyeBolero", "AlexanderRoss_VelvetCurtain",
"AvaLuna_Waterduct", "BigTroubles_Phantom", "DreamersOfTheGhetto_HeavyLove",
"FacesOnFilm_WaitingForGa", "FamilyBand_Again", "Handel_TornamiAVagheggiar",
"HeladoNegro_MitadDelMundo", "HopAlong_SisterCities", "LizNelson_Coldwar",
"LizNelson_ImComingHome", "LizNelson_Rainfall", "Meaxic_TakeAStep", "Meaxic_YouListen",
"MusicDelta_80sRock", "MusicDelta_Beatles", "MusicDelta_Britpop", "MusicDelta_Country1",
"MusicDelta_Country2", "MusicDelta_Disco", "MusicDelta_Grunge", "MusicDelta_Hendrix",
"MusicDelta_Punk", "MusicDelta_Reggae", "MusicDelta_Rock", "MusicDelta_Rockabilly",
"PurlingHiss_Lolita", "StevenClark_Bounty", "SweetLights_YouLetMeDown",
"TheDistricts_Vermont", "TheScarletBrand_LesFleursDuMal", "TheSoSoGlos_Emergency",
"Wolf_DieBekherte"]
val_songlist = ["BrandonWebster_DontHearAThing", "BrandonWebster_YesSirICanFly",
"ClaraBerryAndWooldog_AirTraffic", "ClaraBerryAndWooldog_Boys", "ClaraBerryAndWooldog_Stella",
"ClaraBerryAndWooldog_TheBadGuys", "ClaraBerryAndWooldog_WaltzForMyVictims",
"HezekiahJones_BorrowedHeart", "InvisibleFamiliars_DisturbingWildlife", "Mozart_DiesBildnis",
"NightPanther_Fire", "SecretMountains_HighHorse", "Snowmine_Curfews"]
test_songlist = ["AClassicEducation_NightOwl", "Auctioneer_OurFutureFaces", "CelestialShore_DieForUs",
"Creepoid_OldTree", "Debussy_LenfantProdigue", "MatthewEntwistle_DontYouEver",
"MatthewEntwistle_Lontano", "Mozart_BesterJungling", "MusicDelta_Gospel",
"PortStWillow_StayEven", "Schubert_Erstarrung", "StrandOfOaks_Spacestation"]
assert len(train_songlist) == 35
assert len(val_songlist) == 13
assert len(test_songlist) == 12
return dict(
training=train_songlist,
validation=val_songlist,
test=test_songlist
)
@staticmethod
def get_adc04_track_ids_fn():
test_songlist = ["daisy1", "daisy2", "daisy3", "daisy4", "opera_fem2", "opera_fem4", "opera_male3",
"opera_male5", "pop1", "pop2", "pop3", "pop4"]
assert len(test_songlist) == 12
return test_songlist
@staticmethod
def get_mirex05_track_ids_fn():
test_songlist = ["train01", "train02", "train03", "train04", "train05", "train06", "train07", "train08",
"train09"]
assert len(test_songlist) == 9
return test_songlist
@staticmethod
def get_mir1k_track_ids_fn():
wav_files = os.path.join(os.environ['mir1k'], 'Wavfile', '*.wav')
wav_files = glob.glob(wav_files)
track_ids = [os.path.basename(wav_file)[:-4] for wav_file in wav_files]
track_ids = set(track_ids)
assert len(track_ids) == 1000
track_ids = list(track_ids)
track_ids = np.sort(track_ids)
track_ids = list(track_ids)
return track_ids
@staticmethod
def get_rwc_track_ids_fn():
track_ids = []
for rec_idx in range(100):
track_ids.append(str(rec_idx))
return track_ids
"""
The class below includes:
the deep learning model proposed,
the loss function,
restoring parameters for the partial and pitch module that were already trained, because in this code we only train the melody module.
"""
class AcousticModel:
def __init__(self, config):
acoustic_model = acoustic_model_module.create_acoustic_model_fn() # create the acoustic model
assert len(acoustic_model.trainable_variables) > 0
self.acoustic_model = acoustic_model
# self.restore_all_but_temporal_fn() # uncomment this line when in training mode to restore the trained partial and pitch module
self.trainable_variables = self.get_trainable_variables_fn() # get trainable variables
self.voicing_threshold = tf.Variable(.15, trainable=False, name='voicing_threshold') # the voicing threshold, which is dynamically adjusted
self.model_for_ckpt = dict(acoustic_model=acoustic_model, voicing_threshold=self.voicing_threshold) # we checkpoint the acoustic model and the voicing threshold
self.config = config
self.cutoff_prob = 4e-3 # cutoff probability used Gaussianizing the target label
self.kernel_indices = self.locate_kernels_for_l2_reg_fn() # locate the kernels for weight decay
self.n_trainables = len(self.trainable_variables)
self.l2_coeff = tf.Variable(0., name='l2_ref_coeff', trainable=False) # coefficient for weight decay, here we did not use weight decay
def restore_all_but_temporal_fn(self):
acoustic_model = self.acoustic_model
weights = acoustic_model.weights
logging.debug('\n\nall weights:')
for idx, w in enumerate(weights):
logging.debug('{}, {}'.format(idx, w.name))
values_before_dict = {}
for idx, w in enumerate(weights):
values_before_dict[w.name] = tf.reduce_sum(tf.abs(w))
ckpt_file = '/media/ssd/music_trans/2206/26_local_global_with_pitch_context_bn/bn_no_update/ckpts/d0-19'
ckpt = tf.train.Checkpoint(model=dict(acoustic_model=acoustic_model))
status = ckpt.restore(ckpt_file)
status.expect_partial()
logging.debug('\n\nrestored list:')
for idx, w in enumerate(weights):
t = tf.reduce_sum(tf.abs(w))
_t = values_before_dict[w.name]
if t != _t:
logging.debug('{}, {}, {}, {}'.format(idx, w.name, _t.numpy(), t.numpy()))
else:
assert w.name.startswith('temporal') or w.name.startswith('melody')
# add weight decay
def add_l2_grads_fn(self, grads):
assert len(grads) == self.n_trainables
for idx in self.kernel_indices:
w = self.trainable_variables[idx]
grad = grads[idx]
assert grad.shape == w.shape
grad = grad + self.l2_coeff * w
grads[idx] = grad
return grads
# calling the acoustic model
def __call__(self, inputs, training):
assert isinstance(training, bool)
outputs = inputs
outputs = self.acoustic_model(outputs, training=training)
return outputs
@staticmethod
def ref_notes_larger_than_min_note_check_fn(ref_notes):
ref_notes.set_shape([None])
assert ref_notes.dtype == tf.float32
t1 = ref_notes == 0.
t2 = ref_notes >= TFDataset.note_range[0]
t1 = tf.logical_or(t1, t2)
tf.debugging.assert_equal(t1, True)
# the loss function
@tf.function(input_signature=[
tf.TensorSpec([None]),
tf.TensorSpec([None, 320])
], autograph=False)
def loss_tf_fn(self, ref_notes, logits):
note_range = TFDataset.note_range
assert np.isclose(note_range[0], 23.6) and len(note_range) == 320
ref_notes = tf.convert_to_tensor(ref_notes, dtype=tf.float32)
logits = tf.convert_to_tensor(logits, dtype=tf.float32)
ref_notes.set_shape([None])
logits.set_shape([None, 320])
AcousticModel.ref_notes_larger_than_min_note_check_fn(ref_notes)
max_note = note_range[-1] + .4
max_note = max_note.astype(np.float32)
ref_notes = tf.minimum(ref_notes, max_note)
note_range = tf.convert_to_tensor(note_range, dtype=tf.float32)
ref_notes = ref_notes[:, None] - note_range[None, :]
ref_notes.set_shape([None, 320])
ref_notes = - ref_notes ** 2 / (2. * .18 ** 2)
ref_notes = tf.exp(ref_notes)
ref_notes = tf.where(ref_notes < self.cutoff_prob, tf.zeros_like(ref_notes), ref_notes)
loss = tf.nn.sigmoid_cross_entropy_with_logits(labels=ref_notes, logits=logits)
loss.set_shape([None, 320])
loss = tf.reduce_mean(loss)
return loss
# restored trained modules
def restore_local_global_part_fn(self):
acoustic_model = self.acoustic_model
folder = '/media/ssd/music_trans/2205/27_local_global_vocal_melody/l2_2em4/local_global_parameters_by_name'
weights = acoustic_model.weights
logging.info('restoring parameters of local-global module ...')
for w in weights:
name = w.name
if name.startswith('local') or name.startswith('global'):
assert name.endswith(':0')
t = name[:-2]
assert '__' not in t
t = t.replace('/', '__')
t = os.path.join(folder, t + '.dat')
_name, data = load_np_array_from_file_fn(t)
assert _name == name
assert data.shape == w.shape
assert data.dtype == 'float32' == w.dtype
w.assign(data)
logging.info('{} restored'.format(name))
def get_trainable_variables_fn(self):
trainables = self.acoustic_model.trainable_variables
_trainables = []
for w in trainables:
name = w.name
if name.startswith('local') or name.startswith('global') or name.startswith('pitch_local'):
continue
assert w.name.startswith('temporal') or w.name.startswith('melody'), w.name
_trainables.append(w)
logging.info('\n\ntrainable variables -')
for idx, w in enumerate(_trainables):
logging.info('{}: {}, {}'.format(idx, w.name, w.shape))
return _trainables
def locate_kernels_for_l2_reg_fn(self):
indices = []
for idx, w in enumerate(self.trainable_variables):
name = w.name
if name.startswith('temporal') and 'kernel' in name:
indices.append(idx)
logging.info('regulated variables -')
for idx in indices:
w = self.trainable_variables[idx]
logging.info('{} {}'.format(w.name, w.shape))
return indices
# base class for creating tf dataset
class TFDataset:
# create multiple nsgt instances for computing the VQT spectrogram
nsgt_instances = []
for power in (17, 18, 19, 20, 21, 22):
nsgt_ins = nsgt_module.NSGT(2 ** power)
assert nsgt_ins.Ls == 2 ** power and not nsgt_ins.use_double
nsgt_instances.append(nsgt_ins)
nsgt_Lses = [ins.Ls for ins in nsgt_instances]
nsgt_hop_size = 64
nsgt_freq_bins = 568
medleydb_dir = os.environ['medleydb'] # top folder of MDB dataset, /media/hd/datasets/medleydb/V1
melody2_dir = os.environ['melody2_dir'] # /home/xian/anaconda2_backup/envs/env_for_tf/lib/python2.7/site-packages/medleydb/data/Annotations/Melody/Melody2
mix_suffix = '_MIX.wav'
melody2_suffix = '_MELODY2.csv'
min_melody_freq = librosa.midi_to_hz(23.6) # minimum melody frequency
note_min = 23.6 # minimum MIDI number for melody
note_range = np.arange(320) / 5.
note_range = note_range + note_min
note_range = note_range.astype(np.float32)
note_range.flags['WRITEABLE'] = False
def __init__(self, model):
self.model = model
# convert linear scale magnitude spectrogram to dB scale
@staticmethod
def spec_transform_fn(spec):
top_db = 120.
spec = librosa.amplitude_to_db(spec, ref=np.max, amin=1e-7, top_db=top_db)
spec = spec / top_db + 1.
spec = spec.astype(np.float32)
return spec
# generate the VQT spectrogram
@staticmethod
def gen_spec_fn(track_id):
nsgt_instances = TFDataset.nsgt_instances
nsgt_Lses = TFDataset.nsgt_Lses
hop_size = TFDataset.nsgt_hop_size
num_freq_bins = TFDataset.nsgt_freq_bins
medleydb_dir = TFDataset.medleydb_dir
mix_suffix = TFDataset.mix_suffix
mix_wav_file = os.path.join(medleydb_dir, track_id, track_id + mix_suffix)
num_samples = soundfile.info(mix_wav_file).frames
t = np.searchsorted(nsgt_Lses, num_samples)
assert 1 <= t <= len(nsgt_instances)
nsgt_fn = nsgt_instances[t - 1].nsgt_of_wav_file_fn
nsgt = nsgt_fn(mix_wav_file)
num_frames = (num_samples + hop_size - 1) // hop_size
assert nsgt.shape == (num_frames, num_freq_bins)
nsgt = nsgt[::4, 1:501]
nsgt = TFDataset.spec_transform_fn(nsgt) # to db scale
nsgt = np.require(nsgt, np.float32, requirements=['O', 'C'])
return nsgt
# hz to midi
@staticmethod
def hz_to_midi_fn(freqs):
notes = np.zeros_like(freqs)
positives = np.nonzero(freqs)
notes[positives] = librosa.hz_to_midi(freqs[positives])
return notes
# midi to hz
@staticmethod
def midi_to_hz_fn(notes):
assert np.all(notes >= 0)
freqs = np.zeros_like(notes)
positives = np.where(notes > 0)
freqs[positives] = librosa.midi_to_hz(notes[positives])
return freqs
# generate ground-truth labels
@staticmethod
def gen_label_fn(track_id):
melody2_dir = TFDataset.melody2_dir
melody2_suffix = TFDataset.melody2_suffix
sr = 44100
annot_path = os.path.join(melody2_dir, track_id + melody2_suffix)
times_labels = np.genfromtxt(annot_path, delimiter=',')
assert np.all(np.logical_not(np.isnan(times_labels)))
assert times_labels.ndim == 2 and times_labels.shape[1] == 2
num_frames = len(times_labels)
tmp = np.arange(num_frames) * (256. / 44100.)
assert np.all(tmp == times_labels[:, 0])
vocal_freqs = np.zeros([num_frames])
section_file = os.environ['section_dir']
section_file = os.path.join(section_file, track_id + '_SOURCEID.lab')
h = 256
hh = h // 2
with open(section_file, 'r') as fh:
lines = fh.readlines()
for line in lines:
if 'start_time' in line:
continue
parts = line.split(',')
instrument = parts[-1]
if 'singer' not in instrument:
continue
st = float(parts[0])
et = float(parts[1])
ss = np.int(np.ceil(st * sr))
es = np.int(np.floor(et * sr))
sf = (ss + hh) // h
ef = (es + hh) // h
vocal_freqs[sf:ef + 1] = times_labels[sf:ef + 1, 1]
TFDataset.validity_check_of_ref_freqs_fn(times_labels[:, 1])
notes = TFDataset.hz_to_midi_fn(vocal_freqs)
result = dict(notes=notes, original=dict(times=times_labels[:, 0], freqs=vocal_freqs))
return result
# generate numpy dataset
def gen_np_dataset_fn(self):
assert not hasattr(self, 'np_dataset')
model = self.model
logging.info('{} - MedleyDB - generate spectrograms and labels'.format(model.name))
config = model.config
track_ids = config.tvt_split_dict[model.name]
num_tracks = len(track_ids)
dataset = []
for track_idx, track_id in enumerate(track_ids):
logging.debug('{}/{}'.format(track_idx + 1, num_tracks))
spec = TFDataset.gen_spec_fn(track_id)
notes_original_dict = TFDataset.gen_label_fn(track_id)
notes = notes_original_dict['notes']
diff = len(notes) - len(spec)
assert 0 <= diff <= 1
if diff == 1:
spec = np.pad(spec, [[0, 1], [0, 0]])
spec = np.require(spec, np.float32, ['O', 'C'])
notes = notes.astype(np.float32)
spec.flags['WRITEABLE'] = False
notes.flags['WRITEABLE'] = False
dataset.append(dict(spectrogram=spec, notes=notes, original=notes_original_dict['original']))
return dataset
def note_out_of_range_chk_fn(self, np_dataset):
model = self.model
note_range = TFDataset.note_range
logging.info('{} - note range checking ... '.format(model.name))
note_min = min(note for rec_dict in np_dataset for note in rec_dict['notes'] if note > 0)
note_max = max(note for rec_dict in np_dataset for note in rec_dict['notes'] if note > 0)
lower_note = note_range[0]
upper_note = note_range[-1]
logging.info('note range - ({}, {})'.format(lower_note, upper_note))
if note_min < lower_note or note_min > upper_note:
logging.warning('note min - {} - out of range'.format(note_min))
if note_max < lower_note or note_max > upper_note:
logging.warning('note max - {} - out of range'.format(note_max))
# cut spectrogram into short snippets
@staticmethod
def gen_split_list_fn(num_frames, snippet_len):
split_frames = range(0, num_frames + 1, snippet_len)
split_frames = list(split_frames)
if split_frames[-1] != num_frames:
split_frames.append(num_frames)
start_end_frame_pairs = zip(split_frames[:-1], split_frames[1:])
start_end_frame_pairs = [list(it) for it in start_end_frame_pairs]
return start_end_frame_pairs
@staticmethod
def validity_check_of_ref_freqs_fn(freqs):
min_melody_freq = TFDataset.min_melody_freq
all_zeros = freqs == 0.
all_positives = freqs > min_melody_freq
all_valid = np.logical_or(all_zeros, all_positives)
assert np.all(all_valid)
# create a tf dataset for the training split in training mode
class TFDatasetForTrainingModeTrainingSplit(TFDataset):
def __init__(self, model):
super(TFDatasetForTrainingModeTrainingSplit, self).__init__(model)
is_inferencing = model.config.train_or_inference.inference is not None
assert not is_inferencing
assert model.is_training
assert 'train' in model.name
self.np_dataset = self.gen_np_dataset_fn()
self.note_out_of_range_chk_fn(self.np_dataset)
self.rec_start_end_idx_list = self.gen_rec_start_end_idx_fn(self.np_dataset)
self.tf_dataset = self.gen_tf_dataset_fn()
self.iterator = iter(self.tf_dataset)
self.set_num_batches_per_epoch_fn()
def gen_rec_start_end_idx_fn(self, np_dataset):
snippet_len = self.model.config.snippet_len
rec_start_and_end_list = []
for rec_idx, rec_dict in enumerate(np_dataset):
split_list = TFDataset.gen_split_list_fn(
num_frames=len(rec_dict['spectrogram']),
snippet_len=snippet_len
)
tmp = [[rec_idx] + se for se in split_list]
rec_start_and_end_list.extend(tmp)
return rec_start_and_end_list
def map_idx_to_data_fn(self, idx):
def py_fn(idx):
idx = idx.numpy().item()
rec_idx, start_frame, end_frame = self.rec_start_end_idx_list[idx]
rec_dict = self.np_dataset[rec_idx]
spec = rec_dict['spectrogram'][start_frame:end_frame]
notes = rec_dict['notes'][start_frame:end_frame]
return spec, notes
spec, notes = tf.py_function(py_fn, inp=[idx], Tout=['float32', 'float32'])
spec.set_shape([None, 500])
notes.set_shape([None])
return dict(spectrogram=spec, notes=notes)
def gen_tf_dataset_fn(self):
num_snippets = len(self.rec_start_end_idx_list)
dataset = tf.data.Dataset.range(num_snippets, output_type=tf.int32)
dataset = dataset.shuffle(num_snippets, reshuffle_each_iteration=True)
dataset = dataset.repeat()
dataset = dataset.map(self.map_idx_to_data_fn)
dataset = dataset.batch(1)
dataset = dataset.prefetch(10)
return dataset
def set_num_batches_per_epoch_fn(self):
model = self.model
if model.config.batches_per_epoch is None:
batches_per_epoch = len(self.rec_start_end_idx_list)
model.config.batches_per_epoch = batches_per_epoch
logging.info('batches per epoch set to {}'.format(batches_per_epoch))
# create tf dataset for inference mode
# It is used for validation split in training model, or all splits in inference mode
class TFDatasetForInferenceMode(TFDataset):
def __init__(self, model):
super(TFDatasetForInferenceMode, self).__init__(model)
is_inferencing = model.config.train_or_inference.inference is not None
if not is_inferencing:
assert not model.is_training
assert 'validation' in model.name
self.np_dataset = self.gen_np_dataset_fn()
track_ids = model.config.tvt_split_dict[model.name]
self.rec_names = tuple(track_ids)
num_frames = [len(rec_dict['spectrogram']) for rec_dict in self.np_dataset]
self.num_frames_vector = np.asarray(num_frames, dtype=np.int64)
self.note_out_of_range_chk_fn(self.np_dataset)
self.rec_start_end_idx_list = self.gen_split_list_fn(self.np_dataset)
self.tf_dataset = self.gen_tf_dataset_fn()
def gen_split_list_fn(self, np_dataset):
model = self.model
snippet_len = model.config.snippet_len
rec_start_end_idx_list = []
for rec_idx, rec_dict in enumerate(np_dataset):
split_list = TFDataset.gen_split_list_fn(
num_frames=len(rec_dict['spectrogram']),
snippet_len=snippet_len
)
rec_dict['split_list'] = split_list
t = [[rec_idx] + se for se in split_list]
rec_start_end_idx_list.extend(t)
return rec_start_end_idx_list
def map_idx_to_data_fn(self, idx):
def py_fn(idx):
idx = idx.numpy().item()
rec_idx, start_frame, end_frame = self.rec_start_end_idx_list[idx]
rec_dict = self.np_dataset[rec_idx]
snippet_len = self.model.config.snippet_len
assert start_frame % snippet_len == 0
snippet_idx = start_frame // snippet_len
spec = rec_dict['spectrogram'][start_frame:end_frame]
notes = rec_dict['notes'][start_frame:end_frame]
return rec_idx, snippet_idx, spec, notes
rec_idx, snippet_idx, spec, notes = tf.py_function(
py_fn,
inp=[idx],
Tout=[tf.int32, tf.int32, tf.float32, tf.float32]
)
rec_idx.set_shape([])
snippet_idx.set_shape([])
spec.set_shape([None, 500])
notes.set_shape([None])
return dict(
rec_idx=rec_idx,
snippet_idx=snippet_idx,
spectrogram=spec,
notes=notes
)
def gen_tf_dataset_fn(self):
num_snippets = len(self.rec_start_end_idx_list)
dataset = tf.data.Dataset.range(num_snippets, output_type=tf.int32)
dataset = dataset.map(self.map_idx_to_data_fn)
dataset = dataset.batch(1)
dataset = dataset.prefetch(10)
return dataset
# create tf dataset for ADC04 dataset
class TFDatasetForAdc04(TFDataset):
def __init__(self, model):
super(TFDatasetForAdc04, self).__init__(model)
is_inferencing = model.config.train_or_inference.inference is not None
assert is_inferencing
self.np_dataset = self.gen_np_dataset_fn()
track_ids = model.config.tvt_split_dict[model.name]
self.rec_names = tuple(track_ids)
num_frames = [len(rec_dict['spectrogram']) for rec_dict in self.np_dataset]
self.num_frames_vector = np.asarray(num_frames, dtype=np.int64)
self.note_out_of_range_chk_fn(self.np_dataset)
self.rec_start_end_idx_list = self.gen_split_list_fn(self.np_dataset)
self.tf_dataset = self.gen_tf_dataset_fn()
@staticmethod
def gen_spec_fn(track_id):
nsgt_instances = TFDataset.nsgt_instances
nsgt_Lses = TFDataset.nsgt_Lses
hop_size = TFDataset.nsgt_hop_size
num_freq_bins = TFDataset.nsgt_freq_bins
mix_wav_file = os.path.join(os.environ['adc04'], track_id + '.wav')
info = soundfile.info(mix_wav_file)
assert info.samplerate == 44100
assert info.subtype == 'PCM_16'
num_samples = info.frames
t = np.searchsorted(nsgt_Lses, num_samples)
assert 1 <= t <= len(nsgt_instances)
nsgt_fn = nsgt_instances[t - 1].nsgt_of_wav_file_fn
nsgt = nsgt_fn(mix_wav_file)
num_frames = (num_samples + hop_size - 1) // hop_size
assert nsgt.shape == (num_frames, num_freq_bins)
nsgt = nsgt[::4, 1:501]
nsgt = TFDataset.spec_transform_fn(nsgt)
nsgt = np.require(nsgt, np.float32, requirements=['O', 'C'])
return nsgt
@staticmethod
def gen_label_fn(track_id):
# the reference melody uses a hop size of 256 samples
melody2_suffix = 'REF.txt'
annot_path = os.path.join(os.environ['adc04'], track_id + melody2_suffix)
times_labels = np.genfromtxt(annot_path, delimiter=None)
assert np.all(np.logical_not(np.isnan(times_labels)))
assert times_labels.ndim == 2 and times_labels.shape[1] == 2
num_frames = len(times_labels)
t = times_labels[-1, 0]
t = int(round(t / (256. / 44100.)))
assert t + 1 == num_frames
assert times_labels[0, 0] == 0.
freqs = times_labels[:, 1]
TFDataset.validity_check_of_ref_freqs_fn(freqs)
notes = TFDataset.hz_to_midi_fn(freqs)
return dict(notes=notes, original=dict(times=times_labels[:, 0], freqs=times_labels[:, 1]))
def gen_np_dataset_fn(self):
assert not hasattr(self, 'np_dataset')
model = self.model
logging.info('{} - adc04 - generate spectrograms and labels'.format(model.name))
config = model.config
track_ids = config.tvt_split_dict[model.name]
num_tracks = len(track_ids)
dataset = []
for track_idx, track_id in enumerate(track_ids):
logging.debug('{}/{}'.format(track_idx + 1, num_tracks))
spec = TFDatasetForAdc04.gen_spec_fn(track_id)
notes_original_dict = TFDatasetForAdc04.gen_label_fn(track_id)
notes = notes_original_dict['notes']
diff = len(notes) - len(spec)
assert 0 <= diff <= 1
if diff == 1:
spec = np.pad(spec, [[0, 1], [0, 0]])
spec = np.require(spec, np.float32, ['O', 'C'])
notes = notes.astype(np.float32)
spec.flags['WRITEABLE'] = False
notes.flags['WRITEABLE'] = False
dataset.append(dict(spectrogram=spec, notes=notes, original=notes_original_dict['original']))
return dataset
def gen_split_list_fn(self, np_dataset):
model = self.model
snippet_len = model.config.snippet_len
rec_start_end_idx_list = []
for rec_idx, rec_dict in enumerate(np_dataset):
split_list = TFDataset.gen_split_list_fn(
num_frames=len(rec_dict['spectrogram']),
snippet_len=snippet_len
)
rec_dict['split_list'] = split_list
t = [[rec_idx] + se for se in split_list]
rec_start_end_idx_list.extend(t)
return rec_start_end_idx_list
def map_idx_to_data_fn(self, idx):
def py_fn(idx):
idx = idx.numpy().item()
rec_idx, start_frame, end_frame = self.rec_start_end_idx_list[idx]
rec_dict = self.np_dataset[rec_idx]
snippet_len = self.model.config.snippet_len
assert start_frame % snippet_len == 0
snippet_idx = start_frame // snippet_len
spec = rec_dict['spectrogram'][start_frame:end_frame]
notes = rec_dict['notes'][start_frame:end_frame]
return rec_idx, snippet_idx, spec, notes
rec_idx, snippet_idx, spec, notes = tf.py_function(
py_fn,
inp=[idx],
Tout=[tf.int32, tf.int32, tf.float32, tf.float32]
)
rec_idx.set_shape([])
snippet_idx.set_shape([])
spec.set_shape([None, 500])
notes.set_shape([None])
return dict(
rec_idx=rec_idx,
snippet_idx=snippet_idx,
spectrogram=spec,
notes=notes
)
def gen_tf_dataset_fn(self):
num_snippets = len(self.rec_start_end_idx_list)
dataset = tf.data.Dataset.range(num_snippets, output_type=tf.int32)
dataset = dataset.map(self.map_idx_to_data_fn)
dataset = dataset.batch(1)
dataset = dataset.prefetch(10)
return dataset
# create tf dataset for MIREX05 dataset
class TFDatasetForMirex05(TFDataset):
def __init__(self, model):
super(TFDatasetForMirex05, self).__init__(model)
is_inferencing = model.config.train_or_inference.inference is not None
assert is_inferencing
self.np_dataset = self.gen_np_dataset_fn()
track_ids = model.config.tvt_split_dict[model.name]
self.rec_names = tuple(track_ids)
num_frames = [len(rec_dict['spectrogram']) for rec_dict in self.np_dataset]
self.num_frames_vector = np.asarray(num_frames, dtype=np.int64)
self.note_out_of_range_chk_fn(self.np_dataset)
self.rec_start_end_idx_list = self.gen_split_list_fn(self.np_dataset)
self.tf_dataset = self.gen_tf_dataset_fn()
@staticmethod
def gen_spec_fn(track_id):
nsgt_instances = TFDataset.nsgt_instances
nsgt_Lses = TFDataset.nsgt_Lses
hop_size = TFDataset.nsgt_hop_size
num_freq_bins = TFDataset.nsgt_freq_bins
mix_wav_file = os.path.join(os.environ['mirex05'], track_id + '.wav')
info = soundfile.info(mix_wav_file)
assert info.samplerate == 44100
assert info.subtype == 'PCM_16'
num_samples = info.frames
t = np.searchsorted(nsgt_Lses, num_samples)
assert 1 <= t <= len(nsgt_instances)
nsgt_fn = nsgt_instances[t - 1].nsgt_of_wav_file_fn
nsgt = nsgt_fn(mix_wav_file)
num_frames = (num_samples + hop_size - 1) // hop_size
assert nsgt.shape == (num_frames, num_freq_bins)
nsgt = nsgt[::4, 1:501]
nsgt = TFDataset.spec_transform_fn(nsgt)
nsgt = np.require(nsgt, np.float32, requirements=['O', 'C'])
return nsgt
@staticmethod
def gen_label_fn(track_id):
# reference melody uses a hop size of 441 samples, or 10 ms
if track_id == 'train13MIDI':
m2_file = os.path.join(os.environ['mirex05'], 'train13REF.txt')
else:
m2_file = os.path.join(os.environ['mirex05'], track_id + 'REF.txt')
times_labels = np.genfromtxt(m2_file, delimiter=None)
assert np.all(np.logical_not(np.isnan(times_labels)))
assert times_labels.ndim == 2 and times_labels.shape[1] == 2
num_frames = len(times_labels)
t = times_labels[-1, 0]
t = int(round(t / .01))
assert t + 1 == num_frames
assert times_labels[0, 0] == 0.
freqs_441 = times_labels[:, 1]
TFDataset.validity_check_of_ref_freqs_fn(freqs_441)