executor.py 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172
  1. # Copyright (c) 2020 Mobvoi Inc (Binbin Zhang)
  2. # 2024 Alibaba Inc (authors: Xiang Lyu)
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. import logging
  16. from contextlib import nullcontext
  17. import os
  18. import torch
  19. import torch.distributed as dist
  20. from cosyvoice.utils.train_utils import update_parameter_and_lr, log_per_step, log_per_save, batch_forward, batch_backward, save_model, cosyvoice_join
  21. class Executor:
  22. def __init__(self, gan: bool = False):
  23. self.gan = gan
  24. self.step = 0
  25. self.epoch = 0
  26. self.rank = int(os.environ.get('RANK', 0))
  27. self.device = torch.device('cuda:{}'.format(self.rank))
  28. def train_one_epoc(self, model, optimizer, scheduler, train_data_loader, cv_data_loader, writer, info_dict, scaler, group_join):
  29. ''' Train one epoch
  30. '''
  31. lr = optimizer.param_groups[0]['lr']
  32. logging.info('Epoch {} TRAIN info lr {} rank {}'.format(self.epoch, lr, self.rank))
  33. logging.info('using accumulate grad, new batch size is {} times'
  34. ' larger than before'.format(info_dict['accum_grad']))
  35. # A context manager to be used in conjunction with an instance of
  36. # torch.nn.parallel.DistributedDataParallel to be able to train
  37. # with uneven inputs across participating processes.
  38. model.train()
  39. model_context = model.join if info_dict['train_engine'] == 'torch_ddp' else nullcontext
  40. with model_context():
  41. for batch_idx, batch_dict in enumerate(train_data_loader):
  42. info_dict["tag"] = "TRAIN"
  43. info_dict["step"] = self.step
  44. info_dict["epoch"] = self.epoch
  45. info_dict["batch_idx"] = batch_idx
  46. if cosyvoice_join(group_join, info_dict):
  47. break
  48. # Disable gradient synchronizations across DDP processes.
  49. # Within this context, gradients will be accumulated on module
  50. # variables, which will later be synchronized.
  51. if info_dict['train_engine'] == 'torch_ddp' and (batch_idx + 1) % info_dict["accum_grad"] != 0:
  52. context = model.no_sync
  53. # Used for single gpu training and DDP gradient synchronization
  54. # processes.
  55. else:
  56. context = nullcontext
  57. with context():
  58. info_dict = batch_forward(model, batch_dict, scaler, info_dict)
  59. info_dict = batch_backward(model, scaler, info_dict)
  60. info_dict = update_parameter_and_lr(model, optimizer, scheduler, scaler, info_dict)
  61. log_per_step(writer, info_dict)
  62. # NOTE specify save_per_step in cosyvoice.yaml if you want to enable step save
  63. if info_dict['save_per_step'] > 0 and (self.step + 1) % info_dict['save_per_step'] == 0 and \
  64. (batch_idx + 1) % info_dict["accum_grad"] == 0:
  65. dist.barrier()
  66. self.cv(model, cv_data_loader, writer, info_dict, on_batch_end=False)
  67. model.train()
  68. if (batch_idx + 1) % info_dict["accum_grad"] == 0:
  69. self.step += 1
  70. dist.barrier()
  71. self.cv(model, cv_data_loader, writer, info_dict, on_batch_end=True)
  72. def train_one_epoc_gan(self, model, optimizer, scheduler, optimizer_d, scheduler_d, train_data_loader, cv_data_loader,
  73. writer, info_dict, scaler, group_join):
  74. ''' Train one epoch
  75. '''
  76. lr = optimizer.param_groups[0]['lr']
  77. logging.info('Epoch {} TRAIN info lr {} rank {}'.format(self.epoch, lr, self.rank))
  78. logging.info('using accumulate grad, new batch size is {} times'
  79. ' larger than before'.format(info_dict['accum_grad']))
  80. # A context manager to be used in conjunction with an instance of
  81. # torch.nn.parallel.DistributedDataParallel to be able to train
  82. # with uneven inputs across participating processes.
  83. model.train()
  84. model_context = model.join if info_dict['train_engine'] == 'torch_ddp' else nullcontext
  85. with model_context():
  86. for batch_idx, batch_dict in enumerate(train_data_loader):
  87. info_dict["tag"] = "TRAIN"
  88. info_dict["step"] = self.step
  89. info_dict["epoch"] = self.epoch
  90. info_dict["batch_idx"] = batch_idx
  91. if cosyvoice_join(group_join, info_dict):
  92. break
  93. # Disable gradient synchronizations across DDP processes.
  94. # Within this context, gradients will be accumulated on module
  95. # variables, which will later be synchronized.
  96. if info_dict['train_engine'] == 'torch_ddp' and (batch_idx + 1) % info_dict["accum_grad"] != 0:
  97. context = model.no_sync
  98. # Used for single gpu training and DDP gradient synchronization
  99. # processes.
  100. else:
  101. context = nullcontext
  102. with context():
  103. batch_dict['turn'] = 'discriminator'
  104. info_dict = batch_forward(model, batch_dict, scaler, info_dict)
  105. info_dict = batch_backward(model, scaler, info_dict)
  106. info_dict = update_parameter_and_lr(model, optimizer_d, scheduler_d, scaler, info_dict)
  107. optimizer.zero_grad()
  108. log_per_step(writer, info_dict)
  109. with context():
  110. batch_dict['turn'] = 'generator'
  111. info_dict = batch_forward(model, batch_dict, scaler, info_dict)
  112. info_dict = batch_backward(model, scaler, info_dict)
  113. info_dict = update_parameter_and_lr(model, optimizer, scheduler, scaler, info_dict)
  114. optimizer_d.zero_grad()
  115. log_per_step(writer, info_dict)
  116. # NOTE specify save_per_step in cosyvoice.yaml if you want to enable step save
  117. if info_dict['save_per_step'] > 0 and (self.step + 1) % info_dict['save_per_step'] == 0 and \
  118. (batch_idx + 1) % info_dict["accum_grad"] == 0:
  119. dist.barrier()
  120. self.cv(model, cv_data_loader, writer, info_dict, on_batch_end=False)
  121. model.train()
  122. if (batch_idx + 1) % info_dict["accum_grad"] == 0:
  123. self.step += 1
  124. dist.barrier()
  125. self.cv(model, cv_data_loader, writer, info_dict, on_batch_end=True)
  126. @torch.inference_mode()
  127. def cv(self, model, cv_data_loader, writer, info_dict, on_batch_end=True):
  128. ''' Cross validation on
  129. '''
  130. logging.info('Epoch {} Step {} on_batch_end {} CV rank {}'.format(self.epoch, self.step + 1, on_batch_end, self.rank))
  131. model.eval()
  132. total_num_utts, total_loss_dict = 0, {} # avoid division by 0
  133. for batch_idx, batch_dict in enumerate(cv_data_loader):
  134. info_dict["tag"] = "CV"
  135. info_dict["step"] = self.step
  136. info_dict["epoch"] = self.epoch
  137. info_dict["batch_idx"] = batch_idx
  138. num_utts = len(batch_dict["utts"])
  139. total_num_utts += num_utts
  140. if self.gan is True:
  141. batch_dict['turn'] = 'generator'
  142. info_dict = batch_forward(model, batch_dict, None, info_dict)
  143. for k, v in info_dict['loss_dict'].items():
  144. if k not in total_loss_dict:
  145. total_loss_dict[k] = []
  146. total_loss_dict[k].append(v.item() * num_utts)
  147. log_per_step(None, info_dict)
  148. for k, v in total_loss_dict.items():
  149. total_loss_dict[k] = sum(v) / total_num_utts
  150. info_dict['loss_dict'] = total_loss_dict
  151. log_per_save(writer, info_dict)
  152. model_name = 'epoch_{}_whole'.format(self.epoch) if on_batch_end else 'epoch_{}_step_{}'.format(self.epoch, self.step + 1)
  153. save_model(model, model_name, info_dict)