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.

288 lines
11 KiB

6 years ago
  1. import os
  2. import time
  3. import argparse
  4. import math
  5. from numpy import finfo
  6. import torch
  7. from distributed import DistributedDataParallel
  8. from torch.utils.data.distributed import DistributedSampler
  9. from torch.nn import DataParallel
  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. torch.distributed.all_reduce(rt, op=torch.distributed.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. torch.distributed.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. if distributed_run or torch.cuda.device_count() > 1:
  105. batch_parser = model.module.parse_batch
  106. else:
  107. batch_parser = model.parse_batch
  108. for i, batch in enumerate(val_loader):
  109. x, y = batch_parser(batch)
  110. y_pred = model(x)
  111. loss = criterion(y_pred, y)
  112. reduced_val_loss = reduce_tensor(loss.data, n_gpus)[0] \
  113. if distributed_run else loss.data[0]
  114. val_loss += reduced_val_loss
  115. val_loss = val_loss / (i + 1)
  116. model.train()
  117. return val_loss
  118. def train(output_directory, log_directory, checkpoint_path, warm_start, n_gpus,
  119. rank, group_name, hparams):
  120. """Training and validation logging results to tensorboard and stdout
  121. Params
  122. ------
  123. output_directory (string): directory to save checkpoints
  124. log_directory (string) directory to save tensorboard logs
  125. checkpoint_path(string): checkpoint path
  126. n_gpus (int): number of gpus
  127. rank (int): rank of current gpu
  128. hparams (object): comma separated list of "name=value" pairs.
  129. """
  130. if hparams.distributed_run:
  131. init_distributed(hparams, n_gpus, rank, group_name)
  132. torch.manual_seed(hparams.seed)
  133. torch.cuda.manual_seed(hparams.seed)
  134. model = load_model(hparams)
  135. learning_rate = hparams.learning_rate
  136. optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate,
  137. weight_decay=hparams.weight_decay)
  138. if hparams.fp16_run:
  139. optimizer = FP16_Optimizer(
  140. optimizer, dynamic_loss_scale=hparams.dynamic_loss_scaling)
  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. iteration += 1 # next iteration is iteration + 1
  155. epoch_offset = max(0, int(iteration / len(train_loader)))
  156. model.train()
  157. if hparams.distributed_run or torch.cuda.device_count() > 1:
  158. batch_parser = model.module.parse_batch
  159. else:
  160. batch_parser = model.parse_batch
  161. # ================ MAIN TRAINNIG LOOP! ===================
  162. for epoch in range(epoch_offset, hparams.epochs):
  163. print("Epoch: {}".format(epoch))
  164. for i, batch in enumerate(train_loader):
  165. start = time.perf_counter()
  166. for param_group in optimizer.param_groups:
  167. param_group['lr'] = learning_rate
  168. model.zero_grad()
  169. x, y = batch_parser(batch)
  170. y_pred = model(x)
  171. loss = criterion(y_pred, y)
  172. reduced_loss = reduce_tensor(loss.data, n_gpus)[0] \
  173. if hparams.distributed_run else loss.data[0]
  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. reduced_val_loss = validate(
  191. model, criterion, valset, iteration, hparams.batch_size,
  192. n_gpus, collate_fn, logger, hparams.distributed_run, rank)
  193. if rank == 0:
  194. print("Validation loss {}: {:9f} ".format(
  195. iteration, reduced_val_loss))
  196. logger.log_validation(
  197. reduced_val_loss, model, y, y_pred, iteration)
  198. checkpoint_path = os.path.join(
  199. output_directory, "checkpoint_{}".format(iteration))
  200. save_checkpoint(model, optimizer, learning_rate, iteration,
  201. checkpoint_path)
  202. iteration += 1
  203. if __name__ == '__main__':
  204. parser = argparse.ArgumentParser()
  205. parser.add_argument('-o', '--output_directory', type=str,
  206. help='directory to save checkpoints')
  207. parser.add_argument('-l', '--log_directory', type=str,
  208. help='directory to save tensorboard logs')
  209. parser.add_argument('-c', '--checkpoint_path', type=str, default=None,
  210. required=False, help='checkpoint path')
  211. parser.add_argument('--warm_start', action='store_true',
  212. help='load the model only (warm start)')
  213. parser.add_argument('--n_gpus', type=int, default=1,
  214. required=False, help='number of gpus')
  215. parser.add_argument('--rank', type=int, default=0,
  216. required=False, help='rank of current gpu')
  217. parser.add_argument('--group_name', type=str, default='group_name',
  218. required=False, help='Distributed group name')
  219. parser.add_argument('--hparams', type=str,
  220. required=False, help='comma separated name=value pairs')
  221. args = parser.parse_args()
  222. hparams = create_hparams(args.hparams)
  223. torch.backends.cudnn.enabled = hparams.cudnn_enabled
  224. torch.backends.cudnn.benchmark = hparams.cudnn_benchmark
  225. print("FP16 Run:", hparams.fp16_run)
  226. print("Dynamic Loss Scaling", hparams.dynamic_loss_scaling)
  227. print("Distributed Run:", hparams.distributed_run)
  228. print("cuDNN Enabled:", hparams.cudnn_enabled)
  229. print("cuDNN Benchmark:", hparams.cudnn_benchmark)
  230. train(args.output_directory, args.log_directory, args.checkpoint_path,
  231. args.warm_start, args.n_gpus, args.rank, args.group_name, hparams)