callbacks.py 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. # YOLOv5 🚀 by Ultralytics, GPL-3.0 license
  2. """
  3. Callback utils
  4. """
  5. class Callbacks:
  6. """"
  7. Handles all registered callbacks for YOLOv5 Hooks
  8. """
  9. def __init__(self):
  10. # Define the available callbacks
  11. self._callbacks = {
  12. 'on_pretrain_routine_start': [],
  13. 'on_pretrain_routine_end': [],
  14. 'on_train_start': [],
  15. 'on_train_epoch_start': [],
  16. 'on_train_batch_start': [],
  17. 'optimizer_step': [],
  18. 'on_before_zero_grad': [],
  19. 'on_train_batch_end': [],
  20. 'on_train_epoch_end': [],
  21. 'on_val_start': [],
  22. 'on_val_batch_start': [],
  23. 'on_val_image_end': [],
  24. 'on_val_batch_end': [],
  25. 'on_val_end': [],
  26. 'on_fit_epoch_end': [], # fit = train + val
  27. 'on_fit_epoch_end_prune': [], # fit = train + val
  28. 'on_model_save': [],
  29. 'on_train_end': [],
  30. 'on_params_update': [],
  31. 'teardown': [],
  32. }
  33. self.stop_training = False # set True to interrupt training
  34. def register_action(self, hook, name='', callback=None):
  35. """
  36. Register a new action to a callback hook
  37. Args:
  38. hook The callback hook name to register the action to
  39. name The name of the action for later reference
  40. callback The callback to fire
  41. """
  42. assert hook in self._callbacks, f"hook '{hook}' not found in callbacks {self._callbacks}"
  43. assert callable(callback), f"callback '{callback}' is not callable"
  44. self._callbacks[hook].append({'name': name, 'callback': callback})
  45. def get_registered_actions(self, hook=None):
  46. """"
  47. Returns all the registered actions by callback hook
  48. Args:
  49. hook The name of the hook to check, defaults to all
  50. """
  51. if hook:
  52. return self._callbacks[hook]
  53. else:
  54. return self._callbacks
  55. def run(self, hook, *args, **kwargs):
  56. """
  57. Loop through the registered actions and fire all callbacks
  58. Args:
  59. hook The name of the hook to check, defaults to all
  60. args Arguments to receive from YOLOv5
  61. kwargs Keyword Arguments to receive from YOLOv5
  62. """
  63. assert hook in self._callbacks, f"hook '{hook}' not found in callbacks {self._callbacks}"
  64. for logger in self._callbacks[hook]:
  65. logger['callback'](*args, **kwargs)