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.py 9.0 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
  1. import argparse
  2. import tensorflow as tf
  3. import numpy as np
  4. from tqdm import trange
  5. from utils.config_manager import ConfigManager
  6. from preprocessing.data_handling import load_files, Dataset, DataPrepper
  7. from utils.decorators import ignore_exception, time_it
  8. from utils.scheduling import piecewise_linear_schedule, reduction_schedule
  9. from utils.logging import SummaryManager
  10. np.random.seed(42)
  11. tf.random.set_seed(42)
  12. # dinamically allocate GPU
  13. gpus = tf.config.experimental.list_physical_devices('GPU')
  14. if gpus:
  15. try:
  16. # Currently, memory growth needs to be the same across GPUs
  17. for gpu in gpus:
  18. tf.config.experimental.set_memory_growth(gpu, True)
  19. logical_gpus = tf.config.experimental.list_logical_devices('GPU')
  20. print(len(gpus), "Physical GPUs,", len(logical_gpus), "Logical GPUs")
  21. except RuntimeError as e:
  22. # Memory growth must be set before GPUs have been initialized
  23. print(e)
  24. @ignore_exception
  25. @time_it
  26. def validate(model,
  27. val_dataset,
  28. summary_manager):
  29. val_loss = {'loss': 0.}
  30. norm = 0.
  31. for val_mel, val_text, val_stop in val_dataset.all_batches():
  32. model_out = model.val_step(inp=val_text,
  33. tar=val_mel,
  34. stop_prob=val_stop)
  35. norm += 1
  36. val_loss['loss'] += model_out['loss']
  37. val_loss['loss'] /= norm
  38. summary_manager.display_loss(model_out, tag='Validation', plot_all=True)
  39. summary_manager.display_attention_heads(model_out, tag='ValidationAttentionHeads')
  40. summary_manager.display_mel(mel=model_out['mel_linear'][0], tag=f'Validation/linear_mel_out')
  41. summary_manager.display_mel(mel=model_out['final_output'][0], tag=f'Validation/predicted_mel')
  42. residual = abs(model_out['mel_linear'] - model_out['final_output'])
  43. summary_manager.display_mel(mel=residual[0], tag=f'Validation/conv-linear_residual')
  44. summary_manager.display_mel(mel=val_mel[0], tag=f'Validation/target_mel')
  45. return val_loss['loss']
  46. # consuming CLI, creating paths and directories, load data
  47. parser = argparse.ArgumentParser()
  48. parser.add_argument('--config', dest='config', type=str)
  49. parser.add_argument('--reset_dir', dest='clear_dir', action='store_true',
  50. help="deletes everything under this config's folder.")
  51. parser.add_argument('--reset_logs', dest='clear_logs', action='store_true',
  52. help="deletes logs under this config's folder.")
  53. parser.add_argument('--reset_weights', dest='clear_weights', action='store_true',
  54. help="deletes weights under this config's folder.")
  55. parser.add_argument('--session_name', dest='session_name', default=None)
  56. args = parser.parse_args()
  57. config_manager = ConfigManager(config_path=args.config, session_name=args.session_name)
  58. config = config_manager.config
  59. config_manager.create_remove_dirs(clear_dir=args.clear_dir,
  60. clear_logs=args.clear_logs,
  61. clear_weights=args.clear_weights)
  62. config_manager.dump_config()
  63. config_manager.print_config()
  64. train_samples, _ = load_files(metafile=str(config_manager.train_datadir / 'train_metafile.txt'),
  65. meldir=str(config_manager.train_datadir / 'mels'),
  66. num_samples=config['n_samples']) # (phonemes, mel)
  67. val_samples, _ = load_files(metafile=str(config_manager.train_datadir / 'test_metafile.txt'),
  68. meldir=str(config_manager.train_datadir / 'mels'),
  69. num_samples=config['n_samples']) # (phonemes, text, mel)
  70. # get model, prepare data for model, create datasets
  71. model = config_manager.get_model()
  72. config_manager.compile_model(model)
  73. data_prep = DataPrepper(config=config,
  74. tokenizer=model.tokenizer)
  75. test_list = [data_prep(s) for s in val_samples]
  76. train_dataset = Dataset(samples=train_samples,
  77. preprocessor=data_prep,
  78. batch_size=config['batch_size'],
  79. mel_channels=config['mel_channels'],
  80. shuffle=True)
  81. val_dataset = Dataset(samples=val_samples,
  82. preprocessor=data_prep,
  83. batch_size=config['batch_size'],
  84. mel_channels=config['mel_channels'],
  85. shuffle=False)
  86. # create logger and checkpointer and restore latest model
  87. summary_manager = SummaryManager(model=model, log_dir=config_manager.log_dir, config=config)
  88. checkpoint = tf.train.Checkpoint(step=tf.Variable(1),
  89. optimizer=model.optimizer,
  90. net=model)
  91. manager = tf.train.CheckpointManager(checkpoint, str(config_manager.weights_dir),
  92. max_to_keep=config['keep_n_weights'],
  93. keep_checkpoint_every_n_hours=config['keep_checkpoint_every_n_hours'])
  94. checkpoint.restore(manager.latest_checkpoint)
  95. if manager.latest_checkpoint:
  96. print(f'\nresuming training from step {model.step} ({manager.latest_checkpoint})')
  97. else:
  98. print(f'\nstarting training from scratch')
  99. # main event
  100. print('\nTRAINING')
  101. losses = []
  102. _ = train_dataset.next_batch()
  103. t = trange(model.step, config['max_steps'], leave=True)
  104. for _ in t:
  105. t.set_description(f'step {model.step}')
  106. mel, phonemes, stop = train_dataset.next_batch()
  107. decoder_prenet_dropout = piecewise_linear_schedule(model.step, config['decoder_dropout_schedule'])
  108. learning_rate = piecewise_linear_schedule(model.step, config['learning_rate_schedule'])
  109. reduction_factor = reduction_schedule(model.step, config['reduction_factor_schedule'])
  110. drop_n_heads = tf.cast(reduction_schedule(model.step, config['head_drop_schedule']), tf.int32)
  111. t.display(f'reduction factor {reduction_factor}', pos=10)
  112. model.set_constants(decoder_prenet_dropout=decoder_prenet_dropout,
  113. learning_rate=learning_rate,
  114. reduction_factor=reduction_factor,
  115. drop_n_heads=drop_n_heads)
  116. output = model.train_step(inp=phonemes,
  117. tar=mel,
  118. stop_prob=stop)
  119. losses.append(float(output['loss']))
  120. t.display(f'step loss: {losses[-1]}', pos=1)
  121. for pos, n_steps in enumerate(config['n_steps_avg_losses']):
  122. if len(losses) > n_steps:
  123. t.display(f'{n_steps}-steps average loss: {sum(losses[-n_steps:]) / n_steps}', pos=pos + 2)
  124. summary_manager.display_loss(output, tag='Train')
  125. summary_manager.display_scalar(tag='Meta/decoder_prenet_dropout', scalar_value=model.decoder_prenet_dropout)
  126. summary_manager.display_scalar(tag='Meta/learning_rate', scalar_value=model.optimizer.lr)
  127. summary_manager.display_scalar(tag='Meta/reduction_factor', scalar_value=model.r)
  128. summary_manager.display_scalar(tag='Meta/drop_n_heads', scalar_value=model.drop_n_heads)
  129. if model.step % config['train_images_plotting_frequency'] == 0:
  130. summary_manager.display_attention_heads(output, tag='TrainAttentionHeads')
  131. summary_manager.display_mel(mel=output['mel_linear'][0], tag=f'Train/linear_mel_out')
  132. summary_manager.display_mel(mel=output['final_output'][0], tag=f'Train/predicted_mel')
  133. residual = abs(output['mel_linear'] - output['final_output'])
  134. summary_manager.display_mel(mel=residual[0], tag=f'Train/conv-linear_residual')
  135. summary_manager.display_mel(mel=mel[0], tag=f'Train/target_mel')
  136. if model.step % config['weights_save_frequency'] == 0:
  137. save_path = manager.save()
  138. t.display(f'checkpoint at step {model.step}: {save_path}', pos=len(config['n_steps_avg_losses']) + 2)
  139. if model.step % config['validation_frequency'] == 0:
  140. val_loss, time_taken = validate(model=model,
  141. val_dataset=val_dataset,
  142. summary_manager=summary_manager)
  143. t.display(f'validation loss at step {model.step}: {val_loss} (took {time_taken}s)',
  144. pos=len(config['n_steps_avg_losses']) + 3)
  145. if model.step % config['prediction_frequency'] == 0 and (model.step >= config['prediction_start_step']):
  146. for j in range(config['n_predictions']):
  147. mel, phonemes, stop = test_list[j]
  148. t.display(f'Predicting {j}', pos=len(config['n_steps_avg_losses']) + 4)
  149. pred = model.predict(phonemes,
  150. max_length=mel.shape[0] + 50,
  151. encode=False,
  152. verbose=False)
  153. pred_mel = pred['mel']
  154. target_mel = mel
  155. summary_manager.display_attention_heads(outputs=pred, tag=f'TestAttentionHeads/sample {j}')
  156. summary_manager.display_mel(mel=pred_mel, tag=f'Test/sample {j}/predicted_mel')
  157. summary_manager.display_mel(mel=target_mel, tag=f'Test/sample {j}/target_mel')
  158. if model.step > config['audio_start_step']:
  159. summary_manager.display_audio(tag=f'Target/sample {j}', mel=target_mel)
  160. summary_manager.display_audio(tag=f'Prediction/sample {j}', mel=pred_mel)
  161. print('Done.')
Tip!

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

Comments

Loading...