Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

#869 Add DagsHub Logger to Super Gradients

Merged
Ghost merged 1 commits into Deci-AI:master from timho102003:dagshub_logger
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
  1. import os
  2. from typing import Union, Any
  3. import numpy as np
  4. from PIL import Image
  5. import matplotlib.pyplot as plt
  6. import torch
  7. from super_gradients.common.abstractions.abstract_logger import get_logger
  8. from super_gradients.common.registry.registry import register_sg_logger
  9. from super_gradients.common.sg_loggers.base_sg_logger import BaseSGLogger
  10. from super_gradients.common.environment.ddp_utils import multi_process_safe
  11. logger = get_logger(__name__)
  12. try:
  13. from clearml import Task
  14. _imported_clear_ml_failure = None
  15. except (ImportError, NameError, ModuleNotFoundError) as import_err:
  16. logger.debug("Failed to import clearml")
  17. _imported_clear_ml_failure = import_err
  18. @register_sg_logger("clearml_sg_logger")
  19. class ClearMLSGLogger(BaseSGLogger):
  20. def __init__(
  21. self,
  22. project_name: str,
  23. experiment_name: str,
  24. storage_location: str,
  25. resumed: bool,
  26. training_params: dict,
  27. checkpoints_dir_path: str,
  28. tb_files_user_prompt: bool = False,
  29. launch_tensorboard: bool = False,
  30. tensorboard_port: int = None,
  31. save_checkpoints_remote: bool = True,
  32. save_tensorboard_remote: bool = True,
  33. save_logs_remote: bool = True,
  34. monitor_system: bool = None,
  35. ):
  36. """
  37. :param project_name: ClearML project name that can include many experiments
  38. :param experiment_name: Name used for logging and loading purposes
  39. :param storage_location: If set to 's3' (i.e. s3://my-bucket) saves the Checkpoints in AWS S3 otherwise saves the Checkpoints Locally
  40. :param resumed: If true, then old tensorboard files will **NOT** be deleted when tb_files_user_prompt=True
  41. :param training_params: training_params for the experiment.
  42. :param checkpoints_dir_path: Local root directory path where all experiment logging directories will reside.
  43. :param tb_files_user_prompt: Asks user for Tensorboard deletion prompt.
  44. :param launch_tensorboard: Whether to launch a TensorBoard process.
  45. :param tensorboard_port: Specific port number for the tensorboard to use when launched (when set to None, some free port number will be used
  46. :param save_checkpoints_remote: Saves checkpoints in s3.
  47. :param save_tensorboard_remote: Saves tensorboard in s3.
  48. :param save_logs_remote: Saves log files in s3.
  49. :param monitor_system: Not Available for ClearML logger. Save the system statistics (GPU utilization, CPU, ...) in the tensorboard
  50. """
  51. if monitor_system is not None:
  52. logger.warning("monitor_system not available on ClearMLSGLogger. To remove this warning, please don't set monitor_system in your logger parameters")
  53. self.s3_location_available = storage_location.startswith("s3")
  54. super().__init__(
  55. project_name=project_name,
  56. experiment_name=experiment_name,
  57. storage_location=storage_location,
  58. resumed=resumed,
  59. training_params=training_params,
  60. checkpoints_dir_path=checkpoints_dir_path,
  61. tb_files_user_prompt=tb_files_user_prompt,
  62. launch_tensorboard=launch_tensorboard,
  63. tensorboard_port=tensorboard_port,
  64. save_checkpoints_remote=self.s3_location_available,
  65. save_tensorboard_remote=self.s3_location_available,
  66. save_logs_remote=self.s3_location_available,
  67. monitor_system=False,
  68. )
  69. if _imported_clear_ml_failure is not None:
  70. raise _imported_clear_ml_failure
  71. self.setup(project_name, experiment_name)
  72. self.save_checkpoints = save_checkpoints_remote
  73. self.save_tensorboard = save_tensorboard_remote
  74. self.save_logs = save_logs_remote
  75. @multi_process_safe
  76. def setup(self, project_name, experiment_name):
  77. from multiprocessing.process import BaseProcess
  78. # Prevent clearml modifying os.fork and BaseProcess.run, which can cause a DataLoader to crash (if num_worker > 0)
  79. # Issue opened here: https://github.com/allegroai/clearml/issues/790
  80. default_fork, default_run = os.fork, BaseProcess.run
  81. self.task = Task.init(
  82. project_name=project_name, # project name of at least 3 characters
  83. task_name=experiment_name, # task name of at least 3 characters
  84. continue_last_task=0, # This prevents clear_ml to add an offset to the epoch
  85. auto_connect_arg_parser=False,
  86. auto_connect_frameworks=False,
  87. auto_resource_monitoring=False,
  88. auto_connect_streams=True,
  89. )
  90. os.fork, BaseProcess.run = default_fork, default_run
  91. self.clearml_logger = self.task.get_logger()
  92. @multi_process_safe
  93. def add_config(self, tag: str, config: dict):
  94. super(ClearMLSGLogger, self).add_config(tag=tag, config=config)
  95. self.task.connect(config)
  96. def __add_scalar(self, tag: str, scalar_value: float, global_step: int):
  97. self.clearml_logger.report_scalar(title=tag, series=tag, value=scalar_value, iteration=global_step)
  98. @multi_process_safe
  99. def add_scalar(self, tag: str, scalar_value: float, global_step: int = 0):
  100. super(ClearMLSGLogger, self).add_scalar(tag=tag, scalar_value=scalar_value, global_step=global_step)
  101. self.__add_scalar(tag=tag, scalar_value=scalar_value, global_step=global_step)
  102. @multi_process_safe
  103. def add_scalars(self, tag_scalar_dict: dict, global_step: int = 0):
  104. super(ClearMLSGLogger, self).add_scalars(tag_scalar_dict=tag_scalar_dict, global_step=global_step)
  105. for tag, scalar_value in tag_scalar_dict.items():
  106. self.__add_scalar(tag=tag, scalar_value=scalar_value, global_step=global_step)
  107. def __add_image(
  108. self,
  109. tag: str,
  110. image: Union[torch.Tensor, np.array, Image.Image],
  111. global_step: int,
  112. ):
  113. if isinstance(image, torch.Tensor):
  114. image = image.cpu().detach().numpy()
  115. if image.shape[0] < 5:
  116. image = image.transpose([1, 2, 0])
  117. self.clearml_logger.report_image(
  118. title=tag,
  119. series=tag,
  120. image=image,
  121. iteration=global_step,
  122. max_image_history=-1,
  123. )
  124. @multi_process_safe
  125. def add_image(
  126. self,
  127. tag: str,
  128. image: Union[torch.Tensor, np.array, Image.Image],
  129. data_format="CHW",
  130. global_step: int = 0,
  131. ):
  132. super(ClearMLSGLogger, self).add_image(tag=tag, image=image, data_format=data_format, global_step=global_step)
  133. self.__add_image(tag, image, global_step)
  134. @multi_process_safe
  135. def add_images(
  136. self,
  137. tag: str,
  138. images: Union[torch.Tensor, np.array],
  139. data_format="NCHW",
  140. global_step: int = 0,
  141. ):
  142. super(ClearMLSGLogger, self).add_images(tag=tag, images=images, data_format=data_format, global_step=global_step)
  143. for image in images:
  144. self.__add_image(tag, image, global_step)
  145. @multi_process_safe
  146. def add_video(self, tag: str, video: Union[torch.Tensor, np.array], global_step: int = 0):
  147. super().add_video(tag, video, global_step)
  148. logger.warning("ClearMLSGLogger does not support uploading video to clearML from a tensor/array.")
  149. @multi_process_safe
  150. def add_histogram(
  151. self,
  152. tag: str,
  153. values: Union[torch.Tensor, np.array],
  154. bins: str,
  155. global_step: int = 0,
  156. ):
  157. super().add_histogram(tag, values, bins, global_step)
  158. self.clearml_logger.report_histogram(title=tag, series=tag, iteration=global_step, values=values)
  159. @multi_process_safe
  160. def add_text(self, tag: str, text_string: str, global_step: int = 0):
  161. super().add_text(tag, text_string, global_step)
  162. self.clearml_logger.report_text(text_string)
  163. @multi_process_safe
  164. def add_figure(self, tag: str, figure: plt.figure, global_step: int = 0):
  165. super().add_figure(tag, figure, global_step)
  166. name = f"tmp_{tag}.png"
  167. path = os.path.join(self._local_dir, name)
  168. figure.savefig(path)
  169. self.task.upload_artifact(name=name, artifact_object=path)
  170. os.remove(path)
  171. @multi_process_safe
  172. def close(self):
  173. super().close()
  174. self.task.close()
  175. @multi_process_safe
  176. def add_file(self, file_name: str = None):
  177. super().add_file(file_name)
  178. self.task.upload_artifact(name=file_name, artifact_object=os.path.join(self._local_dir, file_name))
  179. @multi_process_safe
  180. def upload(self):
  181. super().upload()
  182. if self.save_tensorboard:
  183. name = self._get_tensorboard_file_name().split("/")[-1]
  184. self.task.upload_artifact(name=name, artifact_object=self._get_tensorboard_file_name())
  185. if self.save_logs:
  186. name = self.experiment_log_path.split("/")[-1]
  187. self.task.upload_artifact(name=name, artifact_object=self.experiment_log_path)
  188. @multi_process_safe
  189. def add_checkpoint(self, tag: str, state_dict: dict, global_step: int = 0):
  190. name = f"ckpt_{global_step}.pth" if tag is None else tag
  191. if not name.endswith(".pth"):
  192. name += ".pth"
  193. path = os.path.join(self._local_dir, name)
  194. torch.save(state_dict, path)
  195. if self.save_checkpoints:
  196. if self.s3_location_available:
  197. self.model_checkpoints_data_interface.save_remote_checkpoints_file(self.experiment_name, self._local_dir, name)
  198. self.task.upload_artifact(name=name, artifact_object=path)
  199. def _get_tensorboard_file_name(self):
  200. try:
  201. tb_file_path = self.tensorboard_writer.file_writer.event_writer._file_name
  202. except RuntimeError:
  203. logger.warning("tensorboard file could not be located for ")
  204. return None
  205. return tb_file_path
  206. def add(self, tag: str, obj: Any, global_step: int = None):
  207. pass
Discard
Tip!

Press p or to see the previous file or, n or to see the next file