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.

296 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. if hparams.distributed_run:
  45. train_sampler = DistributedSampler(trainset)
  46. shuffle = False
  47. else:
  48. train_sampler = None
  49. shuffle = True
  50. train_loader = DataLoader(trainset, num_workers=1, shuffle=shuffle,
  51. sampler=train_sampler,
  52. batch_size=hparams.batch_size, pin_memory=False,
  53. drop_last=True, collate_fn=collate_fn)
  54. return train_loader, valset, collate_fn
  55. def prepare_directories_and_logger(output_directory, log_directory, rank):
  56. if rank == 0:
  57. if not os.path.isdir(output_directory):
  58. os.makedirs(output_directory)
  59. os.chmod(output_directory, 0o775)
  60. logger = Tacotron2Logger(os.path.join(output_directory, log_directory))
  61. else:
  62. logger = None
  63. return logger
  64. def load_model(hparams):
  65. model = Tacotron2(hparams).cuda()
  66. if hparams.fp16_run:
  67. model = batchnorm_to_float(model.half())
  68. model.decoder.attention_layer.score_mask_value = float(finfo('float16').min)
  69. if hparams.distributed_run:
  70. model = apply_gradient_allreduce(model)
  71. return model
  72. def warm_start_model(checkpoint_path, model, ignore_layers):
  73. assert os.path.isfile(checkpoint_path)
  74. print("Warm starting model from checkpoint '{}'".format(checkpoint_path))
  75. checkpoint_dict = torch.load(checkpoint_path, map_location='cpu')
  76. model_dict = checkpoint_dict['state_dict']
  77. if len(ignore_layers) > 0:
  78. model_dict = {k: v for k, v in model_dict.items()
  79. if k not in ignore_layers}
  80. dummy_dict = model.state_dict()
  81. dummy_dict.update(model_dict)
  82. model_dict = dummy_dict
  83. model.load_state_dict(model_dict)
  84. return model
  85. def load_checkpoint(checkpoint_path, model, optimizer):
  86. assert os.path.isfile(checkpoint_path)
  87. print("Loading checkpoint '{}'".format(checkpoint_path))
  88. checkpoint_dict = torch.load(checkpoint_path, map_location='cpu')
  89. model.load_state_dict(checkpoint_dict['state_dict'])
  90. optimizer.load_state_dict(checkpoint_dict['optimizer'])
  91. learning_rate = checkpoint_dict['learning_rate']
  92. iteration = checkpoint_dict['iteration']
  93. print("Loaded checkpoint '{}' from iteration {}" .format(
  94. checkpoint_path, iteration))
  95. return model, optimizer, learning_rate, iteration
  96. def save_checkpoint(model, optimizer, learning_rate, iteration, filepath):
  97. print("Saving model and optimizer state at iteration {} to {}".format(
  98. iteration, filepath))
  99. torch.save({'iteration': iteration,
  100. 'state_dict': model.state_dict(),
  101. 'optimizer': optimizer.state_dict(),
  102. 'learning_rate': learning_rate}, filepath)
  103. def validate(model, criterion, valset, iteration, batch_size, n_gpus,
  104. collate_fn, logger, distributed_run, rank):
  105. """Handles all the validation scoring and printing"""
  106. model.eval()
  107. with torch.no_grad():
  108. val_sampler = DistributedSampler(valset) if distributed_run else None
  109. val_loader = DataLoader(valset, sampler=val_sampler, num_workers=1,
  110. shuffle=False, batch_size=batch_size,
  111. pin_memory=False, collate_fn=collate_fn)
  112. val_loss = 0.0
  113. for i, batch in enumerate(val_loader):
  114. x, y = model.parse_batch(batch)
  115. y_pred = model(x)
  116. loss = criterion(y_pred, y)
  117. if distributed_run:
  118. reduced_val_loss = reduce_tensor(loss.data, n_gpus).item()
  119. else:
  120. reduced_val_loss = loss.item()
  121. val_loss += reduced_val_loss
  122. val_loss = val_loss / (i + 1)
  123. model.train()
  124. if rank == 0:
  125. print("Validation loss {}: {:9f} ".format(iteration, reduced_val_loss))
  126. logger.log_validation(reduced_val_loss, model, y, y_pred, iteration)
  127. def train(output_directory, log_directory, checkpoint_path, warm_start, n_gpus,
  128. rank, group_name, hparams):
  129. """Training and validation logging results to tensorboard and stdout
  130. Params
  131. ------
  132. output_directory (string): directory to save checkpoints
  133. log_directory (string) directory to save tensorboard logs
  134. checkpoint_path(string): checkpoint path
  135. n_gpus (int): number of gpus
  136. rank (int): rank of current gpu
  137. hparams (object): comma separated list of "name=value" pairs.
  138. """
  139. if hparams.distributed_run:
  140. init_distributed(hparams, n_gpus, rank, group_name)
  141. torch.manual_seed(hparams.seed)
  142. torch.cuda.manual_seed(hparams.seed)
  143. model = load_model(hparams)
  144. learning_rate = hparams.learning_rate
  145. optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate,
  146. weight_decay=hparams.weight_decay)
  147. if hparams.fp16_run:
  148. optimizer = FP16_Optimizer(
  149. optimizer, dynamic_loss_scale=hparams.dynamic_loss_scaling)
  150. if hparams.distributed_run:
  151. model = apply_gradient_allreduce(model)
  152. criterion = Tacotron2Loss()
  153. logger = prepare_directories_and_logger(
  154. output_directory, log_directory, rank)
  155. train_loader, valset, collate_fn = prepare_dataloaders(hparams)
  156. # Load checkpoint if one exists
  157. iteration = 0
  158. epoch_offset = 0
  159. if checkpoint_path is not None:
  160. if warm_start:
  161. model = warm_start_model(
  162. checkpoint_path, model, hparams.ignore_layers)
  163. else:
  164. model, optimizer, _learning_rate, iteration = load_checkpoint(
  165. checkpoint_path, model, optimizer)
  166. if hparams.use_saved_learning_rate:
  167. learning_rate = _learning_rate
  168. iteration += 1 # next iteration is iteration + 1
  169. epoch_offset = max(0, int(iteration / len(train_loader)))
  170. model.train()
  171. # ================ MAIN TRAINNIG LOOP! ===================
  172. for epoch in range(epoch_offset, hparams.epochs):
  173. print("Epoch: {}".format(epoch))
  174. for i, batch in enumerate(train_loader):
  175. start = time.perf_counter()
  176. for param_group in optimizer.param_groups:
  177. param_group['lr'] = learning_rate
  178. model.zero_grad()
  179. x, y = model.parse_batch(batch)
  180. y_pred = model(x)
  181. loss = criterion(y_pred, y)
  182. if hparams.distributed_run:
  183. reduced_loss = reduce_tensor(loss.data, n_gpus).item()
  184. else:
  185. reduced_loss = loss.item()
  186. if hparams.fp16_run:
  187. optimizer.backward(loss)
  188. grad_norm = optimizer.clip_fp32_grads(hparams.grad_clip_thresh)
  189. else:
  190. loss.backward()
  191. grad_norm = torch.nn.utils.clip_grad_norm_(
  192. model.parameters(), hparams.grad_clip_thresh)
  193. optimizer.step()
  194. overflow = optimizer.overflow if hparams.fp16_run else False
  195. if not overflow and not math.isnan(reduced_loss) and rank == 0:
  196. duration = time.perf_counter() - start
  197. print("Train loss {} {:.6f} Grad Norm {:.6f} {:.2f}s/it".format(
  198. iteration, reduced_loss, grad_norm, duration))
  199. logger.log_training(
  200. reduced_loss, grad_norm, learning_rate, duration, iteration)
  201. if not overflow and (iteration % hparams.iters_per_checkpoint == 0):
  202. validate(model, criterion, valset, iteration,
  203. hparams.batch_size, n_gpus, collate_fn, logger,
  204. hparams.distributed_run, rank)
  205. if rank == 0:
  206. checkpoint_path = os.path.join(
  207. output_directory, "checkpoint_{}".format(iteration))
  208. save_checkpoint(model, optimizer, learning_rate, iteration,
  209. checkpoint_path)
  210. iteration += 1
  211. if __name__ == '__main__':
  212. parser = argparse.ArgumentParser()
  213. parser.add_argument('-o', '--output_directory', type=str,
  214. help='directory to save checkpoints')
  215. parser.add_argument('-l', '--log_directory', type=str,
  216. help='directory to save tensorboard logs')
  217. parser.add_argument('-c', '--checkpoint_path', type=str, default=None,
  218. required=False, help='checkpoint path')
  219. parser.add_argument('--warm_start', action='store_true',
  220. help='load model weights only, ignore specified layers')
  221. parser.add_argument('--n_gpus', type=int, default=1,
  222. required=False, help='number of gpus')
  223. parser.add_argument('--rank', type=int, default=0,
  224. required=False, help='rank of current gpu')
  225. parser.add_argument('--group_name', type=str, default='group_name',
  226. required=False, help='Distributed group name')
  227. parser.add_argument('--hparams', type=str,
  228. required=False, help='comma separated name=value pairs')
  229. args = parser.parse_args()
  230. hparams = create_hparams(args.hparams)
  231. torch.backends.cudnn.enabled = hparams.cudnn_enabled
  232. torch.backends.cudnn.benchmark = hparams.cudnn_benchmark
  233. print("FP16 Run:", hparams.fp16_run)
  234. print("Dynamic Loss Scaling:", hparams.dynamic_loss_scaling)
  235. print("Distributed Run:", hparams.distributed_run)
  236. print("cuDNN Enabled:", hparams.cudnn_enabled)
  237. print("cuDNN Benchmark:", hparams.cudnn_benchmark)
  238. train(args.output_directory, args.log_directory, args.checkpoint_path,
  239. args.warm_start, args.n_gpus, args.rank, args.group_name, hparams)