neptune.py 3.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. # Ultralytics YOLO 🚀, AGPL-3.0 license
  2. import matplotlib.image as mpimg
  3. import matplotlib.pyplot as plt
  4. from ultralytics.utils import LOGGER, SETTINGS, TESTS_RUNNING
  5. from ultralytics.utils.torch_utils import model_info_for_loggers
  6. try:
  7. import neptune
  8. from neptune.types import File
  9. assert not TESTS_RUNNING # do not log pytest
  10. assert hasattr(neptune, '__version__')
  11. assert SETTINGS['neptune'] is True # verify integration is enabled
  12. except (ImportError, AssertionError):
  13. neptune = None
  14. run = None # NeptuneAI experiment logger instance
  15. def _log_scalars(scalars, step=0):
  16. """Log scalars to the NeptuneAI experiment logger."""
  17. if run:
  18. for k, v in scalars.items():
  19. run[k].append(value=v, step=step)
  20. def _log_images(imgs_dict, group=''):
  21. """Log scalars to the NeptuneAI experiment logger."""
  22. if run:
  23. for k, v in imgs_dict.items():
  24. run[f'{group}/{k}'].upload(File(v))
  25. def _log_plot(title, plot_path):
  26. """Log plots to the NeptuneAI experiment logger."""
  27. """
  28. Log image as plot in the plot section of NeptuneAI
  29. arguments:
  30. title (str) Title of the plot
  31. plot_path (PosixPath or str) Path to the saved image file
  32. """
  33. img = mpimg.imread(plot_path)
  34. fig = plt.figure()
  35. ax = fig.add_axes([0, 0, 1, 1], frameon=False, aspect='auto', xticks=[], yticks=[]) # no ticks
  36. ax.imshow(img)
  37. run[f'Plots/{title}'].upload(fig)
  38. def on_pretrain_routine_start(trainer):
  39. """Callback function called before the training routine starts."""
  40. try:
  41. global run
  42. run = neptune.init_run(project=trainer.args.project or 'YOLOv8', name=trainer.args.name, tags=['YOLOv8'])
  43. run['Configuration/Hyperparameters'] = {k: '' if v is None else v for k, v in vars(trainer.args).items()}
  44. except Exception as e:
  45. LOGGER.warning(f'WARNING ⚠️ NeptuneAI installed but not initialized correctly, not logging this run. {e}')
  46. def on_train_epoch_end(trainer):
  47. """Callback function called at end of each training epoch."""
  48. _log_scalars(trainer.label_loss_items(trainer.tloss, prefix='train'), trainer.epoch + 1)
  49. _log_scalars(trainer.lr, trainer.epoch + 1)
  50. if trainer.epoch == 1:
  51. _log_images({f.stem: str(f) for f in trainer.save_dir.glob('train_batch*.jpg')}, 'Mosaic')
  52. def on_fit_epoch_end(trainer):
  53. """Callback function called at end of each fit (train+val) epoch."""
  54. if run and trainer.epoch == 0:
  55. run['Configuration/Model'] = model_info_for_loggers(trainer)
  56. _log_scalars(trainer.metrics, trainer.epoch + 1)
  57. def on_val_end(validator):
  58. """Callback function called at end of each validation."""
  59. if run:
  60. # Log val_labels and val_pred
  61. _log_images({f.stem: str(f) for f in validator.save_dir.glob('val*.jpg')}, 'Validation')
  62. def on_train_end(trainer):
  63. """Callback function called at end of training."""
  64. if run:
  65. # Log final results, CM matrix + PR plots
  66. files = [
  67. 'results.png', 'confusion_matrix.png', 'confusion_matrix_normalized.png',
  68. *(f'{x}_curve.png' for x in ('F1', 'PR', 'P', 'R'))]
  69. files = [(trainer.save_dir / f) for f in files if (trainer.save_dir / f).exists()] # filter
  70. for f in files:
  71. _log_plot(title=f.stem, plot_path=f)
  72. # Log the final model
  73. run[f'weights/{trainer.args.name or trainer.args.task}/{str(trainer.best.name)}'].upload(File(str(
  74. trainer.best)))
  75. callbacks = {
  76. 'on_pretrain_routine_start': on_pretrain_routine_start,
  77. 'on_train_epoch_end': on_train_epoch_end,
  78. 'on_fit_epoch_end': on_fit_epoch_end,
  79. 'on_val_end': on_val_end,
  80. 'on_train_end': on_train_end} if neptune else {}