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.

284 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, n_gpus):
  25. rt = tensor.clone()
  26. dist.all_reduce(rt, op=dist.reduce_op.SUM)
  27. rt /= n_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 = apply_gradient_allreduce(model)
  67. return model
  68. def warm_start_model(checkpoint_path, model):
  69. assert os.path.isfile(checkpoint_path)
  70. print("Warm starting model from checkpoint '{}'".format(checkpoint_path))
  71. checkpoint_dict = torch.load(checkpoint_path, map_location='cpu')
  72. model.load_state_dict(checkpoint_dict['state_dict'])
  73. return model
  74. def load_checkpoint(checkpoint_path, model, optimizer):
  75. assert os.path.isfile(checkpoint_path)
  76. print("Loading checkpoint '{}'".format(checkpoint_path))
  77. checkpoint_dict = torch.load(checkpoint_path, map_location='cpu')
  78. model.load_state_dict(checkpoint_dict['state_dict'])
  79. optimizer.load_state_dict(checkpoint_dict['optimizer'])
  80. learning_rate = checkpoint_dict['learning_rate']
  81. iteration = checkpoint_dict['iteration']
  82. print("Loaded checkpoint '{}' from iteration {}" .format(
  83. checkpoint_path, iteration))
  84. return model, optimizer, learning_rate, iteration
  85. def save_checkpoint(model, optimizer, learning_rate, iteration, filepath):
  86. print("Saving model and optimizer state at iteration {} to {}".format(
  87. iteration, filepath))
  88. torch.save({'iteration': iteration,
  89. 'state_dict': model.state_dict(),
  90. 'optimizer': optimizer.state_dict(),
  91. 'learning_rate': learning_rate}, filepath)
  92. def validate(model, criterion, valset, iteration, batch_size, n_gpus,
  93. collate_fn, logger, distributed_run, rank):
  94. """Handles all the validation scoring and printing"""
  95. model.eval()
  96. with torch.no_grad():
  97. val_sampler = DistributedSampler(valset) if distributed_run else None
  98. val_loader = DataLoader(valset, sampler=val_sampler, num_workers=1,
  99. shuffle=False, batch_size=batch_size,
  100. pin_memory=False, collate_fn=collate_fn)
  101. val_loss = 0.0
  102. for i, batch in enumerate(val_loader):
  103. x, y = model.parse_batch(batch)
  104. y_pred = model(x)
  105. loss = criterion(y_pred, y)
  106. if distributed_run:
  107. reduced_val_loss = reduce_tensor(loss.data, n_gpus).item()
  108. else:
  109. reduced_val_loss = loss.item()
  110. val_loss += reduced_val_loss
  111. val_loss = val_loss / (i + 1)
  112. model.train()
  113. if rank == 0:
  114. print("Validation loss {}: {:9f} ".format(iteration, reduced_val_loss))
  115. logger.log_validation(reduced_val_loss, model, y, y_pred, iteration)
  116. def train(output_directory, log_directory, checkpoint_path, warm_start, n_gpus,
  117. rank, group_name, hparams):
  118. """Training and validation logging results to tensorboard and stdout
  119. Params
  120. ------
  121. output_directory (string): directory to save checkpoints
  122. log_directory (string) directory to save tensorboard logs
  123. checkpoint_path(string): checkpoint path
  124. n_gpus (int): number of gpus
  125. rank (int): rank of current gpu
  126. hparams (object): comma separated list of "name=value" pairs.
  127. """
  128. if hparams.distributed_run:
  129. init_distributed(hparams, n_gpus, rank, group_name)
  130. torch.manual_seed(hparams.seed)
  131. torch.cuda.manual_seed(hparams.seed)
  132. model = load_model(hparams)
  133. learning_rate = hparams.learning_rate
  134. optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate,
  135. weight_decay=hparams.weight_decay)
  136. if hparams.fp16_run:
  137. optimizer = FP16_Optimizer(
  138. optimizer, dynamic_loss_scale=hparams.dynamic_loss_scaling)
  139. if hparams.distributed_run:
  140. model = apply_gradient_allreduce(model)
  141. criterion = Tacotron2Loss()
  142. logger = prepare_directories_and_logger(
  143. output_directory, log_directory, rank)
  144. train_loader, valset, collate_fn = prepare_dataloaders(hparams)
  145. # Load checkpoint if one exists
  146. iteration = 0
  147. epoch_offset = 0
  148. if checkpoint_path is not None:
  149. if warm_start:
  150. model = warm_start_model(checkpoint_path, model)
  151. else:
  152. model, optimizer, _learning_rate, iteration = load_checkpoint(
  153. checkpoint_path, model, optimizer)
  154. if hparams.use_saved_learning_rate:
  155. learning_rate = _learning_rate
  156. iteration += 1 # next iteration is iteration + 1
  157. epoch_offset = max(0, int(iteration / len(train_loader)))
  158. model.train()
  159. # ================ MAIN TRAINNIG LOOP! ===================
  160. for epoch in range(epoch_offset, hparams.epochs):
  161. print("Epoch: {}".format(epoch))
  162. for i, batch in enumerate(train_loader):
  163. start = time.perf_counter()
  164. for param_group in optimizer.param_groups:
  165. param_group['lr'] = learning_rate
  166. model.zero_grad()
  167. x, y = model.parse_batch(batch)
  168. y_pred = model(x)
  169. loss = criterion(y_pred, y)
  170. if hparams.distributed_run:
  171. reduced_loss = reduce_tensor(loss.data, n_gpus).item()
  172. else:
  173. reduced_loss = loss.item()
  174. if hparams.fp16_run:
  175. optimizer.backward(loss)
  176. grad_norm = optimizer.clip_fp32_grads(hparams.grad_clip_thresh)
  177. else:
  178. loss.backward()
  179. grad_norm = torch.nn.utils.clip_grad_norm_(
  180. model.parameters(), hparams.grad_clip_thresh)
  181. optimizer.step()
  182. overflow = optimizer.overflow if hparams.fp16_run else False
  183. if not overflow and not math.isnan(reduced_loss) and rank == 0:
  184. duration = time.perf_counter() - start
  185. print("Train loss {} {:.6f} Grad Norm {:.6f} {:.2f}s/it".format(
  186. iteration, reduced_loss, grad_norm, duration))
  187. logger.log_training(
  188. reduced_loss, grad_norm, learning_rate, duration, iteration)
  189. if not overflow and (iteration % hparams.iters_per_checkpoint == 0):
  190. validate(model, criterion, valset, iteration,
  191. hparams.batch_size, n_gpus, collate_fn, logger,
  192. 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)