Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

train_aligner.py 11 KB

You have to be logged in to leave a comment. Sign In
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
  1. import tensorflow as tf
  2. import numpy as np
  3. from tqdm import trange
  4. from utils.training_config_manager import TrainingConfigManager
  5. from data.datasets import AlignerDataset, AlignerPreprocessor
  6. from utils.decorators import ignore_exception, time_it
  7. from utils.scheduling import piecewise_linear_schedule, reduction_schedule
  8. from utils.logging_utils import SummaryManager
  9. from utils.scripts_utils import dynamic_memory_allocation, basic_train_parser
  10. from utils.metrics import attention_score
  11. from utils.spectrogram_ops import mel_lengths, phoneme_lengths
  12. from utils.alignments import get_durations_from_alignment
  13. np.random.seed(42)
  14. tf.random.set_seed(42)
  15. dynamic_memory_allocation()
  16. parser = basic_train_parser()
  17. args = parser.parse_args()
  18. def cut_with_durations(durations, mel, phonemes, snippet_len=10):
  19. phon_dur = np.pad(durations, (1, 0))
  20. starts = np.cumsum(phon_dur)[:-1]
  21. ends = np.cumsum(phon_dur)[1:]
  22. cut_mels = []
  23. cut_texts = []
  24. for end_idx in range(snippet_len, len(phon_dur), snippet_len):
  25. start_idx = end_idx - snippet_len
  26. cut_mels.append(mel[starts[start_idx]: ends[end_idx - 1], :])
  27. cut_texts.append(phonemes[start_idx: end_idx])
  28. return cut_mels, cut_texts
  29. @ignore_exception
  30. @time_it
  31. def validate(model,
  32. val_dataset,
  33. summary_manager,
  34. weighted_durations):
  35. val_loss = {'loss': 0.}
  36. norm = 0.
  37. current_r = model.r
  38. model.set_constants(reduction_factor=1)
  39. for val_mel, val_text, val_stop, fname in val_dataset.all_batches():
  40. model_out = model.val_step(inp=val_text,
  41. tar=val_mel,
  42. stop_prob=val_stop)
  43. norm += 1
  44. val_loss['loss'] += model_out['loss']
  45. val_loss['loss'] /= norm
  46. summary_manager.display_loss(model_out, tag='Validation', plot_all=True)
  47. summary_manager.display_last_attention(model_out, tag='ValidationAttentionHeads', fname=fname)
  48. attention_values = model_out['decoder_attention']['Decoder_LastBlock_CrossAttention'].numpy()
  49. text = val_text.numpy()
  50. mel = val_mel.numpy()
  51. model.set_constants(reduction_factor=current_r)
  52. modes = list({False, weighted_durations})
  53. for mode in modes:
  54. durations, final_align, jumpiness, peakiness, diag_measure = get_durations_from_alignment(
  55. batch_alignments=attention_values,
  56. mels=mel,
  57. phonemes=text,
  58. weighted=mode)
  59. for k in range(len(durations)):
  60. phon_dur = durations[k]
  61. imel = mel[k][1:] # remove start token (is padded so end token can't be removed/not an issue)
  62. itext = text[k][1:] # remove start token (is padded so end token can't be removed/not an issue)
  63. iphon = model.text_pipeline.tokenizer.decode(itext).replace('/', '')
  64. cut_mels, cut_texts = cut_with_durations(durations=phon_dur, mel=imel, phonemes=iphon)
  65. for cut_idx, cut_text in enumerate(cut_texts):
  66. weighted_label = 'weighted_' * mode
  67. summary_manager.display_audio(
  68. tag=f'CutAudio {weighted_label}{fname[k].numpy().decode("utf-8")}/{cut_idx}/{cut_text}',
  69. mel=cut_mels[cut_idx], description=iphon)
  70. return val_loss['loss']
  71. config_manager = TrainingConfigManager(config_path=args.config, aligner=True)
  72. config = config_manager.config
  73. config_manager.create_remove_dirs(clear_dir=args.clear_dir,
  74. clear_logs=args.clear_logs,
  75. clear_weights=args.clear_weights)
  76. config_manager.dump_config()
  77. config_manager.print_config()
  78. # get model, prepare data for model, create datasets
  79. model = config_manager.get_model()
  80. config_manager.compile_model(model)
  81. data_prep = AlignerPreprocessor.from_config(config_manager,
  82. tokenizer=model.text_pipeline.tokenizer) # TODO: tokenizer is now static
  83. train_data_handler = AlignerDataset.from_config(config_manager,
  84. preprocessor=data_prep,
  85. kind='train')
  86. valid_data_handler = AlignerDataset.from_config(config_manager,
  87. preprocessor=data_prep,
  88. kind='valid')
  89. train_dataset = train_data_handler.get_dataset(bucket_batch_sizes=config['bucket_batch_sizes'],
  90. bucket_boundaries=config['bucket_boundaries'],
  91. shuffle=True)
  92. valid_dataset = valid_data_handler.get_dataset(bucket_batch_sizes=config['val_bucket_batch_size'],
  93. bucket_boundaries=config['bucket_boundaries'],
  94. shuffle=False, drop_remainder=True)
  95. # create logger and checkpointer and restore latest model
  96. summary_manager = SummaryManager(model=model, log_dir=config_manager.log_dir, config=config)
  97. checkpoint = tf.train.Checkpoint(step=tf.Variable(1),
  98. optimizer=model.optimizer,
  99. net=model)
  100. manager = tf.train.CheckpointManager(checkpoint, str(config_manager.weights_dir),
  101. max_to_keep=config['keep_n_weights'],
  102. keep_checkpoint_every_n_hours=config['keep_checkpoint_every_n_hours'])
  103. manager_training = tf.train.CheckpointManager(checkpoint, str(config_manager.weights_dir / 'latest'),
  104. max_to_keep=1, checkpoint_name='latest')
  105. checkpoint.restore(manager_training.latest_checkpoint)
  106. if manager_training.latest_checkpoint:
  107. print(f'\nresuming training from step {model.step} ({manager_training.latest_checkpoint})')
  108. else:
  109. print(f'\nstarting training from scratch')
  110. if config['debug'] is True:
  111. print('\nWARNING: DEBUG is set to True. Training in eager mode.')
  112. # main event
  113. print('\nTRAINING')
  114. texts = []
  115. for text_file in config['test_stencences']:
  116. with open(text_file, 'r') as file:
  117. text = file.readlines()
  118. texts.append(text)
  119. losses = []
  120. test_mel, test_phonemes, _, test_fname = valid_dataset.next_batch()
  121. val_test_sample, val_test_fname, val_test_mel = test_phonemes[0], test_fname[0], test_mel[0]
  122. val_test_sample = tf.boolean_mask(val_test_sample, val_test_sample!=0)
  123. _ = train_dataset.next_batch()
  124. t = trange(model.step, config['max_steps'], leave=True)
  125. for _ in t:
  126. t.set_description(f'step {model.step}')
  127. mel, phonemes, stop, sample_name = train_dataset.next_batch()
  128. learning_rate = piecewise_linear_schedule(model.step, config['learning_rate_schedule'])
  129. reduction_factor = reduction_schedule(model.step, config['reduction_factor_schedule'])
  130. t.display(f'reduction factor {reduction_factor}', pos=10)
  131. force_encoder_diagonal = model.step < config['force_encoder_diagonal_steps']
  132. force_decoder_diagonal = model.step < config['force_decoder_diagonal_steps']
  133. model.set_constants(learning_rate=learning_rate,
  134. reduction_factor=reduction_factor,
  135. force_encoder_diagonal=force_encoder_diagonal,
  136. force_decoder_diagonal=force_decoder_diagonal)
  137. output = model.train_step(inp=phonemes,
  138. tar=mel,
  139. stop_prob=stop)
  140. losses.append(float(output['loss']))
  141. t.display(f'step loss: {losses[-1]}', pos=1)
  142. for pos, n_steps in enumerate(config['n_steps_avg_losses']):
  143. if len(losses) > n_steps:
  144. t.display(f'{n_steps}-steps average loss: {sum(losses[-n_steps:]) / n_steps}', pos=pos + 2)
  145. summary_manager.display_loss(output, tag='Train')
  146. summary_manager.display_scalar(tag='Meta/learning_rate', scalar_value=model.optimizer.lr)
  147. summary_manager.display_scalar(tag='Meta/reduction_factor', scalar_value=model.r)
  148. summary_manager.display_scalar(scalar_value=t.avg_time, tag='Meta/iter_time')
  149. summary_manager.display_scalar(scalar_value=tf.shape(sample_name)[0], tag='Meta/batch_size')
  150. if model.step % config['train_images_plotting_frequency'] == 0:
  151. summary_manager.display_attention_heads(output, tag='TrainAttentionHeads')
  152. summary_manager.display_mel(mel=output['mel'][0], tag=f'Train/predicted_mel')
  153. for layer, k in enumerate(output['decoder_attention'].keys()):
  154. mel_lens = mel_lengths(mel_batch=mel, padding_value=0) // model.r # [N]
  155. phon_len = phoneme_lengths(phonemes)
  156. loc_score, peak_score, diag_measure = attention_score(att=output['decoder_attention'][k],
  157. mel_len=mel_lens,
  158. phon_len=phon_len,
  159. r=model.r)
  160. loc_score = tf.reduce_mean(loc_score, axis=0)
  161. peak_score = tf.reduce_mean(peak_score, axis=0)
  162. diag_measure = tf.reduce_mean(diag_measure, axis=0)
  163. for i in range(tf.shape(loc_score)[0]):
  164. summary_manager.display_scalar(tag=f'TrainDecoderAttentionJumpiness/layer{layer}_head{i}',
  165. scalar_value=tf.reduce_mean(loc_score[i]))
  166. summary_manager.display_scalar(tag=f'TrainDecoderAttentionPeakiness/layer{layer}_head{i}',
  167. scalar_value=tf.reduce_mean(peak_score[i]))
  168. summary_manager.display_scalar(tag=f'TrainDecoderAttentionDiagonality/layer{layer}_head{i}',
  169. scalar_value=tf.reduce_mean(diag_measure[i]))
  170. if model.step % 1000 == 0:
  171. save_path = manager_training.save()
  172. if model.step % config['weights_save_frequency'] == 0:
  173. save_path = manager.save()
  174. t.display(f'checkpoint at step {model.step}: {save_path}', pos=len(config['n_steps_avg_losses']) + 2)
  175. if model.step % config['validation_frequency'] == 0 and (model.step >= config['prediction_start_step']):
  176. val_loss, time_taken = validate(model=model,
  177. val_dataset=valid_dataset,
  178. summary_manager=summary_manager,
  179. weighted_durations=config['extract_attention_weighted'])
  180. t.display(f'validation loss at step {model.step}: {val_loss} (took {time_taken}s)',
  181. pos=len(config['n_steps_avg_losses']) + 3)
  182. if model.step % config['prediction_frequency'] == 0 and (model.step >= config['prediction_start_step']):
  183. for j, text in enumerate(texts):
  184. for i, text_line in enumerate(text):
  185. out = model.predict(text_line, encode=True)
  186. wav = summary_manager.audio.reconstruct_waveform(out['mel'].numpy().T)
  187. wav = tf.expand_dims(wav, 0)
  188. wav = tf.expand_dims(wav, -1)
  189. summary_manager.add_audio(f'Predictions/{text_line}', wav.numpy(), sr=summary_manager.config['sampling_rate'],
  190. step=summary_manager.global_step)
  191. out = model.predict(val_test_sample, encode=False)#, max_length=tf.shape(val_test_mel)[-2])
  192. wav = summary_manager.audio.reconstruct_waveform(out['mel'].numpy().T)
  193. wav = tf.expand_dims(wav, 0)
  194. wav = tf.expand_dims(wav, -1)
  195. summary_manager.add_audio(f'Predictions/val_sample {val_test_fname.numpy().decode("utf-8")}', wav.numpy(), sr=summary_manager.config['sampling_rate'],
  196. step=summary_manager.global_step)
  197. print('Done.')
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...