-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathMahlerNet.py
2242 lines (2072 loc) · 136 KB
/
MahlerNet.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
import os
os.environ['FOR_DISABLE_CONSOLE_CTRL_HANDLER'] = 'T' # https://github.com/ContinuumIO/anaconda-issues/issues/905 needed to install SIGINT handler on Windows 64-bit with Anaconda, otherwise Scipy handler overrides somehow
import numpy as np
import functools
import os.path, pprint, signal
import tensorflow as tf
import numpy as np
from DataProcessor import DataProcessor
import math, time, sys, copy
from utilities import print_divider
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
tf.logging.set_verbosity(tf.logging.FATAL) # can use DEBUG, INFO, WARN, ERROR, FATAL
np.set_printoptions(threshold = sys.maxsize, precision = 30)
class MahlerNet:
def __init__(self, params):
self.params = {
# general
"root_dir": "",
"save_dir": "",
"model_name": None,
"validation_set_ratio": 0.0,
"save_graph": False,
"save_stats": False,
"save_model": None, # use a number and then a letter e or s indicating if the number refers to epochs or global steps, for example "25e", use literal None not to save at all
"end_of_epoch_fns": 1,
"use_randomness": True,
"use_gpu": True,
"gpu": None,
"verbose": 1, # 0 means no more printouts than training progress, 1 means basic output, 2 means verbose output
"batch_sz" : 4,
"epochs" : 1000,
"num_pitches" : 96,
"num_x_features": None,
"num_y_features": None,
"num_ctx_features": None,
"num_xr_features": None,
"num_features": None,
"num_instruments" : None,
"num_durations" : None,
"num_beats": None,
"num_special_tokens": None,
"learning_rate" : 0.001,
"optimizer": "rmsprop",
"batch_norm": False, # puts batch normalization on all non-recurrent layers
"batch_norm_before_act": True,
"act": "tanh",
"generation": {
"default_durations": None,
"default_bar": None,
"default_beats": None,
"sequence_base": None,
"ctx_length": 1,
"inp_length": 1,
"default_duration_set": None,
"default_duration_sets": None,
"default_duplet_duration": None,
"default_triplet_duration": None
},
"property_order": {
"ctx": ["offset", "beats", "duration", "pitch", "instrument", "special_tokens"],
"inp": ["offset", "beats", "duration", "pitch", "instrument"],
"dec": {
"inp": ["offset", "beats", "duration", "pitch", "instrument", "active_instruments", "active_pitches"],
"out": ["offset", "duration", "pitch", "instrument"]
}
},
"modelling_properties": {
"offset": {
"include": True,
"num_features": None,
"key": "o",
"indices": None,
"dropout": 0.0,
"multiclass": False,
"dist_metric": True,
"generation_temperature": 1.0
},
"duration": {
"include": True,
"num_features": None,
"key": "d",
"indices": None,
"dropout": 0.0,
"multiclass": False,
"dist_metric": True,
"next_step_reduction": True,
"generation_temperature": 1.0
},
"pitch": {
"include": True,
"num_features": None,
"key": "p",
"indices": None,
"dropout": 0.0,
"multiclass": False,
"same_step_reduction": True,
"dist_metric": True,
"generation_temperature": 1.0
},
"instrument": {
"include": True,
"num_features": None,
"key": "i",
"indices": None,
"dropout": 0.0,
"multiclass": False,
"dist_metric": False,
"generation_temperature": 1.0
},
"special_tokens": {
"include": True,
"num_features": None,
"key": "s",
"indices": None
},
"beats": {
"include": True,
"num_features": None,
"key": "b",
"indices": None
},
"active_pitches": {
"include": True,
"num_features": None,
"key": "ap",
"indices": None
},
"active_instruments": {
"include": True,
"num_features": None,
"key": "ai",
"indices": None
}
},
"model" : {
"ctx": True,
"inp": True,
"vae": True,
"dec": True
},
"cell_versions": {
"lstm": {
"lstm": tf.nn.rnn_cell.LSTMCell,
"block": tf.contrib.rnn.LSTMBlockCell,
"bn": tf.contrib.rnn.LayerNormBasicLSTMCell
},
"gru": {
"gru": tf.nn.rnn_cell.GRUCell,
"blockv2": tf.contrib.rnn.GRUBlockCellV2,
"keras_gru": tf.keras.layers.GRUCell
}
},
# encoder input summary
"inp_enc" : {
"type": "lstm",
"version": "lstm",
"dropout": 0.5,
"init": "var",
"num_layers" : 1,
"sz_state" : 128,
"bidirectional_type": "default"
},
#encoder context summary
"ctx_enc" : {
"type": "lstm",
"version": "lstm",
"dropout": 0.5,
"init": "var",
"num_layers" : 1,
"sz_state" : 128,
"bidirectional_type": "stack" # "stack" or "default", the former uses a bidirectional rnn where directions are mixed for each layer whereas the latter uses separate directions for layers and concatenates after
},
# vae
"vae" : {
"z_dim" : 64,
"dropout": 0.0
},
# decoder
"dec" : {
"num_layers" : 1,
"sz_state" : 256,
"model": "lstm", # "balstm" or "lstm"
"framework": "rnn", # Tensorflow framework to use: "seq2seq" or "rnn"
"type": "lstm", # Cell type to use: "gru" or "lstm"
"version": "lstm",
"init": "z", # How to initialize the states of the decoder: "var" (trainable variables) or "zeros" or "z" (latent vector from vae)
"layer_strategy": "same", # How to initialize different layers (if more than one): "same" or "diff"
"scheduled_sampling": False,
"scheduled_sampling_scheme": "sigmoid", # "sigmoid" or "linear"
"scheduled_sampling_min_truth": 0.0,
"scheduled_sampling_mode": "sample", # "sample" or "max" depending on if we want to sample from distribution or take the most probable class
"scheduled_sampling_rate": 1000, # ln(rate) * rate is the number of steps when there will be a 50% chance that we sample from output instead of ground truth, for rate 1000 this is about 6907
"dropout": 0.5,
"balstm": {
"sz_conv": 25, # the size of the BALSTM convolution, this is how many surrounding pitches are taken into account
"init": "same", # "diff" or "same"
"add_pitch": True,
"num_filters": 64,
"conv_dropout": 0.0
},
"feed": {
"z": {
"use": True,
"strategy": "proj", # "raw" or "proj" can't combine "proj" with "layer_strategy" "diff" in which case the latters defaults to "same"
"sz": 128
},
"ctx": {
"use": True,
}
}
},
"output_layers": {
"offset": [], # last output layer without activation to the correct number of output units will be taken care of automatically
"pitch": [],
"duration": [],
"instrument": []
},
"scopes": {
"offset": "",
"pitch": "",
"duration": "",
"instrument": ""
},
"loss": {
"vae": True,
"recon": True,
"regularization": 0.05,
"free_bits": 0,
"beta_annealing": False,
"beta_max": 0.0,
"beta_rate": 0.99999,
"p_weight": 1.0,
"o_weight": 1.0,
"d_weight": 1.0,
"i_weight": 1.0,
"framework": "seq2seq" # "seq2seq" to use sequence_loss, "plain" to use regular loss
},
"training_output": {
"dists": False # whether to continuously output the distribution of guesses, targets and the diff between
}
}
p = self.params
def update_params(param_object, incoming):
for key in incoming:
if key in param_object:
if isinstance(incoming[key], dict) and isinstance(param_object[key], dict):
update_params(param_object[key], incoming[key])
elif not isinstance(incoming[key], dict) and not isinstance(param_object[key], dict):
param_object[key] = incoming[key]
update_params(p, params)
# adjust and process some input parameters
if not p["use_randomness"]:
tf.reset_default_graph()
tf.set_random_seed(12345)
np.random.seed(12345)
if p["use_gpu"] and tf.test.is_gpu_available():
p["gpu"] = True
p["cell_versions"]["lstm"]["cudnn"] = tf.contrib.cudnn_rnn.CudnnCompatibleLSTMCell
p["cell_versions"]["gru"]["cudnn"] = tf.contrib.cudnn_rnn.CudnnCompatibleGRUCell
config = tf.ConfigProto()
else:
p["gpu"] = False
config = tf.ConfigProto(device_count = {'GPU': 0})
os.environ['CUDA_VISIBLE_DEVICES'] = '-1' # in case there is a gpu but we don't want to use it
num_x_features = 0 # total numbers of features in the input to the decoder
num_xr_features = 0 # the number of original features in the BALSTM input (if used) except for the pitch input
num_y_features = 0 # total number of features in the output
num_ctx_features = 0 # total number of features in the context
num_features = 0
p["modelling_properties"]["special_tokens"]["num_features"] = p["num_special_tokens"]
p["modelling_properties"]["offset"]["num_features"] = p["num_durations"]
p["modelling_properties"]["beats"]["num_features"] = p["num_beats"]
p["modelling_properties"]["duration"]["num_features"] = p["num_durations"]
p["modelling_properties"]["pitch"]["num_features"] = p["num_pitches"]
p["modelling_properties"]["active_pitches"]["num_features"] = p["num_pitches"]
p["modelling_properties"]["instrument"]["num_features"] = p["num_instruments"]
p["modelling_properties"]["active_instruments"]["num_features"] = p["num_instruments"]
for cat in p["modelling_properties"]:
cat_params = p["modelling_properties"][cat]
if cat_params["include"]:
if cat in p["property_order"]["ctx"]:
num_ctx_features += cat_params["num_features"]
if cat in p["property_order"]["inp"]:
num_y_features += cat_params["num_features"]
if cat in p["property_order"]["dec"]["inp"]:
num_x_features += cat_params["num_features"]
if cat in p["property_order"]["dec"]["out"]:
p["output_layers"][cat] += [(p["modelling_properties"][cat]["num_features"], None)]
num_features += cat_params["num_features"]
num_xr_features = num_x_features
if p["modelling_properties"]["pitch"]["include"]:
num_xr_features -= p["modelling_properties"]["pitch"]["num_features"]
if p["modelling_properties"]["active_pitches"]["include"]:
num_xr_features -= p["modelling_properties"]["pitch"]["num_features"]
print("[MAHLERNET]: features in total (only based on what properties are being modelled): ", num_features)
print("[MAHLERNET]: features in context (only based on what properties are being modelled): ", num_ctx_features)
print("[MAHLERNET]: features in input to decoder (only based on what properties are being modelled): ", num_x_features)
print("[MAHLERNET]: features in non-pitch input to balstm (only based on what properties are being modelled): ", num_xr_features)
print("[MAHLERNET]: features in output from decoder (only based on what properties are being modelled): ", num_y_features)
p["num_x_features"] = num_x_features
p["num_y_features"] = num_y_features
p["num_ctx_features"] = num_ctx_features
p["num_xr_features"] = num_xr_features
p["num_features"] = num_features
# correct input parameters if illegal combinations have been chosen
if p["act"] not in ["relu", "tanh", "sigmoid", "leakyrelu"]:
assert(False), '[MAHLERNET]: parameter error: unknown default activation function, please use one of "relu", "tanh", "sigmoid" or "leakyrelu"'
if not p["model"]["vae"] and p["model"]["inp"]:
assert(False), "[MAHLERNET]: parameter error: can't use input encode without using the vae"
if p["model"]["vae"] and (not p["model"]["inp"] and not p["model"]["ctx"]):
assert(False), "[MAHLERNET]: parameter error: can't use vae without either of input or context"
if not p["modelling_properties"]["pitch"]["include"] and p["modelling_properties"]["active_pitches"]["include"]:
assert(False), "[MAHLERNET]: parameter error: can't use active pitches as additional pitch input when not modelling pitches"
if not p["modelling_properties"]["offset"]["include"] and p["modelling_properties"]["beats"]["include"]:
assert(False), "[MAHLERNET]: parameter error: can't model beats without modelling offset"
if not p["modelling_properties"]["offset"]["include"] and p["modelling_properties"]["pitch"]["same_step_reduction"]:
assert(False), "[MAHLERNET]: parameter error: can't preform same step reduction while modelling pitch without offset"
if not p["modelling_properties"]["instrument"]["include"] and p["modelling_properties"]["active_instruments"]["include"]:
assert(False), "[MAHLERNET]: parameter error: can't use active instruments as additional instrument input when not modelling instruments"
if not p["modelling_properties"]["pitch"]["include"] and p["dec"]["model"] == "balstm":
assert(False), "[MAHLERNET]: parameter error: can't use BALSTM without modelling pitch"
if p["dec"]["num_layers"] == 1 and p["dec"]["layer_strategy"] == "diff":
assert(False), "[MAHLERNET]: parameter error: only one layer in decoder, switch to layer_strategy \"same\""
if p["dec"]["init"] == "z" and not p["model"]["vae"]:
assert(False), "[MAHLERNET]: parameter error: can't use latent vector as initialization for decoder when not vae is in use"
if p["dec"]["feed"]["z"]["use"] and not p["model"]["vae"]:
assert(False), "[MAHLERNET]: parameter error: can't use latent vector as feed while decoding when not vae is in use"
if p["dec"]["scheduled_sampling"] and p["dec"]["model"] == "balstm":
assert(False), "[MAHLERNET]: parameter error: can't use scheduled sampling togther with BALSTM since there is no way to sample the next timestep from single pitches"
if p["dec"]["scheduled_sampling"] and p["modelling_properties"]["pitch"]["include"] and p["modelling_properties"]["active_pitches"]["include"]:
assert(False), "[MAHLERNET]: parameter error: can't use scheduled sampling while including active pitches as an input feature"
if p["dec"]["scheduled_sampling"] and p["modelling_properties"]["instrument"]["include"] and p["modelling_properties"]["active_instruments"]["include"]:
assert(False), "[MAHLERNET]: parameter error: can't use scheduled sampling while including active instruments as an input feature"
if p["dec"]["scheduled_sampling"] and p["modelling_properties"]["beats"]["include"]:
assert(False), "[MAHLERNET]: parameter error: scheduled sampling can not be used with beats since it affects the upcoming timesteps"
if p["dec"]["scheduled_sampling"] and p["dec"]["framework"] == "rnn":
assert(False), "[MAHLERNET]: parameter error: scheduled sampling can only be implemented in seq2seq framework"
if p["act"] == "relu":
p["act"] = tf.nn.relu
elif p["act"] == "tanh":
p["act"] = tf.nn.tanh
elif p["act"] == "sigmoid":
p["act"] = tf.nn.sigmoid
else:
p["act"] = tf.nn.leaky_relu
for part, part_name in [("inp", "inp_enc"), ("ctx", "ctx_enc"), ("dec", "dec")]:
if not p["gpu"] and p["model"][part] and p[part_name]["version"] == "cudnn":
assert(False), "[MAHLERNET]: parameter error: cudnn cells can only be used with GPU"
for cat in p["property_order"]["dec"]["out"]:
if p["modelling_properties"][cat]["include"]:
if p["modelling_properties"][cat]["dist_metric"] and p["modelling_properties"][cat]["multiclass"]:
assert(False), "[MAHLERNET]: parameter error: can't use distance metric for multiclass properties"
if p["modelling_properties"][cat]["multiclass"] and p["loss"]["framework"] == "seq2seq":
assert(False), "[MAHLERNET]: parameter error: Altered parameter: can't use seq2seq framework for loss with multiclass properties"
# assert(param in kwargs and isinstance(kwargs[param], int) and kwargs[param] > 0), "Input param error: " + param " = " str(kwargs[param])
self.weights = {
"vae" : {},
"output" : {},
"conv" : {}
}
self.ops = lambda: None # object to store ops in
config.gpu_options.allow_growth = True
config.gpu_options.per_process_gpu_memory_fraction = 1.0
self.session = tf.Session(config=config)
print("[MAHLERNET]: Input parameters ok, printing used parameters:")
pp = pprint.PrettyPrinter()
pp.pprint(p)
def check_params(param_object):
for key in param_object:
if isinstance(param_object[key], dict):
check_params(param_object[key])
else:
if param_object[key] is None:
print("BULL!", param_object, key)
exit()
check_params(p)
def save_graph(self, output_folder = "graphs"):
# start Tensorboard session with "tensorboard --logdir=graphs --host=localhost" then go to localhost in browser
path = os.path.join(self.params["save_dir"], output_folder)
if not os.path.exists(path):
os.makedirs(path)
writer = tf.summary.FileWriter(path, self.session.graph)
def save_model(self, save_file):
saver = tf.train.Saver()
path = os.path.join(self.params["save_dir"], "trained_models")
os.makedirs(path, exist_ok = True)
path = os.path.join(path, save_file)
save_path = saver.save(self.session, path)
print("[MAHLERNET]: successfully saved model to \"" + path + "\"")
def load_model(self, file_name):
saver = tf.train.Saver()
path = os.path.join(self.params["save_dir"], "trained_models", file_name)
saver.restore(self.session, path)
print("[MAHLERNET]: successfully loaded model from \"" + path + "\"")
def print_op(self, op, text = "PRINT"):
return tf.Print(op, [op], summarize = 10000000, message = text)
def variable_count(self):
if not hasattr(self, "num_variables"):
shapes = [var.get_shape() for var in tf.trainable_variables()]
prods = [np.prod(shape) for shape in shapes]
self.num_variables = np.sum(prods)
return self.num_variables
def build(self):
def _inputs(o, p):
with tf.variable_scope("inputs"):
o.inp_enc_dropout = tf.placeholder(tf.float32, (), name = "inp_enc_dropout")
o.ctx_enc_dropout = tf.placeholder(tf.float32, (), name = "ctx_enc_dropout")
o.vae_dropout = tf.placeholder(tf.float32, (), name = "vae_dropout")
o.dec_dropout = tf.placeholder(tf.float32, (), name = "dec_dropout")
o.dec_balstm_conv_dropout = tf.placeholder(tf.float32, (), name = "dec_balstm_conv_dropout")
o.pitch_dropout = tf.placeholder(tf.float32, (), name = "pitch_dropout")
o.offset_dropout = tf.placeholder(tf.float32, (), name = "offset_dropout")
o.duration_dropout = tf.placeholder(tf.float32, (), name = "duration_dropout")
o.instrument_dropout = tf.placeholder(tf.float32, (), name = "instrument_dropout")
o.batch_sz = tf.placeholder(tf.int32, (), name = "batch_sz")
o.global_step = tf.get_variable("global_step", (), dtype = tf.float32, trainable = False, initializer=tf.constant_initializer(0.0))
# placeholders for inputs needed during generation
o.instrument_temp = tf.constant(1.0, dtype = tf.float32, name = "instrument_temp")
o.pitch_temp = tf.constant(1.0, dtype = tf.float32, name = "pitch_temp")
o.offset_temp = tf.constant(1.0, dtype = tf.float32, name = "offset_temp")
o.duration_temp = tf.constant(1.0, dtype = tf.float32, name = "duration_temp")
o.sample_from_predictions = tf.constant(False, dtype = tf.bool, name = "sample_from_predictions")
o.training = tf.placeholder(tf.bool, (), name = "training")
o.durations = tf.placeholder(tf.float32, (1, 1, p["num_durations"]), name = "durations")
o.last_time = tf.placeholder(tf.float32, (), name = "last_time")
o.bar = tf.placeholder(tf.float32, (), name = "bar")
o.beats = tf.placeholder(tf.float32, (1, 1, p["num_beats"]), name = "beats")
o.inp_lengths = tf.placeholder(tf.int32, [None], name = "inp_lengths")
# calculate actual lengths for input
o.inp_lengths_mask = tf.expand_dims(tf.sequence_mask(o.inp_lengths, dtype = tf.float32), axis = 2)
o.inp_lengths_sum = tf.reduce_sum(o.inp_lengths, name = "inp_lengths_sum")
o.inp_lengths_max = tf.reduce_max(o.inp_lengths, name = "inp_lengths_max")
o.y_p_zero = tf.constant(0)
o.y_i_zero = tf.constant(0)
# placeholders for training data
y = []
if p["dec"]["model"] == "balstm": # have to split pitch properties and the rest into different parts
x_rest = []
o.x_p = None
o.x_ap = None
else: # all in the same part but to preserve original order, we put the active_pitches and instruments last
x = []
x_a = []
if p["model"]["ctx"]:
o.ctx_s = tf.placeholder(tf.float32, (None, None, p["num_special_tokens"]), name = "ctx_s")
ctx = [o.ctx_s]
if p["modelling_properties"]["offset"]["include"]:
print("[MAHLERNET]: adding \"offset\" as a parameter to model")
o.x_o = tf.placeholder(tf.float32, (None, None, p["num_durations"]), name = "x_o")
o.y_o_ = tf.placeholder(tf.float32, (None, None, p["num_durations"]), name = "y_o_")
if p["training_output"]["dists"]:
o.y_o_guess_tot_dist_var = tf.get_variable("y_o_guesses_tot_var", [p["num_durations"]], dtype = tf.int64, trainable = False, initializer=tf.constant_initializer(0))
if p["dec"]["model"] == "balstm":
x_rest += [o.x_o]
else:
x += [o.x_o]
if p["model"]["ctx"]:
o.ctx_o = tf.placeholder(tf.float32, (None, None, p["num_durations"]), name = "ctx_o")
ctx += [o.ctx_o]
y += [o.y_o_]
if p["modelling_properties"]["beats"]["include"]:
print("[MAHLERNET]: adding \"beats\" as a parameter to model")
o.x_b = tf.placeholder(tf.float32, (None, None, p["num_beats"]), name = "x_b")
o.y_b_ = tf.placeholder(tf.float32, (None, None, p["num_beats"]), name = "y_b_")
if p["dec"]["model"] == "balstm":
x_rest += [o.x_b]
else:
x += [o.x_b]
if p["model"]["ctx"]:
o.ctx_b = tf.placeholder(tf.float32, (None, None, p["num_beats"]), name = "ctx_b")
ctx += [o.ctx_b]
y += [o.y_b_]
if p["modelling_properties"]["duration"]["include"]:
print("[MAHLERNET]: adding \"duration\" as a parameter to model")
o.x_d = tf.placeholder(tf.float32, (None, None, p["num_durations"]),name = "x_d")
o.y_d_ = tf.placeholder(tf.float32, (None, None, p["num_durations"]),name = "y_d_")
if p["training_output"]["dists"]:
o.y_d_guess_tot_dist_var = tf.get_variable("y_d_guesses_tot_var", [p["num_durations"]], dtype = tf.int64, trainable = False, initializer=tf.constant_initializer(0))
if p["dec"]["model"] == "balstm":
x_rest += [o.x_d]
else:
x += [o.x_d]
if p["model"]["ctx"]:
o.ctx_d = tf.placeholder(tf.float32, (None, None, p["num_durations"]), name = "ctx_d")
ctx += [o.ctx_d]
y += [o.y_d_]
if p["modelling_properties"]["pitch"]["include"]:
print("[MAHLERNET]: adding \"pitch\" as a parameter to model")
o.x_p = tf.placeholder(tf.float32, (None, None, p["num_pitches"]), name = "x_p")
o.y_p_ = tf.placeholder(tf.float32, (None, None, p["num_pitches"]), name = "y_p_")
o.pd_mask = tf.reduce_max(o.y_p_, axis = 2)
o.y_p_zero = tf.reduce_sum(tf.multiply(tf.subtract(tf.constant(1.0, dtype = tf.float32), o.pd_mask), tf.squeeze(o.inp_lengths_mask, axis = 2)))
if p["training_output"]["dists"]:
o.y_p_guess_tot_dist_var = tf.get_variable("y_p_guesses_tot_var", [p["num_pitches"]], dtype = tf.int64, trainable = False, initializer=tf.constant_initializer(0))
if p["dec"]["model"] != "balstm":
x += [o.x_p]
if p["modelling_properties"]["active_pitches"]["include"]:
print("[MAHLERNET]: adding \"active_pitches\" as a helping input during decoding to the model")
o.x_ap = tf.placeholder(tf.float32, (None, None, p["num_pitches"]), name = "x_ap")
if p["dec"]["model"] != "balstm":
x_a += [o.x_ap]
if p["model"]["ctx"]:
o.ctx_p = tf.placeholder(tf.float32, (None, None, p["num_pitches"]), name = "ctx_p")
ctx += [o.ctx_p]
y += [o.y_p_]
if p["modelling_properties"]["instrument"]["include"]:
print("[MAHLERNET]: adding \"instrument\" as a parameter to model")
o.x_i = tf.placeholder(tf.float32, (None, None, p["num_instruments"]),name = "x_i")
o.y_i_ = tf.placeholder(tf.float32, (None, None, p["num_instruments"]),name = "y_i_")
if not hasattr(o, "pd_mask"):
o.pd_mask = tf.reduce_max(o.y_i_, axis = 2)
o.y_i_zero = tf.reduce_sum(tf.multiply(tf.subtract(tf.constant(1.0, dtype = tf.float32), o.pd_mask), tf.squeeze(o.inp_lengths_mask, axis = 2)))
#o.y_i_zero = tf.reduce_sum(tf.multiply(tf.squeeze(tf.cast(tf.logical_not(tf.cast(tf.reduce_max(o.y_i_, axis = 2), tf.bool)), tf.float32)), tf.squeeze(o.inp_lengths_mask))) # was before
if p["training_output"]["dists"]:
o.y_i_guess_tot_dist_var = tf.get_variable("y_i_guesses_tot_var", [p["num_instruments"]], dtype = tf.int64, trainable = False, initializer=tf.constant_initializer(0))
if p["dec"]["model"] == "balstm":
x_rest += [o.x_i]
else:
x += [o.x_i]
if p["modelling_properties"]["active_instruments"]["include"]:
print("[MAHLERNET]: adding \"active_instrument\" as a helping input during decoding to the model")
o.x_ai = tf.placeholder(tf.float32, (None, None, p["num_instruments"]),name = "x_ai")
if p["dec"]["model"] == "balstm":
x_rest += [o.x_ai]
else:
x_a += [o.x_ai]
if p["model"]["ctx"]:
o.ctx_i = tf.placeholder(tf.float32, (None, None, p["num_instruments"]), name = "ctx_i")
ctx += [o.ctx_i]
y += [o.y_i_]
if p["dec"]["model"] == "balstm":
if len(x_rest) > 0:
o.x_rest = tf.concat(x_rest, axis = 2) if len(x_rest) > 1 else x_rest[0]
else:
o.x_rest = None
else:
x = x + x_a
if len(x) > 0:
o.x = tf.concat(x, axis = 2) if len(x) > 1 else x[0]
else:
o.x = None # should never happen since it implies that we are not modelling anything at all and this should be checked earlier
o.inp = tf.concat(y, axis = -1) if len(y) > 1 else y[0]
if p["model"]["ctx"]:
o.ctx = tf.concat(ctx, axis = -1) if len(ctx) > 1 else ctx[0]
o.ctx_lengths = tf.placeholder(tf.int32, [None], name = "ctx_lengths")
def _stats(o, p):
with tf.variable_scope("stats"):
# for dynamic batch size with last batch possibly smaller than others
if p["model"]["ctx"]:
# calculate actual lengths for context
o.ctx_lengths_mask = tf.expand_dims(tf.sequence_mask(o.ctx_lengths, dtype = tf.float32), axis = 2)
o.ctx_lengths_sum = tf.reduce_sum(o.ctx_lengths, name = "ctx_lengths_sum") # total number of timesteps in the current context
o.ctx_lengths_max = tf.reduce_max(o.ctx_lengths, name = "ctx_lengths_max")
if p["dec"]["model"] == "balstm":
# augment input lengths to work with the balstm that treats each dimension of features as a single sequence
balstm_lengths = tf.expand_dims(o.inp_lengths, axis = 1) # arrange in (batch_sz, 1)
balstm_lengths = tf.tile(balstm_lengths, (1, p["num_pitches"])) # augment each length the same times as there are number of pitches -> (batch_sz, num_pitches)
o.balstm_batch_sz = tf.multiply(o.batch_sz, p["num_pitches"], name = "balstm_batch_sz")
o.balstm_lengths = tf.reshape(balstm_lengths, [o.balstm_batch_sz], name = "balstm_lengths")
def _rnn_setup(batch_sz, cell_type, cell_version, versions, bidirectional, state_sz, num_layers, rnn_dropout, proj_dropout, init_state, prefix, training):
with tf.variable_scope(prefix + "_rnn_setup"):
tot_cells = 2 * num_layers if bidirectional else num_layers
if cell_type == "gru":
if cell_version == "blockv2":
cells = [versions[cell_type][cell_version](num_units = state_sz) for i in range(tot_cells)]
else:
cells = [versions[cell_type][cell_version](state_sz) for i in range(tot_cells)]
else:
if cell_version == "lstm":
cells = [versions[cell_type][cell_version](state_sz, state_is_tuple = True) for i in range(tot_cells)]
else:
cells = [versions[cell_type][cell_version](state_sz) for i in range(tot_cells)]
if rnn_dropout is not None:
cells = [tf.nn.rnn_cell.DropoutWrapper(cell, output_keep_prob = 1.0 - rnn_dropout) for cell in cells]
if cell_type == "gru":
cell = [tf.nn.rnn_cell.MultiRNNCell(cells[a: a + num_layers]) for a in range(0, tot_cells, num_layers)]
else:
cell = [tf.nn.rnn_cell.MultiRNNCell(cells[a: a + num_layers], state_is_tuple = True) for a in range(0, tot_cells, num_layers)]
# get variables of size (1, state_sz) for all layers both forward and backwards and cell and hidden (if lstm)
if init_state is not None: # if it is None, we don't take care of initial state at all
if init_state == "zeros":
# use 0's as initial state
init = [c.zero_state(batch_sz, tf.float32) for c in cell]
else: # initial state is "var" or a dict specifying a specific initialization with projection
if isinstance(init_state, dict): # the dict contains "vector" which is the raw vector, "spec" which is a list of initializations and names for projections, typically named "projX"
projections = { k: v for k, v in init_state.items() if "vector" not in k and "spec" not in k}
projections["raw"] = init_state["vector"]
raw = init_state["vector"]
specs = init_state["spec"]
assert(len(specs) == tot_cells * (1 + int(cell_type == "lstm"))), "Mismatch between specification of cell initializations and number of cells"
else:
specs = ["var" for i in range(2 * tot_cells)] if cell_type == "lstm" else ["var" for i in range(tot_cells)]
vars = 0
init = []
for spec in specs:
if spec == "var":
init += [tf.tile(tf.get_variable("init_state_" + str(vars), [1, state_sz]), [batch_sz, 1])]
vars += 1
elif spec == "zeros":
init += [tf.zeros([batch_sz, state_sz])]
elif spec == "raw":
init += [projections["raw"]] # must fit the dimensions of [batch_sz, state_sz]
else:
if spec not in projections:
if p["batch_norm"] and p["batch_norm_before_act"]:
to_add = p["act"](tf.layers.batch_normalization(tf.layers.Dense(state_sz, activation = None)(projections["raw"]), training = training))
else:
to_add = tf.layers.Dense(state_sz, activation = p["act"])(projections["raw"])
if proj_dropout is not None:
to_add = tf.nn.dropout(to_add, rate = proj_dropout)
if p["batch_norm"] and not p["batch_norm_before_act"]:
to_add = tf.layers.batch_normalization(to_add, training = training)
projections[spec] = to_add
init += [tf.identity(projections[spec])] # must have shape [batch_sz, state_sz], always use the identity so that we may set these states to different values later without accidentally setting them all
# initial states should be a tuple of tensors (batch_sz, state_sz) for each state_sz in cell.state_size (if it is a tuple, otherwise (batch, statesz
if cell_type == "gru":
init = [tuple(init[a: a + num_layers]) for a in range(0, tot_cells, num_layers)] # each index holds initial states for all layers
else:
# create one LSTMStateTuple for each pair of states (c and h states), all in all amounting to one tuple per layer per direction
init = [tf.nn.rnn_cell.LSTMStateTuple(init[a], init[a + 1]) for a in range(0, 2 * tot_cells, 2)] # one per layer and direction
init = [tuple(init[a: a + num_layers]) for a in range(0, tot_cells, num_layers)]
return (cell, init)
else: # don't bother with initial state, just return the cell
return cell
def _rnn(o, cell, input, batch_sz, seq_lengths, cell_type, bidirectional, prefix):
with tf.variable_scope(prefix + "_rnn"):
if input is None:
input = tf.zeros([batch_sz, o.inp_lengths_max, 1])
if bidirectional is not None:
if bidirectional == "stack":
args = [cell[0]._cells, cell[1]._cells]
init_fw = list(getattr(o, prefix + "_init_fw"))
init_bw = list(getattr(o, prefix + "_init_bw"))
else:
args = [cell[0], cell[1]]
init_fw = getattr(o, prefix + "_init_fw")
init_bw = getattr(o, prefix + "_init_bw")
if bidirectional == "stack":
print("[MAHLERNET]: adding a bidirectional stacked " + prefix + "_rnn ")
kwargs = {"inputs": input, "initial_states_fw": init_fw, "initial_states_bw": init_bw, "dtype": tf.float32, "sequence_length": seq_lengths}
output, final_state_fw, final_state_bw = tf.contrib.rnn.stack_bidirectional_dynamic_rnn(*args, **kwargs)
final_state = (final_state_fw, final_state_bw)
else:
print("[MAHLERNET]: adding a bidirectional default " + prefix + "_rnn ")
kwargs = {"inputs": input, "initial_state_fw": init_fw, "initial_state_bw": init_bw, "dtype": tf.float32, "sequence_length": seq_lengths}
output, final_state = tf.nn.bidirectional_dynamic_rnn(*args, **kwargs)
# output for bidirectional is a tuple (output_fw, output_bw) where output_fw / _bw has shape [batch_sz, max_steps, state_sz]
# finalstates is also a tuple (fw, bw) where each part holds the final state of all layers. In case of LSTM, these states are LSTMStateTuples
summary = list(map(lambda a: a[-1].h if cell_type == "lstm" else a[-1], final_state))
# concatenate the final hidden states from the forward and backward rnns (indexed by 0 and 1,and cell state and hidden state indexed by c and h)
summary = tf.concat(summary, axis = 1)
else:
print("[MAHLERNET]: adding a unidirectional " + prefix + "_rnn ")
args = [cell[0]]
init = getattr(o, prefix + "_init")
kwargs = {"inputs": input, "initial_state": init, "dtype": tf.float32, "sequence_length": seq_lengths}
# output is an array of shape (batch_size, time_steps, state_size) containing the hidden state ONLY (not cell state) from all timesteps,
# final state is cell AND hidden state from last valid time step like (cell_state, hidden_state)
# final state has shape (2, state_size) if the cell is a single cell, and (layers, 2, state_size) if it is a multi cell
output, final_state = tf.nn.dynamic_rnn(*args, **kwargs)
# output is (num_layers)
summary = final_state[-1].h if cell_type == "lstm" else final_state[-1]
setattr(o, prefix + "_summary", summary)
setattr(o, prefix + "_output", output)
setattr(o, prefix + "_final_state", final_state)
def _seq2seq(o, cell, input, batch_sz, seq_lengths, cell_type, prefix, fn = None, aux = None):
with tf.variable_scope(prefix + "_seq2seq"):
init = getattr(o, prefix + "_init")
#o.dummy = tf.Print(o.dummy, [init, input], message = "IN SEQ", summarize = 1000000)
# HELPER FUNCTIONS
# one-hot encodes a chosen class by the helper, simplest form of embedding to use with ScheduledEmbeddingTrainingHelper
#emb_fctn = lambda a: tf.one_hot(a, self.params["num_pitches"]) # for ScheduledEmbedding.... since it samples a CLASS INDEX, this is the embedding so to speak
# samples or chooses the argmax of the output layer then one-hot encodes it, sampling gives the same function as ScheduledEmbeddingTrainingHelper
# and arg_max gives the same results as TrainingHelper (although TrainingHelper feeds the ground truth always)
#out_sample_fctn = lambda a: tf.one_hot(tf.squeeze(tf.random.categorical(a, 1, dtype = tf.int32), axis = 1), self.params["num_pitches"]) # samples from classes
#out_max_fctn = lambda a: tf.one_hot(tf.argmax(a, axis = -1), self.params["num_pitches"]) # takes MOST PROBABLE class
# HELPERS - load data and returns outputs at each step of the decoding
# plain helper, feeds targets to next input using teacher forcing, sampled ids are argmax of the output layer
if not p["dec"]["scheduled_sampling"]:
helper = tf.contrib.seq2seq.TrainingHelper(input, seq_lengths)
# scheduled sampling where output are treated as logits and a sample is drawn from this distribution, embedding layer encodes chosen class
# sample ids are -1 for outputs where no sampling was made, otherwise the sampled output
#helper = tf.contrib.seq2seq.ScheduledEmbeddingTrainingHelper(self.ops.decoder_input, seql, emb_fctn, 0.3)
# scheduled sampling, more versatile than previous, function for sampling and adding to chosen inputs can be given by the user
# sample ids are False for outputs where no sampling took place, True otherwise
else:
rate = tf.cast(p["dec"]["scheduled_sampling_rate"], tf.float32)
if p["dec"]["scheduled_sampling_scheme"] == "sigmoid":
prob = (1 - (rate / (rate + tf.exp(tf.divide(o.global_step, rate))))) ** 2
else: # linear, max(e, k - ci) where e is the minimum truth and k is the maximum truth and c is a linerear coefficient factor to global steps (i)
prob = 1 - tf.math.maximum(p["dec"]["scheduled_sampling_min_truth"], tf.constant(1.0, dtype = tf.float32) - tf.multiply(p["dec"]["scheduled_sampling_rate"], o.global_step))
helper = tf.contrib.seq2seq.ScheduledOutputTrainingHelper(input, seq_lengths, prob, next_inputs_fn = fn, auxiliary_inputs = aux)
kwargs = {"maximum_iterations": o.inp_lengths_max, "impute_finished": True}
decoder = tf.contrib.seq2seq.BasicDecoder(cell[0], helper, init, None)
'''
output from dynamic_decode are:
(decoder_outputs, decoder_final_states, seq_lengths)
... where decoder_outputs has porperties .rnn_output and .sample_id
decoder_output.rnn_output is exactly the output from the corresponding dynamic_rnn with the same sequence lengths run through a linear layer
decoder_output.sample_id is exactly the argmax of the output of a dynamic_rnn with same sequence lengths run through a linear layer
decoder_final_states are exactly the final states of the corresponding dynamic_rnn
seq_lengths is a list of sequence length with the same content as the input sequence lengths if max_iterations was set equal to or higher
than the longest sequence
'''
decoder_output_tuple, decoder_final_state, sequences = tf.contrib.seq2seq.dynamic_decode(decoder, **kwargs)
setattr(o, prefix + "_final_state", decoder_final_state)
setattr(o, prefix + "_output", decoder_output_tuple.rnn_output)
setattr(o, prefix + "_preds", decoder_output_tuple.sample_id) # sample ids are arg max of rnn_output with regular traininghelper
def _encoder_component(o, p):
summaries = []
for key in ["inp", "ctx"]:
if p["model"][key]:
print("[MAHLERNET]: adding " + key + " encoder")
data = getattr(o, key)
lengths = getattr(o, key + "_lengths")
key = key + "_enc"
bidirectional_type = p[key]["bidirectional_type"]
dropout = getattr(o, key + "_dropout") if p[key]["dropout"] > 0.0 else None
cell, init = _rnn_setup(o.batch_sz, p[key]["type"], p[key]["version"], p["cell_versions"], True, p[key]["sz_state"],
p[key]["num_layers"], dropout, None, p[key]["init"], key, o.training)
setattr(o, key + "_init_fw", init[0])
setattr(o, key + "_init_bw", init[1])
_rnn(o, cell, data, o.batch_sz, lengths, p[key]["type"], bidirectional_type, key)
summaries += [getattr(o, key + "_summary")]
# now either (batch_sz, 2 * inp_state + 2 * ctx_state) or (batch_sz, 2 * inp_state)
o.vae_input = tf.concat(summaries, axis = 1) if len(summaries) > 1 else summaries[0]
def _vae(o, p, w):
# vae input
with tf.variable_scope("vae"):
vae_inp_sz = 2 * (p["inp_enc"]["sz_state"] * int(p["model"]["inp"]) + p["ctx_enc"]["sz_state"] * int(p["model"]["ctx"]))
z_dim = p["vae"]["z_dim"]
w["vae"]['mu_W'] = tf.get_variable("vae_mu_W", (vae_inp_sz, z_dim), initializer=tf.random_normal_initializer(stddev=0.001))
w["vae"]["mu_b"] = tf.get_variable("vae_mu_bias", (z_dim), initializer=tf.constant_initializer(0.0))
o.mu = tf.matmul(o.vae_input, w["vae"]["mu_W"]) + w["vae"]["mu_b"]
w["vae"]["log_sigma_sq_W"] = tf.get_variable("vae_log_sigma_sq_W", (vae_inp_sz, z_dim), initializer=tf.random_normal_initializer(stddev=0.001))
w["vae"]["log_sigma_sq_b"] = tf.get_variable("vae_log_sigma_sq_bias", (z_dim), initializer=tf.constant_initializer(0.0))
o.log_sigma_sq = tf.nn.softplus(tf.matmul(o.vae_input, w["vae"]["log_sigma_sq_W"]) + w["vae"]["log_sigma_sq_b"]) + 1e-10
# sample a vector
if p["use_randomness"]:
eps = tf.random_normal((o.batch_sz, z_dim), 0, 1, dtype=tf.float32)
else:
eps = tf.random_normal((o.batch_sz, z_dim), 0, 1, dtype=tf.float32, seed = 1)
o.z = tf.add(o.mu, tf.multiply(tf.sqrt(tf.exp(o.log_sigma_sq)), eps), name = "sampled_z")
def _decoder_ctx_setup(o, p):
with tf.variable_scope("init_decoder_context"):
# decoder context
o.num_dec_ctx_features = 0
o.dec_init_raw = None
dec_ctx = []
if p["model"]["ctx"] and p["dec"]["feed"]["ctx"]["use"]:
o.num_dec_ctx_features += 2 * p["ctx_enc"]["sz_state"]
dec_ctx += [o.ctx_enc_summary]
if p["model"]["vae"]:
if p["dec"]["init"] == "z": # set up the initial state as a projection from the latent vector
layer_states = 2 if p["dec"]["type"] == "lstm" else 1
tot_states = layer_states * p["dec"]["num_layers"]
if p["dec"]["model"] == "balstm":
# ONLY set up the initial state for the balstm if we want a custom setup, that is, use special projections for its initial state
if p["dec"]["balstm"]["init"] == "diff": # use different projections of latent space for all rnn instances
if p["dec"]["layer_strategy"] == "diff":
if p["batch_norm"] and p["batch_norm_before_act"]:
o.dec_init = [p["act"](tf.layers.batch_normalization(tf.layers.Dense(p["dec"]["sz_state"] * p["num_pitches"], activation = None)(o.z), training = o.training)) for _ in range(tot_states)] # (batch, num_p * state_sz)
else:
o.dec_init = [tf.layers.Dense(p["dec"]["sz_state"] * p["num_pitches"], activation = p["act"])(o.z) for _ in range(tot_states)] # (batch, num_p * state_sz)
if p["vae"]["dropout"] > 0.0:
o.dec_init = [tf.nn.dropout(init_layer, rate = o.vae_dropout) for init_layer in o.dec_init] # (batch, num_p * state_sz)
if p["batch_norm"] and not p["batch_norm_before_act"]:
o.dec_init = [tf.layers.batch_normalization(init_layer, training = o.training) for init_layer in o.dec_init] # (batch, num_p * state_sz)
o.dec_init = [tf.reshape(in_st, [o.balstm_batch_sz, p["dec"]["sz_state"]]) for in_st in o.dec_init]
else: # same setup for every layer
if p["batch_norm"] and p["batch_norm_before_act"]:
o.dec_init = [p["act"](tf.layers.batch_normalization(tf.layers.Dense(p["dec"]["sz_state"] * p["num_pitches"], activation = None)(o.z), training = o.training)) for _ in range(layer_states)] # (batch, num_p * state_sz)
else:
o.dec_init = [tf.layers.Dense(p["dec"]["sz_state"] * p["num_pitches"], activation = p["act"])(o.z) for _ in range(layer_states)] # (batch, num_p * state_sz)
if p["vae"]["dropout"] > 0.0:
o.dec_init = [tf.nn.dropout(init_layer, rate = o.vae_dropout) for init_layer in o.dec_init] # (batch, num_p * state_sz)
if p["batch_norm"] and not p["batch_norm_before_act"]:
o.dec_init = [tf.layers.batch_normalization(init_layer, training = o.training) for init_layer in o.dec_init] # (batch, num_p * state_sz)
o.dec_init = [tf.reshape(in_st, [o.balstm_batch_sz, p["dec"]["sz_state"]]) for in_st in o.dec_init]
o.dec_init = [[tf.identity(in_st) for in_st in o.dec_init] for _ in range(p["dec"]["num_layers"])] # all layers gets the same initial states
else: # use the same projection from latent space on all rnn instances
if p["dec"]["layer_strategy"] == "diff": # different between layers however
if p["batch_norm"] and p["batch_norm_before_act"]:
o.dec_init = [p["act"](tf.layers.batch_normalization(tf.layers.Dense(p["dec"]["sz_state"], activation = None)(o.z), training = o.training)) for _ in range(p["dec"]["num_layers"])] # (batch, sz_state)
else:
o.dec_init = [tf.layers.Dense(p["dec"]["sz_state"], activation = p["act"])(o.z) for _ in range(p["dec"]["num_layers"])] # (batch, sz_state)
if p["vae"]["dropout"] > 0.0:
o.dec_init = [tf.nn.dropout(init_layer, rate = o.vae_dropout) for init_layer in o.dec_init] # (batch, sz_state)
if p["batch_norm"] and not p["batch_norm_before_act"]:
o.dec_init = [tf.layers.batch_normalization(init_layer, training = o.training) for init_layer in o.dec_init] # (batch, sz_state)
o.dec_init = [tf.tile(in_st, [1, p["num_pitches"]]) for in_st in o.dec_init]
o.dec_init = [tf.reshape(in_st, [o.balstm_batch_sz, p["dec"]["sz_state"]]) for in_st in o.dec_init]
o.dec_init = [tf.identity(in_st) for in_st in o.dec_init]
else: # same for all instances and for all layers
if p["batch_norm"] and p["batch_norm_before_act"]:
o.dec_init_raw = p["act"](tf.layers.batch_normalization(tf.layers.Dense(p["dec"]["sz_state"], activation = None, name = "dec_init_raw")(o.z), training = o.training)) # (batch, sz_state)
else:
o.dec_init_raw = tf.layers.Dense(p["dec"]["sz_state"], activation = p["act"], name = "dec_init_raw")(o.z) # (batch, sz_state)
if p["vae"]["dropout"] > 0.0:
o.dec_init_raw = tf.nn.dropout(o.dec_init_raw, rate = o.vae_dropout)
if p["batch_norm"] and not p["batch_norm_before_act"]:
o.dec_init_raw = tf.layers.batch_normalization(o.dec_init_raw, training = o.training)
o.dec_init = tf.tile(o.dec_init_raw, [1, p["num_pitches"]]) # (batch, num_pitches * state_sz)
o.dec_init = tf.reshape(o.dec_init, [o.balstm_batch_sz, p["dec"]["sz_state"]]) # (batch * num_pitches, state_sz)
o.dec_init = [tf.identity(o.dec_init) for _ in range(tot_states)]
if p["dec"]["type"] == "lstm":
# create one LSTMStateTuple for each pair of states (c and h states), all in all amounting to one tuple per layer
o.dec_init = [tf.nn.rnn_cell.LSTMStateTuple(o.dec_init[a], o.dec_init[a + 1]) for a in range(0, tot_states, 2)] # one per layer
o.dec_init = [tuple(o.dec_init)] # input init state is supposed to be a tuple of tensors and the function expects a list
if p["dec"]["feed"]["z"]["use"]: # use the latent vector as part of the input at every time step during decoding
if p["dec"]["feed"]["z"]["strategy"] == "raw":
o.num_dec_ctx_features += p["vae"]["z_dim"]
dec_ctx += [o.z]
else:
if o.dec_init_raw is None: # either we are NOT using the BALSTM OR we are using a strategy with the BALSTM that makes it impossible to use a single projection of z as a feed during decoding
# if we use a regular lstm, no initial states have been created and if layer strategy is same, the one created below will be reused,
# otherwise, new projections will be created for each layer.
# under these circumstances, we need to add a new layer for projections of z since either different projections or none has been used earlier
if p["dec"]["init"] != "z" or p["dec"]["model"] == "balstm" or (p["dec"]["model"] == "lstm" and p["dec"]["layer_strategy"] == "diff"):
# this is the scenario where there might be other projections of z but not compatible with the use as input feed during decoding. These scenarios include the use of BALSTM with "diff" as either
# layer_strategy or initialization or regular LSTM with "diff" as layer strategy (none of these cases allows the use of a single vector to feed during decoding since thee is no way to pick a single
# and we can't feed them all, thus we create a new one using the specification under "feed". The third case is where not z is used as initialization at all, then we don't have to adhere to the
# state size of the decoder
if p["batch_norm"] and p["batch_norm_before_act"]:
o.dec_init_raw = p["act"](tf.layers.batch_normalization(tf.layers.Dense(p["dec"]["feed"]["z"]["sz"], activation = None, name = "dec_init_raw")(o.z), training = o.training)) # (batch, sz_state)
else:
o.dec_init_raw = tf.layers.Dense(p["dec"]["feed"]["z"]["sz"], activation = p["act"], name = "dec_init_raw")(o.z) # (batch, sz_state)
if p["vae"]["dropout"] > 0.0:
o.dec_init_raw = tf.dropout(o.dec_init_raw, rate = o.vae_dropout) # (batch, sz_state)
if p["batch_norm"] and not p["batch_norm_before_act"]:
o.dec_init_raw = tf.layers.batch_normalization(o.dec_init_raw, training = o.training)
o.num_dec_ctx_features += p["dec"]["feed"]["z"]["sz"]
else:
# in this scenario, the BALSTM is not used at all (since then, either dec_init_raw was set or a separate projection was created above), thus we are using the regular LSTM model with z_dim
# initialization and layer strategy same, thus we must make the projection so that it matches the size of the decoder state so that we may use the same for feeding and initialization.
if p["batch_norm"] and p["batch_norm_before_act"]:
o.dec_init_raw = p["act"](tf.layers.batch_normalization(tf.layers.Dense(p["dec"]["sz_state"], activation = None, name = "dec_init_raw")(o.z), training = o.training)) # (batch, sz_state)
else:
o.dec_init_raw = tf.layers.Dense(p["dec"]["sz_state"], activation = p["act"], name = "dec_init_raw")(o.z) # (batch, sz_state)
if p["vae"]["dropout"] > 0.0:
o.dec_init_raw = tf.nn.dropout(o.dec_init_raw, rate = o.vae_dropout) # (batch, sz_state)
if p["batch_norm"] and not p["batch_norm_before_act"]:
o.dec_init_raw = tf.layers.batch_normalization(o.dec_init_raw, training = o.training)
o.num_dec_ctx_features += p["dec"]["sz_state"]
else: # if dec_init_raw was created, it was due to the use of BALSTM with layer and init strategy "same" and thus it has the size of the decoder state
o.num_dec_ctx_features += p["dec"]["sz_state"]
dec_ctx += [o.dec_init_raw]
if len(dec_ctx) > 1:
o.init_dec_ctx = tf.concat(dec_ctx, axis = 1) # (batch, z_dim + 2 * ctx_encoder state)
elif len(dec_ctx) > 0:
o.init_dec_ctx = dec_ctx[0]
else:
o.init_dec_ctx = None
def _balstm_decoder(o, p, w):
# it is assumed that if we reach here, pitch is modelled in the network
with tf.variable_scope("balstm_decoder"):
# 1D convolution along the feature axis of every time step
convs = []
feats = 0
if p["modelling_properties"]["pitch"]["include"]:
feats += p["dec"]["balstm"]["num_filters"]
# Since 1D convolution treats the features as channels, we can't achieve the kind of padding desired, convert to 2D and do convolution there
w["conv"]["p_W"] = tf.get_variable("conv_p_W", (1, p["dec"]["balstm"]["sz_conv"], 1, p["dec"]["balstm"]["num_filters"])) # features will be treated as width after reshape to 2D
w["conv"]["p_b"] = tf.get_variable("conv_p_bias", [p["dec"]["balstm"]["num_filters"]], initializer=tf.constant_initializer(0.0))
conv_p = tf.reshape(o.x_p, (o.batch_sz, o.inp_lengths_max, p["num_pitches"], 1)) # reshape to 2D
conv_p = tf.nn.conv2d(conv_p, w["conv"]["p_W"], strides = [1, 1, 1, 1], padding = "SAME")
conv_p = tf.add(conv_p, w["conv"]["p_b"])
if p["batch_norm"] and p["batch_norm_before_act"]:
conv_p = tf.layers.batch_normalization(conv_p, training = o.training)
o.conv_p_output = p["act"](conv_p) # is now (batch_sz, num_steps, num_pitches, filters)
convs += [o.conv_p_output]
if p["modelling_properties"]["active_pitches"]["include"]:
feats += p["dec"]["balstm"]["num_filters"]
# Since 1D convolution treats the features as channels, we can't achieve the kind of padding desired, convert to 2D and do convolution there
w["conv"]["a_W"] = tf.get_variable("conv_a_W", (1, p["dec"]["balstm"]["sz_conv"], 1, p["dec"]["balstm"]["num_filters"])) # features will be treated as width after reshape to 2D
w["conv"]["a_b"] = tf.get_variable("conv_a_bias", [p["dec"]["balstm"]["num_filters"]], initializer=tf.constant_initializer(0.0))
conv_a = tf.reshape(o.x_ap, (o.batch_sz, o.inp_lengths_max, p["num_pitches"], 1)) # reshape to 2D
conv_a = tf.nn.conv2d(conv_a, w["conv"]["a_W"], strides = [1, 1, 1, 1], padding = "SAME")
conv_a = tf.add(conv_a, w["conv"]["a_b"])
if p["batch_norm"] and p["batch_norm_before_act"]:
conv_a = tf.layers.batch_normalization(conv_a, training = o.training)
o.conv_a_output = p["act"](conv_a) # is now (batch_sz, num_steps, num_pitches, 1)
convs += [o.conv_a_output]
o.conv_output = tf.concat(convs, axis = -1) if len(convs) > 1 else convs[0]
if p["dec"]["balstm"]["conv_dropout"] > 0.0:
o.conv_output = tf.nn.dropout(o.conv_output, rate = o.dec_balstm_conv_dropout)
if p["batch_norm"] and not p["batch_norm_before_act"]:
o.conv_output = tf.layers.batch_normalization(o.conv_output, training = o.training)
# decoder_context
if o.init_dec_ctx is not None:
o.dec_ctx = tf.tile(o.init_dec_ctx, [1, o.inp_lengths_max * p["num_pitches"]]) # repeat for each batch the ctx and x stes * pitches times
o.dec_ctx = tf.reshape(o.dec_ctx, [o.balstm_batch_sz, o.inp_lengths_max, o.num_dec_ctx_features])
else:
o.dec_ctx = None
if o.x_rest is not None:
# in the x_rest vector, (batch, steps, features), for each sequence, repeat the sequence as a whole num_pitches time since each sequence is
# about to be turned into num_pitches sequences of with features size 1
repeated_x_rest = tf.tile(o.x_rest, [1, p["num_pitches"], 1]) # is now (batch, num_pitches * steps, num_features - num_pitches)
repeated_x_rest = tf.reshape(repeated_x_rest, [o.balstm_batch_sz, o.inp_lengths_max, p["num_xr_features"]])
o.dec_ctx = tf.concat((repeated_x_rest, o.dec_ctx), axis = 2) if o.dec_ctx is not None else repeated_x_rest
if p["dec"]["balstm"]["add_pitch"]:
pitch = tf.range(p["num_pitches"], dtype = tf.int32)
pitch = tf.reshape(pitch, [p["num_pitches"], 1])
# in the balstm we have (batch * pitch, steps, feat) so the SAME pitch must be provided for all timesteps, inp_lengths_max in a row and repeated for each sequence in the batch
pitch = tf.tile(pitch, [o.batch_sz, o.inp_lengths_max])
pitch = tf.one_hot(pitch, depth = p["num_pitches"], dtype = tf.float32)
o.dec_ctx = tf.concat([o.dec_ctx, pitch], axis = 2) if o.dec_ctx is not None else pitch
# decoder input
o.dec_inp = tf.transpose(o.conv_output, [0, 2, 1, 3]) # switch steps and pitch convolutions so we get (batch, pitch, steps, 1-2)
o.dec_inp = tf.reshape(o.dec_inp, [o.balstm_batch_sz, o.inp_lengths_max, feats]) # now (batch * pitch, steps, 1-2), all sequences are of features size 1-2
o.dec_inp = tf.concat([o.dec_inp, o.dec_ctx], axis = 2) if o.dec_ctx is not None else o.dec_inp
rnn_dropout = o.dec_dropout if p["dec"]["dropout"] > 0.0 else None
proj_dropout = o.vae_dropout if p["vae"]["dropout"] > 0.0 else None
if p["model"]["vae"] and p["dec"]["init"] == "z":
cell = _rnn_setup(o.balstm_batch_sz, p["dec"]["type"], p["dec"]["version"], p["cell_versions"], False, p["dec"]["sz_state"], p["dec"]["num_layers"], rnn_dropout, proj_dropout, None, "dec", o.training)
init = o.dec_init
else:
cell, init = _rnn_setup(o.balstm_batch_sz, p["dec"]["type"], p["dec"]["version"], p["cell_versions"], False, p["dec"]["sz_state"], p["dec"]["num_layers"], rnn_dropout, proj_dropout, p["dec"]["init"], "dec", o.training)
inits = []
for i in range(p["dec"]["num_layers"]):
if p["dec"]["type"] == "lstm":
setattr(o, "dec_init_h_" + str(i), init[0][i].h)
setattr(o, "dec_init_c_" + str(i), init[0][i].c)
inits += [tf.nn.rnn_cell.LSTMStateTuple(getattr(o, "dec_init_c_" + str(i)), getattr(o, "dec_init_h_" + str(i)))]
else:
setattr(o, "dec_init_" + str(i), init[0][i])
inits += [getattr(o, "dec_init_" + str(i))]
o.dec_init = tuple(inits)
if p["dec"]["framework"] == "seq2seq":