executor.py 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  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):
  23. self.step = 0
  24. self.epoch = 0
  25. self.rank = int(os.environ.get('RANK', 0))
  26. self.device = torch.device('cuda:{}'.format(self.rank))
  27. def train_one_epoc(self, model, optimizer, scheduler, train_data_loader, cv_data_loader, writer, info_dict, group_join):
  28. ''' Train one epoch
  29. '''
  30. lr = optimizer.param_groups[0]['lr']
  31. logging.info('Epoch {} TRAIN info lr {} rank {}'.format(self.epoch, lr, self.rank))
  32. logging.info('using accumulate grad, new batch size is {} times'
  33. ' larger than before'.format(info_dict['accum_grad']))
  34. # A context manager to be used in conjunction with an instance of
  35. # torch.nn.parallel.DistributedDataParallel to be able to train
  36. # with uneven inputs across participating processes.
  37. model.train()
  38. model_context = model.join if info_dict['train_engine'] == 'torch_ddp' else nullcontext
  39. with model_context():
  40. for batch_idx, batch_dict in enumerate(train_data_loader):
  41. info_dict["tag"] = "TRAIN"
  42. info_dict["step"] = self.step
  43. info_dict["epoch"] = self.epoch
  44. info_dict["batch_idx"] = batch_idx
  45. if cosyvoice_join(group_join, info_dict):
  46. break
  47. # Disable gradient synchronizations across DDP processes.
  48. # Within this context, gradients will be accumulated on module
  49. # variables, which will later be synchronized.
  50. if info_dict['train_engine'] == 'torch_ddp' and (batch_idx + 1) % info_dict["accum_grad"] != 0:
  51. context = model.no_sync
  52. # Used for single gpu training and DDP gradient synchronization
  53. # processes.
  54. else:
  55. context = nullcontext
  56. with context():
  57. info_dict = batch_forward(model, batch_dict, info_dict)
  58. info_dict = batch_backward(model, info_dict)
  59. info_dict = update_parameter_and_lr(model, optimizer, scheduler, info_dict)
  60. log_per_step(writer, info_dict)
  61. # NOTE specify save_per_step in cosyvoice.yaml if you want to enable step save
  62. if info_dict['save_per_step'] > 0 and (self.step + 1) % info_dict['save_per_step'] == 0 and (batch_idx + 1) % info_dict["accum_grad"] == 0:
  63. dist.barrier()
  64. self.cv(model, cv_data_loader, writer, info_dict, on_batch_end=False)
  65. model.train()
  66. if (batch_idx + 1) % info_dict["accum_grad"] == 0:
  67. self.step += 1
  68. dist.barrier()
  69. self.cv(model, cv_data_loader, writer, info_dict, on_batch_end=True)
  70. @torch.inference_mode()
  71. def cv(self, model, cv_data_loader, writer, info_dict, on_batch_end=True):
  72. ''' Cross validation on
  73. '''
  74. logging.info('Epoch {} Step {} on_batch_end {} CV rank {}'.format(self.epoch, self.step + 1, on_batch_end, self.rank))
  75. model.eval()
  76. total_num_utts, total_loss_dict = 0, {} # avoid division by 0
  77. for batch_idx, batch_dict in enumerate(cv_data_loader):
  78. info_dict["tag"] = "CV"
  79. info_dict["step"] = self.step
  80. info_dict["epoch"] = self.epoch
  81. info_dict["batch_idx"] = batch_idx
  82. num_utts = len(batch_dict["utts"])
  83. total_num_utts += num_utts
  84. info_dict = batch_forward(model, batch_dict, info_dict)
  85. for k, v in info_dict['loss_dict'].items():
  86. if k not in total_loss_dict:
  87. total_loss_dict[k] = []
  88. total_loss_dict[k].append(v.item() * num_utts)
  89. log_per_step(None, info_dict)
  90. for k, v in total_loss_dict.items():
  91. total_loss_dict[k] = sum(v) / total_num_utts
  92. info_dict['loss_dict'] = total_loss_dict
  93. log_per_save(writer, info_dict)
  94. model_name = 'epoch_{}_whole'.format(self.epoch) if on_batch_end else 'epoch_{}_step_{}'.format(self.epoch, self.step + 1)
  95. save_model(model, model_name, info_dict)