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.

290 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 model import Tacotron2
  12. from data_utils import TextMelLoader, TextMelCollate
  13. from loss_function import Tacotron2Loss
  14. from logger import Tacotron2Logger
  15. from hparams import create_hparams
  16. def reduce_tensor(tensor, n_gpus):
  17. rt = tensor.clone()
  18. dist.all_reduce(rt, op=dist.reduce_op.SUM)
  19. rt /= n_gpus
  20. return rt
  21. def init_distributed(hparams, n_gpus, rank, group_name):
  22. assert torch.cuda.is_available(), "Distributed mode requires CUDA."
  23. print("Initializing Distributed")
  24. # Set cuda device so everything is done on the right GPU.
  25. torch.cuda.set_device(rank % torch.cuda.device_count())
  26. # Initialize distributed communication
  27. dist.init_process_group(
  28. backend=hparams.dist_backend, init_method=hparams.dist_url,
  29. world_size=n_gpus, rank=rank, group_name=group_name)
  30. print("Done initializing distributed")
  31. def prepare_dataloaders(hparams):
  32. # Get data, data loaders and collate function ready
  33. trainset = TextMelLoader(hparams.training_files, hparams)
  34. valset = TextMelLoader(hparams.validation_files, hparams)
  35. collate_fn = TextMelCollate(hparams.n_frames_per_step)
  36. if hparams.distributed_run:
  37. train_sampler = DistributedSampler(trainset)
  38. shuffle = False
  39. else:
  40. train_sampler = None
  41. shuffle = True
  42. train_loader = DataLoader(trainset, num_workers=1, shuffle=shuffle,
  43. sampler=train_sampler,
  44. batch_size=hparams.batch_size, pin_memory=False,
  45. drop_last=True, collate_fn=collate_fn)
  46. return train_loader, valset, collate_fn
  47. def prepare_directories_and_logger(output_directory, log_directory, rank):
  48. if rank == 0:
  49. if not os.path.isdir(output_directory):
  50. os.makedirs(output_directory)
  51. os.chmod(output_directory, 0o775)
  52. logger = Tacotron2Logger(os.path.join(output_directory, log_directory))
  53. else:
  54. logger = None
  55. return logger
  56. def load_model(hparams):
  57. model = Tacotron2(hparams).cuda()
  58. if hparams.fp16_run:
  59. model.decoder.attention_layer.score_mask_value = finfo('float16').min
  60. if hparams.distributed_run:
  61. model = apply_gradient_allreduce(model)
  62. return model
  63. def warm_start_model(checkpoint_path, model, ignore_layers):
  64. assert os.path.isfile(checkpoint_path)
  65. print("Warm starting model from checkpoint '{}'".format(checkpoint_path))
  66. checkpoint_dict = torch.load(checkpoint_path, map_location='cpu')
  67. model_dict = checkpoint_dict['state_dict']
  68. if len(ignore_layers) > 0:
  69. model_dict = {k: v for k, v in model_dict.items()
  70. if k not in ignore_layers}
  71. dummy_dict = model.state_dict()
  72. dummy_dict.update(model_dict)
  73. model_dict = dummy_dict
  74. model.load_state_dict(model_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, n_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. if rank == 0:
  116. print("Validation loss {}: {:9f} ".format(iteration, reduced_val_loss))
  117. logger.log_validation(val_loss, model, y, y_pred, iteration)
  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. from apex import amp
  140. model, optimizer = amp.initialize(
  141. model, optimizer, opt_level='O2')
  142. if hparams.distributed_run:
  143. model = apply_gradient_allreduce(model)
  144. criterion = Tacotron2Loss()
  145. logger = prepare_directories_and_logger(
  146. output_directory, log_directory, rank)
  147. train_loader, valset, collate_fn = prepare_dataloaders(hparams)
  148. # Load checkpoint if one exists
  149. iteration = 0
  150. epoch_offset = 0
  151. if checkpoint_path is not None:
  152. if warm_start:
  153. model = warm_start_model(
  154. checkpoint_path, model, hparams.ignore_layers)
  155. else:
  156. model, optimizer, _learning_rate, iteration = load_checkpoint(
  157. checkpoint_path, model, optimizer)
  158. if hparams.use_saved_learning_rate:
  159. learning_rate = _learning_rate
  160. iteration += 1 # next iteration is iteration + 1
  161. epoch_offset = max(0, int(iteration / len(train_loader)))
  162. model.train()
  163. is_overflow = False
  164. # ================ MAIN TRAINNIG LOOP! ===================
  165. for epoch in range(epoch_offset, hparams.epochs):
  166. print("Epoch: {}".format(epoch))
  167. for i, batch in enumerate(train_loader):
  168. start = time.perf_counter()
  169. for param_group in optimizer.param_groups:
  170. param_group['lr'] = learning_rate
  171. model.zero_grad()
  172. x, y = model.parse_batch(batch)
  173. y_pred = model(x)
  174. loss = criterion(y_pred, y)
  175. if hparams.distributed_run:
  176. reduced_loss = reduce_tensor(loss.data, n_gpus).item()
  177. else:
  178. reduced_loss = loss.item()
  179. if hparams.fp16_run:
  180. with amp.scale_loss(loss, optimizer) as scaled_loss:
  181. scaled_loss.backward()
  182. else:
  183. loss.backward()
  184. if hparams.fp16_run:
  185. grad_norm = torch.nn.utils.clip_grad_norm_(
  186. amp.master_params(optimizer), hparams.grad_clip_thresh)
  187. is_overflow = math.isnan(grad_norm)
  188. else:
  189. grad_norm = torch.nn.utils.clip_grad_norm_(
  190. model.parameters(), hparams.grad_clip_thresh)
  191. optimizer.step()
  192. if not is_overflow and rank == 0:
  193. duration = time.perf_counter() - start
  194. print("Train loss {} {:.6f} Grad Norm {:.6f} {:.2f}s/it".format(
  195. iteration, reduced_loss, grad_norm, duration))
  196. logger.log_training(
  197. reduced_loss, grad_norm, learning_rate, duration, iteration)
  198. if not is_overflow and (iteration % hparams.iters_per_checkpoint == 0):
  199. validate(model, criterion, valset, iteration,
  200. hparams.batch_size, n_gpus, collate_fn, logger,
  201. hparams.distributed_run, rank)
  202. if rank == 0:
  203. checkpoint_path = os.path.join(
  204. output_directory, "checkpoint_{}".format(iteration))
  205. save_checkpoint(model, optimizer, learning_rate, iteration,
  206. checkpoint_path)
  207. iteration += 1
  208. if __name__ == '__main__':
  209. parser = argparse.ArgumentParser()
  210. parser.add_argument('-o', '--output_directory', type=str,
  211. help='directory to save checkpoints')
  212. parser.add_argument('-l', '--log_directory', type=str,
  213. help='directory to save tensorboard logs')
  214. parser.add_argument('-c', '--checkpoint_path', type=str, default=None,
  215. required=False, help='checkpoint path')
  216. parser.add_argument('--warm_start', action='store_true',
  217. help='load model weights only, ignore specified layers')
  218. parser.add_argument('--n_gpus', type=int, default=1,
  219. required=False, help='number of gpus')
  220. parser.add_argument('--rank', type=int, default=0,
  221. required=False, help='rank of current gpu')
  222. parser.add_argument('--group_name', type=str, default='group_name',
  223. required=False, help='Distributed group name')
  224. parser.add_argument('--hparams', type=str,
  225. required=False, help='comma separated name=value pairs')
  226. args = parser.parse_args()
  227. hparams = create_hparams(args.hparams)
  228. torch.backends.cudnn.enabled = hparams.cudnn_enabled
  229. torch.backends.cudnn.benchmark = hparams.cudnn_benchmark
  230. print("FP16 Run:", hparams.fp16_run)
  231. print("Dynamic Loss Scaling:", hparams.dynamic_loss_scaling)
  232. print("Distributed Run:", hparams.distributed_run)
  233. print("cuDNN Enabled:", hparams.cudnn_enabled)
  234. print("cuDNN Benchmark:", hparams.cudnn_benchmark)
  235. train(args.output_directory, args.log_directory, args.checkpoint_path,
  236. args.warm_start, args.n_gpus, args.rank, args.group_name, hparams)