wandb_utils.py 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193
  1. # YOLOv5 🚀 by Ultralytics, AGPL-3.0 license
  2. # WARNING ⚠️ wandb is deprecated and will be removed in future release.
  3. # See supported integrations at https://github.com/ultralytics/yolov5#integrations
  4. import logging
  5. import os
  6. import sys
  7. from contextlib import contextmanager
  8. from pathlib import Path
  9. from utils.general import LOGGER, colorstr
  10. FILE = Path(__file__).resolve()
  11. ROOT = FILE.parents[3] # YOLOv5 root directory
  12. if str(ROOT) not in sys.path:
  13. sys.path.append(str(ROOT)) # add ROOT to PATH
  14. RANK = int(os.getenv('RANK', -1))
  15. DEPRECATION_WARNING = f"{colorstr('wandb')}: WARNING ⚠️ wandb is deprecated and will be removed in a future release. " \
  16. f'See supported integrations at https://github.com/ultralytics/yolov5#integrations.'
  17. try:
  18. import wandb
  19. assert hasattr(wandb, '__version__') # verify package import not local dir
  20. LOGGER.warning(DEPRECATION_WARNING)
  21. except (ImportError, AssertionError):
  22. wandb = None
  23. class WandbLogger():
  24. """Log training runs, datasets, models, and predictions to Weights & Biases.
  25. This logger sends information to W&B at wandb.ai. By default, this information
  26. includes hyperparameters, system configuration and metrics, model metrics,
  27. and basic data metrics and analyses.
  28. By providing additional command line arguments to train.py, datasets,
  29. models and predictions can also be logged.
  30. For more on how this logger is used, see the Weights & Biases documentation:
  31. https://docs.wandb.com/guides/integrations/yolov5
  32. """
  33. def __init__(self, opt, run_id=None, job_type='Training'):
  34. """
  35. - Initialize WandbLogger instance
  36. - Upload dataset if opt.upload_dataset is True
  37. - Setup training processes if job_type is 'Training'
  38. arguments:
  39. opt (namespace) -- Commandline arguments for this run
  40. run_id (str) -- Run ID of W&B run to be resumed
  41. job_type (str) -- To set the job_type for this run
  42. """
  43. # Pre-training routine --
  44. self.job_type = job_type
  45. self.wandb, self.wandb_run = wandb, wandb.run if wandb else None
  46. self.val_artifact, self.train_artifact = None, None
  47. self.train_artifact_path, self.val_artifact_path = None, None
  48. self.result_artifact = None
  49. self.val_table, self.result_table = None, None
  50. self.max_imgs_to_log = 16
  51. self.data_dict = None
  52. if self.wandb:
  53. self.wandb_run = wandb.init(config=opt,
  54. resume='allow',
  55. project='YOLOv5' if opt.project == 'runs/train' else Path(opt.project).stem,
  56. entity=opt.entity,
  57. name=opt.name if opt.name != 'exp' else None,
  58. job_type=job_type,
  59. id=run_id,
  60. allow_val_change=True) if not wandb.run else wandb.run
  61. if self.wandb_run:
  62. if self.job_type == 'Training':
  63. if isinstance(opt.data, dict):
  64. # This means another dataset manager has already processed the dataset info (e.g. ClearML)
  65. # and they will have stored the already processed dict in opt.data
  66. self.data_dict = opt.data
  67. self.setup_training(opt)
  68. def setup_training(self, opt):
  69. """
  70. Setup the necessary processes for training YOLO models:
  71. - Attempt to download model checkpoint and dataset artifacts if opt.resume stats with WANDB_ARTIFACT_PREFIX
  72. - Update data_dict, to contain info of previous run if resumed and the paths of dataset artifact if downloaded
  73. - Setup log_dict, initialize bbox_interval
  74. arguments:
  75. opt (namespace) -- commandline arguments for this run
  76. """
  77. self.log_dict, self.current_epoch = {}, 0
  78. self.bbox_interval = opt.bbox_interval
  79. if isinstance(opt.resume, str):
  80. model_dir, _ = self.download_model_artifact(opt)
  81. if model_dir:
  82. self.weights = Path(model_dir) / 'last.pt'
  83. config = self.wandb_run.config
  84. opt.weights, opt.save_period, opt.batch_size, opt.bbox_interval, opt.epochs, opt.hyp, opt.imgsz = str(
  85. self.weights), config.save_period, config.batch_size, config.bbox_interval, config.epochs, \
  86. config.hyp, config.imgsz
  87. if opt.bbox_interval == -1:
  88. self.bbox_interval = opt.bbox_interval = (opt.epochs // 10) if opt.epochs > 10 else 1
  89. if opt.evolve or opt.noplots:
  90. self.bbox_interval = opt.bbox_interval = opt.epochs + 1 # disable bbox_interval
  91. def log_model(self, path, opt, epoch, fitness_score, best_model=False):
  92. """
  93. Log the model checkpoint as W&B artifact
  94. arguments:
  95. path (Path) -- Path of directory containing the checkpoints
  96. opt (namespace) -- Command line arguments for this run
  97. epoch (int) -- Current epoch number
  98. fitness_score (float) -- fitness score for current epoch
  99. best_model (boolean) -- Boolean representing if the current checkpoint is the best yet.
  100. """
  101. model_artifact = wandb.Artifact('run_' + wandb.run.id + '_model',
  102. type='model',
  103. metadata={
  104. 'original_url': str(path),
  105. 'epochs_trained': epoch + 1,
  106. 'save period': opt.save_period,
  107. 'project': opt.project,
  108. 'total_epochs': opt.epochs,
  109. 'fitness_score': fitness_score})
  110. model_artifact.add_file(str(path / 'last.pt'), name='last.pt')
  111. wandb.log_artifact(model_artifact,
  112. aliases=['latest', 'last', 'epoch ' + str(self.current_epoch), 'best' if best_model else ''])
  113. LOGGER.info(f'Saving model artifact on epoch {epoch + 1}')
  114. def val_one_image(self, pred, predn, path, names, im):
  115. pass
  116. def log(self, log_dict):
  117. """
  118. save the metrics to the logging dictionary
  119. arguments:
  120. log_dict (Dict) -- metrics/media to be logged in current step
  121. """
  122. if self.wandb_run:
  123. for key, value in log_dict.items():
  124. self.log_dict[key] = value
  125. def end_epoch(self):
  126. """
  127. commit the log_dict, model artifacts and Tables to W&B and flush the log_dict.
  128. arguments:
  129. best_result (boolean): Boolean representing if the result of this evaluation is best or not
  130. """
  131. if self.wandb_run:
  132. with all_logging_disabled():
  133. try:
  134. wandb.log(self.log_dict)
  135. except BaseException as e:
  136. LOGGER.info(
  137. f'An error occurred in wandb logger. The training will proceed without interruption. More info\n{e}'
  138. )
  139. self.wandb_run.finish()
  140. self.wandb_run = None
  141. self.log_dict = {}
  142. def finish_run(self):
  143. """
  144. Log metrics if any and finish the current W&B run
  145. """
  146. if self.wandb_run:
  147. if self.log_dict:
  148. with all_logging_disabled():
  149. wandb.log(self.log_dict)
  150. wandb.run.finish()
  151. LOGGER.warning(DEPRECATION_WARNING)
  152. @contextmanager
  153. def all_logging_disabled(highest_level=logging.CRITICAL):
  154. """ source - https://gist.github.com/simon-weber/7853144
  155. A context manager that will prevent any logging messages triggered during the body from being processed.
  156. :param highest_level: the maximum logging level in use.
  157. This would only need to be changed if a custom level greater than CRITICAL is defined.
  158. """
  159. previous_level = logging.root.manager.disable
  160. logging.disable(highest_level)
  161. try:
  162. yield
  163. finally:
  164. logging.disable(previous_level)