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

#868 Draw fix

Merged
Ghost merged 1 commits into Deci-AI:master from deci-ai:hotfix/SG-000-fix_draw
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
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
  1. import json
  2. import os
  3. import signal
  4. import time
  5. from typing import Union, Any
  6. import matplotlib.pyplot as plt
  7. import numpy as np
  8. import psutil
  9. import torch
  10. from PIL import Image
  11. from super_gradients.common.registry.registry import register_sg_logger
  12. from super_gradients.common.data_interface.adnn_model_repository_data_interface import ADNNModelRepositoryDataInterfaces
  13. from super_gradients.common.abstractions.abstract_logger import get_logger
  14. from super_gradients.common.decorators.code_save_decorator import saved_codes
  15. from super_gradients.common.environment.ddp_utils import multi_process_safe
  16. from super_gradients.common.sg_loggers.abstract_sg_logger import AbstractSGLogger
  17. from super_gradients.training.params import TrainingParams
  18. from super_gradients.training.utils import sg_trainer_utils
  19. from super_gradients.common.environment.monitoring import SystemMonitor
  20. from super_gradients.common.auto_logging.auto_logger import AutoLoggerConfig
  21. from super_gradients.common.auto_logging.console_logging import ConsoleSink
  22. logger = get_logger(__name__)
  23. EXPERIMENT_LOGS_PREFIX = "experiment_logs"
  24. LOGGER_LOGS_PREFIX = "logs"
  25. CONSOLE_LOGS_PREFIX = "console"
  26. @register_sg_logger("base_sg_logger")
  27. class BaseSGLogger(AbstractSGLogger):
  28. def __init__(
  29. self,
  30. project_name: str,
  31. experiment_name: str,
  32. storage_location: str,
  33. resumed: bool,
  34. training_params: TrainingParams,
  35. checkpoints_dir_path: str,
  36. tb_files_user_prompt: bool = False,
  37. launch_tensorboard: bool = False,
  38. tensorboard_port: int = None,
  39. save_checkpoints_remote: bool = True,
  40. save_tensorboard_remote: bool = True,
  41. save_logs_remote: bool = True,
  42. monitor_system: bool = True,
  43. ):
  44. """
  45. :param experiment_name: Name used for logging and loading purposes
  46. :param storage_location: If set to 's3' (i.e. s3://my-bucket) saves the Checkpoints in AWS S3 otherwise saves the Checkpoints Locally
  47. :param resumed: If true, then old tensorboard files will **NOT** be deleted when tb_files_user_prompt=True
  48. :param training_params: training_params for the experiment.
  49. :param checkpoints_dir_path: Local root directory path where all experiment logging directories will reside.
  50. :param tb_files_user_prompt: Asks user for Tensorboard deletion prompt.
  51. :param launch_tensorboard: Whether to launch a TensorBoard process.
  52. :param tensorboard_port: Specific port number for the tensorboard to use when launched (when set to None, some free port number will be used
  53. :param save_checkpoints_remote: Saves checkpoints in s3.
  54. :param save_tensorboard_remote: Saves tensorboard in s3.
  55. :param save_logs_remote: Saves log files in s3.
  56. :param monitor_system: Save the system statistics (GPU utilization, CPU, ...) in the tensorboard
  57. """
  58. super().__init__()
  59. self.project_name = project_name
  60. self.experiment_name = experiment_name
  61. self.storage_location = storage_location
  62. if storage_location.startswith("s3"):
  63. self.save_checkpoints_remote = save_checkpoints_remote
  64. self.save_tensorboard_remote = save_tensorboard_remote
  65. self.save_logs_remote = save_logs_remote
  66. self.remote_storage_available = True
  67. else:
  68. self.remote_storage_available = False
  69. if save_checkpoints_remote:
  70. logger.error("save_checkpoints_remote == True but storage_location is not s3 path. Files will not be saved remotely")
  71. if save_tensorboard_remote:
  72. logger.error("save_tensorboard_remote == True but storage_location is not s3 path. Files will not be saved remotely")
  73. if save_logs_remote:
  74. logger.error("save_logs_remote == True but storage_location is not s3 path. Files will not be saved remotely")
  75. self.save_checkpoints_remote = False
  76. self.save_tensorboard_remote = False
  77. self.save_logs_remote = False
  78. self.tensor_board_process = None
  79. self.max_global_steps = training_params.max_epochs
  80. self._local_dir = checkpoints_dir_path
  81. self._make_dir()
  82. self._init_tensorboard(resumed, tb_files_user_prompt)
  83. self._init_log_file()
  84. self.model_checkpoints_data_interface = ADNNModelRepositoryDataInterfaces(data_connection_location=self.storage_location)
  85. if launch_tensorboard:
  86. self._launch_tensorboard(port=tensorboard_port)
  87. self._init_system_monitor(monitor_system)
  88. self._save_code()
  89. @multi_process_safe
  90. def _launch_tensorboard(self, port):
  91. self.tensor_board_process, _ = sg_trainer_utils.launch_tensorboard_process(self._local_dir, port=port)
  92. @multi_process_safe
  93. def _init_tensorboard(self, resumed, tb_files_user_prompt):
  94. self.tensorboard_writer = sg_trainer_utils.init_summary_writer(self._local_dir, resumed, tb_files_user_prompt)
  95. @multi_process_safe
  96. def _init_system_monitor(self, monitor_system: bool):
  97. if monitor_system:
  98. self.system_monitor = SystemMonitor.start(tensorboard_writer=self.tensorboard_writer)
  99. else:
  100. self.system_monitor = None
  101. @multi_process_safe
  102. def _make_dir(self):
  103. if not os.path.isdir(self._local_dir):
  104. os.makedirs(self._local_dir)
  105. @multi_process_safe
  106. def _init_log_file(self):
  107. time_string = time.strftime("%b%d_%H_%M_%S", time.localtime())
  108. # Where the experiment related info will be saved (config and training/validation results per epoch_
  109. self.experiment_log_path = f"{self._local_dir}/{EXPERIMENT_LOGS_PREFIX}_{time_string}.txt"
  110. # Where the logger.log will be saved
  111. self.logs_path = f"{self._local_dir}/{LOGGER_LOGS_PREFIX}_{time_string}.txt"
  112. # Where the console prints/logs will be saved
  113. self.console_sink_path = f"{self._local_dir}/{CONSOLE_LOGS_PREFIX}_{time_string}.txt"
  114. AutoLoggerConfig.setup_logging(filename=self.logs_path, copy_already_logged_messages=True)
  115. ConsoleSink.set_location(filename=self.console_sink_path)
  116. @multi_process_safe
  117. def _write_to_log_file(self, lines: list):
  118. with open(self.experiment_log_path, "a" if os.path.exists(self.experiment_log_path) else "w") as log_file:
  119. for line in lines:
  120. log_file.write(line + "\n")
  121. @multi_process_safe
  122. def add_config(self, tag: str, config: dict):
  123. log_lines = ["--------- config parameters ----------"]
  124. log_lines.append(json.dumps(config, indent=4, default=str))
  125. log_lines.append("------- config parameters end --------")
  126. self.tensorboard_writer.add_text(tag, json.dumps(config, indent=4, default=str).replace(" ", " ").replace("\n", " \n "))
  127. self._write_to_log_file(log_lines)
  128. @multi_process_safe
  129. def add_scalar(self, tag: str, scalar_value: float, global_step: int = None):
  130. self.tensorboard_writer.add_scalar(tag=tag.lower().replace(" ", "_"), scalar_value=scalar_value, global_step=global_step)
  131. @multi_process_safe
  132. def add_scalars(self, tag_scalar_dict: dict, global_step: int = None):
  133. """
  134. add multiple scalars.
  135. Unlike Tensorboard implementation, this does not add all scalars with a main tag (all scalars to the same chart).
  136. Instead, scalars are added to tensorboard like in add_scalar and are written in log together.
  137. """
  138. for tag, value in tag_scalar_dict.items():
  139. self.tensorboard_writer.add_scalar(tag=tag.lower().replace(" ", "_"), scalar_value=value, global_step=global_step)
  140. self.tensorboard_writer.flush()
  141. # WRITE THE EPOCH RESULTS TO LOG FILE
  142. log_line = f"\nEpoch {global_step} ({global_step+1}/{self.max_global_steps}) - "
  143. for tag, value in tag_scalar_dict.items():
  144. if isinstance(value, torch.Tensor):
  145. value = value.item()
  146. log_line += f'{tag.replace(" ", "_")}: {value}\t'
  147. self._write_to_log_file([log_line])
  148. @multi_process_safe
  149. def add_image(self, tag: str, image: Union[torch.Tensor, np.array, Image.Image], data_format="CHW", global_step: int = None):
  150. self.tensorboard_writer.add_image(tag=tag, img_tensor=image, dataformats=data_format, global_step=global_step)
  151. @multi_process_safe
  152. def add_images(self, tag: str, images: Union[torch.Tensor, np.array], data_format="NCHW", global_step: int = None):
  153. """
  154. Add multiple images to SGLogger.
  155. Typically, this function will add a set of images to tensorboard, save them to disk or add it to experiment management framework.
  156. :param tag: Data identifier
  157. :param images: images to be added. The values should lie in [0, 255] for type uint8 or [0, 1] for type float.
  158. :param data_format: Image data format specification of the form NCHW, NHWC, CHW, HWC, HW, WH, etc.
  159. :param global_step: Global step value to record
  160. """
  161. self.tensorboard_writer.add_images(tag=tag, img_tensor=images, dataformats=data_format, global_step=global_step)
  162. @multi_process_safe
  163. def add_video(self, tag: str, video: Union[torch.Tensor, np.array], global_step: int = None):
  164. """
  165. Add a single video to SGLogger.
  166. Typically, this function will add a video to tensorboard, save it to disk or add it to experiment management framework.
  167. :param tag: Data identifier
  168. :param video: the video to add. shape (N,T,C,H,W) or (T,C,H,W). The values should lie in [0, 255] for type uint8 or [0, 1] for type float.
  169. :param global_step: Global step value to record
  170. """
  171. if video.ndim < 5:
  172. video = video[
  173. None,
  174. ]
  175. self.tensorboard_writer.add_video(tag=tag, video=video, global_step=global_step)
  176. @multi_process_safe
  177. def add_histogram(self, tag: str, values: Union[torch.Tensor, np.array], bins: str, global_step: int = None):
  178. self.tensorboard_writer.add_histogram(tag=tag, values=values, bins=bins, global_step=global_step)
  179. @multi_process_safe
  180. def add_model_graph(self, tag: str, model: torch.nn.Module, dummy_input: torch.Tensor):
  181. """
  182. Add a pytorch model graph to the SGLogger.
  183. Only the model structure/architecture will be preserved and collected, NOT the model weights.
  184. :param tag: Data identifier
  185. :param model: the model to be added
  186. :param dummy_input: an input to be used for a forward call on the model
  187. """
  188. self.tensorboard_writer.add_graph(model=model, input_to_model=dummy_input)
  189. @multi_process_safe
  190. def add_text(self, tag: str, text_string: str, global_step: int = None):
  191. self.tensorboard_writer.add_text(tag=tag, text_string=text_string, global_step=global_step)
  192. @multi_process_safe
  193. def add_figure(self, tag: str, figure: plt.figure, global_step: int = None):
  194. """
  195. Add a text to SGLogger.
  196. Typically, this function will add a figure to tensorboard or add it to experiment management framework.
  197. :param tag: Data identifier
  198. :param figure: the figure to add
  199. :param global_step: Global step value to record
  200. """
  201. self.tensorboard_writer.add_figure(tag=tag, figure=figure, global_step=global_step)
  202. @multi_process_safe
  203. def add_file(self, file_name: str = None):
  204. if self.remote_storage_available:
  205. self.model_checkpoints_data_interface.save_remote_tensorboard_event_files(self.experiment_name, self._local_dir, file_name)
  206. @multi_process_safe
  207. def upload(self):
  208. """Upload the local tensorboard and log files to remote system."""
  209. self.flush()
  210. if self.save_tensorboard_remote:
  211. self.model_checkpoints_data_interface.save_remote_tensorboard_event_files(self.experiment_name, self._local_dir)
  212. if self.save_logs_remote:
  213. log_file_name = self.experiment_log_path.split("/")[-1]
  214. self.model_checkpoints_data_interface.save_remote_checkpoints_file(self.experiment_name, self._local_dir, log_file_name)
  215. @multi_process_safe
  216. def flush(self):
  217. self.tensorboard_writer.flush()
  218. ConsoleSink.flush()
  219. @multi_process_safe
  220. def close(self):
  221. self.upload()
  222. if self.system_monitor is not None:
  223. self.system_monitor.close()
  224. logger.info("[CLEANUP] - Successfully stopped system monitoring process")
  225. self.tensorboard_writer.close()
  226. if self.tensor_board_process is not None:
  227. try:
  228. logger.info("[CLEANUP] - Stopping tensorboard process")
  229. process = psutil.Process(self.tensor_board_process.pid)
  230. process.send_signal(signal.SIGTERM)
  231. logger.info("[CLEANUP] - Successfully stopped tensorboard process")
  232. except Exception as ex:
  233. logger.info("[CLEANUP] - Could not stop tensorboard process properly: " + str(ex))
  234. @multi_process_safe
  235. def add_checkpoint(self, tag: str, state_dict: dict, global_step: int = None) -> None:
  236. """Add checkpoint to experiment folder.
  237. :param tag: Identifier of the checkpoint. If None, global_step will be used to name the checkpoint.
  238. :param state_dict: Checkpoint state_dict.
  239. :param global_step: Epoch number.
  240. """
  241. name = f"ckpt_{global_step}.pth" if tag is None else tag
  242. if not name.endswith(".pth"):
  243. name += ".pth"
  244. path = os.path.join(self._local_dir, name)
  245. self._save_checkpoint(path=path, state_dict=state_dict)
  246. @multi_process_safe
  247. def _save_checkpoint(self, path: str, state_dict: dict) -> None:
  248. """Save the Checkpoint locally.
  249. :param path: Full path of the checkpoint
  250. :param state_dict: State dict of the checkpoint
  251. """
  252. name = os.path.basename(path)
  253. torch.save(state_dict, path)
  254. if "best" in name:
  255. logger.info("Checkpoint saved in " + path)
  256. if self.save_checkpoints_remote:
  257. self.model_checkpoints_data_interface.save_remote_checkpoints_file(self.experiment_name, self._local_dir, name)
  258. def add(self, tag: str, obj: Any, global_step: int = None):
  259. pass
  260. def local_dir(self) -> str:
  261. return self._local_dir
  262. @multi_process_safe
  263. def _save_code(self):
  264. for name, code in saved_codes.items():
  265. if not name.endswith("py"):
  266. name = name + ".py"
  267. path = os.path.join(self._local_dir, name)
  268. with open(path, "w") as f:
  269. f.write(code)
  270. self.add_file(name)
  271. code = "\t" + code
  272. self.add_text(name, code.replace("\n", " \n \t")) # this replacement makes tb format the code as code
Discard
Tip!

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