Spaces:
Build error
Build error
Add first version
Browse files- README.md +1 -1
- __pycache__/layers.cpython-39.pyc +0 -0
- __pycache__/models.cpython-39.pyc +0 -0
- __pycache__/parse_test.cpython-39.pyc +0 -0
- __pycache__/utils.cpython-39.pyc +0 -0
- app.py +15 -0
- checkpoints/classical/dec.h5 +3 -0
- checkpoints/classical/dec2.h5 +3 -0
- checkpoints/classical/gen_ema.h5 +3 -0
- checkpoints/techno/dec.h5 +3 -0
- checkpoints/techno/dec2.h5 +3 -0
- checkpoints/techno/gen_ema.h5 +3 -0
- layers.py +164 -0
- models.py +831 -0
- musika.py +17 -0
- parse_test.py +165 -0
- requirements.txt +20 -0
- utils.py +560 -0
README.md
CHANGED
@@ -4,7 +4,7 @@ emoji: 🚀
|
|
4 |
colorFrom: purple
|
5 |
colorTo: blue
|
6 |
sdk: gradio
|
7 |
-
sdk_version:
|
8 |
app_file: app.py
|
9 |
pinned: false
|
10 |
license: cc-by-4.0
|
|
|
4 |
colorFrom: purple
|
5 |
colorTo: blue
|
6 |
sdk: gradio
|
7 |
+
sdk_version: 2.5.2
|
8 |
app_file: app.py
|
9 |
pinned: false
|
10 |
license: cc-by-4.0
|
__pycache__/layers.cpython-39.pyc
ADDED
Binary file (5.8 kB). View file
|
|
__pycache__/models.cpython-39.pyc
ADDED
Binary file (13.5 kB). View file
|
|
__pycache__/parse_test.cpython-39.pyc
ADDED
Binary file (3.47 kB). View file
|
|
__pycache__/utils.cpython-39.pyc
ADDED
Binary file (16.5 kB). View file
|
|
app.py
ADDED
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from parse_test import parse_args
|
2 |
+
from models import Models_functions
|
3 |
+
from utils import Utils_functions
|
4 |
+
|
5 |
+
|
6 |
+
# parse args
|
7 |
+
args = parse_args()
|
8 |
+
|
9 |
+
# initialize networks
|
10 |
+
M = Models_functions(args)
|
11 |
+
models_ls_techno, models_ls_classical = M.get_networks()
|
12 |
+
|
13 |
+
# test musika
|
14 |
+
U = Utils_functions(args)
|
15 |
+
U.render_gradio(models_ls_techno, models_ls_classical, train=False)
|
checkpoints/classical/dec.h5
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:32e50f938685f56e1dc5e137e95c59472418194125e435cafb668584e65b0fcc
|
3 |
+
size 29745512
|
checkpoints/classical/dec2.h5
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:643e1415f5ebf34cb067b2ccaced657f1f3e3f068810c2d130dfc3abb20c3cc2
|
3 |
+
size 26799136
|
checkpoints/classical/gen_ema.h5
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:1508fa1fad225f7c29ed64252b531e4462c97b0f0c80dd6d212014916f6261eb
|
3 |
+
size 56431944
|
checkpoints/techno/dec.h5
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:953f70f8c874d36fd57dfd825b3bceff2f7dba04c93f4a1464c0c5d223c2b2e7
|
3 |
+
size 29745512
|
checkpoints/techno/dec2.h5
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:cd0a9e2eb78bae5178dd25022b4d0ac5020a6366c98fa009830c6c8818582045
|
3 |
+
size 26799136
|
checkpoints/techno/gen_ema.h5
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:9a81012a6bc318e23bb12ed0fc70260d260e71c9b355b553593c60bfec0fab41
|
3 |
+
size 56431944
|
layers.py
ADDED
@@ -0,0 +1,164 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import tensorflow as tf
|
2 |
+
import tensorflow.keras.backend as K
|
3 |
+
from tensorflow.keras.layers import Conv2D, Conv2DTranspose, Dense
|
4 |
+
from tensorflow.python.eager import context
|
5 |
+
from tensorflow.python.framework import tensor_shape
|
6 |
+
from tensorflow.python.keras import activations, constraints, initializers, regularizers
|
7 |
+
from tensorflow.python.keras.layers.convolutional import SeparableConv
|
8 |
+
from tensorflow.python.ops import (
|
9 |
+
array_ops,
|
10 |
+
gen_math_ops,
|
11 |
+
math_ops,
|
12 |
+
sparse_ops,
|
13 |
+
standard_ops,
|
14 |
+
)
|
15 |
+
|
16 |
+
|
17 |
+
def l2normalize(v, eps=1e-12):
|
18 |
+
return v / (tf.norm(v) + eps)
|
19 |
+
|
20 |
+
|
21 |
+
class ConvSN2D(tf.keras.layers.Conv2D):
|
22 |
+
def __init__(self, filters, kernel_size, power_iterations=1, **kwargs):
|
23 |
+
super(ConvSN2D, self).__init__(filters, kernel_size, **kwargs)
|
24 |
+
self.power_iterations = power_iterations
|
25 |
+
|
26 |
+
def build(self, input_shape):
|
27 |
+
super(ConvSN2D, self).build(input_shape)
|
28 |
+
|
29 |
+
if self.data_format == "channels_first":
|
30 |
+
channel_axis = 1
|
31 |
+
else:
|
32 |
+
channel_axis = -1
|
33 |
+
|
34 |
+
self.u = self.add_weight(
|
35 |
+
self.name + "_u",
|
36 |
+
shape=tuple([1, self.kernel.shape.as_list()[-1]]),
|
37 |
+
initializer=tf.initializers.RandomNormal(0, 1),
|
38 |
+
trainable=False,
|
39 |
+
dtype=self.dtype,
|
40 |
+
)
|
41 |
+
|
42 |
+
def compute_spectral_norm(self, W, new_u, W_shape):
|
43 |
+
for _ in range(self.power_iterations):
|
44 |
+
|
45 |
+
new_v = l2normalize(tf.matmul(new_u, tf.transpose(W)))
|
46 |
+
new_u = l2normalize(tf.matmul(new_v, W))
|
47 |
+
|
48 |
+
sigma = tf.matmul(tf.matmul(new_v, W), tf.transpose(new_u))
|
49 |
+
W_bar = W / sigma
|
50 |
+
|
51 |
+
with tf.control_dependencies([self.u.assign(new_u)]):
|
52 |
+
W_bar = tf.reshape(W_bar, W_shape)
|
53 |
+
|
54 |
+
return W_bar
|
55 |
+
|
56 |
+
def call(self, inputs):
|
57 |
+
W_shape = self.kernel.shape.as_list()
|
58 |
+
W_reshaped = tf.reshape(self.kernel, (-1, W_shape[-1]))
|
59 |
+
new_kernel = self.compute_spectral_norm(W_reshaped, self.u, W_shape)
|
60 |
+
outputs = self._convolution_op(inputs, new_kernel)
|
61 |
+
|
62 |
+
if self.use_bias:
|
63 |
+
if self.data_format == "channels_first":
|
64 |
+
outputs = tf.nn.bias_add(outputs, self.bias, data_format="NCHW")
|
65 |
+
else:
|
66 |
+
outputs = tf.nn.bias_add(outputs, self.bias, data_format="NHWC")
|
67 |
+
if self.activation is not None:
|
68 |
+
return self.activation(outputs)
|
69 |
+
|
70 |
+
return outputs
|
71 |
+
|
72 |
+
|
73 |
+
class DenseSN(Dense):
|
74 |
+
def build(self, input_shape):
|
75 |
+
super(DenseSN, self).build(input_shape)
|
76 |
+
|
77 |
+
self.u = self.add_weight(
|
78 |
+
self.name + "_u",
|
79 |
+
shape=tuple([1, self.kernel.shape.as_list()[-1]]),
|
80 |
+
initializer=tf.initializers.RandomNormal(0, 1),
|
81 |
+
trainable=False,
|
82 |
+
dtype=self.dtype,
|
83 |
+
)
|
84 |
+
|
85 |
+
def compute_spectral_norm(self, W, new_u, W_shape):
|
86 |
+
new_v = l2normalize(tf.matmul(new_u, tf.transpose(W)))
|
87 |
+
new_u = l2normalize(tf.matmul(new_v, W))
|
88 |
+
sigma = tf.matmul(tf.matmul(new_v, W), tf.transpose(new_u))
|
89 |
+
W_bar = W / sigma
|
90 |
+
with tf.control_dependencies([self.u.assign(new_u)]):
|
91 |
+
W_bar = tf.reshape(W_bar, W_shape)
|
92 |
+
return W_bar
|
93 |
+
|
94 |
+
def call(self, inputs):
|
95 |
+
W_shape = self.kernel.shape.as_list()
|
96 |
+
W_reshaped = tf.reshape(self.kernel, (-1, W_shape[-1]))
|
97 |
+
new_kernel = self.compute_spectral_norm(W_reshaped, self.u, W_shape)
|
98 |
+
rank = len(inputs.shape)
|
99 |
+
if rank > 2:
|
100 |
+
outputs = standard_ops.tensordot(inputs, new_kernel, [[rank - 1], [0]])
|
101 |
+
if not context.executing_eagerly():
|
102 |
+
shape = inputs.shape.as_list()
|
103 |
+
output_shape = shape[:-1] + [self.units]
|
104 |
+
outputs.set_shape(output_shape)
|
105 |
+
else:
|
106 |
+
inputs = math_ops.cast(inputs, self._compute_dtype)
|
107 |
+
if K.is_sparse(inputs):
|
108 |
+
outputs = sparse_ops.sparse_tensor_dense_matmul(inputs, new_kernel)
|
109 |
+
else:
|
110 |
+
outputs = gen_math_ops.mat_mul(inputs, new_kernel)
|
111 |
+
if self.use_bias:
|
112 |
+
outputs = tf.nn.bias_add(outputs, self.bias)
|
113 |
+
if self.activation is not None:
|
114 |
+
return self.activation(outputs)
|
115 |
+
return outputs
|
116 |
+
|
117 |
+
|
118 |
+
class AddNoise(tf.keras.layers.Layer):
|
119 |
+
def build(self, input_shape):
|
120 |
+
self.b = self.add_weight(
|
121 |
+
shape=[
|
122 |
+
1,
|
123 |
+
],
|
124 |
+
initializer=tf.keras.initializers.zeros(),
|
125 |
+
trainable=True,
|
126 |
+
name="noise_weight",
|
127 |
+
)
|
128 |
+
|
129 |
+
def call(self, inputs):
|
130 |
+
rand = tf.random.normal(
|
131 |
+
[tf.shape(inputs)[0], inputs.shape[1], inputs.shape[2], 1],
|
132 |
+
mean=0.0,
|
133 |
+
stddev=1.0,
|
134 |
+
dtype=self.dtype,
|
135 |
+
)
|
136 |
+
output = inputs + self.b * rand
|
137 |
+
return output
|
138 |
+
|
139 |
+
|
140 |
+
class PosEnc(tf.keras.layers.Layer):
|
141 |
+
def __init__(self, **kwargs):
|
142 |
+
super(PosEnc, self).__init__(**kwargs)
|
143 |
+
|
144 |
+
def call(self, inputs):
|
145 |
+
# inputs shape: [bs,mel_bins,shape,1]
|
146 |
+
pos = tf.repeat(
|
147 |
+
tf.reshape(tf.range(inputs.shape[-3], dtype=tf.int32), [1, -1, 1, 1]),
|
148 |
+
inputs.shape[-2],
|
149 |
+
-2,
|
150 |
+
)
|
151 |
+
pos = tf.cast(tf.repeat(pos, tf.shape(inputs)[0], 0), self.dtype) / tf.cast(
|
152 |
+
inputs.shape[-3], self.dtype
|
153 |
+
)
|
154 |
+
return tf.concat([inputs, pos], -1) # [bs,1,hop,2]
|
155 |
+
|
156 |
+
|
157 |
+
def flatten_hw(x, data_format="channels_last"):
|
158 |
+
if data_format == "channels_last":
|
159 |
+
x = tf.transpose(x, perm=[0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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import numpy as np
|
2 |
+
import tensorflow as tf
|
3 |
+
import tensorflow_addons as tfa
|
4 |
+
from tensorflow.keras import mixed_precision
|
5 |
+
from tensorflow.keras.layers import (
|
6 |
+
Add,
|
7 |
+
BatchNormalization,
|
8 |
+
Concatenate,
|
9 |
+
Conv2D,
|
10 |
+
Conv2DTranspose,
|
11 |
+
Cropping1D,
|
12 |
+
Cropping2D,
|
13 |
+
Dense,
|
14 |
+
Dot,
|
15 |
+
Flatten,
|
16 |
+
GlobalAveragePooling2D,
|
17 |
+
Input,
|
18 |
+
Lambda,
|
19 |
+
LeakyReLU,
|
20 |
+
Multiply,
|
21 |
+
ReLU,
|
22 |
+
Reshape,
|
23 |
+
SeparableConv2D,
|
24 |
+
UpSampling2D,
|
25 |
+
ZeroPadding2D,
|
26 |
+
)
|
27 |
+
from tensorflow.keras.models import Model, Sequential
|
28 |
+
from tensorflow.keras.optimizers import Adam
|
29 |
+
from tensorflow.python.keras.utils.layer_utils import count_params
|
30 |
+
|
31 |
+
from layers import ConvSN2D, DenseSN, PosEnc, AddNoise
|
32 |
+
|
33 |
+
|
34 |
+
class Models_functions:
|
35 |
+
def __init__(self, args):
|
36 |
+
|
37 |
+
self.args = args
|
38 |
+
if self.args.mixed_precision:
|
39 |
+
self.mixed_precision = mixed_precision
|
40 |
+
self.policy = mixed_precision.Policy("mixed_float16")
|
41 |
+
mixed_precision.set_global_policy(self.policy)
|
42 |
+
self.init = tf.keras.initializers.he_uniform()
|
43 |
+
|
44 |
+
def conv_util(
|
45 |
+
self,
|
46 |
+
inp,
|
47 |
+
filters,
|
48 |
+
kernel_size=(1, 3),
|
49 |
+
strides=(1, 1),
|
50 |
+
noise=False,
|
51 |
+
upsample=False,
|
52 |
+
padding="same",
|
53 |
+
bn=True,
|
54 |
+
):
|
55 |
+
|
56 |
+
x = inp
|
57 |
+
|
58 |
+
if upsample:
|
59 |
+
x = tf.keras.layers.Conv2DTranspose(
|
60 |
+
filters,
|
61 |
+
kernel_size=kernel_size,
|
62 |
+
strides=strides,
|
63 |
+
activation="linear",
|
64 |
+
padding=padding,
|
65 |
+
kernel_initializer=self.init,
|
66 |
+
)(x)
|
67 |
+
else:
|
68 |
+
x = tf.keras.layers.Conv2D(
|
69 |
+
filters,
|
70 |
+
kernel_size=kernel_size,
|
71 |
+
strides=strides,
|
72 |
+
activation="linear",
|
73 |
+
padding=padding,
|
74 |
+
kernel_initializer=self.init,
|
75 |
+
)(x)
|
76 |
+
|
77 |
+
if noise:
|
78 |
+
x = AddNoise()(x)
|
79 |
+
|
80 |
+
if bn:
|
81 |
+
x = tf.keras.layers.BatchNormalization()(x)
|
82 |
+
|
83 |
+
x = tf.keras.activations.swish(x)
|
84 |
+
|
85 |
+
return x
|
86 |
+
|
87 |
+
def adain(self, x, emb):
|
88 |
+
emb = tf.keras.layers.Conv2D(
|
89 |
+
x.shape[-1],
|
90 |
+
kernel_size=(1, 1),
|
91 |
+
strides=1,
|
92 |
+
activation="linear",
|
93 |
+
padding="same",
|
94 |
+
kernel_initializer=self.init,
|
95 |
+
use_bias=True,
|
96 |
+
)(emb)
|
97 |
+
x = x / (tf.math.reduce_std(x, -2, keepdims=True) + 1e-7)
|
98 |
+
return x * emb
|
99 |
+
|
100 |
+
def se_layer(self, x, filters):
|
101 |
+
x = tf.reduce_mean(x, -2, keepdims=True)
|
102 |
+
x = tf.keras.layers.Conv2D(
|
103 |
+
filters,
|
104 |
+
kernel_size=(1, 1),
|
105 |
+
strides=(1, 1),
|
106 |
+
activation="linear",
|
107 |
+
padding="valid",
|
108 |
+
kernel_initializer=self.init,
|
109 |
+
use_bias=True,
|
110 |
+
)(x)
|
111 |
+
x = tf.keras.activations.swish(x)
|
112 |
+
return tf.keras.layers.Conv2D(
|
113 |
+
filters,
|
114 |
+
kernel_size=(1, 1),
|
115 |
+
strides=(1, 1),
|
116 |
+
activation="sigmoid",
|
117 |
+
padding="valid",
|
118 |
+
kernel_initializer=self.init,
|
119 |
+
use_bias=True,
|
120 |
+
)(x)
|
121 |
+
|
122 |
+
def conv_util_gen(
|
123 |
+
self,
|
124 |
+
inp,
|
125 |
+
filters,
|
126 |
+
kernel_size=(1, 9),
|
127 |
+
strides=(1, 1),
|
128 |
+
noise=False,
|
129 |
+
upsample=False,
|
130 |
+
emb=None,
|
131 |
+
se1=None,
|
132 |
+
):
|
133 |
+
|
134 |
+
x = inp
|
135 |
+
|
136 |
+
if upsample:
|
137 |
+
x = tf.keras.layers.Conv2DTranspose(
|
138 |
+
filters,
|
139 |
+
kernel_size=kernel_size,
|
140 |
+
strides=strides,
|
141 |
+
activation="linear",
|
142 |
+
padding="same",
|
143 |
+
kernel_initializer=self.init,
|
144 |
+
use_bias=True,
|
145 |
+
)(x)
|
146 |
+
else:
|
147 |
+
x = tf.keras.layers.Conv2D(
|
148 |
+
filters,
|
149 |
+
kernel_size=kernel_size,
|
150 |
+
strides=strides,
|
151 |
+
activation="linear",
|
152 |
+
padding="same",
|
153 |
+
kernel_initializer=self.init,
|
154 |
+
use_bias=True,
|
155 |
+
)(x)
|
156 |
+
|
157 |
+
if noise:
|
158 |
+
x = AddNoise()(x)
|
159 |
+
|
160 |
+
if emb is not None:
|
161 |
+
x = self.adain(x, emb)
|
162 |
+
else:
|
163 |
+
x = tf.keras.layers.BatchNormalization()(x)
|
164 |
+
|
165 |
+
x1 = tf.keras.activations.swish(x)
|
166 |
+
|
167 |
+
if se1 is not None:
|
168 |
+
x1 = x1 * se1
|
169 |
+
|
170 |
+
return x1
|
171 |
+
|
172 |
+
def res_block_disc(self, inp, filters, kernel_size=(1, 3), kernel_size_2=None, strides=(1, 1)):
|
173 |
+
|
174 |
+
if kernel_size_2 is None:
|
175 |
+
kernel_size_2 = kernel_size
|
176 |
+
|
177 |
+
x = tf.keras.layers.Conv2D(
|
178 |
+
inp.shape[-1],
|
179 |
+
kernel_size=kernel_size_2,
|
180 |
+
strides=1,
|
181 |
+
activation="linear",
|
182 |
+
padding="same",
|
183 |
+
kernel_initializer=self.init,
|
184 |
+
)(inp)
|
185 |
+
x = tf.keras.layers.LeakyReLU(0.2)(x)
|
186 |
+
x = tf.math.sqrt(tf.cast(0.5, self.args.datatype)) * x
|
187 |
+
x = tf.keras.layers.Conv2D(
|
188 |
+
filters,
|
189 |
+
kernel_size=kernel_size,
|
190 |
+
strides=strides,
|
191 |
+
activation="linear",
|
192 |
+
padding="same",
|
193 |
+
kernel_initializer=self.init,
|
194 |
+
)(x)
|
195 |
+
x = tf.keras.layers.LeakyReLU(0.2)(x)
|
196 |
+
x = tf.math.sqrt(tf.cast(0.5, self.args.datatype)) * x
|
197 |
+
|
198 |
+
if strides != (1, 1):
|
199 |
+
inp = tf.keras.layers.AveragePooling2D(strides, padding="same")(inp)
|
200 |
+
|
201 |
+
if inp.shape[-1] != filters:
|
202 |
+
inp = tf.keras.layers.Conv2D(
|
203 |
+
filters,
|
204 |
+
kernel_size=1,
|
205 |
+
strides=1,
|
206 |
+
activation="linear",
|
207 |
+
padding="same",
|
208 |
+
kernel_initializer=self.init,
|
209 |
+
use_bias=False,
|
210 |
+
)(inp)
|
211 |
+
|
212 |
+
return x + inp
|
213 |
+
|
214 |
+
def build_encoder2(self):
|
215 |
+
|
216 |
+
dim = 128
|
217 |
+
|
218 |
+
inpf = Input((1, self.args.shape, dim))
|
219 |
+
|
220 |
+
inpfls = tf.split(inpf, 16, -2)
|
221 |
+
inpb = tf.concat(inpfls, 0)
|
222 |
+
|
223 |
+
g0 = self.conv_util(inpb, 256, kernel_size=(1, 1), strides=(1, 1), padding="valid")
|
224 |
+
g1 = self.conv_util(g0, 256 + 256, kernel_size=(1, 3), strides=(1, 1), padding="valid")
|
225 |
+
g2 = self.conv_util(g1, 512 + 128, kernel_size=(1, 3), strides=(1, 1), padding="valid")
|
226 |
+
g3 = self.conv_util(g2, 512 + 128, kernel_size=(1, 1), strides=(1, 1), padding="valid")
|
227 |
+
g4 = self.conv_util(g3, 512 + 256, kernel_size=(1, 3), strides=(1, 1), padding="valid")
|
228 |
+
g5 = self.conv_util(g4, 512 + 256, kernel_size=(1, 2), strides=(1, 1), padding="valid")
|
229 |
+
|
230 |
+
g = tf.keras.layers.Conv2D(
|
231 |
+
64,
|
232 |
+
kernel_size=(1, 1),
|
233 |
+
strides=1,
|
234 |
+
padding="valid",
|
235 |
+
kernel_initializer=self.init,
|
236 |
+
name="cbottle",
|
237 |
+
activation="tanh",
|
238 |
+
)(g5)
|
239 |
+
|
240 |
+
gls = tf.split(g, 16, 0)
|
241 |
+
g = tf.concat(gls, -2)
|
242 |
+
gls = tf.split(g, 2, -2)
|
243 |
+
g = tf.concat(gls, 0)
|
244 |
+
|
245 |
+
gf = tf.cast(g, tf.float32)
|
246 |
+
return Model(inpf, gf, name="ENC2")
|
247 |
+
|
248 |
+
def build_decoder2(self):
|
249 |
+
|
250 |
+
dim = 128
|
251 |
+
bottledim = 64
|
252 |
+
|
253 |
+
inpf = Input((1, self.args.shape // 16, bottledim))
|
254 |
+
|
255 |
+
g = inpf
|
256 |
+
|
257 |
+
g = self.conv_util(
|
258 |
+
g,
|
259 |
+
512 + 128 + 128,
|
260 |
+
kernel_size=(1, 4),
|
261 |
+
strides=(1, 1),
|
262 |
+
upsample=False,
|
263 |
+
noise=True,
|
264 |
+
)
|
265 |
+
g = self.conv_util(
|
266 |
+
g,
|
267 |
+
512 + 128 + 128,
|
268 |
+
kernel_size=(1, 4),
|
269 |
+
strides=(1, 2),
|
270 |
+
upsample=True,
|
271 |
+
noise=True,
|
272 |
+
)
|
273 |
+
g = self.conv_util(g, 512 + 128, kernel_size=(1, 4), strides=(1, 2), upsample=True, noise=True)
|
274 |
+
g = self.conv_util(g, 512, kernel_size=(1, 4), strides=(1, 1), upsample=False, noise=True)
|
275 |
+
g = self.conv_util(g, 256 + 128, kernel_size=(1, 4), strides=(1, 2), upsample=True, noise=True)
|
276 |
+
|
277 |
+
gf = tf.keras.layers.Conv2D(
|
278 |
+
dim,
|
279 |
+
kernel_size=(1, 1),
|
280 |
+
strides=1,
|
281 |
+
padding="same",
|
282 |
+
activation="tanh",
|
283 |
+
kernel_initializer=self.init,
|
284 |
+
)(g)
|
285 |
+
|
286 |
+
gfls = tf.split(gf, 2, 0)
|
287 |
+
gf = tf.concat(gfls, -2)
|
288 |
+
|
289 |
+
gf = tf.cast(gf, tf.float32)
|
290 |
+
|
291 |
+
return Model(inpf, gf, name="DEC2")
|
292 |
+
|
293 |
+
def build_encoder(self):
|
294 |
+
|
295 |
+
dim = ((4 * self.args.hop) // 2) + 1
|
296 |
+
|
297 |
+
inpf = Input((dim, self.args.shape, 1))
|
298 |
+
|
299 |
+
ginp = tf.transpose(inpf, [0, 3, 2, 1])
|
300 |
+
|
301 |
+
g0 = self.conv_util(
|
302 |
+
ginp,
|
303 |
+
self.args.hop * 2 + 32,
|
304 |
+
kernel_size=(1, 1),
|
305 |
+
strides=(1, 1),
|
306 |
+
padding="valid",
|
307 |
+
)
|
308 |
+
|
309 |
+
g = self.conv_util(
|
310 |
+
g0,
|
311 |
+
self.args.hop * 2 + 64,
|
312 |
+
kernel_size=(1, 1),
|
313 |
+
strides=(1, 1),
|
314 |
+
padding="valid",
|
315 |
+
)
|
316 |
+
g = self.conv_util(
|
317 |
+
g,
|
318 |
+
self.args.hop * 2 + 64 + 64,
|
319 |
+
kernel_size=(1, 1),
|
320 |
+
strides=(1, 1),
|
321 |
+
padding="valid",
|
322 |
+
)
|
323 |
+
g = self.conv_util(
|
324 |
+
g,
|
325 |
+
self.args.hop * 2 + 128 + 64,
|
326 |
+
kernel_size=(1, 1),
|
327 |
+
strides=(1, 1),
|
328 |
+
padding="valid",
|
329 |
+
)
|
330 |
+
g = self.conv_util(
|
331 |
+
g,
|
332 |
+
self.args.hop * 2 + 128 + 128,
|
333 |
+
kernel_size=(1, 1),
|
334 |
+
strides=(1, 1),
|
335 |
+
padding="valid",
|
336 |
+
)
|
337 |
+
|
338 |
+
g = tf.keras.layers.Conv2D(
|
339 |
+
128,
|
340 |
+
kernel_size=(1, 1),
|
341 |
+
strides=1,
|
342 |
+
padding="valid",
|
343 |
+
kernel_initializer=self.init,
|
344 |
+
)(g)
|
345 |
+
gb = tf.keras.activations.tanh(g)
|
346 |
+
|
347 |
+
gbls = tf.split(gb, 2, -2)
|
348 |
+
gb = tf.concat(gbls, 0)
|
349 |
+
|
350 |
+
gb = tf.cast(gb, tf.float32)
|
351 |
+
return Model(inpf, gb, name="ENC")
|
352 |
+
|
353 |
+
def build_decoder(self):
|
354 |
+
|
355 |
+
dim = ((4 * self.args.hop) // 2) + 1
|
356 |
+
|
357 |
+
inpf = Input((1, self.args.shape // 2, 128))
|
358 |
+
|
359 |
+
g = inpf
|
360 |
+
|
361 |
+
g0 = self.conv_util(g, self.args.hop * 3, kernel_size=(1, 1), strides=(1, 1), noise=True)
|
362 |
+
|
363 |
+
g1 = self.conv_util(g0, self.args.hop * 2, kernel_size=(1, 3), strides=(1, 2), noise=True)
|
364 |
+
g2 = self.conv_util(
|
365 |
+
g1,
|
366 |
+
self.args.hop + self.args.hop // 2,
|
367 |
+
kernel_size=(1, 3),
|
368 |
+
strides=(1, 2),
|
369 |
+
noise=True,
|
370 |
+
)
|
371 |
+
g = self.conv_util(
|
372 |
+
g2,
|
373 |
+
self.args.hop + self.args.hop // 4,
|
374 |
+
kernel_size=(1, 3),
|
375 |
+
strides=(1, 2),
|
376 |
+
noise=True,
|
377 |
+
)
|
378 |
+
|
379 |
+
g = self.conv_util(
|
380 |
+
g,
|
381 |
+
self.args.hop + self.args.hop // 2,
|
382 |
+
kernel_size=(1, 4),
|
383 |
+
strides=(1, 2),
|
384 |
+
upsample=True,
|
385 |
+
noise=True,
|
386 |
+
)
|
387 |
+
g = self.conv_util(
|
388 |
+
g + g2,
|
389 |
+
self.args.hop * 2,
|
390 |
+
kernel_size=(1, 4),
|
391 |
+
strides=(1, 2),
|
392 |
+
upsample=True,
|
393 |
+
noise=True,
|
394 |
+
)
|
395 |
+
g = self.conv_util(
|
396 |
+
g + g1,
|
397 |
+
self.args.hop * 3,
|
398 |
+
kernel_size=(1, 4),
|
399 |
+
strides=(1, 2),
|
400 |
+
upsample=True,
|
401 |
+
noise=True,
|
402 |
+
)
|
403 |
+
|
404 |
+
g = self.conv_util(g + g0, self.args.hop * 5, kernel_size=(1, 1), strides=(1, 1), noise=True)
|
405 |
+
|
406 |
+
g = Conv2D(
|
407 |
+
dim * 2,
|
408 |
+
kernel_size=(1, 1),
|
409 |
+
strides=(1, 1),
|
410 |
+
kernel_initializer=self.init,
|
411 |
+
padding="same",
|
412 |
+
)(g)
|
413 |
+
g = tf.clip_by_value(g, -1.0, 1.0)
|
414 |
+
|
415 |
+
gf, pf = tf.split(g, 2, -1)
|
416 |
+
|
417 |
+
gfls = tf.split(gf, self.args.shape // self.args.window, 0)
|
418 |
+
gf = tf.concat(gfls, -2)
|
419 |
+
|
420 |
+
pfls = tf.split(pf, self.args.shape // self.args.window, 0)
|
421 |
+
pf = tf.concat(pfls, -2)
|
422 |
+
|
423 |
+
s = tf.transpose(gf, [0, 2, 3, 1])
|
424 |
+
p = tf.transpose(pf, [0, 2, 3, 1])
|
425 |
+
|
426 |
+
s = tf.cast(tf.squeeze(s, -1), tf.float32)
|
427 |
+
p = tf.cast(tf.squeeze(p, -1), tf.float32)
|
428 |
+
|
429 |
+
return Model(inpf, [s, p], name="DEC")
|
430 |
+
|
431 |
+
def build_critic(self):
|
432 |
+
|
433 |
+
sinp = Input(shape=(1, self.args.latlen, self.args.latdepth * 2))
|
434 |
+
|
435 |
+
dim = 64 * 2
|
436 |
+
|
437 |
+
sf = tf.keras.layers.Conv2D(
|
438 |
+
self.args.latdepth * 4,
|
439 |
+
kernel_size=(1, 1),
|
440 |
+
strides=(1, 1),
|
441 |
+
activation="linear",
|
442 |
+
padding="valid",
|
443 |
+
kernel_initializer=self.init,
|
444 |
+
use_bias=False,
|
445 |
+
trainable=False,
|
446 |
+
)(sinp)
|
447 |
+
|
448 |
+
sf = tf.keras.layers.Conv2D(
|
449 |
+
256 + 128,
|
450 |
+
kernel_size=(1, 3),
|
451 |
+
strides=(1, 2),
|
452 |
+
activation="linear",
|
453 |
+
padding="same",
|
454 |
+
kernel_initializer=self.init,
|
455 |
+
)(sf)
|
456 |
+
sf = tf.keras.layers.LeakyReLU(0.2)(sf)
|
457 |
+
sf = self.res_block_disc(sf, 256 + 128 + 128, kernel_size=(1, 3), strides=(1, 2))
|
458 |
+
sf = self.res_block_disc(sf, 512 + 128, kernel_size=(1, 3), strides=(1, 2))
|
459 |
+
sf = self.res_block_disc(sf, 512 + 256, kernel_size=(1, 3), strides=(1, 2))
|
460 |
+
sf = self.res_block_disc(sf, 512 + 128 + 256, kernel_size=(1, 3), strides=(1, 2))
|
461 |
+
sfo = self.res_block_disc(sf, 512 + 512, kernel_size=(1, 3), strides=(1, 2), kernel_size_2=(1, 1))
|
462 |
+
sf = sfo
|
463 |
+
|
464 |
+
gf = tf.keras.layers.Dense(1, activation="linear", use_bias=True, kernel_initializer=self.init)(Flatten()(sf))
|
465 |
+
|
466 |
+
gf = tf.cast(gf, tf.float32)
|
467 |
+
sfo = tf.cast(sfo, tf.float32)
|
468 |
+
|
469 |
+
return Model(sinp, [gf, sfo], name="C")
|
470 |
+
|
471 |
+
def build_critic_rec(self):
|
472 |
+
|
473 |
+
sinp = Input(shape=(1, self.args.latlen // 64, 512 + 512))
|
474 |
+
|
475 |
+
dim = self.args.latdepth * 2
|
476 |
+
|
477 |
+
sf = tf.keras.layers.Conv2DTranspose(
|
478 |
+
512,
|
479 |
+
kernel_size=(1, 4),
|
480 |
+
strides=(1, 2),
|
481 |
+
activation="linear",
|
482 |
+
padding="same",
|
483 |
+
kernel_initializer=self.init,
|
484 |
+
)(sinp)
|
485 |
+
sf = tf.keras.layers.LeakyReLU(0.2)(sf)
|
486 |
+
|
487 |
+
sf = tf.keras.layers.Conv2DTranspose(
|
488 |
+
256 + 128 + 64,
|
489 |
+
kernel_size=(1, 4),
|
490 |
+
strides=(1, 2),
|
491 |
+
activation="linear",
|
492 |
+
padding="same",
|
493 |
+
kernel_initializer=self.init,
|
494 |
+
)(sf)
|
495 |
+
sf = tf.keras.layers.LeakyReLU(0.2)(sf)
|
496 |
+
sf = tf.keras.layers.Conv2DTranspose(
|
497 |
+
256 + 128,
|
498 |
+
kernel_size=(1, 4),
|
499 |
+
strides=(1, 2),
|
500 |
+
activation="linear",
|
501 |
+
padding="same",
|
502 |
+
kernel_initializer=self.init,
|
503 |
+
)(sf)
|
504 |
+
sf = tf.keras.layers.LeakyReLU(0.2)(sf)
|
505 |
+
sf = tf.keras.layers.Conv2DTranspose(
|
506 |
+
256 + 64,
|
507 |
+
kernel_size=(1, 4),
|
508 |
+
strides=(1, 2),
|
509 |
+
activation="linear",
|
510 |
+
padding="same",
|
511 |
+
kernel_initializer=self.init,
|
512 |
+
)(sf)
|
513 |
+
sf = tf.keras.layers.LeakyReLU(0.2)(sf)
|
514 |
+
sf = tf.keras.layers.Conv2DTranspose(
|
515 |
+
256,
|
516 |
+
kernel_size=(1, 4),
|
517 |
+
strides=(1, 2),
|
518 |
+
activation="linear",
|
519 |
+
padding="same",
|
520 |
+
kernel_initializer=self.init,
|
521 |
+
)(sf)
|
522 |
+
sf = tf.keras.layers.LeakyReLU(0.2)(sf)
|
523 |
+
sf = tf.keras.layers.Conv2DTranspose(
|
524 |
+
128 + 64,
|
525 |
+
kernel_size=(1, 4),
|
526 |
+
strides=(1, 2),
|
527 |
+
activation="linear",
|
528 |
+
padding="same",
|
529 |
+
kernel_initializer=self.init,
|
530 |
+
)(sf)
|
531 |
+
sf = tf.keras.layers.LeakyReLU(0.2)(sf)
|
532 |
+
|
533 |
+
gf = tf.keras.layers.Conv2D(
|
534 |
+
dim,
|
535 |
+
kernel_size=(1, 1),
|
536 |
+
strides=(1, 1),
|
537 |
+
activation="tanh",
|
538 |
+
padding="same",
|
539 |
+
kernel_initializer=self.init,
|
540 |
+
)(sf)
|
541 |
+
|
542 |
+
gf = tf.cast(gf, tf.float32)
|
543 |
+
|
544 |
+
return Model(sinp, gf, name="CR")
|
545 |
+
|
546 |
+
def build_generator(self):
|
547 |
+
|
548 |
+
dim = self.args.latdepth * 2
|
549 |
+
|
550 |
+
inpf = Input((self.args.latlen, self.args.latdepth * 2))
|
551 |
+
|
552 |
+
inpfls = tf.split(inpf, 2, -2)
|
553 |
+
inpb = tf.concat(inpfls, 0)
|
554 |
+
|
555 |
+
inpg = tf.reduce_mean(inpb, -2)
|
556 |
+
inp1 = tf.keras.layers.AveragePooling2D((1, 2), padding="valid")(tf.expand_dims(inpb, -3))
|
557 |
+
inp2 = tf.keras.layers.AveragePooling2D((1, 2), padding="valid")(inp1)
|
558 |
+
inp3 = tf.keras.layers.AveragePooling2D((1, 2), padding="valid")(inp2)
|
559 |
+
inp4 = tf.keras.layers.AveragePooling2D((1, 2), padding="valid")(inp3)
|
560 |
+
inp5 = tf.keras.layers.AveragePooling2D((1, 2), padding="valid")(inp4)
|
561 |
+
inp6 = tf.keras.layers.AveragePooling2D((1, 2), padding="valid")(inp5)
|
562 |
+
|
563 |
+
g = tf.keras.layers.Dense(
|
564 |
+
4 * (512 + 256 + 128),
|
565 |
+
activation="linear",
|
566 |
+
use_bias=True,
|
567 |
+
kernel_initializer=self.init,
|
568 |
+
)(Flatten()(inp6))
|
569 |
+
g = tf.keras.layers.Reshape((1, 4, 512 + 256 + 128))(g)
|
570 |
+
g = AddNoise()(g)
|
571 |
+
g = self.adain(g, inp5)
|
572 |
+
g = tf.keras.activations.swish(g)
|
573 |
+
|
574 |
+
g = self.conv_util_gen(
|
575 |
+
g,
|
576 |
+
512 + 256,
|
577 |
+
kernel_size=(1, 4),
|
578 |
+
strides=(1, 2),
|
579 |
+
upsample=True,
|
580 |
+
noise=True,
|
581 |
+
emb=inp4,
|
582 |
+
)
|
583 |
+
g1 = self.conv_util_gen(
|
584 |
+
g,
|
585 |
+
512 + 256,
|
586 |
+
kernel_size=(1, 1),
|
587 |
+
strides=(1, 1),
|
588 |
+
upsample=False,
|
589 |
+
noise=True,
|
590 |
+
emb=inp4,
|
591 |
+
)
|
592 |
+
g2 = self.conv_util_gen(
|
593 |
+
g1,
|
594 |
+
512 + 128,
|
595 |
+
kernel_size=(1, 4),
|
596 |
+
strides=(1, 2),
|
597 |
+
upsample=True,
|
598 |
+
noise=True,
|
599 |
+
emb=inp3,
|
600 |
+
)
|
601 |
+
g2b = self.conv_util_gen(
|
602 |
+
g2,
|
603 |
+
512 + 128,
|
604 |
+
kernel_size=(1, 3),
|
605 |
+
strides=(1, 1),
|
606 |
+
upsample=False,
|
607 |
+
noise=True,
|
608 |
+
emb=inp3,
|
609 |
+
)
|
610 |
+
g3 = self.conv_util_gen(
|
611 |
+
g2b,
|
612 |
+
256 + 256,
|
613 |
+
kernel_size=(1, 4),
|
614 |
+
strides=(1, 2),
|
615 |
+
upsample=True,
|
616 |
+
noise=True,
|
617 |
+
emb=inp2,
|
618 |
+
se1=self.se_layer(g, 256 + 256),
|
619 |
+
)
|
620 |
+
g3 = self.conv_util_gen(
|
621 |
+
g3,
|
622 |
+
256 + 256,
|
623 |
+
kernel_size=(1, 3),
|
624 |
+
strides=(1, 1),
|
625 |
+
upsample=False,
|
626 |
+
noise=True,
|
627 |
+
emb=inp2,
|
628 |
+
se1=self.se_layer(g1, 256 + 256),
|
629 |
+
)
|
630 |
+
g4 = self.conv_util_gen(
|
631 |
+
g3,
|
632 |
+
256 + 128,
|
633 |
+
kernel_size=(1, 4),
|
634 |
+
strides=(1, 2),
|
635 |
+
upsample=True,
|
636 |
+
noise=True,
|
637 |
+
emb=inp1,
|
638 |
+
se1=self.se_layer(g2, 256 + 128),
|
639 |
+
)
|
640 |
+
g4 = self.conv_util_gen(
|
641 |
+
g4,
|
642 |
+
256 + 128,
|
643 |
+
kernel_size=(1, 3),
|
644 |
+
strides=(1, 1),
|
645 |
+
upsample=False,
|
646 |
+
noise=True,
|
647 |
+
emb=inp1,
|
648 |
+
se1=self.se_layer(g2b, 256 + 128),
|
649 |
+
)
|
650 |
+
g5 = self.conv_util_gen(
|
651 |
+
g4,
|
652 |
+
256,
|
653 |
+
kernel_size=(1, 4),
|
654 |
+
strides=(1, 2),
|
655 |
+
upsample=True,
|
656 |
+
noise=True,
|
657 |
+
emb=tf.expand_dims(tf.cast(inpb, dtype=self.args.datatype), -3),
|
658 |
+
)
|
659 |
+
|
660 |
+
gf = tf.keras.layers.Conv2D(
|
661 |
+
dim,
|
662 |
+
kernel_size=(1, 1),
|
663 |
+
strides=(1, 1),
|
664 |
+
kernel_initializer=self.init,
|
665 |
+
padding="same",
|
666 |
+
activation="tanh",
|
667 |
+
)(g5)
|
668 |
+
|
669 |
+
gfls = tf.split(gf, 2, 0)
|
670 |
+
gf = tf.concat(gfls, -2)
|
671 |
+
|
672 |
+
gf = tf.cast(gf, tf.float32)
|
673 |
+
|
674 |
+
return Model(inpf, gf, name="GEN")
|
675 |
+
|
676 |
+
# Load past models from path to resume training or test
|
677 |
+
def load(self, path, load_dec=False):
|
678 |
+
gen = self.build_generator()
|
679 |
+
critic = self.build_critic()
|
680 |
+
enc = self.build_encoder()
|
681 |
+
dec = self.build_decoder()
|
682 |
+
enc2 = self.build_encoder2()
|
683 |
+
dec2 = self.build_decoder2()
|
684 |
+
critic_rec = self.build_critic_rec()
|
685 |
+
gen_ema = self.build_generator()
|
686 |
+
|
687 |
+
if self.args.mixed_precision:
|
688 |
+
opt_disc = self.mixed_precision.LossScaleOptimizer(tf.keras.optimizers.Adam(0.0001, 0.9))
|
689 |
+
opt_dec = self.mixed_precision.LossScaleOptimizer(tf.keras.optimizers.Adam(0.0001, 0.9))
|
690 |
+
else:
|
691 |
+
opt_disc = tf.keras.optimizers.Adam(0.0001, 0.9)
|
692 |
+
opt_dec = tf.keras.optimizers.Adam(0.0001, 0.9)
|
693 |
+
|
694 |
+
if load_dec:
|
695 |
+
dec.load_weights(self.args.dec_path + "/dec.h5")
|
696 |
+
dec2.load_weights(self.args.dec_path + "/dec2.h5")
|
697 |
+
|
698 |
+
else:
|
699 |
+
grad_vars = critic.trainable_weights + critic_rec.trainable_weights
|
700 |
+
zero_grads = [tf.zeros_like(w) for w in grad_vars]
|
701 |
+
opt_disc.apply_gradients(zip(zero_grads, grad_vars))
|
702 |
+
|
703 |
+
grad_vars = gen.trainable_variables
|
704 |
+
zero_grads = [tf.zeros_like(w) for w in grad_vars]
|
705 |
+
opt_dec.apply_gradients(zip(zero_grads, grad_vars))
|
706 |
+
|
707 |
+
if not self.args.testing:
|
708 |
+
opt_disc.set_weights(np.load(path + "/opt_disc.npy", allow_pickle=True))
|
709 |
+
opt_dec.set_weights(np.load(path + "/opt_dec.npy", allow_pickle=True))
|
710 |
+
|
711 |
+
if not self.args.testing:
|
712 |
+
critic.load_weights(path + "/critic.h5")
|
713 |
+
gen.load_weights(path + "/gen.h5")
|
714 |
+
enc.load_weights(path + "/enc.h5")
|
715 |
+
enc2.load_weights(path + "/enc2.h5")
|
716 |
+
critic_rec.load_weights(path + "/critic_rec.h5")
|
717 |
+
gen_ema.load_weights(path + "/gen_ema.h5")
|
718 |
+
dec.load_weights(path + "/dec.h5")
|
719 |
+
dec2.load_weights(path + "/dec2.h5")
|
720 |
+
|
721 |
+
return (
|
722 |
+
critic,
|
723 |
+
gen,
|
724 |
+
enc,
|
725 |
+
dec,
|
726 |
+
enc2,
|
727 |
+
dec2,
|
728 |
+
critic_rec,
|
729 |
+
gen_ema,
|
730 |
+
[opt_dec, opt_disc],
|
731 |
+
)
|
732 |
+
|
733 |
+
def build(self):
|
734 |
+
gen = self.build_generator()
|
735 |
+
critic = self.build_critic()
|
736 |
+
enc = self.build_encoder()
|
737 |
+
dec = self.build_decoder()
|
738 |
+
enc2 = self.build_encoder2()
|
739 |
+
dec2 = self.build_decoder2()
|
740 |
+
critic_rec = self.build_critic_rec()
|
741 |
+
gen_ema = self.build_generator()
|
742 |
+
|
743 |
+
gen_ema = tf.keras.models.clone_model(gen)
|
744 |
+
gen_ema.set_weights(gen.get_weights())
|
745 |
+
|
746 |
+
if self.args.mixed_precision:
|
747 |
+
opt_disc = self.mixed_precision.LossScaleOptimizer(tf.keras.optimizers.Adam(0.0001, 0.9))
|
748 |
+
opt_dec = self.mixed_precision.LossScaleOptimizer(tf.keras.optimizers.Adam(0.0001, 0.9))
|
749 |
+
else:
|
750 |
+
opt_disc = tf.keras.optimizers.Adam(0.0001, 0.9)
|
751 |
+
opt_dec = tf.keras.optimizers.Adam(0.0001, 0.9)
|
752 |
+
|
753 |
+
return (
|
754 |
+
critic,
|
755 |
+
gen,
|
756 |
+
enc,
|
757 |
+
dec,
|
758 |
+
enc2,
|
759 |
+
dec2,
|
760 |
+
critic_rec,
|
761 |
+
gen_ema,
|
762 |
+
[opt_dec, opt_disc],
|
763 |
+
)
|
764 |
+
|
765 |
+
def get_networks(self):
|
766 |
+
(
|
767 |
+
critic,
|
768 |
+
gen,
|
769 |
+
enc,
|
770 |
+
dec_techno,
|
771 |
+
enc2,
|
772 |
+
dec2_techno,
|
773 |
+
critic_rec,
|
774 |
+
gen_ema_techno,
|
775 |
+
[opt_dec, opt_disc],
|
776 |
+
) = self.load(self.args.load_path_techno, load_dec=False)
|
777 |
+
print(f"Techno networks loaded from {self.args.load_path_techno}")
|
778 |
+
|
779 |
+
(
|
780 |
+
critic,
|
781 |
+
gen,
|
782 |
+
enc,
|
783 |
+
dec_classical,
|
784 |
+
enc2,
|
785 |
+
dec2_classical,
|
786 |
+
critic_rec,
|
787 |
+
gen_ema_classical,
|
788 |
+
[opt_dec, opt_disc],
|
789 |
+
) = self.load(self.args.load_path_classical, load_dec=False)
|
790 |
+
print(f"Classical networks loaded from {self.args.load_path_classical}")
|
791 |
+
|
792 |
+
return [critic, gen, enc, dec_techno, enc2, dec2_techno, critic_rec, gen_ema_techno, [opt_dec, opt_disc]], [
|
793 |
+
critic,
|
794 |
+
gen,
|
795 |
+
enc,
|
796 |
+
dec_classical,
|
797 |
+
enc2,
|
798 |
+
dec2_classical,
|
799 |
+
critic_rec,
|
800 |
+
gen_ema_classical,
|
801 |
+
[opt_dec, opt_disc],
|
802 |
+
]
|
803 |
+
|
804 |
+
def initialize_networks(self):
|
805 |
+
|
806 |
+
[critic, gen, enc, dec_techno, enc2, dec2_techno, critic_rec, gen_ema_techno, [opt_dec, opt_disc]], [
|
807 |
+
critic,
|
808 |
+
gen,
|
809 |
+
enc,
|
810 |
+
dec_classical,
|
811 |
+
enc2,
|
812 |
+
dec2_classical,
|
813 |
+
critic_rec,
|
814 |
+
gen_ema_classical,
|
815 |
+
[opt_dec, opt_disc],
|
816 |
+
] = self.get_networks()
|
817 |
+
|
818 |
+
print(f"Generator params: {count_params(gen_ema_techno.trainable_variables)}")
|
819 |
+
print(f"Decoder params: {count_params(dec_techno.trainable_variables+dec2_techno.trainable_variables)}")
|
820 |
+
|
821 |
+
return [critic, gen, enc, dec_techno, enc2, dec2_techno, critic_rec, gen_ema_techno, [opt_dec, opt_disc]], [
|
822 |
+
critic,
|
823 |
+
gen,
|
824 |
+
enc,
|
825 |
+
dec_classical,
|
826 |
+
enc2,
|
827 |
+
dec2_classical,
|
828 |
+
critic_rec,
|
829 |
+
gen_ema_classical,
|
830 |
+
[opt_dec, opt_disc],
|
831 |
+
]
|
musika.py
ADDED
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from parse_test import parse_args
|
2 |
+
from models import Models_functions
|
3 |
+
from utils import Utils_functions
|
4 |
+
import os
|
5 |
+
|
6 |
+
if __name__ == "__main__":
|
7 |
+
|
8 |
+
# parse args
|
9 |
+
args = parse_args()
|
10 |
+
|
11 |
+
# initialize networks
|
12 |
+
M = Models_functions(args)
|
13 |
+
models_ls_techno, models_ls_classical = M.get_networks()
|
14 |
+
|
15 |
+
# test musika
|
16 |
+
U = Utils_functions(args)
|
17 |
+
U.render_gradio(models_ls_techno, models_ls_classical, train=False)
|
parse_test.py
ADDED
@@ -0,0 +1,165 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import argparse
|
2 |
+
from typing import Any
|
3 |
+
import tensorflow as tf
|
4 |
+
|
5 |
+
|
6 |
+
class EasyDict(dict):
|
7 |
+
def __getattr__(self, name: str) -> Any:
|
8 |
+
try:
|
9 |
+
return self[name]
|
10 |
+
except KeyError:
|
11 |
+
raise AttributeError(name)
|
12 |
+
|
13 |
+
def __setattr__(self, name: str, value: Any) -> None:
|
14 |
+
self[name] = value
|
15 |
+
|
16 |
+
def __delattr__(self, name: str) -> None:
|
17 |
+
del self[name]
|
18 |
+
|
19 |
+
|
20 |
+
def params_args(args):
|
21 |
+
parser = argparse.ArgumentParser()
|
22 |
+
|
23 |
+
parser.add_argument(
|
24 |
+
"--hop",
|
25 |
+
type=int,
|
26 |
+
default=256,
|
27 |
+
help="Hop size (window size = 4*hop)",
|
28 |
+
)
|
29 |
+
parser.add_argument(
|
30 |
+
"--mel_bins",
|
31 |
+
type=int,
|
32 |
+
default=256,
|
33 |
+
help="Mel bins in mel-spectrograms",
|
34 |
+
)
|
35 |
+
parser.add_argument(
|
36 |
+
"--sr",
|
37 |
+
type=int,
|
38 |
+
default=22050,
|
39 |
+
help="Sampling Rate",
|
40 |
+
)
|
41 |
+
parser.add_argument(
|
42 |
+
"--latlen",
|
43 |
+
type=int,
|
44 |
+
default=256,
|
45 |
+
help="Length of generated latent vectors",
|
46 |
+
)
|
47 |
+
parser.add_argument(
|
48 |
+
"--latdepth",
|
49 |
+
type=int,
|
50 |
+
default=64,
|
51 |
+
help="Depth of generated latent vectors",
|
52 |
+
)
|
53 |
+
parser.add_argument(
|
54 |
+
"--shape",
|
55 |
+
type=int,
|
56 |
+
default=128,
|
57 |
+
help="Length of spectrograms time axis",
|
58 |
+
)
|
59 |
+
parser.add_argument(
|
60 |
+
"--window",
|
61 |
+
type=int,
|
62 |
+
default=64,
|
63 |
+
help="Generator spectrogram window (must divide shape)",
|
64 |
+
)
|
65 |
+
parser.add_argument(
|
66 |
+
"--mu_rescale",
|
67 |
+
type=int,
|
68 |
+
default=-25.0,
|
69 |
+
help="Spectrogram mu used to normalize",
|
70 |
+
)
|
71 |
+
parser.add_argument(
|
72 |
+
"--sigma_rescale",
|
73 |
+
type=int,
|
74 |
+
default=75.0,
|
75 |
+
help="Spectrogram sigma used to normalize",
|
76 |
+
)
|
77 |
+
parser.add_argument(
|
78 |
+
"--load_path_techno",
|
79 |
+
type=str,
|
80 |
+
default="checkpoints/techno/",
|
81 |
+
help="Path of pretrained networks weights (techno)",
|
82 |
+
)
|
83 |
+
parser.add_argument(
|
84 |
+
"--load_path_classical",
|
85 |
+
type=str,
|
86 |
+
default="checkpoints/classical/",
|
87 |
+
help="Path of pretrained networks weights (classical)",
|
88 |
+
)
|
89 |
+
parser.add_argument(
|
90 |
+
"--dec_path_techno",
|
91 |
+
type=str,
|
92 |
+
default="checkpoints/techno/",
|
93 |
+
help="Path of pretrained decoders weights (techno)",
|
94 |
+
)
|
95 |
+
parser.add_argument(
|
96 |
+
"--dec_path_classical",
|
97 |
+
type=str,
|
98 |
+
default="checkpoints/classical/",
|
99 |
+
help="Path of pretrained decoders weights (classical)",
|
100 |
+
)
|
101 |
+
parser.add_argument(
|
102 |
+
"--testing",
|
103 |
+
type=bool,
|
104 |
+
default=True,
|
105 |
+
help="True if optimizers weight do not need to be loaded",
|
106 |
+
)
|
107 |
+
parser.add_argument(
|
108 |
+
"--cpu",
|
109 |
+
type=bool,
|
110 |
+
default=False,
|
111 |
+
help="True if you wish to use cpu",
|
112 |
+
)
|
113 |
+
parser.add_argument(
|
114 |
+
"--mixed_precision",
|
115 |
+
type=bool,
|
116 |
+
default=True,
|
117 |
+
help="True if your GPU supports mixed precision",
|
118 |
+
)
|
119 |
+
|
120 |
+
tmp_args = parser.parse_args()
|
121 |
+
|
122 |
+
args.hop = tmp_args.hop
|
123 |
+
args.mel_bins = tmp_args.mel_bins
|
124 |
+
args.sr = tmp_args.sr
|
125 |
+
args.latlen = tmp_args.latlen
|
126 |
+
args.latdepth = tmp_args.latdepth
|
127 |
+
args.shape = tmp_args.shape
|
128 |
+
args.window = tmp_args.window
|
129 |
+
args.mu_rescale = tmp_args.mu_rescale
|
130 |
+
args.sigma_rescale = tmp_args.sigma_rescale
|
131 |
+
args.load_path_techno = tmp_args.load_path_techno
|
132 |
+
args.load_path_classical = tmp_args.load_path_classical
|
133 |
+
args.dec_path_techno = tmp_args.dec_path_techno
|
134 |
+
args.dec_path_classical = tmp_args.dec_path_classical
|
135 |
+
args.testing = tmp_args.testing
|
136 |
+
args.cpu = tmp_args.cpu
|
137 |
+
args.mixed_precision = tmp_args.mixed_precision
|
138 |
+
|
139 |
+
print()
|
140 |
+
|
141 |
+
args.datatype = tf.float32
|
142 |
+
gpuls = tf.config.list_physical_devices("GPU")
|
143 |
+
if len(gpuls) == 0 or args.cpu:
|
144 |
+
args.cpu = True
|
145 |
+
args.mixed_precision = False
|
146 |
+
tf.config.set_visible_devices([], "GPU")
|
147 |
+
print()
|
148 |
+
print("Using CPU...")
|
149 |
+
print()
|
150 |
+
if args.mixed_precision:
|
151 |
+
args.datatype = tf.float16
|
152 |
+
print()
|
153 |
+
print("Using GPU with mixed precision enabled...")
|
154 |
+
print()
|
155 |
+
if not args.mixed_precision and not args.cpu:
|
156 |
+
print()
|
157 |
+
print("Using GPU without mixed precision...")
|
158 |
+
print()
|
159 |
+
|
160 |
+
return args
|
161 |
+
|
162 |
+
|
163 |
+
def parse_args():
|
164 |
+
args = EasyDict()
|
165 |
+
return params_args(args)
|
requirements.txt
ADDED
@@ -0,0 +1,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# This file may be used to create an environment using:
|
2 |
+
# $ conda create --name <env> --file <this file>
|
3 |
+
# platform: linux-64
|
4 |
+
audioread==2.1.9
|
5 |
+
gradio==2.5.2
|
6 |
+
ipython==7.29.0
|
7 |
+
librosa==0.8.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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import io
|
2 |
+
import os
|
3 |
+
import random
|
4 |
+
import time
|
5 |
+
from glob import glob
|
6 |
+
|
7 |
+
import IPython
|
8 |
+
import librosa
|
9 |
+
import matplotlib.pyplot as plt
|
10 |
+
import numpy as np
|
11 |
+
import soundfile as sf
|
12 |
+
import tensorflow as tf
|
13 |
+
import tensorflow_io as tfio
|
14 |
+
|
15 |
+
from tensorflow.keras import mixed_precision
|
16 |
+
from tensorflow.keras.optimizers import Adam
|
17 |
+
from tensorflow.python.framework import random_seed
|
18 |
+
from tqdm import tqdm
|
19 |
+
import gradio as gr
|
20 |
+
from scipy.io.wavfile import write as write_wav
|
21 |
+
|
22 |
+
|
23 |
+
class Utils_functions:
|
24 |
+
def __init__(self, args):
|
25 |
+
|
26 |
+
self.args = args
|
27 |
+
|
28 |
+
melmat = tf.signal.linear_to_mel_weight_matrix(
|
29 |
+
num_mel_bins=args.mel_bins,
|
30 |
+
num_spectrogram_bins=(4 * args.hop) // 2 + 1,
|
31 |
+
sample_rate=args.sr,
|
32 |
+
lower_edge_hertz=0.0,
|
33 |
+
upper_edge_hertz=args.sr // 2,
|
34 |
+
)
|
35 |
+
mel_f = tf.convert_to_tensor(librosa.mel_frequencies(n_mels=args.mel_bins + 2, fmin=0.0, fmax=args.sr // 2))
|
36 |
+
enorm = tf.cast(
|
37 |
+
tf.expand_dims(
|
38 |
+
tf.constant(2.0 / (mel_f[2 : args.mel_bins + 2] - mel_f[: args.mel_bins])),
|
39 |
+
0,
|
40 |
+
),
|
41 |
+
tf.float32,
|
42 |
+
)
|
43 |
+
melmat = tf.multiply(melmat, enorm)
|
44 |
+
melmat = tf.divide(melmat, tf.reduce_sum(melmat, axis=0))
|
45 |
+
self.melmat = tf.where(tf.math.is_nan(melmat), tf.zeros_like(melmat), melmat)
|
46 |
+
|
47 |
+
with np.errstate(divide="ignore", invalid="ignore"):
|
48 |
+
self.melmatinv = tf.constant(np.nan_to_num(np.divide(melmat.numpy().T, np.sum(melmat.numpy(), axis=1))).T)
|
49 |
+
|
50 |
+
def conc_tog_specphase(self, S, P):
|
51 |
+
S = tf.cast(S, tf.float32)
|
52 |
+
P = tf.cast(P, tf.float32)
|
53 |
+
S = self.denormalize(S, clip=False)
|
54 |
+
S = tf.math.sqrt(self.db2power(S) + 1e-7)
|
55 |
+
P = P * np.pi
|
56 |
+
Sls = tf.split(S, S.shape[0], 0)
|
57 |
+
S = tf.squeeze(tf.concat(Sls, 1), 0)
|
58 |
+
Pls = tf.split(P, P.shape[0], 0)
|
59 |
+
P = tf.squeeze(tf.concat(Pls, 1), 0)
|
60 |
+
SP = tf.cast(S, tf.complex64) * tf.math.exp(1j * tf.cast(P, tf.complex64))
|
61 |
+
wv = tf.signal.inverse_stft(
|
62 |
+
SP,
|
63 |
+
4 * self.args.hop,
|
64 |
+
self.args.hop,
|
65 |
+
fft_length=4 * self.args.hop,
|
66 |
+
window_fn=tf.signal.inverse_stft_window_fn(self.args.hop),
|
67 |
+
)
|
68 |
+
return np.squeeze(wv)
|
69 |
+
|
70 |
+
def _tf_log10(self, x):
|
71 |
+
numerator = tf.math.log(x)
|
72 |
+
denominator = tf.math.log(tf.constant(10, dtype=numerator.dtype))
|
73 |
+
return numerator / denominator
|
74 |
+
|
75 |
+
def normalize(self, S, clip=False):
|
76 |
+
S = (S - self.args.mu_rescale) / self.args.sigma_rescale
|
77 |
+
if clip:
|
78 |
+
S = tf.clip_by_value(S, -1.0, 1.0)
|
79 |
+
return S
|
80 |
+
|
81 |
+
def normalize_rel(self, S):
|
82 |
+
S = S - tf.math.reduce_min(S + 1e-7)
|
83 |
+
S = (S / (tf.math.reduce_max(S + 1e-7) + 1e-7)) + 1e-7
|
84 |
+
return S
|
85 |
+
|
86 |
+
def denormalize(self, S, clip=False):
|
87 |
+
if clip:
|
88 |
+
S = tf.clip_by_value(S, -1.0, 1.0)
|
89 |
+
return (S * self.args.sigma_rescale) + self.args.mu_rescale
|
90 |
+
|
91 |
+
def amp2db(self, x):
|
92 |
+
return 20 * self._tf_log10(tf.clip_by_value(tf.abs(x), 1e-5, 1e100))
|
93 |
+
|
94 |
+
def db2amp(self, x):
|
95 |
+
return tf.pow(tf.ones(tf.shape(x)) * 10.0, x * 0.05)
|
96 |
+
|
97 |
+
def power2db(self, power, ref_value=1.0, amin=1e-10, top_db=None, norm=False):
|
98 |
+
log_spec = 10.0 * self._tf_log10(tf.maximum(amin, power))
|
99 |
+
log_spec -= 10.0 * self._tf_log10(tf.maximum(amin, ref_value))
|
100 |
+
if top_db is not None:
|
101 |
+
log_spec = tf.maximum(log_spec, tf.reduce_max(log_spec) - top_db)
|
102 |
+
return log_spec
|
103 |
+
|
104 |
+
def power2db_batch(self, power, ref_value=1.0, amin=1e-10, top_db=None, norm=False):
|
105 |
+
log_spec = 10.0 * self._tf_log10(tf.maximum(amin, power))
|
106 |
+
log_spec -= 10.0 * self._tf_log10(tf.maximum(amin, ref_value))
|
107 |
+
if top_db is not None:
|
108 |
+
log_spec = tf.maximum(log_spec, tf.reduce_max(log_spec, [-2, -1], keepdims=True) - top_db)
|
109 |
+
return log_spec
|
110 |
+
|
111 |
+
def db2power(self, S_db, ref=1.0):
|
112 |
+
return ref * tf.math.pow(10.0, 0.1 * S_db)
|
113 |
+
|
114 |
+
def wv2mel(self, wv, topdb=80.0):
|
115 |
+
X = tf.signal.stft(
|
116 |
+
wv,
|
117 |
+
frame_length=4 * self.args.hop,
|
118 |
+
frame_step=self.args.hop,
|
119 |
+
fft_length=4 * self.args.hop,
|
120 |
+
window_fn=tf.signal.hann_window,
|
121 |
+
pad_end=False,
|
122 |
+
)
|
123 |
+
S = self.normalize(self.power2db(tf.abs(X) ** 2, top_db=topdb) - self.args.ref_level_db)
|
124 |
+
SM = tf.tensordot(S, self.melmat, 1)
|
125 |
+
return SM
|
126 |
+
|
127 |
+
def mel2spec(self, SM):
|
128 |
+
return tf.tensordot(SM, tf.transpose(self.melmatinv), 1)
|
129 |
+
|
130 |
+
def spec2mel(self, S):
|
131 |
+
return tf.tensordot(S, self.melmat, 1)
|
132 |
+
|
133 |
+
def wv2spec(self, wv, hop_size=256, fac=4):
|
134 |
+
X = tf.signal.stft(
|
135 |
+
wv,
|
136 |
+
frame_length=fac * hop_size,
|
137 |
+
frame_step=hop_size,
|
138 |
+
fft_length=fac * hop_size,
|
139 |
+
window_fn=tf.signal.hann_window,
|
140 |
+
pad_end=False,
|
141 |
+
)
|
142 |
+
return self.normalize(self.power2db(tf.abs(X) ** 2, top_db=None))
|
143 |
+
|
144 |
+
def wv2spec_hop(self, wv, topdb=80.0, hopsize=256):
|
145 |
+
X = tf.signal.stft(
|
146 |
+
wv,
|
147 |
+
frame_length=4 * hopsize,
|
148 |
+
frame_step=hopsize,
|
149 |
+
fft_length=4 * hopsize,
|
150 |
+
window_fn=tf.signal.hann_window,
|
151 |
+
pad_end=False,
|
152 |
+
)
|
153 |
+
S = self.normalize(self.power2db(tf.abs(X) ** 2, top_db=topdb))
|
154 |
+
return tf.tensordot(S, self.melmat, 1)
|
155 |
+
|
156 |
+
def distribute(self, x, model, bs=64, dual_out=False):
|
157 |
+
outls = []
|
158 |
+
if isinstance(x, list):
|
159 |
+
bdim = x[0].shape[0]
|
160 |
+
for i in range(((bdim - 2) // bs) + 1):
|
161 |
+
outls.append(model([el[i * bs : i * bs + bs] for el in x], training=False))
|
162 |
+
else:
|
163 |
+
bdim = x.shape[0]
|
164 |
+
for i in range(((bdim - 2) // bs) + 1):
|
165 |
+
outls.append(model(x[i * bs : i * bs + bs], training=False))
|
166 |
+
|
167 |
+
if dual_out:
|
168 |
+
return np.concatenate([outls[k][0] for k in range(len(outls))], 0), np.concatenate(
|
169 |
+
[outls[k][1] for k in range(len(outls))], 0
|
170 |
+
)
|
171 |
+
else:
|
172 |
+
return np.concatenate(outls, 0)
|
173 |
+
|
174 |
+
def distribute_enc(self, x, model, bs=64):
|
175 |
+
outls = []
|
176 |
+
if isinstance(x, list):
|
177 |
+
bdim = x[0].shape[0]
|
178 |
+
for i in range(((bdim - 2) // bs) + 1):
|
179 |
+
res = model([el[i * bs : i * bs + bs] for el in x], training=False)
|
180 |
+
resls = tf.split(res, self.args.shape // self.args.window, 0)
|
181 |
+
res = tf.concat(resls, -2)
|
182 |
+
outls.append(res)
|
183 |
+
else:
|
184 |
+
bdim = x.shape[0]
|
185 |
+
for i in range(((bdim - 2) // bs) + 1):
|
186 |
+
res = model(x[i * bs : i * bs + bs], training=False)
|
187 |
+
resls = tf.split(res, self.args.shape // self.args.window, 0)
|
188 |
+
res = tf.concat(resls, -2)
|
189 |
+
outls.append(res)
|
190 |
+
|
191 |
+
return np.concatenate(outls, 0)
|
192 |
+
|
193 |
+
def distribute_dec(self, x, model, bs=64):
|
194 |
+
outls = []
|
195 |
+
bdim = x.shape[0]
|
196 |
+
for i in range(((bdim - 2) // bs) + 1):
|
197 |
+
inp = x[i * bs : i * bs + bs]
|
198 |
+
inpls = tf.split(inp, 2, -2)
|
199 |
+
inp = tf.concat(inpls, 0)
|
200 |
+
res = model(inp, training=False)
|
201 |
+
outls.append(res)
|
202 |
+
return np.concatenate([outls[k][0] for k in range(len(outls))], 0), np.concatenate(
|
203 |
+
[outls[k][1] for k in range(len(outls))], 0
|
204 |
+
)
|
205 |
+
|
206 |
+
def distribute_dec2(self, x, model, bs=64):
|
207 |
+
outls = []
|
208 |
+
bdim = x.shape[0]
|
209 |
+
for i in range(((bdim - 2) // bs) + 1):
|
210 |
+
inp1 = x[i * bs : i * bs + bs]
|
211 |
+
inpls = tf.split(inp1, 2, -2)
|
212 |
+
inp1 = tf.concat(inpls, 0)
|
213 |
+
outls.append(model(inp1, training=False))
|
214 |
+
|
215 |
+
return np.concatenate(outls, 0)
|
216 |
+
|
217 |
+
def get_noise_interp(self):
|
218 |
+
noiseg = tf.random.normal([1, 64], dtype=tf.float32)
|
219 |
+
|
220 |
+
noisel = tf.concat([tf.random.normal([1, 64], dtype=tf.float32), noiseg], -1)
|
221 |
+
noisec = tf.concat([tf.random.normal([1, 64], dtype=tf.float32), noiseg], -1)
|
222 |
+
noiser = tf.concat([tf.random.normal([1, 64], dtype=tf.float32), noiseg], -1)
|
223 |
+
|
224 |
+
rl = tf.linspace(noisel, noisec, self.args.latlen + 1, axis=-2)[:, :-1, :]
|
225 |
+
rr = tf.linspace(noisec, noiser, self.args.latlen + 1, axis=-2)
|
226 |
+
|
227 |
+
noisetot = tf.concat([rl, rr], -2)
|
228 |
+
return tf.image.random_crop(noisetot, [1, self.args.latlen, 64 + 64])
|
229 |
+
|
230 |
+
def generate_example_stereo(self, models_ls):
|
231 |
+
(
|
232 |
+
critic,
|
233 |
+
gen,
|
234 |
+
enc,
|
235 |
+
dec,
|
236 |
+
enc2,
|
237 |
+
dec2,
|
238 |
+
critic_rec,
|
239 |
+
gen_ema,
|
240 |
+
[opt_dec, opt_disc],
|
241 |
+
) = models_ls
|
242 |
+
abb = gen_ema(self.get_noise_interp(), training=False)
|
243 |
+
abbls = tf.split(abb, abb.shape[-2] // 16, -2)
|
244 |
+
abb = tf.concat(abbls, 0)
|
245 |
+
|
246 |
+
chls = []
|
247 |
+
for channel in range(2):
|
248 |
+
|
249 |
+
ab = self.distribute_dec2(
|
250 |
+
abb[
|
251 |
+
:,
|
252 |
+
:,
|
253 |
+
:,
|
254 |
+
channel * self.args.latdepth : channel * self.args.latdepth + self.args.latdepth,
|
255 |
+
],
|
256 |
+
dec2,
|
257 |
+
)
|
258 |
+
abls = tf.split(ab, ab.shape[-2] // self.args.shape, -2)
|
259 |
+
ab = tf.concat(abls, 0)
|
260 |
+
ab_m, ab_p = self.distribute_dec(ab, dec)
|
261 |
+
wv = self.conc_tog_specphase(ab_m, ab_p)
|
262 |
+
chls.append(wv)
|
263 |
+
|
264 |
+
return np.stack(chls, -1)
|
265 |
+
|
266 |
+
# Save in training loop
|
267 |
+
def save_test_image_full(self, path, models_ls=None):
|
268 |
+
|
269 |
+
abwv = self.generate_example_stereo(models_ls)
|
270 |
+
abwv2 = self.generate_example_stereo(models_ls)
|
271 |
+
abwv3 = self.generate_example_stereo(models_ls)
|
272 |
+
abwv4 = self.generate_example_stereo(models_ls)
|
273 |
+
|
274 |
+
# IPython.display.display(
|
275 |
+
# IPython.display.Audio(np.squeeze(np.transpose(abwv)), rate=self.args.sr)
|
276 |
+
# )
|
277 |
+
# IPython.display.display(
|
278 |
+
# IPython.display.Audio(np.squeeze(np.transpose(abwv2)), rate=self.args.sr)
|
279 |
+
# )
|
280 |
+
# IPython.display.display(
|
281 |
+
# IPython.display.Audio(np.squeeze(np.transpose(abwv3)), rate=self.args.sr)
|
282 |
+
# )
|
283 |
+
# IPython.display.display(
|
284 |
+
# IPython.display.Audio(np.squeeze(np.transpose(abwv4)), rate=self.args.sr)
|
285 |
+
# )
|
286 |
+
|
287 |
+
write_wav(f"{path}/out1.wav", self.args.sr, np.squeeze(abwv))
|
288 |
+
write_wav(f"{path}/out2.wav", self.args.sr, np.squeeze(abwv2))
|
289 |
+
write_wav(f"{path}/out3.wav", self.args.sr, np.squeeze(abwv3))
|
290 |
+
write_wav(f"{path}/out4.wav", self.args.sr, np.squeeze(abwv4))
|
291 |
+
|
292 |
+
fig, axs = plt.subplots(nrows=4, ncols=1, figsize=(20, 20))
|
293 |
+
axs[0].imshow(
|
294 |
+
np.flip(
|
295 |
+
np.array(
|
296 |
+
tf.transpose(
|
297 |
+
self.wv2spec_hop((abwv[:, 0] + abwv[:, 1]) / 2.0, 80.0, 256),
|
298 |
+
[1, 0],
|
299 |
+
)
|
300 |
+
),
|
301 |
+
-2,
|
302 |
+
),
|
303 |
+
cmap=None,
|
304 |
+
)
|
305 |
+
axs[0].axis("off")
|
306 |
+
axs[0].set_title("Generated1")
|
307 |
+
axs[1].imshow(
|
308 |
+
np.flip(
|
309 |
+
np.array(
|
310 |
+
tf.transpose(
|
311 |
+
self.wv2spec_hop((abwv2[:, 0] + abwv2[:, 1]) / 2.0, 80.0, 256),
|
312 |
+
[1, 0],
|
313 |
+
)
|
314 |
+
),
|
315 |
+
-2,
|
316 |
+
),
|
317 |
+
cmap=None,
|
318 |
+
)
|
319 |
+
axs[1].axis("off")
|
320 |
+
axs[1].set_title("Generated2")
|
321 |
+
axs[2].imshow(
|
322 |
+
np.flip(
|
323 |
+
np.array(
|
324 |
+
tf.transpose(
|
325 |
+
self.wv2spec_hop((abwv3[:, 0] + abwv3[:, 1]) / 2.0, 80.0, 256),
|
326 |
+
[1, 0],
|
327 |
+
)
|
328 |
+
),
|
329 |
+
-2,
|
330 |
+
),
|
331 |
+
cmap=None,
|
332 |
+
)
|
333 |
+
axs[2].axis("off")
|
334 |
+
axs[2].set_title("Generated3")
|
335 |
+
axs[3].imshow(
|
336 |
+
np.flip(
|
337 |
+
np.array(
|
338 |
+
tf.transpose(
|
339 |
+
self.wv2spec_hop((abwv4[:, 0] + abwv4[:, 1]) / 2.0, 80.0, 256),
|
340 |
+
[1, 0],
|
341 |
+
)
|
342 |
+
),
|
343 |
+
-2,
|
344 |
+
),
|
345 |
+
cmap=None,
|
346 |
+
)
|
347 |
+
axs[3].axis("off")
|
348 |
+
axs[3].set_title("Generated4")
|
349 |
+
# plt.show()
|
350 |
+
plt.savefig(f"{path}/output.png")
|
351 |
+
|
352 |
+
# Save in training loop
|
353 |
+
def save_end(
|
354 |
+
self,
|
355 |
+
epoch,
|
356 |
+
gloss,
|
357 |
+
closs,
|
358 |
+
mloss,
|
359 |
+
models_ls=None,
|
360 |
+
n_save=3,
|
361 |
+
save_path="checkpoints",
|
362 |
+
):
|
363 |
+
(
|
364 |
+
critic,
|
365 |
+
gen,
|
366 |
+
enc,
|
367 |
+
dec,
|
368 |
+
enc2,
|
369 |
+
dec2,
|
370 |
+
critic_rec,
|
371 |
+
gen_ema,
|
372 |
+
[opt_dec, opt_disc],
|
373 |
+
) = models_ls
|
374 |
+
if epoch % n_save == 0:
|
375 |
+
print("Saving...")
|
376 |
+
path = f"{save_path}/MUSIKA!_-{str(gloss)[:9]}-{str(closs)[:9]}-{str(mloss)[:9]}"
|
377 |
+
os.mkdir(path)
|
378 |
+
critic.save_weights(path + "/critic.h5")
|
379 |
+
critic_rec.save_weights(path + "/critic_rec.h5")
|
380 |
+
gen.save_weights(path + "/gen.h5")
|
381 |
+
gen_ema.save_weights(path + "/gen_ema.h5")
|
382 |
+
# enc.save_weights(path + "/enc.h5")
|
383 |
+
# dec.save_weights(path + "/dec.h5")
|
384 |
+
# enc2.save_weights(path + "/enc2.h5")
|
385 |
+
# dec2.save_weights(path + "/dec2.h5")
|
386 |
+
np.save(path + "/opt_dec.npy", opt_dec.get_weights())
|
387 |
+
np.save(path + "/opt_disc.npy", opt_disc.get_weights())
|
388 |
+
self.save_test_image_full(path, models_ls=models_ls)
|
389 |
+
|
390 |
+
def truncated_normal(self, shape, bound=2.0, dtype=tf.float32):
|
391 |
+
seed1, seed2 = random_seed.get_seed(tf.random.uniform((), tf.int32.min, tf.int32.max, dtype=tf.int32))
|
392 |
+
return tf.random.stateless_parameterized_truncated_normal(shape, [seed1, seed2], 0.0, 1.0, -bound, bound)
|
393 |
+
|
394 |
+
def distribute_gen(self, x, model, bs=64):
|
395 |
+
outls = []
|
396 |
+
bdim = x.shape[0]
|
397 |
+
if bdim == 1:
|
398 |
+
bdim = 2
|
399 |
+
for i in range(((bdim - 2) // bs) + 1):
|
400 |
+
outls.append(model(x[i * bs : i * bs + bs], training=False))
|
401 |
+
return np.concatenate(outls, 0)
|
402 |
+
|
403 |
+
def get_noise_interp_multi(self, fac=1, var=2.0):
|
404 |
+
noiseg = self.truncated_normal([1, 64], var, dtype=tf.float32)
|
405 |
+
|
406 |
+
if var < 1.75:
|
407 |
+
var = 1.75
|
408 |
+
|
409 |
+
noisels = [
|
410 |
+
tf.concat([self.truncated_normal([1, 64], var, dtype=tf.float32), noiseg], -1) for i in range(2 + (fac - 1))
|
411 |
+
]
|
412 |
+
rls = [
|
413 |
+
tf.linspace(noisels[k], noisels[k + 1], self.args.latlen + 1, axis=-2)[:, :-1, :]
|
414 |
+
for k in range(len(noisels) - 1)
|
415 |
+
]
|
416 |
+
return tf.concat(rls, 0)
|
417 |
+
|
418 |
+
def stfunc(self, genre, z, var, models_ls_techno, models_ls_classical):
|
419 |
+
|
420 |
+
(
|
421 |
+
critic,
|
422 |
+
gen,
|
423 |
+
enc,
|
424 |
+
dec_techno,
|
425 |
+
enc2,
|
426 |
+
dec2_techno,
|
427 |
+
critic_rec,
|
428 |
+
gen_ema_techno,
|
429 |
+
[opt_dec, opt_disc],
|
430 |
+
) = models_ls_techno
|
431 |
+
(
|
432 |
+
critic,
|
433 |
+
gen,
|
434 |
+
enc,
|
435 |
+
dec_classical,
|
436 |
+
enc2,
|
437 |
+
dec2_classical,
|
438 |
+
critic_rec,
|
439 |
+
gen_ema_classical,
|
440 |
+
[opt_dec, opt_disc],
|
441 |
+
) = models_ls_classical
|
442 |
+
|
443 |
+
var = 0.01 + (3.5 * (var / 100.0))
|
444 |
+
|
445 |
+
if z == 0:
|
446 |
+
fac = 1
|
447 |
+
elif z == 1:
|
448 |
+
fac = 5
|
449 |
+
else:
|
450 |
+
fac = 10
|
451 |
+
|
452 |
+
if genre == 0:
|
453 |
+
dec = dec_techno
|
454 |
+
dec2 = dec2_techno
|
455 |
+
gen_ema = gen_ema_techno
|
456 |
+
else:
|
457 |
+
dec = dec_classical
|
458 |
+
dec2 = dec2_classical
|
459 |
+
gen_ema = gen_ema_classical
|
460 |
+
|
461 |
+
bef = time.time()
|
462 |
+
ab = self.distribute_gen(self.get_noise_interp_multi(fac, var), gen_ema)
|
463 |
+
abls = tf.split(ab, ab.shape[0], 0)
|
464 |
+
ab = tf.concat(abls, -2)
|
465 |
+
abls = tf.split(ab, ab.shape[-2] // 16, -2)
|
466 |
+
abi = tf.concat(abls, 0)
|
467 |
+
|
468 |
+
chls = []
|
469 |
+
for channel in range(2):
|
470 |
+
|
471 |
+
ab = self.distribute_dec2(
|
472 |
+
abi[:, :, :, channel * self.args.latdepth : channel * self.args.latdepth + self.args.latdepth],
|
473 |
+
dec2,
|
474 |
+
bs=128,
|
475 |
+
)
|
476 |
+
# abls = tf.split(ab, ab.shape[-2] // (self.args.shape // 2), -2)
|
477 |
+
abls = tf.split(ab, ab.shape[-2] // self.args.shape, -2)
|
478 |
+
ab = tf.concat(abls, 0)
|
479 |
+
|
480 |
+
ab_m, ab_p = self.distribute_dec(ab, dec, bs=128)
|
481 |
+
abwv = self.conc_tog_specphase(ab_m, ab_p)
|
482 |
+
chls.append(abwv)
|
483 |
+
|
484 |
+
print(
|
485 |
+
f"Time for complete generation pipeline: {time.time()-bef} s {int(np.round((fac*23.)/(time.time()-bef)))}x faster than Real Time!"
|
486 |
+
)
|
487 |
+
|
488 |
+
abwvc = np.clip(np.squeeze(np.stack(chls, -1)), -1.0, 1.0)
|
489 |
+
spec = np.flip(
|
490 |
+
np.array(
|
491 |
+
tf.transpose(
|
492 |
+
self.wv2spec_hop((abwvc[: 23 * self.args.sr, 0] + abwvc[: 23 * self.args.sr, 1]) / 2.0, 80.0, 256),
|
493 |
+
[1, 0],
|
494 |
+
)
|
495 |
+
),
|
496 |
+
-2,
|
497 |
+
)
|
498 |
+
|
499 |
+
return (
|
500 |
+
spec,
|
501 |
+
(self.args.sr, np.int16(abwvc * 32767.0)),
|
502 |
+
)
|
503 |
+
|
504 |
+
def render_gradio(self, models_ls_techno, models_ls_classical, train=True):
|
505 |
+
article_text = "Original work by Marco Pasini ([Twitter](https://twitter.com/marco_ppasini)) at Johannes Kepler Universität Linz. Supervised by Jan Schlüter."
|
506 |
+
|
507 |
+
def gradio_func(x, y, z):
|
508 |
+
return self.stfunc(x, y, z, models_ls_techno, models_ls_classical)
|
509 |
+
|
510 |
+
iface = gr.Interface(
|
511 |
+
fn=gradio_func,
|
512 |
+
inputs=[
|
513 |
+
gr.inputs.Radio(
|
514 |
+
choices=["Techno", "Classical"],
|
515 |
+
type="index",
|
516 |
+
default="Techno",
|
517 |
+
label="Music Genre to Generate (Brace yourself for very high levels of weirdness!)",
|
518 |
+
),
|
519 |
+
gr.inputs.Radio(
|
520 |
+
choices=["23 s", "115 s", "230 s"],
|
521 |
+
type="index",
|
522 |
+
default="115 s",
|
523 |
+
label="Generated Music Length",
|
524 |
+
),
|
525 |
+
gr.inputs.Slider(
|
526 |
+
minimum=0,
|
527 |
+
maximum=100,
|
528 |
+
step=1,
|
529 |
+
default=50,
|
530 |
+
label="Stability[left]/Variety[right] Tradeoff (Truncation Trick)",
|
531 |
+
),
|
532 |
+
],
|
533 |
+
outputs=[
|
534 |
+
gr.outputs.Image(label="Log-MelSpectrogram of Generated Audio (first 23 sec)"),
|
535 |
+
gr.outputs.Audio(type="numpy", label="Generated Audio"),
|
536 |
+
],
|
537 |
+
allow_screenshot=False,
|
538 |
+
title="musika!",
|
539 |
+
description="Blazingly Fast Stereo Waveform Music Generation of Arbitrary Length",
|
540 |
+
article=article_text,
|
541 |
+
layout="vertical",
|
542 |
+
theme="huggingface",
|
543 |
+
)
|
544 |
+
|
545 |
+
print("--------------------------------")
|
546 |
+
print("--------------------------------")
|
547 |
+
print("--------------------------------")
|
548 |
+
print("--------------------------------")
|
549 |
+
print("--------------------------------")
|
550 |
+
print("CLICK ON LINK BELOW TO OPEN GRADIO INTERFACE")
|
551 |
+
if train:
|
552 |
+
iface.launch(prevent_thread_lock=True)
|
553 |
+
else:
|
554 |
+
iface.launch()
|
555 |
+
# iface.launch(share=True, enable_queue=True)
|
556 |
+
print("--------------------------------")
|
557 |
+
print("--------------------------------")
|
558 |
+
print("--------------------------------")
|
559 |
+
print("--------------------------------")
|
560 |
+
print("--------------------------------")
|