CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutSign UpSign In
hukaixuan19970627

Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place. Commercial Alternative to JupyterHub.

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