-
Notifications
You must be signed in to change notification settings - Fork 8
/
wavenet.py
175 lines (138 loc) · 8.64 KB
/
wavenet.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
import tensorflow as tf
import numpy as np
import datasets
from model import NetworkMelody, AdjustVoicingHook
from collections import namedtuple
import sys
import common
# https://github.com/lmartak/amt-wavenet/blob/master/wavenet/model.py
def create_model(self, args):
receptive_field = args.stack_number * (args.max_dilation * 2) - (args.stack_number - 1)
receptive_field_ms = (receptive_field * 1000) / args.samplerate
context_width = self.context_width
print("receptive field: {} samples, {:.4f} ms".format(receptive_field, receptive_field_ms))
if self.context_width > receptive_field:
context_width = receptive_field
diff = self.context_width - receptive_field
window = self.window[:, diff:-diff]
print("cutting window {}->{}".format(self.window.shape, window.shape))
else:
window = self.window
print("warning: receptive field larger than context width")
window = common.input_normalization(window, args)
window_with_channel = tf.expand_dims(window, axis=2)
initial_layer = window_with_channel
if args.initial_filter_width > 0:
initial_layer = tf.layers.conv1d(initial_layer, args.residual_channels, args.initial_filter_width, 1, args.initial_filter_padding,
activation=None, bias_regularizer=tf.nn.l2_loss, kernel_regularizer=tf.nn.l2_loss)
skip_connections = []
dilations = [2**x for x in range(int(np.log2(args.max_dilation))+1)]*args.stack_number
print(dilations)
current_layer = initial_layer
with tf.name_scope('dilated_stack'):
for layer_index, dilation in enumerate(dilations):
with tf.name_scope('layer{}'.format(layer_index)):
conv_filter = tf.layers.conv1d(current_layer, args.residual_channels, args.filter_width, 1, "same", dilation_rate=dilation,
use_bias=args.use_biases, bias_regularizer=tf.nn.l2_loss, kernel_regularizer=tf.nn.l2_loss)
conv_gate = tf.layers.conv1d(current_layer, args.residual_channels, args.filter_width, 1, "same", dilation_rate=dilation,
use_bias=args.use_biases, bias_regularizer=tf.nn.l2_loss, kernel_regularizer=tf.nn.l2_loss)
out = tf.tanh(conv_filter) * tf.sigmoid(conv_gate)
skip = tf.layers.conv1d(out, args.skip_channels, 1, 1, "same", use_bias=args.use_biases, bias_regularizer=tf.nn.l2_loss, kernel_regularizer=tf.nn.l2_loss)
transformed = tf.layers.conv1d(out, args.residual_channels, 1, 1, "same", use_bias=args.use_biases, bias_regularizer=tf.nn.l2_loss, kernel_regularizer=tf.nn.l2_loss)
if args.dilation_layer_dropout:
transformed = tf.layers.dropout(transformed, args.dilation_layer_dropout, training=self.is_training)
current_layer = transformed + current_layer
skip_connections.append(skip)
print(skip)
with tf.name_scope('postprocessing'):
if args.skip == "add":
skip_sum = tf.math.add_n(skip_connections)
elif args.skip == "concat":
skip_sum = tf.concat(skip_connections, -1)
elif args.skip == "last":
skip_sum = skip_connections[-1]
if context_width:
skip_sum = skip_sum[:, context_width:-context_width, :]
print("skip output", skip_sum.shape)
skip = tf.nn.relu(skip_sum)
if args.skip_layer_dropout:
skip = tf.layers.dropout(skip, args.skip_layer_dropout, training=self.is_training)
# skip = tf.layers.average_pooling1d(skip, 93, 93, "valid")
# skip = tf.layers.conv1d(skip, self.bin_count, 3, 1, "same", activation=tf.nn.relu, bias_regularizer=tf.nn.l2_loss, kernel_regularizer=tf.nn.l2_loss)
# output_layer = tf.layers.conv1d(skip, self.bin_count, 3, 1, "same", activation=None, bias_regularizer=tf.nn.l2_loss, kernel_regularizer=tf.nn.l2_loss)
output_layer = common.add_layers_from_string(self, skip, args.postprocessing)
# skip = tf.layers.conv1d(skip, 256, 16, 8, "same", activation=tf.nn.relu, use_bias=args.use_biases, bias_regularizer=tf.nn.l2_loss, kernel_regularizer=tf.nn.l2_loss)
# skip = tf.layers.conv1d(skip, 256, 16, 8, "same", activation=tf.nn.relu, use_bias=args.use_biases, bias_regularizer=tf.nn.l2_loss, kernel_regularizer=tf.nn.l2_loss)
# skip = tf.nn.relu(skip_sum)
print("after skip output processing", output_layer.shape)
if output_layer.shape.as_list() != [None, self.annotations_per_window, self.bin_count]:
print("shape not compatible, adding FC layer")
output_layer = tf.nn.relu(output_layer)
output_layer = tf.layers.flatten(output_layer)
output_layer = tf.layers.dense(output_layer, self.annotations_per_window*self.bin_count, activation=None, bias_regularizer=tf.nn.l2_loss, kernel_regularizer=tf.nn.l2_loss)
output_layer = tf.reshape(output_layer, [-1, self.annotations_per_window, self.bin_count])
self.note_logits = output_layer
self.voicing_threshold = tf.Variable(0.15, trainable=False)
self.loss = common.loss(self, args)
self.est_notes = common.est_notes(self, args)
self.training = common.optimizer(self, args)
def parse_args(argv):
parser = common.common_arguments_parser()
# Model specific arguments
parser.add_argument("--use_biases", action='store_true', default=False, help="Use biases in the convolutions")
parser.add_argument("--input_normalization", type=int, help="Enable normalizing each input example")
parser.add_argument("--initial_filter_width", type=int, help="First conv layer filter width")
parser.add_argument("--initial_filter_padding", type=str, help="First conv layer padding")
parser.add_argument("--filter_width", type=int, help="Dilation stack filter width (2 or 3)")
parser.add_argument("--skip_channels", type=int, help="Skip channels")
parser.add_argument("--residual_channels", type=int, help="Residual channels")
parser.add_argument("--stack_number", type=int, help="Number of dilated stacks")
parser.add_argument("--max_dilation", type=int, help="Maximum dilation rate")
parser.add_argument("--dilation_layer_dropout", type=float, help="Dropout in dilation layer")
parser.add_argument("--skip_layer_dropout", type=float, help="Dropout in skip connections")
parser.add_argument("--skip", type=str, help="Skip add or concat")
parser.add_argument("--postprocessing", type=str, help="Postprocessing layer")
args = parser.parse_args(argv)
defaults = {
"note_range": 72, "min_note": 24,
"evaluate_every": 5000,
"evaluate_small_every": 5000,
"batch_size": 8,
"annotations_per_window": 10,
"context_width": 94,
"annotation_smoothing": 0.18,
"input_normalization": 1,
"initial_filter_width": 32,
"initial_filter_padding": "same",
"filter_width": 3,
"skip_channels": 64,
"residual_channels": 32,
"stack_number": 1,
"max_dilation": 512,
"dilation_layer_dropout": 0.0,
"skip_layer_dropout": 0.0,
"skip": "add",
"postprocessing": "avgpool_p93_s93_Psame--conv_f256_k16_s8_Psame_arelu--conv_f256_k16_s8_Psame_arelu",
}
specified_args = common.argument_defaults(args, defaults)
common.name(args, specified_args, "wavenet")
return args
def construct(args):
network = NetworkMelody(args)
with network.session.graph.as_default():
def preload_fn(aa):
aa.annotation = datasets.Annotation.from_time_series(*aa.annotation)
aa.audio.load_resampled_audio(args.samplerate)
def dataset_transform(tf_dataset, dataset):
return tf_dataset.map(dataset.prepare_example, num_parallel_calls=args.threads).batch(args.batch_size_evaluation).prefetch(10)
def dataset_transform_train(tf_dataset, dataset):
return tf_dataset.shuffle(10**5).map(dataset.prepare_example, num_parallel_calls=args.threads).filter(dataset.is_example_voiced).batch(args.batch_size).prefetch(10)
train_dataset, test_datasets, validation_datasets = common.prepare_datasets(args.datasets, args, preload_fn, dataset_transform, dataset_transform_train)
# Add voicing hook to the validation dataset
for vd in validation_datasets:
if not vd.name.startswith("small_"):
vd.hooks.append(AdjustVoicingHook())
network.construct(args, create_model, train_dataset.dataset.output_types, train_dataset.dataset.output_shapes)
return network, train_dataset, validation_datasets, test_datasets
if __name__ == "__main__":
common.main(sys.argv[1:], construct, parse_args)