You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

285 lines
11 KiB

  1. import os
  2. import time
  3. import argparse
  4. import math
  5. from numpy import finfo
  6. import torch
  7. from distributed import apply_gradient_allreduce
  8. import torch.distributed as dist
  9. from torch.utils.data.distributed import DistributedSampler
  10. from torch.utils.data import DataLoader
  11. from fp16_optimizer import FP16_Optimizer
  12. from model import Tacotron2
  13. from data_utils import TextMelLoader, TextMelCollate
  14. from loss_function import Tacotron2Loss
  15. from logger import Tacotron2Logger
  16. from hparams import create_hparams
  17. def batchnorm_to_float(module):
  18. """Converts batch norm modules to FP32"""
  19. if isinstance(module, torch.nn.modules.batchnorm._BatchNorm):
  20. module.float()
  21. for child in module.children():
  22. batchnorm_to_float(child)
  23. return module
  24. def reduce_tensor(tensor, num_gpus):
  25. rt = tensor.clone()
  26. dist.all_reduce(rt, op=dist.reduce_op.SUM)
  27. rt /= num_gpus
  28. return rt
  29. def init_distributed(hparams, n_gpus, rank, group_name):
  30. assert torch.cuda.is_available(), "Distributed mode requires CUDA."
  31. print("Initializing Distributed")
  32. # Set cuda device so everything is done on the right GPU.
  33. torch.cuda.set_device(rank % torch.cuda.device_count())
  34. # Initialize distributed communication
  35. dist.init_process_group(
  36. backend=hparams.dist_backend, init_method=hparams.dist_url,
  37. world_size=n_gpus, rank=rank, group_name=group_name)
  38. print("Done initializing distributed")
  39. def prepare_dataloaders(hparams):
  40. # Get data, data loaders and collate function ready
  41. trainset = TextMelLoader(hparams.training_files, hparams)
  42. valset = TextMelLoader(hparams.validation_files, hparams)
  43. collate_fn = TextMelCollate(hparams.n_frames_per_step)
  44. train_sampler = DistributedSampler(trainset) \
  45. if hparams.distributed_run else None
  46. train_loader = DataLoader(trainset, num_workers=1, shuffle=False,
  47. sampler=train_sampler,
  48. batch_size=hparams.batch_size, pin_memory=False,
  49. drop_last=True, collate_fn=collate_fn)
  50. return train_loader, valset, collate_fn
  51. def prepare_directories_and_logger(output_directory, log_directory, rank):
  52. if rank == 0:
  53. if not os.path.isdir(output_directory):
  54. os.makedirs(output_directory)
  55. os.chmod(output_directory, 0o775)
  56. logger = Tacotron2Logger(os.path.join(output_directory, log_directory))
  57. else:
  58. logger = None
  59. return logger
  60. def load_model(hparams):
  61. model = Tacotron2(hparams).cuda()
  62. if hparams.fp16_run:
  63. model = batchnorm_to_float(model.half())
  64. model.decoder.attention_layer.score_mask_value = float(finfo('float16').min)
  65. if hparams.distributed_run:
  66. model = DistributedDataParallel(model)
  67. elif torch.cuda.device_count() > 1:
  68. model = DataParallel(model)
  69. return model
  70. def warm_start_model(checkpoint_path, model):
  71. assert os.path.isfile(checkpoint_path)
  72. print("Warm starting model from checkpoint '{}'".format(checkpoint_path))
  73. checkpoint_dict = torch.load(checkpoint_path, map_location='cpu')
  74. model.load_state_dict(checkpoint_dict['state_dict'])
  75. return model
  76. def load_checkpoint(checkpoint_path, model, optimizer):
  77. assert os.path.isfile(checkpoint_path)
  78. print("Loading checkpoint '{}'".format(checkpoint_path))
  79. checkpoint_dict = torch.load(checkpoint_path, map_location='cpu')
  80. model.load_state_dict(checkpoint_dict['state_dict'])
  81. optimizer.load_state_dict(checkpoint_dict['optimizer'])
  82. learning_rate = checkpoint_dict['learning_rate']
  83. iteration = checkpoint_dict['iteration']
  84. print("Loaded checkpoint '{}' from iteration {}" .format(
  85. checkpoint_path, iteration))
  86. return model, optimizer, learning_rate, iteration
  87. def save_checkpoint(model, optimizer, learning_rate, iteration, filepath):
  88. print("Saving model and optimizer state at iteration {} to {}".format(
  89. iteration, filepath))
  90. torch.save({'iteration': iteration,
  91. 'state_dict': model.state_dict(),
  92. 'optimizer': optimizer.state_dict(),
  93. 'learning_rate': learning_rate}, filepath)
  94. def validate(model, criterion, valset, iteration, batch_size, n_gpus,
  95. collate_fn, logger, distributed_run, rank):
  96. """Handles all the validation scoring and printing"""
  97. model.eval()
  98. with torch.no_grad():
  99. val_sampler = DistributedSampler(valset) if distributed_run else None
  100. val_loader = DataLoader(valset, sampler=val_sampler, num_workers=1,
  101. shuffle=False, batch_size=batch_size,
  102. pin_memory=False, collate_fn=collate_fn)
  103. val_loss = 0.0
  104. for i, batch in enumerate(val_loader):
  105. x, y = model.parse_batch(batch)
  106. y_pred = model(x)
  107. loss = criterion(y_pred, y)
  108. if distributed_run:
  109. reduced_val_loss = reduce_tensor(loss.data, num_gpus).item()
  110. else:
  111. reduced_val_loss = loss.item()
  112. val_loss += reduced_val_loss
  113. val_loss = val_loss / (i + 1)
  114. model.train()
  115. print("Validation loss {}: {:9f} ".format(iteration, reduced_val_loss))
  116. logger.log_validation(reduced_val_loss, model, y, y_pred, iteration)
  117. def train(output_directory, log_directory, checkpoint_path, warm_start, n_gpus,
  118. rank, group_name, hparams):
  119. """Training and validation logging results to tensorboard and stdout
  120. Params
  121. ------
  122. output_directory (string): directory to save checkpoints
  123. log_directory (string) directory to save tensorboard logs
  124. checkpoint_path(string): checkpoint path
  125. n_gpus (int): number of gpus
  126. rank (int): rank of current gpu
  127. hparams (object): comma separated list of "name=value" pairs.
  128. """
  129. if hparams.distributed_run:
  130. init_distributed(hparams, n_gpus, rank, group_name)
  131. torch.manual_seed(hparams.seed)
  132. torch.cuda.manual_seed(hparams.seed)
  133. model = load_model(hparams)
  134. learning_rate = hparams.learning_rate
  135. optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate,
  136. weight_decay=hparams.weight_decay)
  137. if hparams.fp16_run:
  138. optimizer = FP16_Optimizer(
  139. optimizer, dynamic_loss_scale=hparams.dynamic_loss_scaling)
  140. if hparams.distributed_run:
  141. model = apply_gradient_allreduce(model)
  142. criterion = Tacotron2Loss()
  143. logger = prepare_directories_and_logger(
  144. output_directory, log_directory, rank)
  145. train_loader, valset, collate_fn = prepare_dataloaders(hparams)
  146. # Load checkpoint if one exists
  147. iteration = 0
  148. epoch_offset = 0
  149. if checkpoint_path is not None:
  150. if warm_start:
  151. model = warm_start_model(checkpoint_path, model)
  152. else:
  153. model, optimizer, _learning_rate, iteration = load_checkpoint(
  154. checkpoint_path, model, optimizer)
  155. if hparams.use_saved_learning_rate:
  156. learning_rate = _learning_rate
  157. iteration += 1 # next iteration is iteration + 1
  158. epoch_offset = max(0, int(iteration / len(train_loader)))
  159. model.train()
  160. # ================ MAIN TRAINNIG LOOP! ===================
  161. for epoch in range(epoch_offset, hparams.epochs):
  162. print("Epoch: {}".format(epoch))
  163. for i, batch in enumerate(train_loader):
  164. start = time.perf_counter()
  165. for param_group in optimizer.param_groups:
  166. param_group['lr'] = learning_rate
  167. model.zero_grad()
  168. x, y = model.parse_batch(batch)
  169. y_pred = model(x)
  170. loss = criterion(y_pred, y)
  171. if hparams.distributed_run:
  172. reduced_loss = reduce_tensor(loss.data, num_gpus).item()
  173. else:
  174. reduced_loss = loss.item()
  175. if hparams.fp16_run:
  176. optimizer.backward(loss)
  177. grad_norm = optimizer.clip_fp32_grads(hparams.grad_clip_thresh)
  178. else:
  179. loss.backward()
  180. grad_norm = torch.nn.utils.clip_grad_norm_(
  181. model.parameters(), hparams.grad_clip_thresh)
  182. optimizer.step()
  183. overflow = optimizer.overflow if hparams.fp16_run else False
  184. if not overflow and not math.isnan(reduced_loss) and rank == 0:
  185. duration = time.perf_counter() - start
  186. print("Train loss {} {:.6f} Grad Norm {:.6f} {:.2f}s/it".format(
  187. iteration, reduced_loss, grad_norm, duration))
  188. logger.log_training(
  189. reduced_loss, grad_norm, learning_rate, duration, iteration)
  190. if not overflow and (iteration % hparams.iters_per_checkpoint == 0):
  191. validate(model, criterion, valset, iteration, hparams.batch_size,
  192. n_gpus, collate_fn, logger, hparams.distributed_run, rank)
  193. if rank == 0:
  194. checkpoint_path = os.path.join(
  195. output_directory, "checkpoint_{}".format(iteration))
  196. save_checkpoint(model, optimizer, learning_rate, iteration,
  197. checkpoint_path)
  198. iteration += 1
  199. if __name__ == '__main__':
  200. parser = argparse.ArgumentParser()
  201. parser.add_argument('-o', '--output_directory', type=str,
  202. help='directory to save checkpoints')
  203. parser.add_argument('-l', '--log_directory', type=str,
  204. help='directory to save tensorboard logs')
  205. parser.add_argument('-c', '--checkpoint_path', type=str, default=None,
  206. required=False, help='checkpoint path')
  207. parser.add_argument('--warm_start', action='store_true',
  208. help='load the model only (warm start)')
  209. parser.add_argument('--n_gpus', type=int, default=1,
  210. required=False, help='number of gpus')
  211. parser.add_argument('--rank', type=int, default=0,
  212. required=False, help='rank of current gpu')
  213. parser.add_argument('--group_name', type=str, default='group_name',
  214. required=False, help='Distributed group name')
  215. parser.add_argument('--hparams', type=str,
  216. required=False, help='comma separated name=value pairs')
  217. args = parser.parse_args()
  218. hparams = create_hparams(args.hparams)
  219. torch.backends.cudnn.enabled = hparams.cudnn_enabled
  220. torch.backends.cudnn.benchmark = hparams.cudnn_benchmark
  221. print("FP16 Run:", hparams.fp16_run)
  222. print("Dynamic Loss Scaling:", hparams.dynamic_loss_scaling)
  223. print("Distributed Run:", hparams.distributed_run)
  224. print("cuDNN Enabled:", hparams.cudnn_enabled)
  225. print("cuDNN Benchmark:", hparams.cudnn_benchmark)
  226. train(args.output_directory, args.log_directory, args.checkpoint_path,
  227. args.warm_start, args.n_gpus, args.rank, args.group_name, hparams)