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

clearml_sg_logger.py 8.9 KB

You have to be logged in to leave a comment. Sign In
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
  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.sg_loggers.base_sg_logger import BaseSGLogger
  9. from super_gradients.common.environment.env_helpers import multi_process_safe
  10. logger = get_logger(__name__)
  11. try:
  12. from clearml import Task
  13. _imported_clear_ml_failure = None
  14. except (ImportError, NameError, ModuleNotFoundError) as import_err:
  15. logger.warn("Failed to import deci_lab_client")
  16. _imported_clear_ml_failure = import_err
  17. class ClearMLSGLogger(BaseSGLogger):
  18. def __init__(
  19. self,
  20. project_name: str,
  21. experiment_name: str,
  22. storage_location: str,
  23. resumed: bool,
  24. training_params: dict,
  25. checkpoints_dir_path: str,
  26. tb_files_user_prompt: bool = False,
  27. launch_tensorboard: bool = False,
  28. tensorboard_port: int = None,
  29. save_checkpoints_remote: bool = True,
  30. save_tensorboard_remote: bool = True,
  31. save_logs_remote: bool = True,
  32. ):
  33. """
  34. :param experiment_name: Used for logging and loading purposes
  35. :param s3_path: If set to 's3' (i.e. s3://my-bucket) saves the Checkpoints in AWS S3 otherwise saves the Checkpoints Locally
  36. :param checkpoint_loaded: If true, then old tensorboard files will *not* be deleted when tb_files_user_prompt=True
  37. :param max_epochs: Number of epochs planned for this training
  38. :param tb_files_user_prompt: Asks user for Tensorboard deletion prompt.
  39. :param launch_tensorboard: Whether to launch a TensorBoard process.
  40. :param tensorboard_port: Specific port number for the tensorboard to use when launched (when set to None, some free port number will be used)
  41. :param save_checkpoints_remote: Saves checkpoints in s3.
  42. :param save_tensorboard_remote: Saves tensorboard in s3.
  43. :param save_logs_remote: Saves log files in s3.
  44. """
  45. self.s3_location_available = storage_location.startswith("s3")
  46. super().__init__(
  47. project_name,
  48. experiment_name,
  49. storage_location,
  50. resumed,
  51. training_params,
  52. checkpoints_dir_path,
  53. tb_files_user_prompt,
  54. launch_tensorboard,
  55. tensorboard_port,
  56. self.s3_location_available,
  57. self.s3_location_available,
  58. self.s3_location_available,
  59. )
  60. if _imported_clear_ml_failure is not None:
  61. raise _imported_clear_ml_failure
  62. self.setup(project_name, experiment_name)
  63. self.save_checkpoints = save_checkpoints_remote
  64. self.save_tensorboard = save_tensorboard_remote
  65. self.save_logs = save_logs_remote
  66. @multi_process_safe
  67. def setup(self, project_name, experiment_name):
  68. from multiprocessing.process import BaseProcess
  69. # Prevent clearml modifying os.fork and BaseProcess.run, which can cause a DataLoader to crash (if num_worker > 0)
  70. # Issue opened here: https://github.com/allegroai/clearml/issues/790
  71. default_fork, default_run = os.fork, BaseProcess.run
  72. self.task = Task.init(
  73. project_name=project_name, # project name of at least 3 characters
  74. task_name=experiment_name, # task name of at least 3 characters
  75. continue_last_task=0, # This prevents clear_ml to add an offset to the epoch
  76. auto_connect_arg_parser=False,
  77. auto_connect_frameworks=False,
  78. auto_resource_monitoring=False,
  79. auto_connect_streams=True,
  80. )
  81. os.fork, BaseProcess.run = default_fork, default_run
  82. self.clearml_logger = self.task.get_logger()
  83. @multi_process_safe
  84. def add_config(self, tag: str, config: dict):
  85. super(ClearMLSGLogger, self).add_config(tag=tag, config=config)
  86. self.task.connect(config)
  87. def __add_scalar(self, tag: str, scalar_value: float, global_step: int):
  88. self.clearml_logger.report_scalar(title=tag, series=tag, value=scalar_value, iteration=global_step)
  89. @multi_process_safe
  90. def add_scalar(self, tag: str, scalar_value: float, global_step: int = 0):
  91. super(ClearMLSGLogger, self).add_scalar(tag=tag, scalar_value=scalar_value, global_step=global_step)
  92. self.__add_scalar(tag=tag, scalar_value=scalar_value, global_step=global_step)
  93. @multi_process_safe
  94. def add_scalars(self, tag_scalar_dict: dict, global_step: int = 0):
  95. super(ClearMLSGLogger, self).add_scalars(tag_scalar_dict=tag_scalar_dict, global_step=global_step)
  96. for tag, scalar_value in tag_scalar_dict.items():
  97. self.__add_scalar(tag=tag, scalar_value=scalar_value, global_step=global_step)
  98. def __add_image(
  99. self,
  100. tag: str,
  101. image: Union[torch.Tensor, np.array, Image.Image],
  102. global_step: int,
  103. ):
  104. if isinstance(image, torch.Tensor):
  105. image = image.cpu().detach().numpy()
  106. if image.shape[0] < 5:
  107. image = image.transpose([1, 2, 0])
  108. self.clearml_logger.report_image(
  109. title=tag,
  110. series=tag,
  111. image=image,
  112. iteration=global_step,
  113. max_image_history=-1,
  114. )
  115. @multi_process_safe
  116. def add_image(
  117. self,
  118. tag: str,
  119. image: Union[torch.Tensor, np.array, Image.Image],
  120. data_format="CHW",
  121. global_step: int = 0,
  122. ):
  123. super(ClearMLSGLogger, self).add_image(tag=tag, image=image, data_format=data_format, global_step=global_step)
  124. self.__add_image(tag, image, global_step)
  125. @multi_process_safe
  126. def add_images(
  127. self,
  128. tag: str,
  129. images: Union[torch.Tensor, np.array],
  130. data_format="NCHW",
  131. global_step: int = 0,
  132. ):
  133. super(ClearMLSGLogger, self).add_images(tag=tag, images=images, data_format=data_format, global_step=global_step)
  134. for image in images:
  135. self.__add_image(tag, image, global_step)
  136. @multi_process_safe
  137. def add_video(self, tag: str, video: Union[torch.Tensor, np.array], global_step: int = 0):
  138. super().add_video(tag, video, global_step)
  139. logger.warning("ClearMLSGLogger does not support uploading video to clearML from a tensor/array.")
  140. @multi_process_safe
  141. def add_histogram(
  142. self,
  143. tag: str,
  144. values: Union[torch.Tensor, np.array],
  145. bins: str,
  146. global_step: int = 0,
  147. ):
  148. super().add_histogram(tag, values, bins, global_step)
  149. self.clearml_logger.report_histogram(title=tag, series=tag, iteration=global_step, values=values)
  150. @multi_process_safe
  151. def add_text(self, tag: str, text_string: str, global_step: int = 0):
  152. super().add_text(tag, text_string, global_step)
  153. self.clearml_logger.report_text(text_string)
  154. @multi_process_safe
  155. def add_figure(self, tag: str, figure: plt.figure, global_step: int = 0):
  156. super().add_figure(tag, figure, global_step)
  157. name = f"tmp_{tag}.png"
  158. path = os.path.join(self._local_dir, name)
  159. figure.savefig(path)
  160. self.task.upload_artifact(name=name, artifact_object=path)
  161. os.remove(path)
  162. @multi_process_safe
  163. def close(self):
  164. super().close()
  165. self.task.close()
  166. @multi_process_safe
  167. def add_file(self, file_name: str = None):
  168. super().add_file(file_name)
  169. self.task.upload_artifact(name=file_name, artifact_object=os.path.join(self._local_dir, file_name))
  170. @multi_process_safe
  171. def upload(self):
  172. super().upload()
  173. if self.save_tensorboard:
  174. name = self._get_tensorboard_file_name().split("/")[-1]
  175. self.task.upload_artifact(name=name, artifact_object=self._get_tensorboard_file_name())
  176. if self.save_logs:
  177. name = self.log_file_path.split("/")[-1]
  178. self.task.upload_artifact(name=name, artifact_object=self.log_file_path)
  179. @multi_process_safe
  180. def add_checkpoint(self, tag: str, state_dict: dict, global_step: int = 0):
  181. name = f"ckpt_{global_step}.pth" if tag is None else tag
  182. if not name.endswith(".pth"):
  183. name += ".pth"
  184. path = os.path.join(self._local_dir, name)
  185. torch.save(state_dict, path)
  186. if self.save_checkpoints:
  187. if self.s3_location_available:
  188. self.model_checkpoints_data_interface.save_remote_checkpoints_file(self.experiment_name, self._local_dir, name)
  189. self.task.upload_artifact(name=name, artifact_object=path)
  190. def _get_tensorboard_file_name(self):
  191. try:
  192. tb_file_path = self.tensorboard_writer.file_writer.event_writer._file_name
  193. except RuntimeError:
  194. logger.warning("tensorboard file could not be located for ")
  195. return None
  196. return tb_file_path
  197. def add(self, tag: str, obj: Any, global_step: int = None):
  198. pass
Tip!

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

Comments

Loading...