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.

179 satır
7.6KB

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