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.

168 lines
7.4KB

  1. # YOLOv5 🚀 by Ultralytics, GPL-3.0 license
  2. """
  3. Logging utils
  4. """
  5. import os
  6. import warnings
  7. from threading import Thread
  8. import pkg_resources as pkg
  9. import torch
  10. from torch.utils.tensorboard import SummaryWriter
  11. from utils.general import colorstr, cv2, emojis
  12. from utils.loggers.wandb.wandb_utils import WandbLogger
  13. from utils.plots import plot_images, plot_results
  14. from utils.torch_utils import de_parallel
  15. LOGGERS = ('csv', 'tb', 'wandb') # text-file, TensorBoard, Weights & Biases
  16. RANK = int(os.getenv('RANK', -1))
  17. try:
  18. import wandb
  19. assert hasattr(wandb, '__version__') # verify package import not local dir
  20. if pkg.parse_version(wandb.__version__) >= pkg.parse_version('0.12.2') and RANK in [0, -1]:
  21. try:
  22. wandb_login_success = wandb.login(timeout=30)
  23. except wandb.errors.UsageError: # known non-TTY terminal issue
  24. wandb_login_success = False
  25. if not wandb_login_success:
  26. wandb = None
  27. except (ImportError, AssertionError):
  28. wandb = None
  29. class Loggers():
  30. # YOLOv5 Loggers class
  31. def __init__(self, save_dir=None, weights=None, opt=None, hyp=None, logger=None, include=LOGGERS):
  32. self.save_dir = save_dir
  33. self.weights = weights
  34. self.opt = opt
  35. self.hyp = hyp
  36. self.logger = logger # for printing results to console
  37. self.include = include
  38. self.keys = ['train/box_loss', 'train/obj_loss', 'train/cls_loss', # train loss
  39. 'metrics/precision', 'metrics/recall', 'metrics/mAP_0.5', 'metrics/mAP_0.5:0.95', # metrics
  40. 'val/box_loss', 'val/obj_loss', 'val/cls_loss', # val loss
  41. 'x/lr0', 'x/lr1', 'x/lr2'] # params
  42. self.best_keys = ['best/epoch', 'best/precision', 'best/recall', 'best/mAP_0.5', 'best/mAP_0.5:0.95']
  43. for k in LOGGERS:
  44. setattr(self, k, None) # init empty logger dictionary
  45. self.csv = True # always log to csv
  46. # Message
  47. if not wandb:
  48. prefix = colorstr('Weights & Biases: ')
  49. s = f"{prefix}run 'pip install wandb' to automatically track and visualize YOLOv5 🚀 runs (RECOMMENDED)"
  50. self.logger.info(emojis(s))
  51. # TensorBoard
  52. s = self.save_dir
  53. if 'tb' in self.include and not self.opt.evolve:
  54. prefix = colorstr('TensorBoard: ')
  55. self.logger.info(f"{prefix}Start with 'tensorboard --logdir {s.parent}', view at http://localhost:6006/")
  56. self.tb = SummaryWriter(str(s))
  57. # W&B
  58. if wandb and 'wandb' in self.include:
  59. wandb_artifact_resume = isinstance(self.opt.resume, str) and self.opt.resume.startswith('wandb-artifact://')
  60. run_id = torch.load(self.weights).get('wandb_id') if self.opt.resume and not wandb_artifact_resume else None
  61. self.opt.hyp = self.hyp # add hyperparameters
  62. self.wandb = WandbLogger(self.opt, run_id)
  63. else:
  64. self.wandb = None
  65. def on_pretrain_routine_end(self):
  66. # Callback runs on pre-train routine end
  67. paths = self.save_dir.glob('*labels*.jpg') # training labels
  68. if self.wandb:
  69. self.wandb.log({"Labels": [wandb.Image(str(x), caption=x.name) for x in paths]})
  70. def on_train_batch_end(self, ni, model, imgs, targets, paths, plots, sync_bn):
  71. # Callback runs on train batch end
  72. if plots:
  73. if ni == 0:
  74. if not sync_bn: # tb.add_graph() --sync known issue https://github.com/ultralytics/yolov5/issues/3754
  75. with warnings.catch_warnings():
  76. warnings.simplefilter('ignore') # suppress jit trace warning
  77. self.tb.add_graph(torch.jit.trace(de_parallel(model), imgs[0:1], strict=False), [])
  78. if ni < 3:
  79. f = self.save_dir / f'train_batch{ni}.jpg' # filename
  80. Thread(target=plot_images, args=(imgs, targets, paths, f), daemon=True).start()
  81. if self.wandb and ni == 10:
  82. files = sorted(self.save_dir.glob('train*.jpg'))
  83. self.wandb.log({'Mosaics': [wandb.Image(str(f), caption=f.name) for f in files if f.exists()]})
  84. def on_train_epoch_end(self, epoch):
  85. # Callback runs on train epoch end
  86. if self.wandb:
  87. self.wandb.current_epoch = epoch + 1
  88. def on_val_image_end(self, pred, predn, path, names, im):
  89. # Callback runs on val image end
  90. if self.wandb:
  91. self.wandb.val_one_image(pred, predn, path, names, im)
  92. def on_val_end(self):
  93. # Callback runs on val end
  94. if self.wandb:
  95. files = sorted(self.save_dir.glob('val*.jpg'))
  96. self.wandb.log({"Validation": [wandb.Image(str(f), caption=f.name) for f in files]})
  97. def on_fit_epoch_end(self, vals, epoch, best_fitness, fi):
  98. # Callback runs at the end of each fit (train+val) epoch
  99. x = {k: v for k, v in zip(self.keys, vals)} # dict
  100. if self.csv:
  101. file = self.save_dir / 'results.csv'
  102. n = len(x) + 1 # number of cols
  103. s = '' if file.exists() else (('%20s,' * n % tuple(['epoch'] + self.keys)).rstrip(',') + '\n') # add header
  104. with open(file, 'a') as f:
  105. f.write(s + ('%20.5g,' * n % tuple([epoch] + vals)).rstrip(',') + '\n')
  106. if self.tb:
  107. for k, v in x.items():
  108. self.tb.add_scalar(k, v, epoch)
  109. if self.wandb:
  110. if best_fitness == fi:
  111. best_results = [epoch] + vals[3:7]
  112. for i, name in enumerate(self.best_keys):
  113. self.wandb.wandb_run.summary[name] = best_results[i] # log best results in the summary
  114. self.wandb.log(x)
  115. self.wandb.end_epoch(best_result=best_fitness == fi)
  116. def on_model_save(self, last, epoch, final_epoch, best_fitness, fi):
  117. # Callback runs on model save event
  118. if self.wandb:
  119. if ((epoch + 1) % self.opt.save_period == 0 and not final_epoch) and self.opt.save_period != -1:
  120. self.wandb.log_model(last.parent, self.opt, epoch, fi, best_model=best_fitness == fi)
  121. def on_train_end(self, last, best, plots, epoch, results):
  122. # Callback runs on training end
  123. if plots:
  124. plot_results(file=self.save_dir / 'results.csv') # save results.png
  125. files = ['results.png', 'confusion_matrix.png', *(f'{x}_curve.png' for x in ('F1', 'PR', 'P', 'R'))]
  126. files = [(self.save_dir / f) for f in files if (self.save_dir / f).exists()] # filter
  127. if self.tb:
  128. for f in files:
  129. self.tb.add_image(f.stem, cv2.imread(str(f))[..., ::-1], epoch, dataformats='HWC')
  130. if self.wandb:
  131. self.wandb.log({k: v for k, v in zip(self.keys[3:10], results)}) # log best.pt val results
  132. self.wandb.log({"Results": [wandb.Image(str(f), caption=f.name) for f in files]})
  133. # Calling wandb.log. TODO: Refactor this into WandbLogger.log_model
  134. if not self.opt.evolve:
  135. wandb.log_artifact(str(best if best.exists() else last), type='model',
  136. name='run_' + self.wandb.wandb_run.id + '_model',
  137. aliases=['latest', 'best', 'stripped'])
  138. self.wandb.finish_run()
  139. def on_params_update(self, params):
  140. # Update hyperparams or configs of the experiment
  141. # params: A dict containing {param: value} pairs
  142. if self.wandb:
  143. self.wandb.wandb_run.config.update(params, allow_val_change=True)