neptune.py 3.8 KB

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