trainer.py 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234
  1. import torch
  2. import os
  3. from funasr.train_utils.device_funcs import to_device
  4. import logging
  5. import time
  6. from tqdm import tqdm
  7. from contextlib import nullcontext
  8. import torch.distributed as dist
  9. from funasr.train_utils.recursive_op import recursive_average
  10. class Trainer:
  11. """
  12. A simple trainer class for training a PyTorch model, saving checkpoints at the end of each epoch,
  13. and optionally resuming from a saved checkpoint.
  14. Attributes:
  15. max_epoch (int): Maximum number of epochs for training.
  16. model (torch.nn.Module): The model to be trained.
  17. optim (torch.optim.Optimizer): The optimizer to use for training.
  18. scheduler (torch.optim.lr_scheduler._LRScheduler): The learning rate scheduler.
  19. dataloader_train (torch.utils.data.DataLoader): DataLoader for the training dataset.
  20. dataloader_val (torch.utils.data.DataLoader): DataLoader for the validation dataset.
  21. output_dir (str): Directory where model checkpoints will be saved.
  22. resume (str, optional): Path to a checkpoint to resume training from.
  23. """
  24. def __init__(self, model,
  25. optim,
  26. scheduler,
  27. dataloader_train,
  28. dataloader_val,
  29. local_rank,
  30. use_ddp=False,
  31. use_fsdp=False,
  32. **kwargs):
  33. """
  34. Initializes the Trainer class with the model, optimizer, scheduler, dataloaders, and other settings.
  35. Args:
  36. model (torch.nn.Module): The model to be trained.
  37. optim (torch.optim.Optimizer): The optimizer to use for training.
  38. scheduler (torch.optim.lr_scheduler._LRScheduler): The learning rate scheduler.
  39. dataloader_train (torch.utils.data.DataLoader): The DataLoader for the training dataset.
  40. dataloader_val (torch.utils.data.DataLoader): The DataLoader for the validation dataset.
  41. **kwargs: Additional keyword arguments:
  42. max_epoch (int): The maximum number of epochs for training.
  43. output_dir (str): The directory where model checkpoints will be saved. Default is './'.
  44. resume (str, optional): The file path to a checkpoint to resume training from.
  45. """
  46. self.model = model
  47. self.optim = optim
  48. self.scheduler = scheduler
  49. self.dataloader_train = dataloader_train
  50. self.dataloader_val = dataloader_val
  51. self.output_dir = kwargs.get('output_dir', './')
  52. self.resume = kwargs.get('resume', True)
  53. self.start_epoch = 0
  54. self.max_epoch = kwargs.get('max_epoch', 100)
  55. self.local_rank = local_rank
  56. self.use_ddp = use_ddp
  57. self.use_fsdp = use_fsdp
  58. self.device = next(model.parameters()).device
  59. self.kwargs = kwargs
  60. if self.resume:
  61. self._resume_checkpoint(self.resume)
  62. try:
  63. rank = dist.get_rank()
  64. world_size = dist.get_world_size()
  65. except:
  66. rank = 0
  67. world_size = 1
  68. logging.warning("distributed is not initialized, only single shard")
  69. self.rank = rank
  70. self.world_size = world_size
  71. def _save_checkpoint(self, epoch):
  72. """
  73. Saves a checkpoint containing the model's state, the optimizer's state,
  74. and the scheduler's state at the end of the given epoch. This method is
  75. intended to be called at the end of each epoch to save the training progress.
  76. Args:
  77. epoch (int): The epoch number at which the checkpoint is being saved.
  78. """
  79. state = {
  80. 'epoch': epoch,
  81. 'state_dict': self.model.state_dict(),
  82. 'optimizer': self.optim.state_dict(),
  83. 'scheduler': self.scheduler.state_dict(),
  84. }
  85. # Create output directory if it does not exist
  86. os.makedirs(self.output_dir, exist_ok=True)
  87. filename = os.path.join(self.output_dir, f'model.e{epoch}.pb')
  88. torch.save(state, filename)
  89. print(f'Checkpoint saved to {filename}')
  90. def _resume_checkpoint(self, resume_path):
  91. """
  92. Resumes training from a checkpoint at the given file path.
  93. Loads the model's state, the optimizer's state, and the scheduler's state.
  94. Args:
  95. resume_path (str): The file path to the checkpoint to resume from.
  96. """
  97. if os.path.isfile(resume_path):
  98. checkpoint = torch.load(resume_path)
  99. self.start_epoch = checkpoint['epoch'] + 1
  100. self.model.load_state_dict(checkpoint['state_dict'])
  101. self.optim.load_state_dict(checkpoint['optimizer'])
  102. self.scheduler.load_state_dict(checkpoint['scheduler'])
  103. print(f"Checkpoint loaded successfully from '{resume_path}' at (epoch {checkpoint['epoch']})")
  104. else:
  105. print(f"No checkpoint found at '{resume_path}', starting from scratch")
  106. def run(self):
  107. """
  108. Starts the training process, iterating over epochs, training the model,
  109. and saving checkpoints at the end of each epoch.
  110. """
  111. for epoch in range(self.start_epoch, self.max_epoch + 1):
  112. self._train_epoch(epoch)
  113. # self._validate_epoch(epoch)
  114. if self.rank == 0:
  115. self._save_checkpoint(epoch)
  116. self.scheduler.step()
  117. break
  118. def _train_epoch(self, epoch):
  119. """
  120. Defines the training process for a single epoch with gradient accumulation.
  121. Args:
  122. epoch (int): The current epoch number.
  123. """
  124. self.model.train()
  125. pbar = tqdm(colour="blue", desc=f"Training Epoch: {epoch + 1}", total=len(self.dataloader_train),
  126. dynamic_ncols=True)
  127. # Set the number of steps for gradient accumulation
  128. accum_grad = self.kwargs.get("accum_grad", 1)
  129. # Initialize the gradient accumulation
  130. self.optim.zero_grad()
  131. speed_stats = {}
  132. time5 = time.perf_counter()
  133. for batch_idx, batch in enumerate(self.dataloader_train):
  134. time1 = time.perf_counter()
  135. speed_stats["data_load"] = f"{time1-time5:0.3f}"
  136. # import pdb;
  137. # pdb.set_trace()
  138. batch = to_device(batch, self.device)
  139. my_context = self.model.no_sync if batch_idx % accum_grad != 0 else nullcontext
  140. with my_context():
  141. time2 = time.perf_counter()
  142. retval = self.model(**batch)
  143. time3 = time.perf_counter()
  144. speed_stats["forward_time"] = f"{time3 - time2:0.3f}"
  145. loss, stats, weight = retval
  146. stats = {k: v for k, v in stats.items() if v is not None}
  147. if self.use_ddp or self.use_fsdp:
  148. # Apply weighted averaging for loss and stats
  149. loss = (loss * weight.type(loss.dtype)).sum()
  150. # if distributed, this method can also apply all_reduce()
  151. stats, weight = recursive_average(stats, weight, distributed=True)
  152. # Now weight is summation over all workers
  153. loss /= weight
  154. # Multiply world_size because DistributedDataParallel
  155. # automatically normalizes the gradient by world_size.
  156. loss *= self.world_size
  157. # Scale the loss since we're not updating for every mini-batch
  158. loss = loss / accum_grad
  159. loss.backward()
  160. time4 = time.perf_counter()
  161. speed_stats["backward_time"] = f"{time4 - time3:0.3f}"
  162. # Perform an optimizer step only after accumulating enough gradients
  163. if (batch_idx + 1) % accum_grad == 0 or (batch_idx + 1) == len(self.dataloader_train):
  164. # Perform gradient clipping if it is set
  165. if self.kwargs.get("grad_clip", None) is not None:
  166. grad_norm = torch.nn.utils.clip_grad_norm_(
  167. self.model.parameters(),
  168. max_norm=self.kwargs.get("grad_clip", 10.0),
  169. norm_type=self.kwargs.get("grad_clip_type", 2.0),
  170. )
  171. if not torch.isfinite(grad_norm):
  172. logging.warning(
  173. f"The grad norm is {grad_norm}. Skipping updating the model."
  174. )
  175. self.optim.zero_grad() # Reset gradients
  176. continue
  177. # Execute an optimization step (update model parameters)
  178. self.optim.step()
  179. self.scheduler.step()
  180. # Clear gradients for the next accumulation stage
  181. self.optim.zero_grad()
  182. total_time = f"{time.perf_counter() - time5:0.3f}"
  183. time5 = time.perf_counter()
  184. speed_stats["optim_time"] = f"{time5 - time4:0.3f}"
  185. speed_stats["total_time"] = total_time
  186. # import pdb;
  187. # pdb.set_trace()
  188. pbar.update(1)
  189. if self.local_rank == 0:
  190. description = (
  191. f"Epoch: {epoch + 1}/{self.max_epoch}, "
  192. f"step {batch_idx}/{len(self.dataloader_train)}, "
  193. f"{speed_stats}, "
  194. f"(loss: {loss.detach().cpu().item():.3f}), "
  195. f"{[(k, round(v.cpu().item(), 3)) for k, v in stats.items()]}"
  196. )
  197. pbar.set_description(description)
  198. # if batch_idx == 2:
  199. # break
  200. pbar.close()
  201. def _validate_epoch(self, epoch):
  202. """
  203. Defines the validation process for a single epoch.
  204. Should be implemented with the actual model validation steps.
  205. Args:
  206. epoch (int): The current epoch number.
  207. """
  208. self.model.eval()
  209. with torch.no_grad():
  210. for data, target in self.dataloader_val:
  211. # Implement the model validation steps here
  212. pass