Spaces:
Build error
Build error
musika clone
Browse files- LICENSE +21 -0
- README.md +6 -6
- app.py +15 -0
- checkpoints/ae/dec.h5 +3 -0
- checkpoints/ae/dec2.h5 +3 -0
- checkpoints/ae/enc.h5 +3 -0
- checkpoints/ae/enc2.h5 +3 -0
- checkpoints/metal/gen_ema.h5 +3 -0
- checkpoints/misc/gen_ema.h5 +3 -0
- checkpoints/techno/gen_ema.h5 +3 -0
- layers.py +163 -0
- models.py +783 -0
- musika_test.py +20 -0
- parse_test.py +196 -0
- requirements.txt +12 -0
- utils.py +689 -0
LICENSE
ADDED
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
MIT License
|
2 |
+
|
3 |
+
Copyright (c) 2022 Marco Pasini
|
4 |
+
|
5 |
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
6 |
+
of this software and associated documentation files (the "Software"), to deal
|
7 |
+
in the Software without restriction, including without limitation the rights
|
8 |
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
9 |
+
copies of the Software, and to permit persons to whom the Software is
|
10 |
+
furnished to do so, subject to the following conditions:
|
11 |
+
|
12 |
+
The above copyright notice and this permission notice shall be included in all
|
13 |
+
copies or substantial portions of the Software.
|
14 |
+
|
15 |
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
16 |
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
17 |
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
18 |
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
19 |
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
20 |
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
21 |
+
SOFTWARE.
|
README.md
CHANGED
@@ -1,13 +1,13 @@
|
|
1 |
---
|
2 |
-
title: Musika
|
3 |
-
emoji:
|
4 |
-
colorFrom:
|
5 |
-
colorTo:
|
6 |
sdk: gradio
|
7 |
-
sdk_version: 3.
|
8 |
app_file: app.py
|
9 |
pinned: false
|
10 |
-
license:
|
11 |
---
|
12 |
|
13 |
Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
|
|
|
1 |
---
|
2 |
+
title: Musika
|
3 |
+
emoji: 🎵
|
4 |
+
colorFrom: purple
|
5 |
+
colorTo: blue
|
6 |
sdk: gradio
|
7 |
+
sdk_version: 3.3.1
|
8 |
app_file: app.py
|
9 |
pinned: false
|
10 |
+
license: cc-by-4.0
|
11 |
---
|
12 |
|
13 |
Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
|
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_1, models_ls_2, models_ls_3 = M.get_networks()
|
12 |
+
|
13 |
+
# test musika
|
14 |
+
U = Utils_functions(args)
|
15 |
+
U.render_gradio(models_ls_1, models_ls_2, models_ls_3, train=False)
|
checkpoints/ae/dec.h5
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:9aebbb210da611415c8e15b4bd7cc62c20d6a702169c709c3e6cc3912fb0aa84
|
3 |
+
size 50781776
|
checkpoints/ae/dec2.h5
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:ffc4c0d6821e23247889a2252da86f9ba22ad6425d004790457e0c2e57e18c65
|
3 |
+
size 26616400
|
checkpoints/ae/enc.h5
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:e56882c9e62aa4703a6d088efc374bfc534a4a8b4f3cdc0418fab1f0da1795a7
|
3 |
+
size 19196936
|
checkpoints/ae/enc2.h5
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:b2f2f2b2b2879ad14690b2e64eb59f3b5dc3fbffaa88b37fdf5e8735b9dad305
|
3 |
+
size 15986152
|
checkpoints/metal/gen_ema.h5
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:4e1f59d7fc67df5fa9eb0ab4665bcc9fe27d346fcfe60a082c8937c622105d7f
|
3 |
+
size 62200720
|
checkpoints/misc/gen_ema.h5
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:2f0cb86f0bf22a568f1ef1ad5782d11543f9779069de996b81907328eeb24c8e
|
3 |
+
size 62200720
|
checkpoints/techno/gen_ema.h5
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:582149f06f50197022758a7ca981a13164364871321ab2cf0662fc6ed7d634b0
|
3 |
+
size 62200304
|
layers.py
ADDED
@@ -0,0 +1,163 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import tensorflow as tf
|
2 |
+
import tensorflow.python.keras.backend as K
|
3 |
+
from tensorflow.python.eager import context
|
4 |
+
from tensorflow.python.ops import (
|
5 |
+
gen_math_ops,
|
6 |
+
math_ops,
|
7 |
+
sparse_ops,
|
8 |
+
standard_ops,
|
9 |
+
)
|
10 |
+
|
11 |
+
|
12 |
+
def l2normalize(v, eps=1e-12):
|
13 |
+
return v / (tf.norm(v) + eps)
|
14 |
+
|
15 |
+
|
16 |
+
class ConvSN2D(tf.keras.layers.Conv2D):
|
17 |
+
def __init__(self, filters, kernel_size, power_iterations=1, datatype=tf.float32, **kwargs):
|
18 |
+
super(ConvSN2D, self).__init__(filters, kernel_size, **kwargs)
|
19 |
+
self.power_iterations = power_iterations
|
20 |
+
self.datatype = datatype
|
21 |
+
|
22 |
+
def build(self, input_shape):
|
23 |
+
super(ConvSN2D, self).build(input_shape)
|
24 |
+
|
25 |
+
if self.data_format == "channels_first":
|
26 |
+
channel_axis = 1
|
27 |
+
else:
|
28 |
+
channel_axis = -1
|
29 |
+
|
30 |
+
self.u = self.add_weight(
|
31 |
+
self.name + "_u",
|
32 |
+
shape=tuple([1, self.kernel.shape.as_list()[-1]]),
|
33 |
+
initializer=tf.initializers.RandomNormal(0, 1),
|
34 |
+
trainable=False,
|
35 |
+
dtype=self.dtype,
|
36 |
+
)
|
37 |
+
|
38 |
+
def compute_spectral_norm(self, W, new_u, W_shape):
|
39 |
+
for _ in range(self.power_iterations):
|
40 |
+
|
41 |
+
new_v = l2normalize(tf.matmul(new_u, tf.transpose(W)))
|
42 |
+
new_u = l2normalize(tf.matmul(new_v, W))
|
43 |
+
|
44 |
+
sigma = tf.matmul(tf.matmul(new_v, W), tf.transpose(new_u))
|
45 |
+
W_bar = W / sigma
|
46 |
+
|
47 |
+
with tf.control_dependencies([self.u.assign(new_u)]):
|
48 |
+
W_bar = tf.reshape(W_bar, W_shape)
|
49 |
+
|
50 |
+
return W_bar
|
51 |
+
|
52 |
+
def call(self, inputs):
|
53 |
+
W_shape = self.kernel.shape.as_list()
|
54 |
+
W_reshaped = tf.reshape(self.kernel, (-1, W_shape[-1]))
|
55 |
+
new_kernel = self.compute_spectral_norm(W_reshaped, self.u, W_shape)
|
56 |
+
outputs = self._convolution_op(inputs, new_kernel)
|
57 |
+
|
58 |
+
if self.use_bias:
|
59 |
+
if self.data_format == "channels_first":
|
60 |
+
outputs = tf.nn.bias_add(outputs, self.bias, data_format="NCHW")
|
61 |
+
else:
|
62 |
+
outputs = tf.nn.bias_add(outputs, self.bias, data_format="NHWC")
|
63 |
+
if self.activation is not None:
|
64 |
+
return self.activation(outputs)
|
65 |
+
|
66 |
+
return outputs
|
67 |
+
|
68 |
+
|
69 |
+
class DenseSN(tf.keras.layers.Dense):
|
70 |
+
def __init__(self, datatype=tf.float32, **kwargs):
|
71 |
+
super(DenseSN, self).__init__(**kwargs)
|
72 |
+
self.datatype = datatype
|
73 |
+
|
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.datatype,
|
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 __init__(self, datatype=tf.float32, **kwargs):
|
120 |
+
super(AddNoise, self).__init__(**kwargs)
|
121 |
+
self.datatype = datatype
|
122 |
+
|
123 |
+
def build(self, input_shape):
|
124 |
+
self.b = self.add_weight(
|
125 |
+
shape=[
|
126 |
+
1,
|
127 |
+
],
|
128 |
+
initializer=tf.keras.initializers.zeros(),
|
129 |
+
trainable=True,
|
130 |
+
name="noise_weight",
|
131 |
+
)
|
132 |
+
|
133 |
+
def call(self, inputs):
|
134 |
+
rand = tf.random.normal(
|
135 |
+
[tf.shape(inputs)[0], inputs.shape[1], inputs.shape[2], 1],
|
136 |
+
mean=0.0,
|
137 |
+
stddev=1.0,
|
138 |
+
dtype=self.datatype,
|
139 |
+
)
|
140 |
+
output = inputs + self.b * rand
|
141 |
+
return output
|
142 |
+
|
143 |
+
|
144 |
+
class PosEnc(tf.keras.layers.Layer):
|
145 |
+
def __init__(self, datatype=tf.float32, **kwargs):
|
146 |
+
super(PosEnc, self).__init__(**kwargs)
|
147 |
+
self.datatype = datatype
|
148 |
+
|
149 |
+
def call(self, inputs):
|
150 |
+
pos = tf.repeat(
|
151 |
+
tf.reshape(tf.range(inputs.shape[-3], dtype=tf.int32), [1, -1, 1, 1]),
|
152 |
+
inputs.shape[-2],
|
153 |
+
-2,
|
154 |
+
)
|
155 |
+
pos = tf.cast(tf.repeat(pos, tf.shape(inputs)[0], 0), self.dtype) / tf.cast(inputs.shape[-3], self.datatype)
|
156 |
+
return tf.concat([inputs, pos], -1) # [bs,1,hop,2]
|
157 |
+
|
158 |
+
|
159 |
+
def flatten_hw(x, data_format="channels_last"):
|
160 |
+
if data_format == "channels_last":
|
161 |
+
x = tf.transpose(x, perm=[0, 3, 1, 2]) # Convert to `channels_first`
|
162 |
+
|
163 |
+
old_shape = tf.shape(x)
|
models.py
ADDED
@@ -0,0 +1,783 @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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import numpy as np
|
2 |
+
import tensorflow as tf
|
3 |
+
from tensorflow.python.keras.utils.layer_utils import count_params
|
4 |
+
|
5 |
+
from layers import AddNoise
|
6 |
+
|
7 |
+
|
8 |
+
class Models_functions:
|
9 |
+
def __init__(self, args):
|
10 |
+
|
11 |
+
self.args = args
|
12 |
+
|
13 |
+
if self.args.mixed_precision:
|
14 |
+
self.mixed_precision = tf.keras.mixed_precision
|
15 |
+
self.policy = tf.keras.mixed_precision.Policy("mixed_float16")
|
16 |
+
tf.keras.mixed_precision.set_global_policy(self.policy)
|
17 |
+
self.init = tf.keras.initializers.he_uniform()
|
18 |
+
|
19 |
+
def conv_util(
|
20 |
+
self, inp, filters, kernel_size=(1, 3), strides=(1, 1), noise=False, upsample=False, padding="same", bnorm=True
|
21 |
+
):
|
22 |
+
|
23 |
+
x = inp
|
24 |
+
|
25 |
+
bias = True
|
26 |
+
if bnorm:
|
27 |
+
bias = False
|
28 |
+
|
29 |
+
if upsample:
|
30 |
+
x = tf.keras.layers.Conv2DTranspose(
|
31 |
+
filters,
|
32 |
+
kernel_size=kernel_size,
|
33 |
+
strides=strides,
|
34 |
+
activation="linear",
|
35 |
+
padding=padding,
|
36 |
+
kernel_initializer=self.init,
|
37 |
+
use_bias=bias,
|
38 |
+
)(x)
|
39 |
+
else:
|
40 |
+
x = tf.keras.layers.Conv2D(
|
41 |
+
filters,
|
42 |
+
kernel_size=kernel_size,
|
43 |
+
strides=strides,
|
44 |
+
activation="linear",
|
45 |
+
padding=padding,
|
46 |
+
kernel_initializer=self.init,
|
47 |
+
use_bias=bias,
|
48 |
+
)(x)
|
49 |
+
|
50 |
+
if noise:
|
51 |
+
x = AddNoise(self.args.datatype)(x)
|
52 |
+
|
53 |
+
if bnorm:
|
54 |
+
x = tf.keras.layers.BatchNormalization()(x)
|
55 |
+
|
56 |
+
x = tf.keras.activations.swish(x)
|
57 |
+
|
58 |
+
return x
|
59 |
+
|
60 |
+
def pixel_shuffle(self, x, factor=2):
|
61 |
+
bs_dim, h_dim, w_dim, c_dim = tf.shape(x)[0], x.shape[1], x.shape[2], x.shape[3]
|
62 |
+
x = tf.reshape(x, [bs_dim, h_dim, w_dim, c_dim // factor, factor])
|
63 |
+
x = tf.transpose(x, [0, 1, 2, 4, 3])
|
64 |
+
return tf.reshape(x, [bs_dim, h_dim, w_dim * factor, c_dim // factor])
|
65 |
+
|
66 |
+
def adain(self, x, emb, name):
|
67 |
+
emb = tf.keras.layers.Conv2D(
|
68 |
+
x.shape[-1],
|
69 |
+
kernel_size=(1, 1),
|
70 |
+
strides=1,
|
71 |
+
activation="linear",
|
72 |
+
padding="same",
|
73 |
+
kernel_initializer=self.init,
|
74 |
+
use_bias=True,
|
75 |
+
name=name,
|
76 |
+
)(emb)
|
77 |
+
x = x / (tf.math.reduce_std(x, -2, keepdims=True) + 1e-5)
|
78 |
+
return x * emb
|
79 |
+
|
80 |
+
def conv_util_gen(
|
81 |
+
self,
|
82 |
+
inp,
|
83 |
+
filters,
|
84 |
+
kernel_size=(1, 9),
|
85 |
+
strides=(1, 1),
|
86 |
+
noise=False,
|
87 |
+
upsample=False,
|
88 |
+
emb=None,
|
89 |
+
se1=None,
|
90 |
+
name="0",
|
91 |
+
):
|
92 |
+
|
93 |
+
x = inp
|
94 |
+
|
95 |
+
if upsample:
|
96 |
+
x = tf.keras.layers.Conv2DTranspose(
|
97 |
+
filters,
|
98 |
+
kernel_size=kernel_size,
|
99 |
+
strides=strides,
|
100 |
+
activation="linear",
|
101 |
+
padding="same",
|
102 |
+
kernel_initializer=self.init,
|
103 |
+
use_bias=True,
|
104 |
+
name=name + "c",
|
105 |
+
)(x)
|
106 |
+
else:
|
107 |
+
x = tf.keras.layers.Conv2D(
|
108 |
+
filters,
|
109 |
+
kernel_size=kernel_size,
|
110 |
+
strides=strides,
|
111 |
+
activation="linear",
|
112 |
+
padding="same",
|
113 |
+
kernel_initializer=self.init,
|
114 |
+
use_bias=True,
|
115 |
+
name=name + "c",
|
116 |
+
)(x)
|
117 |
+
|
118 |
+
if noise:
|
119 |
+
x = AddNoise(self.args.datatype, name=name + "r")(x)
|
120 |
+
|
121 |
+
if emb is not None:
|
122 |
+
x = self.adain(x, emb, name=name + "ai")
|
123 |
+
else:
|
124 |
+
x = tf.keras.layers.BatchNormalization(name=name + "bn")(x)
|
125 |
+
|
126 |
+
x = tf.keras.activations.swish(x)
|
127 |
+
|
128 |
+
return x
|
129 |
+
|
130 |
+
def res_block_disc(self, inp, filters, kernel_size=(1, 3), kernel_size_2=None, strides=(1, 1), name="0"):
|
131 |
+
|
132 |
+
if kernel_size_2 is None:
|
133 |
+
kernel_size_2 = kernel_size
|
134 |
+
|
135 |
+
x = tf.keras.layers.Conv2D(
|
136 |
+
inp.shape[-1],
|
137 |
+
kernel_size=kernel_size_2,
|
138 |
+
strides=1,
|
139 |
+
activation="linear",
|
140 |
+
padding="same",
|
141 |
+
kernel_initializer=self.init,
|
142 |
+
name=name + "c0",
|
143 |
+
)(inp)
|
144 |
+
x = tf.keras.layers.LeakyReLU(0.2)(x)
|
145 |
+
x = tf.math.sqrt(tf.cast(0.5, self.args.datatype)) * x
|
146 |
+
x = tf.keras.layers.Conv2D(
|
147 |
+
filters,
|
148 |
+
kernel_size=kernel_size,
|
149 |
+
strides=strides,
|
150 |
+
activation="linear",
|
151 |
+
padding="same",
|
152 |
+
kernel_initializer=self.init,
|
153 |
+
name=name + "c1",
|
154 |
+
)(x)
|
155 |
+
x = tf.keras.layers.LeakyReLU(0.2)(x)
|
156 |
+
x = tf.math.sqrt(tf.cast(0.5, self.args.datatype)) * x
|
157 |
+
|
158 |
+
if strides != (1, 1):
|
159 |
+
inp = tf.keras.layers.AveragePooling2D(strides, padding="same")(inp)
|
160 |
+
|
161 |
+
if inp.shape[-1] != filters:
|
162 |
+
inp = tf.keras.layers.Conv2D(
|
163 |
+
filters,
|
164 |
+
kernel_size=1,
|
165 |
+
strides=1,
|
166 |
+
activation="linear",
|
167 |
+
padding="same",
|
168 |
+
kernel_initializer=self.init,
|
169 |
+
use_bias=False,
|
170 |
+
name=name + "c3",
|
171 |
+
)(inp)
|
172 |
+
|
173 |
+
return x + inp
|
174 |
+
|
175 |
+
def build_encoder2(self):
|
176 |
+
|
177 |
+
inpf = tf.keras.layers.Input((1, self.args.shape, self.args.hop // 4))
|
178 |
+
|
179 |
+
inpfls = tf.split(inpf, 8, -2)
|
180 |
+
inpb = tf.concat(inpfls, 0)
|
181 |
+
|
182 |
+
g0 = self.conv_util(inpb, self.args.hop, kernel_size=(1, 3), strides=(1, 1), padding="same", bnorm=False)
|
183 |
+
g1 = self.conv_util(
|
184 |
+
g0, self.args.hop + self.args.hop // 2, kernel_size=(1, 3), strides=(1, 2), padding="valid", bnorm=False
|
185 |
+
)
|
186 |
+
g2 = self.conv_util(
|
187 |
+
g1, self.args.hop + self.args.hop // 2, kernel_size=(1, 3), strides=(1, 1), padding="same", bnorm=False
|
188 |
+
)
|
189 |
+
g3 = self.conv_util(g2, self.args.hop * 2, kernel_size=(1, 3), strides=(1, 2), padding="valid", bnorm=False)
|
190 |
+
g4 = self.conv_util(g3, self.args.hop * 2, kernel_size=(1, 3), strides=(1, 1), padding="same", bnorm=False)
|
191 |
+
g5 = self.conv_util(g4, self.args.hop * 3, kernel_size=(1, 3), strides=(1, 1), padding="valid", bnorm=False)
|
192 |
+
g5 = self.conv_util(g5, self.args.hop * 3, kernel_size=(1, 1), strides=(1, 1), padding="valid", bnorm=False)
|
193 |
+
|
194 |
+
g = tf.keras.layers.Conv2D(
|
195 |
+
self.args.latdepth,
|
196 |
+
kernel_size=(1, 1),
|
197 |
+
strides=1,
|
198 |
+
padding="valid",
|
199 |
+
kernel_initializer=self.init,
|
200 |
+
name="cbottle",
|
201 |
+
activation="tanh",
|
202 |
+
)(g5)
|
203 |
+
|
204 |
+
gls = tf.split(g, 8, 0)
|
205 |
+
g = tf.concat(gls, -2)
|
206 |
+
gls = tf.split(g, 2, -2)
|
207 |
+
g = tf.concat(gls, 0)
|
208 |
+
|
209 |
+
gf = tf.cast(g, tf.float32)
|
210 |
+
|
211 |
+
return tf.keras.Model(inpf, gf, name="ENC2")
|
212 |
+
|
213 |
+
def build_decoder2(self):
|
214 |
+
|
215 |
+
inpf = tf.keras.layers.Input((1, self.args.shape // 32, self.args.latdepth))
|
216 |
+
|
217 |
+
g = inpf
|
218 |
+
|
219 |
+
g = self.conv_util(
|
220 |
+
g, self.args.hop * 3, kernel_size=(1, 3), strides=(1, 1), upsample=False, noise=True, bnorm=False
|
221 |
+
)
|
222 |
+
g = self.conv_util(
|
223 |
+
g,
|
224 |
+
self.args.hop * 2 + self.args.hop // 2,
|
225 |
+
kernel_size=(1, 4),
|
226 |
+
strides=(1, 2),
|
227 |
+
upsample=True,
|
228 |
+
noise=True,
|
229 |
+
bnorm=False,
|
230 |
+
)
|
231 |
+
g = self.conv_util(
|
232 |
+
g,
|
233 |
+
self.args.hop * 2 + self.args.hop // 2,
|
234 |
+
kernel_size=(1, 3),
|
235 |
+
strides=(1, 1),
|
236 |
+
upsample=False,
|
237 |
+
noise=True,
|
238 |
+
bnorm=False,
|
239 |
+
)
|
240 |
+
g = self.conv_util(
|
241 |
+
g, self.args.hop * 2, kernel_size=(1, 4), strides=(1, 2), upsample=True, noise=True, bnorm=False
|
242 |
+
)
|
243 |
+
g = self.conv_util(
|
244 |
+
g, self.args.hop * 2, kernel_size=(1, 3), strides=(1, 1), upsample=False, noise=True, bnorm=False
|
245 |
+
)
|
246 |
+
g = self.conv_util(
|
247 |
+
g,
|
248 |
+
self.args.hop + self.args.hop // 2,
|
249 |
+
kernel_size=(1, 4),
|
250 |
+
strides=(1, 2),
|
251 |
+
upsample=True,
|
252 |
+
noise=True,
|
253 |
+
bnorm=False,
|
254 |
+
)
|
255 |
+
g = self.conv_util(g, self.args.hop, kernel_size=(1, 4), strides=(1, 2), upsample=True, noise=True, bnorm=False)
|
256 |
+
|
257 |
+
gf = tf.keras.layers.Conv2D(
|
258 |
+
self.args.hop // 4, kernel_size=(1, 1), strides=1, padding="same", kernel_initializer=self.init, name="cout"
|
259 |
+
)(g)
|
260 |
+
|
261 |
+
gfls = tf.split(gf, 2, 0)
|
262 |
+
gf = tf.concat(gfls, -2)
|
263 |
+
|
264 |
+
gf = tf.cast(gf, tf.float32)
|
265 |
+
|
266 |
+
return tf.keras.Model(inpf, gf, name="DEC2")
|
267 |
+
|
268 |
+
def build_encoder(self):
|
269 |
+
|
270 |
+
dim = ((4 * self.args.hop) // 2) + 1
|
271 |
+
|
272 |
+
inpf = tf.keras.layers.Input((dim, self.args.shape, 1))
|
273 |
+
|
274 |
+
ginp = tf.transpose(inpf, [0, 3, 2, 1])
|
275 |
+
|
276 |
+
g0 = self.conv_util(ginp, self.args.hop * 4, kernel_size=(1, 1), strides=(1, 1), padding="valid", bnorm=False)
|
277 |
+
g1 = self.conv_util(g0, self.args.hop * 4, kernel_size=(1, 1), strides=(1, 1), padding="valid", bnorm=False)
|
278 |
+
g2 = self.conv_util(g1, self.args.hop * 4, kernel_size=(1, 1), strides=(1, 1), padding="valid", bnorm=False)
|
279 |
+
g4 = self.conv_util(g2, self.args.hop * 4, kernel_size=(1, 1), strides=(1, 1), padding="valid", bnorm=False)
|
280 |
+
g5 = self.conv_util(g4, self.args.hop * 4, kernel_size=(1, 1), strides=(1, 1), padding="valid", bnorm=False)
|
281 |
+
|
282 |
+
g = tf.keras.layers.Conv2D(
|
283 |
+
self.args.hop // 4, kernel_size=(1, 1), strides=1, padding="valid", kernel_initializer=self.init
|
284 |
+
)(g5)
|
285 |
+
|
286 |
+
g = tf.keras.activations.tanh(g)
|
287 |
+
|
288 |
+
gls = tf.split(g, 2, -2)
|
289 |
+
g = tf.concat(gls, 0)
|
290 |
+
|
291 |
+
gf = tf.cast(g, tf.float32)
|
292 |
+
|
293 |
+
return tf.keras.Model(inpf, gf, name="ENC")
|
294 |
+
|
295 |
+
def build_decoder(self):
|
296 |
+
|
297 |
+
dim = ((4 * self.args.hop) // 2) + 1
|
298 |
+
|
299 |
+
inpf = tf.keras.layers.Input((1, self.args.shape // 2, self.args.hop // 4))
|
300 |
+
|
301 |
+
g = inpf
|
302 |
+
|
303 |
+
g0 = self.conv_util(g, self.args.hop * 3, kernel_size=(1, 3), strides=(1, 1), noise=True, bnorm=False)
|
304 |
+
g1 = self.conv_util(g0, self.args.hop * 3, kernel_size=(1, 3), strides=(1, 2), noise=True, bnorm=False)
|
305 |
+
g2 = self.conv_util(g1, self.args.hop * 2, kernel_size=(1, 3), strides=(1, 2), noise=True, bnorm=False)
|
306 |
+
g3 = self.conv_util(g2, self.args.hop, kernel_size=(1, 3), strides=(1, 2), noise=True, bnorm=False)
|
307 |
+
g = self.conv_util(g3, self.args.hop, kernel_size=(1, 3), strides=(1, 2), noise=True, bnorm=False)
|
308 |
+
|
309 |
+
g33 = self.conv_util(
|
310 |
+
g, self.args.hop, kernel_size=(1, 4), strides=(1, 2), upsample=True, noise=True, bnorm=False
|
311 |
+
)
|
312 |
+
g22 = self.conv_util(
|
313 |
+
g3, self.args.hop * 2, kernel_size=(1, 4), strides=(1, 2), upsample=True, noise=True, bnorm=False
|
314 |
+
)
|
315 |
+
g11 = self.conv_util(
|
316 |
+
g22 + g2, self.args.hop * 3, kernel_size=(1, 4), strides=(1, 2), upsample=True, noise=True, bnorm=False
|
317 |
+
)
|
318 |
+
g00 = self.conv_util(
|
319 |
+
g11 + g1, self.args.hop * 3, kernel_size=(1, 4), strides=(1, 2), upsample=True, noise=True, bnorm=False
|
320 |
+
)
|
321 |
+
|
322 |
+
g = tf.keras.layers.Conv2D(
|
323 |
+
dim, kernel_size=(1, 1), strides=(1, 1), kernel_initializer=self.init, padding="same"
|
324 |
+
)(g00 + g0)
|
325 |
+
gf = tf.clip_by_value(g, -1.0, 1.0)
|
326 |
+
|
327 |
+
g = self.conv_util(
|
328 |
+
g22, self.args.hop * 3, kernel_size=(1, 4), strides=(1, 2), upsample=True, noise=True, bnorm=False
|
329 |
+
)
|
330 |
+
g = self.conv_util(
|
331 |
+
g + g11, self.args.hop * 3, kernel_size=(1, 4), strides=(1, 2), upsample=True, noise=True, bnorm=False
|
332 |
+
)
|
333 |
+
g = tf.keras.layers.Conv2D(
|
334 |
+
dim, kernel_size=(1, 1), strides=(1, 1), kernel_initializer=self.init, padding="same"
|
335 |
+
)(g + g00)
|
336 |
+
pf = tf.clip_by_value(g, -1.0, 1.0)
|
337 |
+
|
338 |
+
gfls = tf.split(gf, self.args.shape // self.args.window, 0)
|
339 |
+
gf = tf.concat(gfls, -2)
|
340 |
+
|
341 |
+
pfls = tf.split(pf, self.args.shape // self.args.window, 0)
|
342 |
+
pf = tf.concat(pfls, -2)
|
343 |
+
|
344 |
+
s = tf.transpose(gf, [0, 2, 3, 1])
|
345 |
+
p = tf.transpose(pf, [0, 2, 3, 1])
|
346 |
+
|
347 |
+
s = tf.cast(tf.squeeze(s, -1), tf.float32)
|
348 |
+
p = tf.cast(tf.squeeze(p, -1), tf.float32)
|
349 |
+
|
350 |
+
return tf.keras.Model(inpf, [s, p], name="DEC")
|
351 |
+
|
352 |
+
def build_critic(self):
|
353 |
+
|
354 |
+
sinp = tf.keras.layers.Input(shape=(1, self.args.latlen, self.args.latdepth * 2))
|
355 |
+
|
356 |
+
sf = tf.keras.layers.Conv2D(
|
357 |
+
self.args.base_channels * 3,
|
358 |
+
kernel_size=(1, 4),
|
359 |
+
strides=(1, 2),
|
360 |
+
activation="linear",
|
361 |
+
padding="same",
|
362 |
+
kernel_initializer=self.init,
|
363 |
+
name="1c",
|
364 |
+
)(sinp)
|
365 |
+
sf = tf.keras.layers.LeakyReLU(0.2)(sf)
|
366 |
+
|
367 |
+
sf = self.res_block_disc(sf, self.args.base_channels * 4, kernel_size=(1, 4), strides=(1, 2), name="2")
|
368 |
+
|
369 |
+
sf = self.res_block_disc(sf, self.args.base_channels * 5, kernel_size=(1, 4), strides=(1, 2), name="3")
|
370 |
+
|
371 |
+
sf = self.res_block_disc(sf, self.args.base_channels * 6, kernel_size=(1, 4), strides=(1, 2), name="4")
|
372 |
+
|
373 |
+
sf = self.res_block_disc(sf, self.args.base_channels * 7, kernel_size=(1, 4), strides=(1, 2), name="5")
|
374 |
+
|
375 |
+
if not self.args.small:
|
376 |
+
sf = self.res_block_disc(
|
377 |
+
sf, self.args.base_channels * 7, kernel_size=(1, 4), strides=(1, 2), kernel_size_2=(1, 1), name="6"
|
378 |
+
)
|
379 |
+
|
380 |
+
sf = tf.keras.layers.Conv2D(
|
381 |
+
self.args.base_channels * 7,
|
382 |
+
kernel_size=(1, 3),
|
383 |
+
strides=(1, 1),
|
384 |
+
activation="linear",
|
385 |
+
padding="same",
|
386 |
+
kernel_initializer=self.init,
|
387 |
+
name="7c",
|
388 |
+
)(sf)
|
389 |
+
sf = tf.keras.layers.LeakyReLU(0.2)(sf)
|
390 |
+
|
391 |
+
gf = tf.keras.layers.Dense(1, activation="linear", use_bias=True, kernel_initializer=self.init, name="7d")(
|
392 |
+
tf.keras.layers.Flatten()(sf)
|
393 |
+
)
|
394 |
+
|
395 |
+
gf = tf.cast(gf, tf.float32)
|
396 |
+
|
397 |
+
return tf.keras.Model(sinp, gf, name="C")
|
398 |
+
|
399 |
+
def build_generator(self):
|
400 |
+
|
401 |
+
dim = self.args.latdepth * 2
|
402 |
+
|
403 |
+
inpf = tf.keras.layers.Input((self.args.latlen, self.args.latdepth * 2))
|
404 |
+
|
405 |
+
inpfls = tf.split(inpf, 2, -2)
|
406 |
+
inpb = tf.concat(inpfls, 0)
|
407 |
+
|
408 |
+
inpg = tf.reduce_mean(inpb, -2)
|
409 |
+
inp1 = tf.keras.layers.AveragePooling2D((1, 2), padding="valid")(tf.expand_dims(inpb, -3))
|
410 |
+
inp2 = tf.keras.layers.AveragePooling2D((1, 2), padding="valid")(inp1)
|
411 |
+
inp3 = tf.keras.layers.AveragePooling2D((1, 2), padding="valid")(inp2)
|
412 |
+
inp4 = tf.keras.layers.AveragePooling2D((1, 2), padding="valid")(inp3)
|
413 |
+
inp5 = tf.keras.layers.AveragePooling2D((1, 2), padding="valid")(inp4)
|
414 |
+
if not self.args.small:
|
415 |
+
inp6 = tf.keras.layers.AveragePooling2D((1, 2), padding="valid")(inp5)
|
416 |
+
|
417 |
+
if not self.args.small:
|
418 |
+
g = tf.keras.layers.Dense(
|
419 |
+
4 * (self.args.base_channels * 7),
|
420 |
+
activation="linear",
|
421 |
+
use_bias=True,
|
422 |
+
kernel_initializer=self.init,
|
423 |
+
name="00d",
|
424 |
+
)(tf.keras.layers.Flatten()(inp6))
|
425 |
+
g = tf.keras.layers.Reshape((1, 4, self.args.base_channels * 7))(g)
|
426 |
+
g = AddNoise(self.args.datatype, name="00n")(g)
|
427 |
+
g = self.adain(g, inp5, name="00ai")
|
428 |
+
g = tf.keras.activations.swish(g)
|
429 |
+
else:
|
430 |
+
g = tf.keras.layers.Dense(
|
431 |
+
4 * (self.args.base_channels * 7),
|
432 |
+
activation="linear",
|
433 |
+
use_bias=True,
|
434 |
+
kernel_initializer=self.init,
|
435 |
+
name="00d",
|
436 |
+
)(tf.keras.layers.Flatten()(inp5))
|
437 |
+
g = tf.keras.layers.Reshape((1, 4, self.args.base_channels * 7))(g)
|
438 |
+
g = AddNoise(self.args.datatype, name="00n")(g)
|
439 |
+
g = self.adain(g, inp4, name="00ai")
|
440 |
+
g = tf.keras.activations.swish(g)
|
441 |
+
|
442 |
+
if not self.args.small:
|
443 |
+
g1 = self.conv_util_gen(
|
444 |
+
g,
|
445 |
+
self.args.base_channels * 6,
|
446 |
+
kernel_size=(1, 4),
|
447 |
+
strides=(1, 2),
|
448 |
+
upsample=True,
|
449 |
+
noise=True,
|
450 |
+
emb=inp4,
|
451 |
+
name="0",
|
452 |
+
)
|
453 |
+
g1 = tf.math.sqrt(tf.cast(0.5, self.args.datatype)) * g1
|
454 |
+
g1 = self.conv_util_gen(
|
455 |
+
g1,
|
456 |
+
self.args.base_channels * 6,
|
457 |
+
kernel_size=(1, 4),
|
458 |
+
strides=(1, 1),
|
459 |
+
upsample=False,
|
460 |
+
noise=True,
|
461 |
+
emb=inp4,
|
462 |
+
name="1",
|
463 |
+
)
|
464 |
+
g1 = tf.math.sqrt(tf.cast(0.5, self.args.datatype)) * g1
|
465 |
+
g1 = g1 + tf.keras.layers.Conv2D(
|
466 |
+
g1.shape[-1],
|
467 |
+
kernel_size=(1, 1),
|
468 |
+
strides=1,
|
469 |
+
activation="linear",
|
470 |
+
padding="same",
|
471 |
+
kernel_initializer=self.init,
|
472 |
+
use_bias=True,
|
473 |
+
name="res1c",
|
474 |
+
)(self.pixel_shuffle(g))
|
475 |
+
else:
|
476 |
+
g1 = self.conv_util_gen(
|
477 |
+
g,
|
478 |
+
self.args.base_channels * 6,
|
479 |
+
kernel_size=(1, 1),
|
480 |
+
strides=(1, 1),
|
481 |
+
upsample=False,
|
482 |
+
noise=True,
|
483 |
+
emb=inp4,
|
484 |
+
name="0_small",
|
485 |
+
)
|
486 |
+
g1 = tf.math.sqrt(tf.cast(0.5, self.args.datatype)) * g1
|
487 |
+
g1 = self.conv_util_gen(
|
488 |
+
g1,
|
489 |
+
self.args.base_channels * 6,
|
490 |
+
kernel_size=(1, 1),
|
491 |
+
strides=(1, 1),
|
492 |
+
upsample=False,
|
493 |
+
noise=True,
|
494 |
+
emb=inp4,
|
495 |
+
name="1_small",
|
496 |
+
)
|
497 |
+
g1 = tf.math.sqrt(tf.cast(0.5, self.args.datatype)) * g1
|
498 |
+
g1 = g1 + tf.keras.layers.Conv2D(
|
499 |
+
g1.shape[-1],
|
500 |
+
kernel_size=(1, 1),
|
501 |
+
strides=1,
|
502 |
+
activation="linear",
|
503 |
+
padding="same",
|
504 |
+
kernel_initializer=self.init,
|
505 |
+
use_bias=True,
|
506 |
+
name="res1c_small",
|
507 |
+
)(g)
|
508 |
+
|
509 |
+
g2 = self.conv_util_gen(
|
510 |
+
g1,
|
511 |
+
self.args.base_channels * 5,
|
512 |
+
kernel_size=(1, 4),
|
513 |
+
strides=(1, 2),
|
514 |
+
upsample=True,
|
515 |
+
noise=True,
|
516 |
+
emb=inp3,
|
517 |
+
name="2",
|
518 |
+
)
|
519 |
+
g2 = tf.math.sqrt(tf.cast(0.5, self.args.datatype)) * g2
|
520 |
+
g2 = self.conv_util_gen(
|
521 |
+
g2,
|
522 |
+
self.args.base_channels * 5,
|
523 |
+
kernel_size=(1, 4),
|
524 |
+
strides=(1, 1),
|
525 |
+
upsample=False,
|
526 |
+
noise=True,
|
527 |
+
emb=inp3,
|
528 |
+
name="3",
|
529 |
+
)
|
530 |
+
g2 = tf.math.sqrt(tf.cast(0.5, self.args.datatype)) * g2
|
531 |
+
g2 = g2 + tf.keras.layers.Conv2D(
|
532 |
+
g2.shape[-1],
|
533 |
+
kernel_size=(1, 1),
|
534 |
+
strides=1,
|
535 |
+
activation="linear",
|
536 |
+
padding="same",
|
537 |
+
kernel_initializer=self.init,
|
538 |
+
use_bias=True,
|
539 |
+
name="res2c",
|
540 |
+
)(self.pixel_shuffle(g1))
|
541 |
+
|
542 |
+
g3 = self.conv_util_gen(
|
543 |
+
g2,
|
544 |
+
self.args.base_channels * 4,
|
545 |
+
kernel_size=(1, 4),
|
546 |
+
strides=(1, 2),
|
547 |
+
upsample=True,
|
548 |
+
noise=True,
|
549 |
+
emb=inp2,
|
550 |
+
name="4",
|
551 |
+
)
|
552 |
+
g3 = tf.math.sqrt(tf.cast(0.5, self.args.datatype)) * g3
|
553 |
+
g3 = self.conv_util_gen(
|
554 |
+
g3,
|
555 |
+
self.args.base_channels * 4,
|
556 |
+
kernel_size=(1, 4),
|
557 |
+
strides=(1, 1),
|
558 |
+
upsample=False,
|
559 |
+
noise=True,
|
560 |
+
emb=inp2,
|
561 |
+
name="5",
|
562 |
+
)
|
563 |
+
g3 = tf.math.sqrt(tf.cast(0.5, self.args.datatype)) * g3
|
564 |
+
g3 = g3 + tf.keras.layers.Conv2D(
|
565 |
+
g3.shape[-1],
|
566 |
+
kernel_size=(1, 1),
|
567 |
+
strides=1,
|
568 |
+
activation="linear",
|
569 |
+
padding="same",
|
570 |
+
kernel_initializer=self.init,
|
571 |
+
use_bias=True,
|
572 |
+
name="res3c",
|
573 |
+
)(self.pixel_shuffle(g2))
|
574 |
+
|
575 |
+
g4 = self.conv_util_gen(
|
576 |
+
g3,
|
577 |
+
self.args.base_channels * 3,
|
578 |
+
kernel_size=(1, 4),
|
579 |
+
strides=(1, 2),
|
580 |
+
upsample=True,
|
581 |
+
noise=True,
|
582 |
+
emb=inp1,
|
583 |
+
name="6",
|
584 |
+
)
|
585 |
+
g4 = tf.math.sqrt(tf.cast(0.5, self.args.datatype)) * g4
|
586 |
+
g4 = self.conv_util_gen(
|
587 |
+
g4,
|
588 |
+
self.args.base_channels * 3,
|
589 |
+
kernel_size=(1, 4),
|
590 |
+
strides=(1, 1),
|
591 |
+
upsample=False,
|
592 |
+
noise=True,
|
593 |
+
emb=inp1,
|
594 |
+
name="7",
|
595 |
+
)
|
596 |
+
g4 = tf.math.sqrt(tf.cast(0.5, self.args.datatype)) * g4
|
597 |
+
g4 = g4 + tf.keras.layers.Conv2D(
|
598 |
+
g4.shape[-1],
|
599 |
+
kernel_size=(1, 1),
|
600 |
+
strides=1,
|
601 |
+
activation="linear",
|
602 |
+
padding="same",
|
603 |
+
kernel_initializer=self.init,
|
604 |
+
use_bias=True,
|
605 |
+
name="res4c",
|
606 |
+
)(self.pixel_shuffle(g3))
|
607 |
+
|
608 |
+
g5 = self.conv_util_gen(
|
609 |
+
g4,
|
610 |
+
self.args.base_channels * 2,
|
611 |
+
kernel_size=(1, 4),
|
612 |
+
strides=(1, 2),
|
613 |
+
upsample=True,
|
614 |
+
noise=True,
|
615 |
+
emb=tf.expand_dims(tf.cast(inpb, dtype=self.args.datatype), -3),
|
616 |
+
name="8",
|
617 |
+
)
|
618 |
+
|
619 |
+
gf = tf.keras.layers.Conv2D(
|
620 |
+
dim, kernel_size=(1, 4), strides=(1, 1), kernel_initializer=self.init, padding="same", name="9c"
|
621 |
+
)(g5)
|
622 |
+
|
623 |
+
gfls = tf.split(gf, 2, 0)
|
624 |
+
gf = tf.concat(gfls, -2)
|
625 |
+
|
626 |
+
gf = tf.cast(gf, tf.float32)
|
627 |
+
|
628 |
+
return tf.keras.Model(inpf, gf, name="GEN")
|
629 |
+
|
630 |
+
# Load past models from path to resume training or test
|
631 |
+
def load(self, path, load_dec=False):
|
632 |
+
gen = self.build_generator()
|
633 |
+
critic = self.build_critic()
|
634 |
+
enc = self.build_encoder()
|
635 |
+
dec = self.build_decoder()
|
636 |
+
enc2 = self.build_encoder2()
|
637 |
+
dec2 = self.build_decoder2()
|
638 |
+
gen_ema = self.build_generator()
|
639 |
+
|
640 |
+
switch = tf.Variable(-1.0, dtype=tf.float32)
|
641 |
+
|
642 |
+
if self.args.mixed_precision:
|
643 |
+
opt_disc = self.mixed_precision.LossScaleOptimizer(tf.keras.optimizers.Adam(0.0001, 0.5))
|
644 |
+
opt_dec = self.mixed_precision.LossScaleOptimizer(tf.keras.optimizers.Adam(0.0001, 0.5))
|
645 |
+
else:
|
646 |
+
opt_disc = tf.keras.optimizers.Adam(0.0001, 0.9)
|
647 |
+
opt_dec = tf.keras.optimizers.Adam(0.0001, 0.9)
|
648 |
+
|
649 |
+
if load_dec:
|
650 |
+
dec.load_weights(self.args.dec_path + "/dec.h5")
|
651 |
+
dec2.load_weights(self.args.dec_path + "/dec2.h5")
|
652 |
+
enc.load_weights(self.args.dec_path + "/enc.h5")
|
653 |
+
enc2.load_weights(self.args.dec_path + "/enc2.h5")
|
654 |
+
|
655 |
+
else:
|
656 |
+
grad_vars = critic.trainable_weights
|
657 |
+
zero_grads = [tf.zeros_like(w) for w in grad_vars]
|
658 |
+
opt_disc.apply_gradients(zip(zero_grads, grad_vars))
|
659 |
+
|
660 |
+
grad_vars = gen.trainable_variables
|
661 |
+
zero_grads = [tf.zeros_like(w) for w in grad_vars]
|
662 |
+
opt_dec.apply_gradients(zip(zero_grads, grad_vars))
|
663 |
+
|
664 |
+
if not self.args.testing:
|
665 |
+
opt_disc.set_weights(np.load(path + "/opt_disc.npy", allow_pickle=True))
|
666 |
+
opt_dec.set_weights(np.load(path + "/opt_dec.npy", allow_pickle=True))
|
667 |
+
critic.load_weights(path + "/critic.h5")
|
668 |
+
gen.load_weights(path + "/gen.h5")
|
669 |
+
switch = tf.Variable(float(np.load(path + "/switch.npy", allow_pickle=True)), dtype=tf.float32)
|
670 |
+
|
671 |
+
gen_ema.load_weights(path + "/gen_ema.h5")
|
672 |
+
dec.load_weights(self.args.dec_path + "/dec.h5")
|
673 |
+
dec2.load_weights(self.args.dec_path + "/dec2.h5")
|
674 |
+
enc.load_weights(self.args.dec_path + "/enc.h5")
|
675 |
+
enc2.load_weights(self.args.dec_path + "/enc2.h5")
|
676 |
+
|
677 |
+
return (
|
678 |
+
critic,
|
679 |
+
gen,
|
680 |
+
enc,
|
681 |
+
dec,
|
682 |
+
enc2,
|
683 |
+
dec2,
|
684 |
+
gen_ema,
|
685 |
+
[opt_dec, opt_disc],
|
686 |
+
switch,
|
687 |
+
)
|
688 |
+
|
689 |
+
def build(self):
|
690 |
+
gen = self.build_generator()
|
691 |
+
critic = self.build_critic()
|
692 |
+
enc = self.build_encoder()
|
693 |
+
dec = self.build_decoder()
|
694 |
+
enc2 = self.build_encoder2()
|
695 |
+
dec2 = self.build_decoder2()
|
696 |
+
gen_ema = self.build_generator()
|
697 |
+
|
698 |
+
switch = tf.Variable(-1.0, dtype=tf.float32)
|
699 |
+
|
700 |
+
gen_ema = tf.keras.models.clone_model(gen)
|
701 |
+
gen_ema.set_weights(gen.get_weights())
|
702 |
+
|
703 |
+
if self.args.mixed_precision:
|
704 |
+
opt_disc = self.mixed_precision.LossScaleOptimizer(tf.keras.optimizers.Adam(0.0001, 0.5))
|
705 |
+
opt_dec = self.mixed_precision.LossScaleOptimizer(tf.keras.optimizers.Adam(0.0001, 0.5))
|
706 |
+
else:
|
707 |
+
opt_disc = tf.keras.optimizers.Adam(0.0001, 0.5)
|
708 |
+
opt_dec = tf.keras.optimizers.Adam(0.0001, 0.5)
|
709 |
+
|
710 |
+
return (
|
711 |
+
critic,
|
712 |
+
gen,
|
713 |
+
enc,
|
714 |
+
dec,
|
715 |
+
enc2,
|
716 |
+
dec2,
|
717 |
+
gen_ema,
|
718 |
+
[opt_dec, opt_disc],
|
719 |
+
switch,
|
720 |
+
)
|
721 |
+
|
722 |
+
def get_networks(self):
|
723 |
+
(
|
724 |
+
critic,
|
725 |
+
gen,
|
726 |
+
enc,
|
727 |
+
dec,
|
728 |
+
enc2,
|
729 |
+
dec2,
|
730 |
+
gen_ema_1,
|
731 |
+
[opt_dec, opt_disc],
|
732 |
+
switch,
|
733 |
+
) = self.load(self.args.load_path_1, load_dec=False)
|
734 |
+
print(f"Networks loaded from {self.args.load_path_1}")
|
735 |
+
|
736 |
+
(
|
737 |
+
critic,
|
738 |
+
gen,
|
739 |
+
enc,
|
740 |
+
dec,
|
741 |
+
enc2,
|
742 |
+
dec2,
|
743 |
+
gen_ema_2,
|
744 |
+
[opt_dec, opt_disc],
|
745 |
+
switch,
|
746 |
+
) = self.load(self.args.load_path_2, load_dec=False)
|
747 |
+
print(f"Networks loaded from {self.args.load_path_2}")
|
748 |
+
|
749 |
+
(
|
750 |
+
critic,
|
751 |
+
gen,
|
752 |
+
enc,
|
753 |
+
dec,
|
754 |
+
enc2,
|
755 |
+
dec2,
|
756 |
+
gen_ema_3,
|
757 |
+
[opt_dec, opt_disc],
|
758 |
+
switch,
|
759 |
+
) = self.load(self.args.load_path_3, load_dec=False)
|
760 |
+
print(f"Networks loaded from {self.args.load_path_3}")
|
761 |
+
|
762 |
+
return (
|
763 |
+
(critic, gen, enc, dec, enc2, dec2, gen_ema_1, [opt_dec, opt_disc], switch),
|
764 |
+
(critic, gen, enc, dec, enc2, dec2, gen_ema_2, [opt_dec, opt_disc], switch),
|
765 |
+
(critic, gen, enc, dec, enc2, dec2, gen_ema_3, [opt_dec, opt_disc], switch),
|
766 |
+
)
|
767 |
+
|
768 |
+
def initialize_networks(self):
|
769 |
+
|
770 |
+
(
|
771 |
+
(critic, gen, enc, dec, enc2, dec2, gen_ema_1, [opt_dec, opt_disc], switch),
|
772 |
+
(critic, gen, enc, dec, enc2, dec2, gen_ema_2, [opt_dec, opt_disc], switch),
|
773 |
+
(critic, gen, enc, dec, enc2, dec2, gen_ema_3, [opt_dec, opt_disc], switch),
|
774 |
+
) = self.get_networks()
|
775 |
+
|
776 |
+
print(f"Critic params: {count_params(critic.trainable_variables)}")
|
777 |
+
print(f"Generator params: {count_params(gen.trainable_variables)}")
|
778 |
+
|
779 |
+
return (
|
780 |
+
(critic, gen, enc, dec, enc2, dec2, gen_ema_1, [opt_dec, opt_disc], switch),
|
781 |
+
(critic, gen, enc, dec, enc2, dec2, gen_ema_2, [opt_dec, opt_disc], switch),
|
782 |
+
(critic, gen, enc, dec, enc2, dec2, gen_ema_3, [opt_dec, opt_disc], switch),
|
783 |
+
)
|
musika_test.py
ADDED
@@ -0,0 +1,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
|
3 |
+
os.environ["TF_CPP_MIN_LOG_LEVEL"] = "3"
|
4 |
+
|
5 |
+
from parse_test import parse_args
|
6 |
+
from models import Models_functions
|
7 |
+
from utils import Utils_functions
|
8 |
+
|
9 |
+
if __name__ == "__main__":
|
10 |
+
|
11 |
+
# parse args
|
12 |
+
args = parse_args()
|
13 |
+
|
14 |
+
# initialize networks
|
15 |
+
M = Models_functions(args)
|
16 |
+
models_ls_1, models_ls_2, models_ls_3 = M.get_networks()
|
17 |
+
|
18 |
+
# test musika
|
19 |
+
U = Utils_functions(args)
|
20 |
+
U.render_gradio(models_ls_1, models_ls_2, models_ls_3, train=False)
|
parse_test.py
ADDED
@@ -0,0 +1,196 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 str2bool(v):
|
21 |
+
if isinstance(v, bool):
|
22 |
+
return v
|
23 |
+
if v.lower() in ("yes", "true", "t", "y", "1"):
|
24 |
+
return True
|
25 |
+
elif v.lower() in ("no", "false", "f", "n", "0"):
|
26 |
+
return False
|
27 |
+
else:
|
28 |
+
raise argparse.ArgumentTypeError("Boolean value expected.")
|
29 |
+
|
30 |
+
|
31 |
+
def params_args(args):
|
32 |
+
parser = argparse.ArgumentParser()
|
33 |
+
|
34 |
+
parser.add_argument(
|
35 |
+
"--hop",
|
36 |
+
type=int,
|
37 |
+
default=256,
|
38 |
+
help="Hop size (window size = 4*hop)",
|
39 |
+
)
|
40 |
+
parser.add_argument(
|
41 |
+
"--mel_bins",
|
42 |
+
type=int,
|
43 |
+
default=256,
|
44 |
+
help="Mel bins in mel-spectrograms",
|
45 |
+
)
|
46 |
+
parser.add_argument(
|
47 |
+
"--sr",
|
48 |
+
type=int,
|
49 |
+
default=44100,
|
50 |
+
help="Sampling Rate",
|
51 |
+
)
|
52 |
+
parser.add_argument(
|
53 |
+
"--small",
|
54 |
+
type=str2bool,
|
55 |
+
default=False,
|
56 |
+
help="If True, use model with shorter available context, useful for small datasets",
|
57 |
+
)
|
58 |
+
parser.add_argument(
|
59 |
+
"--latdepth",
|
60 |
+
type=int,
|
61 |
+
default=64,
|
62 |
+
help="Depth of generated latent vectors",
|
63 |
+
)
|
64 |
+
parser.add_argument(
|
65 |
+
"--coorddepth",
|
66 |
+
type=int,
|
67 |
+
default=64,
|
68 |
+
help="Dimension of latent coordinate and style random vectors",
|
69 |
+
)
|
70 |
+
parser.add_argument(
|
71 |
+
"--base_channels",
|
72 |
+
type=int,
|
73 |
+
default=128,
|
74 |
+
help="Base channels for generator and discriminator architectures",
|
75 |
+
)
|
76 |
+
parser.add_argument(
|
77 |
+
"--shape",
|
78 |
+
type=int,
|
79 |
+
default=128,
|
80 |
+
help="Length of spectrograms time axis",
|
81 |
+
)
|
82 |
+
parser.add_argument(
|
83 |
+
"--window",
|
84 |
+
type=int,
|
85 |
+
default=64,
|
86 |
+
help="Generator spectrogram window (must divide shape)",
|
87 |
+
)
|
88 |
+
parser.add_argument(
|
89 |
+
"--mu_rescale",
|
90 |
+
type=float,
|
91 |
+
default=-25.0,
|
92 |
+
help="Spectrogram mu used to normalize",
|
93 |
+
)
|
94 |
+
parser.add_argument(
|
95 |
+
"--sigma_rescale",
|
96 |
+
type=float,
|
97 |
+
default=75.0,
|
98 |
+
help="Spectrogram sigma used to normalize",
|
99 |
+
)
|
100 |
+
parser.add_argument(
|
101 |
+
"--load_path_1",
|
102 |
+
type=str,
|
103 |
+
default="checkpoints/techno/",
|
104 |
+
help="Path of pretrained networks weights 1",
|
105 |
+
)
|
106 |
+
parser.add_argument(
|
107 |
+
"--load_path_2",
|
108 |
+
type=str,
|
109 |
+
default="checkpoints/metal/",
|
110 |
+
help="Path of pretrained networks weights 2",
|
111 |
+
)
|
112 |
+
parser.add_argument(
|
113 |
+
"--load_path_3",
|
114 |
+
type=str,
|
115 |
+
default="checkpoints/misc/",
|
116 |
+
help="Path of pretrained networks weights 3",
|
117 |
+
)
|
118 |
+
parser.add_argument(
|
119 |
+
"--dec_path",
|
120 |
+
type=str,
|
121 |
+
default="checkpoints/ae/",
|
122 |
+
help="Path of pretrained decoders weights",
|
123 |
+
)
|
124 |
+
parser.add_argument(
|
125 |
+
"--testing",
|
126 |
+
type=str2bool,
|
127 |
+
default=True,
|
128 |
+
help="True if optimizers weight do not need to be loaded",
|
129 |
+
)
|
130 |
+
parser.add_argument(
|
131 |
+
"--cpu",
|
132 |
+
type=str2bool,
|
133 |
+
default=False,
|
134 |
+
help="True if you wish to use cpu",
|
135 |
+
)
|
136 |
+
parser.add_argument(
|
137 |
+
"--mixed_precision",
|
138 |
+
type=str2bool,
|
139 |
+
default=True,
|
140 |
+
help="True if your GPU supports mixed precision",
|
141 |
+
)
|
142 |
+
|
143 |
+
tmp_args = parser.parse_args()
|
144 |
+
|
145 |
+
args.hop = tmp_args.hop
|
146 |
+
args.mel_bins = tmp_args.mel_bins
|
147 |
+
args.sr = tmp_args.sr
|
148 |
+
args.small = tmp_args.small
|
149 |
+
args.latdepth = tmp_args.latdepth
|
150 |
+
args.coorddepth = tmp_args.coorddepth
|
151 |
+
args.base_channels = tmp_args.base_channels
|
152 |
+
args.shape = tmp_args.shape
|
153 |
+
args.window = tmp_args.window
|
154 |
+
args.mu_rescale = tmp_args.mu_rescale
|
155 |
+
args.sigma_rescale = tmp_args.sigma_rescale
|
156 |
+
args.load_path_1 = tmp_args.load_path_1
|
157 |
+
args.load_path_2 = tmp_args.load_path_2
|
158 |
+
args.load_path_3 = tmp_args.load_path_3
|
159 |
+
args.dec_path = tmp_args.dec_path
|
160 |
+
args.testing = tmp_args.testing
|
161 |
+
args.cpu = tmp_args.cpu
|
162 |
+
args.mixed_precision = tmp_args.mixed_precision
|
163 |
+
|
164 |
+
if args.small:
|
165 |
+
args.latlen = 128
|
166 |
+
else:
|
167 |
+
args.latlen = 256
|
168 |
+
args.coordlen = (args.latlen // 2) * 3
|
169 |
+
|
170 |
+
print()
|
171 |
+
|
172 |
+
args.datatype = tf.float32
|
173 |
+
gpuls = tf.config.list_physical_devices("GPU")
|
174 |
+
if len(gpuls) == 0 or args.cpu:
|
175 |
+
args.cpu = True
|
176 |
+
args.mixed_precision = False
|
177 |
+
tf.config.set_visible_devices([], "GPU")
|
178 |
+
print()
|
179 |
+
print("Using CPU...")
|
180 |
+
print()
|
181 |
+
if args.mixed_precision:
|
182 |
+
args.datatype = tf.float16
|
183 |
+
print()
|
184 |
+
print("Using GPU with mixed precision enabled...")
|
185 |
+
print()
|
186 |
+
if not args.mixed_precision and not args.cpu:
|
187 |
+
print()
|
188 |
+
print("Using GPU without mixed precision...")
|
189 |
+
print()
|
190 |
+
|
191 |
+
return args
|
192 |
+
|
193 |
+
|
194 |
+
def parse_args():
|
195 |
+
args = EasyDict()
|
196 |
+
return params_args(args)
|
requirements.txt
ADDED
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# This file may be used to create an environment using:
|
2 |
+
# $ conda create --name <env> --file <this file>
|
3 |
+
# platform: linux-64
|
4 |
+
gradio==3.3.1
|
5 |
+
librosa==0.8.1
|
6 |
+
matplotlib==3.4.3
|
7 |
+
numpy==1.20.3
|
8 |
+
scipy==1.7.1
|
9 |
+
tensorboard==2.10.0
|
10 |
+
tensorflow==2.10.0
|
11 |
+
tqdm==4.62.3
|
12 |
+
pydub==0.25.1
|
utils.py
ADDED
@@ -0,0 +1,689 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import time
|
3 |
+
import datetime
|
4 |
+
from glob import glob
|
5 |
+
from tqdm import tqdm
|
6 |
+
import librosa
|
7 |
+
import matplotlib.pyplot as plt
|
8 |
+
import numpy as np
|
9 |
+
import tensorflow as tf
|
10 |
+
from tensorflow.python.framework import random_seed
|
11 |
+
import gradio as gr
|
12 |
+
from scipy.io.wavfile import write as write_wav
|
13 |
+
|
14 |
+
|
15 |
+
class Utils_functions:
|
16 |
+
def __init__(self, args):
|
17 |
+
|
18 |
+
self.args = args
|
19 |
+
|
20 |
+
melmat = tf.signal.linear_to_mel_weight_matrix(
|
21 |
+
num_mel_bins=args.mel_bins,
|
22 |
+
num_spectrogram_bins=(4 * args.hop * 2) // 2 + 1,
|
23 |
+
sample_rate=args.sr,
|
24 |
+
lower_edge_hertz=0.0,
|
25 |
+
upper_edge_hertz=args.sr // 2,
|
26 |
+
)
|
27 |
+
mel_f = tf.convert_to_tensor(librosa.mel_frequencies(n_mels=args.mel_bins + 2, fmin=0.0, fmax=args.sr // 2))
|
28 |
+
enorm = tf.cast(
|
29 |
+
tf.expand_dims(
|
30 |
+
tf.constant(2.0 / (mel_f[2 : args.mel_bins + 2] - mel_f[: args.mel_bins])),
|
31 |
+
0,
|
32 |
+
),
|
33 |
+
tf.float32,
|
34 |
+
)
|
35 |
+
melmat = tf.multiply(melmat, enorm)
|
36 |
+
melmat = tf.divide(melmat, tf.reduce_sum(melmat, axis=0))
|
37 |
+
self.melmat = tf.where(tf.math.is_nan(melmat), tf.zeros_like(melmat), melmat)
|
38 |
+
|
39 |
+
with np.errstate(divide="ignore", invalid="ignore"):
|
40 |
+
self.melmatinv = tf.constant(np.nan_to_num(np.divide(melmat.numpy().T, np.sum(melmat.numpy(), axis=1))).T)
|
41 |
+
|
42 |
+
def conc_tog_specphase(self, S, P):
|
43 |
+
S = tf.cast(S, tf.float32)
|
44 |
+
P = tf.cast(P, tf.float32)
|
45 |
+
S = self.denormalize(S, clip=False)
|
46 |
+
S = tf.math.sqrt(self.db2power(S) + 1e-7)
|
47 |
+
P = P * np.pi
|
48 |
+
Sls = tf.split(S, S.shape[0], 0)
|
49 |
+
S = tf.squeeze(tf.concat(Sls, 1), 0)
|
50 |
+
Pls = tf.split(P, P.shape[0], 0)
|
51 |
+
P = tf.squeeze(tf.concat(Pls, 1), 0)
|
52 |
+
SP = tf.cast(S, tf.complex64) * tf.math.exp(1j * tf.cast(P, tf.complex64))
|
53 |
+
wv = tf.signal.inverse_stft(
|
54 |
+
SP,
|
55 |
+
4 * self.args.hop,
|
56 |
+
self.args.hop,
|
57 |
+
fft_length=4 * self.args.hop,
|
58 |
+
window_fn=tf.signal.inverse_stft_window_fn(self.args.hop),
|
59 |
+
)
|
60 |
+
return np.squeeze(wv)
|
61 |
+
|
62 |
+
def _tf_log10(self, x):
|
63 |
+
numerator = tf.math.log(x)
|
64 |
+
denominator = tf.math.log(tf.constant(10, dtype=numerator.dtype))
|
65 |
+
return numerator / denominator
|
66 |
+
|
67 |
+
def normalize(self, S, clip=False):
|
68 |
+
S = (S - self.args.mu_rescale) / self.args.sigma_rescale
|
69 |
+
if clip:
|
70 |
+
S = tf.clip_by_value(S, -1.0, 1.0)
|
71 |
+
return S
|
72 |
+
|
73 |
+
def normalize_rel(self, S):
|
74 |
+
S = S - tf.math.reduce_min(S + 1e-7)
|
75 |
+
S = (S / (tf.math.reduce_max(S + 1e-7) + 1e-7)) + 1e-7
|
76 |
+
return S
|
77 |
+
|
78 |
+
def denormalize(self, S, clip=False):
|
79 |
+
if clip:
|
80 |
+
S = tf.clip_by_value(S, -1.0, 1.0)
|
81 |
+
return (S * self.args.sigma_rescale) + self.args.mu_rescale
|
82 |
+
|
83 |
+
def amp2db(self, x):
|
84 |
+
return 20 * self._tf_log10(tf.clip_by_value(tf.abs(x), 1e-5, 1e100))
|
85 |
+
|
86 |
+
def db2amp(self, x):
|
87 |
+
return tf.pow(tf.ones(tf.shape(x)) * 10.0, x * 0.05)
|
88 |
+
|
89 |
+
def power2db(self, power, ref_value=1.0, amin=1e-10, top_db=None, norm=False):
|
90 |
+
log_spec = 10.0 * self._tf_log10(tf.maximum(amin, power))
|
91 |
+
log_spec -= 10.0 * self._tf_log10(tf.maximum(amin, ref_value))
|
92 |
+
if top_db is not None:
|
93 |
+
log_spec = tf.maximum(log_spec, tf.reduce_max(log_spec) - top_db)
|
94 |
+
return log_spec
|
95 |
+
|
96 |
+
def power2db_batch(self, power, ref_value=1.0, amin=1e-10, top_db=None, norm=False):
|
97 |
+
log_spec = 10.0 * self._tf_log10(tf.maximum(amin, power))
|
98 |
+
log_spec -= 10.0 * self._tf_log10(tf.maximum(amin, ref_value))
|
99 |
+
if top_db is not None:
|
100 |
+
log_spec = tf.maximum(log_spec, tf.reduce_max(log_spec, [-2, -1], keepdims=True) - top_db)
|
101 |
+
return log_spec
|
102 |
+
|
103 |
+
def db2power(self, S_db, ref=1.0):
|
104 |
+
return ref * tf.math.pow(10.0, 0.1 * S_db)
|
105 |
+
|
106 |
+
def wv2mel(self, wv, topdb=80.0):
|
107 |
+
X = tf.signal.stft(
|
108 |
+
wv,
|
109 |
+
frame_length=4 * self.args.hop,
|
110 |
+
frame_step=self.args.hop,
|
111 |
+
fft_length=4 * self.args.hop,
|
112 |
+
window_fn=tf.signal.hann_window,
|
113 |
+
pad_end=False,
|
114 |
+
)
|
115 |
+
S = self.normalize(self.power2db(tf.abs(X) ** 2, top_db=topdb) - self.args.ref_level_db)
|
116 |
+
SM = tf.tensordot(S, self.melmat, 1)
|
117 |
+
return SM
|
118 |
+
|
119 |
+
def mel2spec(self, SM):
|
120 |
+
return tf.tensordot(SM, tf.transpose(self.melmatinv), 1)
|
121 |
+
|
122 |
+
def spec2mel(self, S):
|
123 |
+
return tf.tensordot(S, self.melmat, 1)
|
124 |
+
|
125 |
+
def wv2spec(self, wv, hop_size=256, fac=4):
|
126 |
+
X = tf.signal.stft(
|
127 |
+
wv,
|
128 |
+
frame_length=fac * hop_size,
|
129 |
+
frame_step=hop_size,
|
130 |
+
fft_length=fac * hop_size,
|
131 |
+
window_fn=tf.signal.hann_window,
|
132 |
+
pad_end=False,
|
133 |
+
)
|
134 |
+
return self.normalize(self.power2db(tf.abs(X) ** 2, top_db=None))
|
135 |
+
|
136 |
+
def wv2spec_hop(self, wv, topdb=80.0, hopsize=256):
|
137 |
+
X = tf.signal.stft(
|
138 |
+
wv,
|
139 |
+
frame_length=4 * hopsize,
|
140 |
+
frame_step=hopsize,
|
141 |
+
fft_length=4 * hopsize,
|
142 |
+
window_fn=tf.signal.hann_window,
|
143 |
+
pad_end=False,
|
144 |
+
)
|
145 |
+
S = self.normalize(self.power2db(tf.abs(X) ** 2, top_db=topdb))
|
146 |
+
return tf.tensordot(S, self.melmat, 1)
|
147 |
+
|
148 |
+
def rand_channel_swap(self, x):
|
149 |
+
s_l, s_r = tf.split(x, 2, -1)
|
150 |
+
if tf.random.uniform((), dtype=tf.float32) > 0.5:
|
151 |
+
sl = s_l
|
152 |
+
sr = s_r
|
153 |
+
else:
|
154 |
+
sl = s_r
|
155 |
+
sr = s_l
|
156 |
+
return tf.concat([sl, sr], -1)
|
157 |
+
|
158 |
+
def distribute(self, x, model, bs=32, dual_out=False):
|
159 |
+
outls = []
|
160 |
+
if isinstance(x, list):
|
161 |
+
bdim = x[0].shape[0]
|
162 |
+
for i in range(((bdim - 2) // bs) + 1):
|
163 |
+
outls.append(model([el[i * bs : i * bs + bs] for el in x], training=False))
|
164 |
+
else:
|
165 |
+
bdim = x.shape[0]
|
166 |
+
for i in range(((bdim - 2) // bs) + 1):
|
167 |
+
outls.append(model(x[i * bs : i * bs + bs], training=False))
|
168 |
+
|
169 |
+
if dual_out:
|
170 |
+
return np.concatenate([outls[k][0] for k in range(len(outls))], 0), np.concatenate(
|
171 |
+
[outls[k][1] for k in range(len(outls))], 0
|
172 |
+
)
|
173 |
+
else:
|
174 |
+
return np.concatenate(outls, 0)
|
175 |
+
|
176 |
+
def distribute_enc(self, x, model, bs=32):
|
177 |
+
outls = []
|
178 |
+
if isinstance(x, list):
|
179 |
+
bdim = x[0].shape[0]
|
180 |
+
for i in range(((bdim - 2) // bs) + 1):
|
181 |
+
res = model([el[i * bs : i * bs + bs] for el in x], training=False)
|
182 |
+
resls = tf.split(res, self.args.shape // self.args.window, 0)
|
183 |
+
res = tf.concat(resls, -2)
|
184 |
+
outls.append(res)
|
185 |
+
else:
|
186 |
+
bdim = x.shape[0]
|
187 |
+
for i in range(((bdim - 2) // bs) + 1):
|
188 |
+
res = model(x[i * bs : i * bs + bs], training=False)
|
189 |
+
resls = tf.split(res, self.args.shape // self.args.window, 0)
|
190 |
+
res = tf.concat(resls, -2)
|
191 |
+
outls.append(res)
|
192 |
+
|
193 |
+
return tf.concat(outls, 0)
|
194 |
+
|
195 |
+
def distribute_dec(self, x, model, bs=32):
|
196 |
+
outls = []
|
197 |
+
bdim = x.shape[0]
|
198 |
+
for i in range(((bdim - 2) // bs) + 1):
|
199 |
+
inp = x[i * bs : i * bs + bs]
|
200 |
+
inpls = tf.split(inp, 2, -2)
|
201 |
+
inp = tf.concat(inpls, 0)
|
202 |
+
res = model(inp, training=False)
|
203 |
+
outls.append(res)
|
204 |
+
return np.concatenate([outls[k][0] for k in range(len(outls))], 0), np.concatenate(
|
205 |
+
[outls[k][1] for k in range(len(outls))], 0
|
206 |
+
)
|
207 |
+
|
208 |
+
def distribute_dec2(self, x, model, bs=32):
|
209 |
+
outls = []
|
210 |
+
bdim = x.shape[0]
|
211 |
+
for i in range(((bdim - 2) // bs) + 1):
|
212 |
+
inp1 = x[i * bs : i * bs + bs]
|
213 |
+
inpls = tf.split(inp1, 2, -2)
|
214 |
+
inp1 = tf.concat(inpls, 0)
|
215 |
+
outls.append(model(inp1, training=False))
|
216 |
+
|
217 |
+
return tf.concat(outls, 0)
|
218 |
+
|
219 |
+
def center_coordinate(
|
220 |
+
self, x
|
221 |
+
): # allows to have sequences with even number length with anchor in the middle of the sequence
|
222 |
+
return tf.reduce_mean(tf.stack([x, tf.roll(x, -1, -2)], 0), 0)[:, :-1, :]
|
223 |
+
|
224 |
+
# hardcoded! need to figure out how to generalize it without breaking jit compiling
|
225 |
+
def crop_coordinate(
|
226 |
+
self, x
|
227 |
+
): # randomly crops a conditioning sequence such that the anchor vector is at center of generator receptive field (maximum context is provided to the generator)
|
228 |
+
fac = tf.random.uniform((), 0, self.args.coordlen // (self.args.latlen // 2), dtype=tf.int32)
|
229 |
+
if fac == 0:
|
230 |
+
return tf.reshape(
|
231 |
+
x[
|
232 |
+
:,
|
233 |
+
(self.args.latlen // 4)
|
234 |
+
+ 0 * (self.args.latlen // 2) : (self.args.latlen // 4)
|
235 |
+
+ 0 * (self.args.latlen // 2)
|
236 |
+
+ self.args.latlen,
|
237 |
+
:,
|
238 |
+
],
|
239 |
+
[-1, self.args.latlen, x.shape[-1]],
|
240 |
+
)
|
241 |
+
elif fac == 1:
|
242 |
+
return tf.reshape(
|
243 |
+
x[
|
244 |
+
:,
|
245 |
+
(self.args.latlen // 4)
|
246 |
+
+ 1 * (self.args.latlen // 2) : (self.args.latlen // 4)
|
247 |
+
+ 1 * (self.args.latlen // 2)
|
248 |
+
+ self.args.latlen,
|
249 |
+
:,
|
250 |
+
],
|
251 |
+
[-1, self.args.latlen, x.shape[-1]],
|
252 |
+
)
|
253 |
+
else:
|
254 |
+
return tf.reshape(
|
255 |
+
x[
|
256 |
+
:,
|
257 |
+
(self.args.latlen // 4)
|
258 |
+
+ 2 * (self.args.latlen // 2) : (self.args.latlen // 4)
|
259 |
+
+ 2 * (self.args.latlen // 2)
|
260 |
+
+ self.args.latlen,
|
261 |
+
:,
|
262 |
+
],
|
263 |
+
[-1, self.args.latlen, x.shape[-1]],
|
264 |
+
)
|
265 |
+
|
266 |
+
def update_switch(self, switch, ca, cab, learning_rate_switch=0.0001, stable_point=0.9):
|
267 |
+
cert = tf.math.minimum(tf.math.maximum(tf.reduce_mean(ca) - tf.reduce_mean(cab), 0.0), 2.0) / 2.0
|
268 |
+
|
269 |
+
if cert > stable_point:
|
270 |
+
switch_new = switch - learning_rate_switch
|
271 |
+
else:
|
272 |
+
switch_new = switch + learning_rate_switch
|
273 |
+
return tf.math.maximum(tf.math.minimum(switch_new, 0.0), -1.0)
|
274 |
+
|
275 |
+
def get_noise_interp(self):
|
276 |
+
noiseg = tf.random.normal([1, 64], dtype=tf.float32)
|
277 |
+
|
278 |
+
noisel = tf.concat([tf.random.normal([1, self.args.coorddepth], dtype=tf.float32), noiseg], -1)
|
279 |
+
noisec = tf.concat([tf.random.normal([1, self.args.coorddepth], dtype=tf.float32), noiseg], -1)
|
280 |
+
noiser = tf.concat([tf.random.normal([1, self.args.coorddepth], dtype=tf.float32), noiseg], -1)
|
281 |
+
|
282 |
+
rl = tf.linspace(noisel, noisec, self.args.coordlen + 1, axis=-2)[:, :-1, :]
|
283 |
+
rr = tf.linspace(noisec, noiser, self.args.coordlen + 1, axis=-2)
|
284 |
+
|
285 |
+
noisetot = tf.concat([rl, rr], -2)
|
286 |
+
noisetot = self.center_coordinate(noisetot)
|
287 |
+
return self.crop_coordinate(noisetot)
|
288 |
+
|
289 |
+
def generate_example_stereo(self, models_ls):
|
290 |
+
(
|
291 |
+
critic,
|
292 |
+
gen,
|
293 |
+
enc,
|
294 |
+
dec,
|
295 |
+
enc2,
|
296 |
+
dec2,
|
297 |
+
gen_ema,
|
298 |
+
[opt_dec, opt_disc],
|
299 |
+
switch,
|
300 |
+
) = models_ls
|
301 |
+
abb = gen_ema(self.get_noise_interp(), training=False)
|
302 |
+
abbls = tf.split(abb, abb.shape[-2] // 8, -2)
|
303 |
+
abb = tf.concat(abbls, 0)
|
304 |
+
|
305 |
+
chls = []
|
306 |
+
for channel in range(2):
|
307 |
+
|
308 |
+
ab = self.distribute_dec2(
|
309 |
+
abb[
|
310 |
+
:,
|
311 |
+
:,
|
312 |
+
:,
|
313 |
+
channel * self.args.latdepth : channel * self.args.latdepth + self.args.latdepth,
|
314 |
+
],
|
315 |
+
dec2,
|
316 |
+
)
|
317 |
+
abls = tf.split(ab, ab.shape[-2] // self.args.shape, -2)
|
318 |
+
ab = tf.concat(abls, 0)
|
319 |
+
ab_m, ab_p = self.distribute_dec(ab, dec)
|
320 |
+
wv = self.conc_tog_specphase(ab_m, ab_p)
|
321 |
+
chls.append(wv)
|
322 |
+
|
323 |
+
return np.stack(chls, -1)
|
324 |
+
|
325 |
+
# Save in training loop
|
326 |
+
def save_test_image_full(self, path, models_ls=None):
|
327 |
+
|
328 |
+
abwv = self.generate_example_stereo(models_ls)
|
329 |
+
abwv2 = self.generate_example_stereo(models_ls)
|
330 |
+
abwv3 = self.generate_example_stereo(models_ls)
|
331 |
+
abwv4 = self.generate_example_stereo(models_ls)
|
332 |
+
|
333 |
+
# IPython.display.display(
|
334 |
+
# IPython.display.Audio(np.squeeze(np.transpose(abwv)), rate=self.args.sr)
|
335 |
+
# )
|
336 |
+
# IPython.display.display(
|
337 |
+
# IPython.display.Audio(np.squeeze(np.transpose(abwv2)), rate=self.args.sr)
|
338 |
+
# )
|
339 |
+
# IPython.display.display(
|
340 |
+
# IPython.display.Audio(np.squeeze(np.transpose(abwv3)), rate=self.args.sr)
|
341 |
+
# )
|
342 |
+
# IPython.display.display(
|
343 |
+
# IPython.display.Audio(np.squeeze(np.transpose(abwv4)), rate=self.args.sr)
|
344 |
+
# )
|
345 |
+
|
346 |
+
write_wav(f"{path}/out1.wav", self.args.sr, np.squeeze(abwv))
|
347 |
+
write_wav(f"{path}/out2.wav", self.args.sr, np.squeeze(abwv2))
|
348 |
+
write_wav(f"{path}/out3.wav", self.args.sr, np.squeeze(abwv3))
|
349 |
+
write_wav(f"{path}/out4.wav", self.args.sr, np.squeeze(abwv4))
|
350 |
+
|
351 |
+
fig, axs = plt.subplots(nrows=4, ncols=1, figsize=(20, 20))
|
352 |
+
axs[0].imshow(
|
353 |
+
np.flip(
|
354 |
+
np.array(
|
355 |
+
tf.transpose(
|
356 |
+
self.wv2spec_hop((abwv[:, 0] + abwv[:, 1]) / 2.0, 80.0, self.args.hop * 2),
|
357 |
+
[1, 0],
|
358 |
+
)
|
359 |
+
),
|
360 |
+
-2,
|
361 |
+
),
|
362 |
+
cmap=None,
|
363 |
+
)
|
364 |
+
axs[0].axis("off")
|
365 |
+
axs[0].set_title("Generated1")
|
366 |
+
axs[1].imshow(
|
367 |
+
np.flip(
|
368 |
+
np.array(
|
369 |
+
tf.transpose(
|
370 |
+
self.wv2spec_hop((abwv2[:, 0] + abwv2[:, 1]) / 2.0, 80.0, self.args.hop * 2),
|
371 |
+
[1, 0],
|
372 |
+
)
|
373 |
+
),
|
374 |
+
-2,
|
375 |
+
),
|
376 |
+
cmap=None,
|
377 |
+
)
|
378 |
+
axs[1].axis("off")
|
379 |
+
axs[1].set_title("Generated2")
|
380 |
+
axs[2].imshow(
|
381 |
+
np.flip(
|
382 |
+
np.array(
|
383 |
+
tf.transpose(
|
384 |
+
self.wv2spec_hop((abwv3[:, 0] + abwv3[:, 1]) / 2.0, 80.0, self.args.hop * 2),
|
385 |
+
[1, 0],
|
386 |
+
)
|
387 |
+
),
|
388 |
+
-2,
|
389 |
+
),
|
390 |
+
cmap=None,
|
391 |
+
)
|
392 |
+
axs[2].axis("off")
|
393 |
+
axs[2].set_title("Generated3")
|
394 |
+
axs[3].imshow(
|
395 |
+
np.flip(
|
396 |
+
np.array(
|
397 |
+
tf.transpose(
|
398 |
+
self.wv2spec_hop((abwv4[:, 0] + abwv4[:, 1]) / 2.0, 80.0, self.args.hop * 2),
|
399 |
+
[1, 0],
|
400 |
+
)
|
401 |
+
),
|
402 |
+
-2,
|
403 |
+
),
|
404 |
+
cmap=None,
|
405 |
+
)
|
406 |
+
axs[3].axis("off")
|
407 |
+
axs[3].set_title("Generated4")
|
408 |
+
# plt.show()
|
409 |
+
plt.savefig(f"{path}/output.png")
|
410 |
+
plt.close()
|
411 |
+
|
412 |
+
def save_end(
|
413 |
+
self,
|
414 |
+
epoch,
|
415 |
+
gloss,
|
416 |
+
closs,
|
417 |
+
mloss,
|
418 |
+
models_ls=None,
|
419 |
+
n_save=3,
|
420 |
+
save_path="checkpoints",
|
421 |
+
):
|
422 |
+
(critic, gen, enc, dec, enc2, dec2, gen_ema, [opt_dec, opt_disc], switch) = models_ls
|
423 |
+
if epoch % n_save == 0:
|
424 |
+
print("Saving...")
|
425 |
+
path = f"{save_path}/MUSIKA_iterations-{((epoch+1)*self.args.totsamples)//(self.args.bs*1000)}k_losses-{str(gloss)[:9]}-{str(closs)[:9]}-{str(mloss)[:9]}"
|
426 |
+
os.mkdir(path)
|
427 |
+
critic.save_weights(path + "/critic.h5")
|
428 |
+
gen.save_weights(path + "/gen.h5")
|
429 |
+
gen_ema.save_weights(path + "/gen_ema.h5")
|
430 |
+
# enc.save_weights(path + "/enc.h5")
|
431 |
+
# dec.save_weights(path + "/dec.h5")
|
432 |
+
# enc2.save_weights(path + "/enc2.h5")
|
433 |
+
# dec2.save_weights(path + "/dec2.h5")
|
434 |
+
np.save(path + "/opt_dec.npy", opt_dec.get_weights())
|
435 |
+
np.save(path + "/opt_disc.npy", opt_disc.get_weights())
|
436 |
+
np.save(path + "/switch.npy", switch.numpy())
|
437 |
+
self.save_test_image_full(path, models_ls=models_ls)
|
438 |
+
|
439 |
+
def truncated_normal(self, shape, bound=2.0, dtype=tf.float32):
|
440 |
+
seed1, seed2 = random_seed.get_seed(tf.random.uniform((), tf.int32.min, tf.int32.max, dtype=tf.int32))
|
441 |
+
return tf.random.stateless_parameterized_truncated_normal(shape, [seed1, seed2], 0.0, 1.0, -bound, bound)
|
442 |
+
|
443 |
+
def distribute_gen(self, x, model, bs=32):
|
444 |
+
outls = []
|
445 |
+
bdim = x.shape[0]
|
446 |
+
if bdim == 1:
|
447 |
+
bdim = 2
|
448 |
+
for i in range(((bdim - 2) // bs) + 1):
|
449 |
+
outls.append(model(x[i * bs : i * bs + bs], training=False))
|
450 |
+
return tf.concat(outls, 0)
|
451 |
+
|
452 |
+
def generate_waveform(self, inp, gen_ema, dec, dec2, batch_size=64):
|
453 |
+
|
454 |
+
ab = self.distribute_gen(inp, gen_ema, bs=batch_size)
|
455 |
+
abls = tf.split(ab, ab.shape[0], 0)
|
456 |
+
ab = tf.concat(abls, -2)
|
457 |
+
abls = tf.split(ab, ab.shape[-2] // 8, -2)
|
458 |
+
abi = tf.concat(abls, 0)
|
459 |
+
|
460 |
+
chls = []
|
461 |
+
for channel in range(2):
|
462 |
+
|
463 |
+
ab = self.distribute_dec2(
|
464 |
+
abi[:, :, :, channel * self.args.latdepth : channel * self.args.latdepth + self.args.latdepth],
|
465 |
+
dec2,
|
466 |
+
bs=batch_size,
|
467 |
+
)
|
468 |
+
abls = tf.split(ab, ab.shape[-2] // self.args.shape, -2)
|
469 |
+
ab = tf.concat(abls, 0)
|
470 |
+
|
471 |
+
ab_m, ab_p = self.distribute_dec(ab, dec, bs=batch_size)
|
472 |
+
abwv = self.conc_tog_specphase(ab_m, ab_p)
|
473 |
+
chls.append(abwv)
|
474 |
+
|
475 |
+
return np.clip(np.squeeze(np.stack(chls, -1)), -1.0, 1.0)
|
476 |
+
|
477 |
+
def decode_waveform(self, lat, dec, dec2, batch_size=64):
|
478 |
+
|
479 |
+
lat = lat[:, :, : (lat.shape[-2] // 8) * 8, :]
|
480 |
+
abls = tf.split(lat, lat.shape[-2] // 8, -2)
|
481 |
+
abi = tf.concat(abls, 0)
|
482 |
+
|
483 |
+
chls = []
|
484 |
+
for channel in range(2):
|
485 |
+
|
486 |
+
ab = self.distribute_dec2(
|
487 |
+
abi[:, :, :, channel * self.args.latdepth : channel * self.args.latdepth + self.args.latdepth],
|
488 |
+
dec2,
|
489 |
+
bs=batch_size,
|
490 |
+
)
|
491 |
+
abls = tf.split(ab, ab.shape[-2] // self.args.shape, -2)
|
492 |
+
ab = tf.concat(abls, 0)
|
493 |
+
|
494 |
+
ab_m, ab_p = self.distribute_dec(ab, dec, bs=batch_size)
|
495 |
+
abwv = self.conc_tog_specphase(ab_m, ab_p)
|
496 |
+
chls.append(abwv)
|
497 |
+
|
498 |
+
return np.clip(np.squeeze(np.stack(chls, -1)), -1.0, 1.0)
|
499 |
+
|
500 |
+
def get_noise_interp_multi(self, fac=1, var=2.0):
|
501 |
+
noiseg = self.truncated_normal([1, self.args.coorddepth], var, dtype=tf.float32)
|
502 |
+
|
503 |
+
coordratio = self.args.coordlen // self.args.latlen
|
504 |
+
|
505 |
+
noisels = [
|
506 |
+
tf.concat([self.truncated_normal([1, 64], var, dtype=tf.float32), noiseg], -1)
|
507 |
+
for i in range(3 + ((fac - 1) // coordratio))
|
508 |
+
]
|
509 |
+
rls = tf.concat(
|
510 |
+
[
|
511 |
+
tf.linspace(noisels[k], noisels[k + 1], self.args.coordlen + 1, axis=-2)[:, :-1, :]
|
512 |
+
for k in range(len(noisels) - 1)
|
513 |
+
],
|
514 |
+
-2,
|
515 |
+
)
|
516 |
+
|
517 |
+
rls = self.center_coordinate(rls)
|
518 |
+
rls = rls[:, self.args.latlen // 4 :, :]
|
519 |
+
rls = rls[:, : (rls.shape[-2] // self.args.latlen) * self.args.latlen, :]
|
520 |
+
|
521 |
+
rls = tf.split(rls, rls.shape[-2] // self.args.latlen, -2)
|
522 |
+
|
523 |
+
return tf.concat(rls[:fac], 0)
|
524 |
+
|
525 |
+
def get_noise_interp_loop(self, fac=1, var=2.0):
|
526 |
+
noiseg = self.truncated_normal([1, self.args.coorddepth], var, dtype=tf.float32)
|
527 |
+
|
528 |
+
coordratio = self.args.coordlen // self.args.latlen
|
529 |
+
|
530 |
+
noisels_pre = [tf.concat([self.truncated_normal([1, 64], var, dtype=tf.float32), noiseg], -1) for i in range(2)]
|
531 |
+
noisels = []
|
532 |
+
for k in range(fac + 2):
|
533 |
+
noisels.append(noisels_pre[0])
|
534 |
+
noisels.append(noisels_pre[1])
|
535 |
+
rls = tf.concat(
|
536 |
+
[
|
537 |
+
tf.linspace(noisels[k], noisels[k + 1], self.args.latlen // 2 + 1, axis=-2)[:, :-1, :]
|
538 |
+
for k in range(len(noisels) - 1)
|
539 |
+
],
|
540 |
+
-2,
|
541 |
+
)
|
542 |
+
|
543 |
+
rls = self.center_coordinate(rls)
|
544 |
+
rls = rls[:, self.args.latlen // 2 :, :]
|
545 |
+
rls = rls[:, : (rls.shape[-2] // self.args.latlen) * self.args.latlen, :]
|
546 |
+
|
547 |
+
rls = tf.split(rls, rls.shape[-2] // self.args.latlen, -2)
|
548 |
+
|
549 |
+
return tf.concat(rls[:fac], 0)
|
550 |
+
|
551 |
+
def generate(self, models_ls):
|
552 |
+
critic, gen, enc, dec, enc2, dec2, gen_ema, [opt_dec, opt_disc], switch = models_ls
|
553 |
+
os.makedirs(self.args.save_path, exist_ok=True)
|
554 |
+
fac = (self.args.seconds // 23) + 1
|
555 |
+
print(f"Generating {self.args.num_samples} samples...")
|
556 |
+
for i in tqdm(range(self.args.num_samples)):
|
557 |
+
wv = self.generate_waveform(
|
558 |
+
self.get_noise_interp_multi(fac, self.args.truncation), gen_ema, dec, dec2, batch_size=64
|
559 |
+
)
|
560 |
+
dt = datetime.datetime.now().strftime("%Y%m%d-%H%M%S")
|
561 |
+
write_wav(
|
562 |
+
f"{self.args.save_path}/{i}_{dt}.wav", self.args.sr, np.squeeze(wv)[: self.args.seconds * self.args.sr]
|
563 |
+
)
|
564 |
+
|
565 |
+
def decode_path(self, models_ls):
|
566 |
+
critic, gen, enc, dec, enc2, dec2, gen_ema, [opt_dec, opt_disc], switch = models_ls
|
567 |
+
os.makedirs(self.args.save_path, exist_ok=True)
|
568 |
+
pathls = glob(self.args.files_path + "/*.npy")
|
569 |
+
print(f"Decoding {len(pathls)} samples...")
|
570 |
+
for p in tqdm(pathls):
|
571 |
+
tp, ext = os.path.splitext(p)
|
572 |
+
bname = os.path.basename(tp)
|
573 |
+
lat = np.load(p, allow_pickle=True)
|
574 |
+
lat = tf.expand_dims(lat, 0)
|
575 |
+
lat = tf.expand_dims(lat, 0)
|
576 |
+
wv = self.decode_waveform(lat, dec, dec2, batch_size=64)
|
577 |
+
# dt = datetime.datetime.now().strftime("%Y%m%d-%H%M%S")
|
578 |
+
write_wav(f"{self.args.save_path}/{bname}.wav", self.args.sr, np.squeeze(wv))
|
579 |
+
|
580 |
+
def stfunc(self, genre, z, var, models_ls_1, models_ls_2, models_ls_3):
|
581 |
+
|
582 |
+
critic, gen, enc, dec, enc2, dec2, gen_ema_1, [opt_dec, opt_disc], switch = models_ls_1
|
583 |
+
critic, gen, enc, dec, enc2, dec2, gen_ema_2, [opt_dec, opt_disc], switch = models_ls_2
|
584 |
+
critic, gen, enc, dec, enc2, dec2, gen_ema_3, [opt_dec, opt_disc], switch = models_ls_3
|
585 |
+
|
586 |
+
if genre == 0:
|
587 |
+
gen_ema = gen_ema_1
|
588 |
+
elif genre == 1:
|
589 |
+
gen_ema = gen_ema_2
|
590 |
+
else:
|
591 |
+
gen_ema = gen_ema_3
|
592 |
+
|
593 |
+
var = float(var)
|
594 |
+
|
595 |
+
if z == 0:
|
596 |
+
fac = 1
|
597 |
+
elif z == 1:
|
598 |
+
fac = 5
|
599 |
+
else:
|
600 |
+
fac = 10
|
601 |
+
|
602 |
+
bef = time.time()
|
603 |
+
|
604 |
+
noiseinp = self.get_noise_interp_multi(fac, var)
|
605 |
+
|
606 |
+
abwvc = self.generate_waveform(noiseinp, gen_ema, dec, dec2, batch_size=64)
|
607 |
+
|
608 |
+
# print(
|
609 |
+
# f"Time for complete generation pipeline: {time.time()-bef} s {int(np.round((fac*23.)/(time.time()-bef)))}x faster than Real Time!"
|
610 |
+
# )
|
611 |
+
|
612 |
+
spec = np.flip(
|
613 |
+
np.array(
|
614 |
+
tf.transpose(
|
615 |
+
self.wv2spec_hop(
|
616 |
+
(abwvc[: 23 * self.args.sr, 0] + abwvc[: 23 * self.args.sr, 1]) / 2.0, 80.0, self.args.hop * 2
|
617 |
+
),
|
618 |
+
[1, 0],
|
619 |
+
)
|
620 |
+
),
|
621 |
+
-2,
|
622 |
+
)
|
623 |
+
|
624 |
+
return (
|
625 |
+
np.clip(spec, -1.0, 1.0),
|
626 |
+
(self.args.sr, np.int16(abwvc * 32767.0)),
|
627 |
+
)
|
628 |
+
|
629 |
+
def render_gradio(self, models_ls_1, models_ls_2, models_ls_3, train=True):
|
630 |
+
article_text = "Original work by Marco Pasini ([Twitter](https://twitter.com/marco_ppasini)) at the Institute of Computational Perception, JKU Linz. Supervised by Jan Schlüter."
|
631 |
+
|
632 |
+
def gradio_func(genre, x, y):
|
633 |
+
return self.stfunc(genre, x, y, models_ls_1, models_ls_2, models_ls_3)
|
634 |
+
|
635 |
+
if self.args.small:
|
636 |
+
durations = ["11s", "59s", "1m 58s"]
|
637 |
+
durations_default = "59s"
|
638 |
+
else:
|
639 |
+
durations = ["23s", "1m 58s", "3m 57s"]
|
640 |
+
durations_default = "1m 58s"
|
641 |
+
|
642 |
+
iface = gr.Interface(
|
643 |
+
fn=gradio_func,
|
644 |
+
inputs=[
|
645 |
+
gr.Radio(
|
646 |
+
choices=["Techno/Experimental", "Death Metal (finetuned)", "Misc"],
|
647 |
+
type="index",
|
648 |
+
value="Techno/Experimental",
|
649 |
+
label="Music Genre to Generate",
|
650 |
+
),
|
651 |
+
gr.Radio(
|
652 |
+
choices=durations,
|
653 |
+
type="index",
|
654 |
+
value=durations_default,
|
655 |
+
label="Generated Music Length",
|
656 |
+
),
|
657 |
+
gr.Slider(
|
658 |
+
minimum=0.1,
|
659 |
+
maximum=3.9,
|
660 |
+
step=0.1,
|
661 |
+
value=1.8,
|
662 |
+
label="How much do you want the music style to be varied? (Stddev truncation for random vectors)",
|
663 |
+
),
|
664 |
+
],
|
665 |
+
outputs=[
|
666 |
+
gr.Image(label="Log-MelSpectrogram of Generated Audio (first 23 s)"),
|
667 |
+
gr.Audio(type="numpy", label="Generated Audio"),
|
668 |
+
],
|
669 |
+
title="musika!",
|
670 |
+
description="Blazingly Fast 44.1 kHz Stereo Waveform Music Generation of Arbitrary Length. Be patient and enjoy the weirdness!",
|
671 |
+
article=article_text,
|
672 |
+
)
|
673 |
+
|
674 |
+
print("--------------------------------")
|
675 |
+
print("--------------------------------")
|
676 |
+
print("--------------------------------")
|
677 |
+
print("--------------------------------")
|
678 |
+
print("--------------------------------")
|
679 |
+
print("CLICK ON LINK BELOW TO OPEN GRADIO INTERFACE")
|
680 |
+
if train:
|
681 |
+
iface.launch(prevent_thread_lock=True)
|
682 |
+
else:
|
683 |
+
iface.launch(enable_queue=True)
|
684 |
+
# iface.launch(share=True, enable_queue=True)
|
685 |
+
print("--------------------------------")
|
686 |
+
print("--------------------------------")
|
687 |
+
print("--------------------------------")
|
688 |
+
print("--------------------------------")
|
689 |
+
print("--------------------------------")
|