-
Notifications
You must be signed in to change notification settings - Fork 7
/
train_transfer.py
191 lines (158 loc) · 9.12 KB
/
train_transfer.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
# -*- coding: utf-8 -*-
# /usr/bin/python2
'''
By kyubyong park. [email protected].
https://www.github.com/kyubyong/dc_tts
Modified by sean leary. [email protected]
https://github.com/SeanPLeary/dc_tts-transfer-learning
'''
from __future__ import print_function
from tqdm import tqdm
from data_load import get_batch, load_vocab
from hyperparams import Hyperparams as hp
from modules import *
from networks import TextEnc, AudioEnc, AudioDec, Attention, SSRN
import tensorflow as tf
from utils import *
import sys
class Graph:
def __init__(self, num=1, mode="train"):
'''
Args:
num: Either 1 or 2. 1 for Text2Mel 2 for SSRN.
mode: Either "train" or "synthesize".
'''
# Load vocabulary
self.char2idx, self.idx2char = load_vocab()
# Set flag
training = True if mode=="train" else False
# Graph
# Data Feeding
## L: Text. (B, N), int32
## mels: Reduced melspectrogram. (B, T/r, n_mels) float32
## mags: Magnitude. (B, T, n_fft//2+1) float32
if mode=="train":
self.L, self.mels, self.mags, self.fnames, self.num_batch = get_batch()
self.prev_max_attentions = tf.ones(shape=(hp.B,), dtype=tf.int32)
self.gts = tf.convert_to_tensor(guided_attention())
else: # Synthesize
self.L = tf.placeholder(tf.int32, shape=(None, None))
self.mels = tf.placeholder(tf.float32, shape=(None, None, hp.n_mels))
self.prev_max_attentions = tf.placeholder(tf.int32, shape=(None,))
if num==1 or (not training):
with tf.variable_scope("Text2Mel"):
# Get S or decoder inputs. (B, T//r, n_mels)
self.S = tf.concat((tf.zeros_like(self.mels[:, :1, :]), self.mels[:, :-1, :]), 1)
# Networks
with tf.variable_scope("TextEnc"):
self.K, self.V = TextEnc(self.L, training=training) # (N, Tx, e)
with tf.variable_scope("AudioEnc"):
self.Q = AudioEnc(self.S, training=training)
with tf.variable_scope("Attention"):
# R: (B, T/r, 2d)
# alignments: (B, N, T/r)
# max_attentions: (B,)
self.R, self.alignments, self.max_attentions = Attention(self.Q, self.K, self.V,
mononotic_attention=(not training),
prev_max_attentions=self.prev_max_attentions)
with tf.variable_scope("AudioDec"):
self.Y_logits, self.Y = AudioDec(self.R, training=training) # (B, T/r, n_mels)
else: # num==2 & training. Note that during training,
# the ground truth melspectrogram values are fed.
with tf.variable_scope("SSRN"):
self.Z_logits, self.Z = SSRN(self.mels, training=training)
if not training:
# During inference, the predicted melspectrogram values are fed.
with tf.variable_scope("SSRN"):
self.Z_logits, self.Z = SSRN(self.Y, training=training)
with tf.variable_scope("gs"):
self.global_step = tf.Variable(0, name='global_step', trainable=False)
if training:
if num==1: # Text2Mel
# mel L1 loss
self.loss_mels = tf.reduce_mean(tf.abs(self.Y - self.mels))
# mel binary divergence loss
self.loss_bd1 = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(logits=self.Y_logits, labels=self.mels))
# guided_attention loss
self.A = tf.pad(self.alignments, [(0, 0), (0, hp.max_N), (0, hp.max_T)], mode="CONSTANT", constant_values=-1.)[:, :hp.max_N, :hp.max_T]
self.attention_masks = tf.to_float(tf.not_equal(self.A, -1))
self.loss_att = tf.reduce_sum(tf.abs(self.A * self.gts) * self.attention_masks)
self.mask_sum = tf.reduce_sum(self.attention_masks)
self.loss_att /= self.mask_sum
# total loss
self.loss = self.loss_mels + self.loss_bd1 + self.loss_att
tf.summary.scalar('train/loss_mels', self.loss_mels)
tf.summary.scalar('train/loss_bd1', self.loss_bd1)
tf.summary.scalar('train/loss_att', self.loss_att)
tf.summary.image('train/mel_gt', tf.expand_dims(tf.transpose(self.mels[:1], [0, 2, 1]), -1))
tf.summary.image('train/mel_hat', tf.expand_dims(tf.transpose(self.Y[:1], [0, 2, 1]), -1))
else: # SSRN
# mag L1 loss
self.loss_mags = tf.reduce_mean(tf.abs(self.Z - self.mags))
# mag binary divergence loss
self.loss_bd2 = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(logits=self.Z_logits, labels=self.mags))
# total loss
self.loss = self.loss_mags + self.loss_bd2
tf.summary.scalar('train/loss_mags', self.loss_mags)
tf.summary.scalar('train/loss_bd2', self.loss_bd2)
tf.summary.image('train/mag_gt', tf.expand_dims(tf.transpose(self.mags[:1], [0, 2, 1]), -1))
tf.summary.image('train/mag_hat', tf.expand_dims(tf.transpose(self.Z[:1], [0, 2, 1]), -1))
# Training Scheme
self.lr = learning_rate_decay(hp.lr, self.global_step)
tvars = tf.trainable_variables()
tvars_new = []
for tvar in hp.selected_tvars:
tvars_new = tvars_new + [var for var in tvars if tvar in var.name]
# tvars_new = [var for var in tvars if ('SSRN/C_13') in var.name] + \
# [var for var in tvars if ('SSRN/C_14') in var.name] + \
# [var for var in tvars if ('SSRN/C_15') in var.name] + \
# [var for var in tvars if ('SSRN/C_16') in var.name] + \
# [var for var in tvars if ('Text2Mel/TextEnc/HC_11') in var.name] + \
# [var for var in tvars if ('Text2Mel/TextEnc/HC_12') in var.name] + \
# [var for var in tvars if ('Text2Mel/TextEnc/HC_13') in var.name] + \
# [var for var in tvars if ('Text2Mel/TextEnc/HC_14') in var.name] + \
# [var for var in tvars if ('Text2Mel/TextEnc/HC_15') in var.name] + \
# [var for var in tvars if ('Text2Mel/AudioEnc/HC_9') in var.name] + \
# [var for var in tvars if ('Text2Mel/AudioEnc/HC_10') in var.name] + \
# [var for var in tvars if ('Text2Mel/AudioEnc/HC_11') in var.name] + \
# [var for var in tvars if ('Text2Mel/AudioEnc/HC_12') in var.name] + \
# [var for var in tvars if ('Text2Mel/AudioEnc/HC_13') in var.name] + \
# [var for var in tvars if ('Text2Mel/AudioDec/HC_7') in var.name] + \
# [var for var in tvars if ('Text2Mel/AudioDec/C_8') in var.name] + \
# [var for var in tvars if ('Text2Mel/AudioDec/C_9') in var.name] + \
# [var for var in tvars if ('Text2Mel/AudioDec/C_10') in var.name] + \
# [var for var in tvars if ('Text2Mel/AudioDec/C_11') in var.name]
self.optimizer = tf.train.AdamOptimizer(learning_rate=self.lr)
#self.optimizer = tf.train.AdamOptimizer(learning_rate=self.lr)
tf.summary.scalar("lr", self.lr)
## gradient clipping
self.gvs = self.optimizer.compute_gradients(self.loss, var_list=tvars_new)
self.clipped = []
for grad, var in self.gvs:
grad = tf.clip_by_value(grad, -1., 1.)
self.clipped.append((grad, var))
self.train_op = self.optimizer.apply_gradients(self.clipped, global_step=self.global_step)
# Summary
self.merged = tf.summary.merge_all()
if __name__ == '__main__':
# argument: 1 or 2. 1 for Text2mel, 2 for SSRN.
num = int(sys.argv[1])
g = Graph(num=num); print("Training Graph loaded")
logdir = hp.logdir + "-" + str(num)
sv = tf.train.Supervisor(logdir=logdir, save_model_secs=0, global_step=g.global_step)
#with sv.managed_session() as sess:
with sv.managed_session(config = tf.ConfigProto(allow_soft_placement=True)) as sess:
sv.saver.restore(sess, tf.train.latest_checkpoint(hp.restoredir + "-" + str(num)))
while 1:
for _ in tqdm(range(g.num_batch), total=g.num_batch, ncols=70, leave=False, unit='b'):
gs, _ = sess.run([g.global_step, g.train_op])
# Write checkpoint files at every 1k steps
if gs % 1000 == 0:
sv.saver.save(sess, logdir + '/model_gs_{}'.format(str(gs // 1000).zfill(3) + "k"))
if num==1:
# plot alignment
alignments = sess.run(g.alignments)
plot_alignment(alignments[0], str(gs // 1000).zfill(3) + "k", logdir)
# break
if gs > hp.num_iterations: break
print("Done")