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

#609 Ci fix

Merged
Ghost merged 1 commits into Deci-AI:master from deci-ai:bugfix/infra-000_ci
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
  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 import ADNNModelRepositoryDataInterfaces
  12. from super_gradients.common.abstractions.abstract_logger import get_logger
  13. from super_gradients.common.decorators.code_save_decorator import saved_codes
  14. from super_gradients.common.environment.ddp_utils import multi_process_safe
  15. from super_gradients.common.sg_loggers.abstract_sg_logger import AbstractSGLogger
  16. from super_gradients.training.params import TrainingParams
  17. from super_gradients.training.utils import sg_trainer_utils
  18. from super_gradients.common.environment.monitoring import SystemMonitor
  19. from super_gradients.common.auto_logging.auto_logger import AutoLoggerConfig
  20. from super_gradients.common.auto_logging.console_logging import ConsoleSink
  21. logger = get_logger(__name__)
  22. class BaseSGLogger(AbstractSGLogger):
  23. def __init__(
  24. self,
  25. project_name: str,
  26. experiment_name: str,
  27. storage_location: str,
  28. resumed: bool,
  29. training_params: TrainingParams,
  30. checkpoints_dir_path: str,
  31. tb_files_user_prompt: bool = False,
  32. launch_tensorboard: bool = False,
  33. tensorboard_port: int = None,
  34. save_checkpoints_remote: bool = True,
  35. save_tensorboard_remote: bool = True,
  36. save_logs_remote: bool = True,
  37. monitor_system: bool = True,
  38. ):
  39. """
  40. :param experiment_name: Used for logging and loading purposes
  41. :param storage_location: If set to 's3' (i.e. s3://my-bucket) saves the Checkpoints in AWS S3 otherwise saves the Checkpoints Locally
  42. :param resumed: if true, then old tensorboard files will *not* be deleted when tb_files_user_prompt=True
  43. :param training_params: training_params for the experiment.
  44. :param checkpoints_dir_path: Local root directory path where all experiment logging directories will
  45. reside.
  46. :param tb_files_user_prompt: Asks user for Tensorboard deletion prompt.
  47. :param launch_tensorboard: Whether to launch a TensorBoard process.
  48. :param tensorboard_port: Specific port number for the tensorboard to use when launched (when set to None, some free port
  49. number will be used
  50. :param save_checkpoints_remote: Saves checkpoints in s3.
  51. :param save_tensorboard_remote: Saves tensorboard in s3.
  52. :param save_logs_remote: Saves log files in s3.
  53. :param monitor_system: Save the system statistics (GPU utilization, CPU, ...) in the tensorboard
  54. """
  55. super().__init__()
  56. self.project_name = project_name
  57. self.experiment_name = experiment_name
  58. self.storage_location = storage_location
  59. if storage_location.startswith("s3"):
  60. self.save_checkpoints_remote = save_checkpoints_remote
  61. self.save_tensorboard_remote = save_tensorboard_remote
  62. self.save_logs_remote = save_logs_remote
  63. self.remote_storage_available = True
  64. else:
  65. self.remote_storage_available = False
  66. if save_checkpoints_remote:
  67. logger.error("save_checkpoints_remote == True but storage_location is not s3 path. Files will not be saved remotely")
  68. if save_tensorboard_remote:
  69. logger.error("save_tensorboard_remote == True but storage_location is not s3 path. Files will not be saved remotely")
  70. if save_logs_remote:
  71. logger.error("save_logs_remote == True but storage_location is not s3 path. Files will not be saved remotely")
  72. self.save_checkpoints_remote = False
  73. self.save_tensorboard_remote = False
  74. self.save_logs_remote = False
  75. self.tensor_board_process = None
  76. self.max_global_steps = training_params.max_epochs
  77. self._local_dir = checkpoints_dir_path
  78. self._make_dir()
  79. self._init_tensorboard(resumed, tb_files_user_prompt)
  80. self._init_log_file()
  81. self.model_checkpoints_data_interface = ADNNModelRepositoryDataInterfaces(data_connection_location=self.storage_location)
  82. if launch_tensorboard:
  83. self._launch_tensorboard(port=tensorboard_port)
  84. self._init_system_monitor(monitor_system)
  85. self._save_code()
  86. @multi_process_safe
  87. def _launch_tensorboard(self, port):
  88. self.tensor_board_process, _ = sg_trainer_utils.launch_tensorboard_process(self._local_dir, port=port)
  89. @multi_process_safe
  90. def _init_tensorboard(self, resumed, tb_files_user_prompt):
  91. self.tensorboard_writer = sg_trainer_utils.init_summary_writer(self._local_dir, resumed, tb_files_user_prompt)
  92. @multi_process_safe
  93. def _init_system_monitor(self, monitor_system: bool):
  94. if monitor_system:
  95. self.system_monitor = SystemMonitor.start(tensorboard_writer=self.tensorboard_writer)
  96. else:
  97. self.system_monitor = None
  98. @multi_process_safe
  99. def _make_dir(self):
  100. if not os.path.isdir(self._local_dir):
  101. os.makedirs(self._local_dir)
  102. @multi_process_safe
  103. def _init_log_file(self):
  104. time_string = time.strftime("%b%d_%H_%M_%S", time.localtime())
  105. # There are two log files, since the regular log_file_path used for `manual` logging of configs/other info
  106. self.log_file_path = f"{self._local_dir}/log_{time_string}.txt"
  107. self.log_full_file_path = f"{self._local_dir}/sg_logs_{time_string}.txt"
  108. self.console_sink_path = f"{self._local_dir}/console_{time_string}.txt"
  109. AutoLoggerConfig.setup_logging(filename=self.log_full_file_path, copy_already_logged_messages=True)
  110. ConsoleSink.set_location(filename=self.console_sink_path)
  111. @multi_process_safe
  112. def _write_to_log_file(self, lines: list):
  113. with open(self.log_file_path, "a" if os.path.exists(self.log_file_path) else "w") as log_file:
  114. for line in lines:
  115. log_file.write(line + "\n")
  116. @multi_process_safe
  117. def add_config(self, tag: str, config: dict):
  118. log_lines = ["--------- config parameters ----------"]
  119. log_lines.append(json.dumps(config, indent=4, default=str))
  120. log_lines.append("------- config parameters end --------")
  121. self.tensorboard_writer.add_text(tag, json.dumps(config, indent=4, default=str).replace(" ", " ").replace("\n", " \n "))
  122. self._write_to_log_file(log_lines)
  123. @multi_process_safe
  124. def add_scalar(self, tag: str, scalar_value: float, global_step: int = None):
  125. self.tensorboard_writer.add_scalar(tag=tag.lower().replace(" ", "_"), scalar_value=scalar_value, global_step=global_step)
  126. @multi_process_safe
  127. def add_scalars(self, tag_scalar_dict: dict, global_step: int = None):
  128. """
  129. add multiple scalars.
  130. Unlike Tensorboard implementation, this does not add all scalars with a main tag (all scalars to the same chart).
  131. Instead, scalars are added to tensorboard like in add_scalar and are written in log together.
  132. """
  133. for tag, value in tag_scalar_dict.items():
  134. self.tensorboard_writer.add_scalar(tag=tag.lower().replace(" ", "_"), scalar_value=value, global_step=global_step)
  135. self.tensorboard_writer.flush()
  136. # WRITE THE EPOCH RESULTS TO LOG FILE
  137. log_line = f"\nEpoch ({global_step}/{self.max_global_steps}) - "
  138. for tag, value in tag_scalar_dict.items():
  139. if isinstance(value, torch.Tensor):
  140. value = value.item()
  141. log_line += f'{tag.replace(" ", "_")}: {value}\t'
  142. self._write_to_log_file([log_line])
  143. @multi_process_safe
  144. def add_image(self, tag: str, image: Union[torch.Tensor, np.array, Image.Image], data_format="CHW", global_step: int = None):
  145. self.tensorboard_writer.add_image(tag=tag, img_tensor=image, dataformats=data_format, global_step=global_step)
  146. @multi_process_safe
  147. def add_images(self, tag: str, images: Union[torch.Tensor, np.array], data_format="NCHW", global_step: int = None):
  148. """
  149. Add multiple images to SGLogger.
  150. Typically, this function will add a set of images to tensorboard, save them to disk or add it to experiment management framework.
  151. :param tag: Data identifier
  152. :param images: images to be added. The values should lie in [0, 255] for type uint8 or [0, 1] for type float.
  153. :param data_format: Image data format specification of the form NCHW, NHWC, CHW, HWC, HW, WH, etc.
  154. :param global_step: Global step value to record
  155. """
  156. self.tensorboard_writer.add_images(tag=tag, img_tensor=images, dataformats=data_format, global_step=global_step)
  157. @multi_process_safe
  158. def add_video(self, tag: str, video: Union[torch.Tensor, np.array], global_step: int = None):
  159. """
  160. Add a single video to SGLogger.
  161. Typically, this function will add a video to tensorboard, save it to disk or add it to experiment management framework.
  162. :param tag: Data identifier
  163. :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.
  164. :param global_step: Global step value to record
  165. """
  166. if video.ndim < 5:
  167. video = video[
  168. None,
  169. ]
  170. self.tensorboard_writer.add_video(tag=tag, video=video, global_step=global_step)
  171. @multi_process_safe
  172. def add_histogram(self, tag: str, values: Union[torch.Tensor, np.array], bins: str, global_step: int = None):
  173. self.tensorboard_writer.add_histogram(tag=tag, values=values, bins=bins, global_step=global_step)
  174. @multi_process_safe
  175. def add_model_graph(self, tag: str, model: torch.nn.Module, dummy_input: torch.Tensor):
  176. """
  177. Add a pytorch model graph to the SGLogger.
  178. Only the model structure/architecture will be preserved and collected, NOT the model weights.
  179. :param tag: Data identifier
  180. :param model: the model to be added
  181. :param dummy_input: an input to be used for a forward call on the model
  182. """
  183. self.tensorboard_writer.add_graph(model=model, input_to_model=dummy_input)
  184. @multi_process_safe
  185. def add_text(self, tag: str, text_string: str, global_step: int = None):
  186. self.tensorboard_writer.add_text(tag=tag, text_string=text_string, global_step=global_step)
  187. @multi_process_safe
  188. def add_figure(self, tag: str, figure: plt.figure, global_step: int = None):
  189. """
  190. Add a text to SGLogger.
  191. Typically, this function will add a figure to tensorboard or add it to experiment management framework.
  192. :param tag: Data identifier
  193. :param figure: the figure to add
  194. :param global_step: Global step value to record
  195. """
  196. self.tensorboard_writer.add_figure(tag=tag, figure=figure, global_step=global_step)
  197. @multi_process_safe
  198. def add_file(self, file_name: str = None):
  199. if self.remote_storage_available:
  200. self.model_checkpoints_data_interface.save_remote_tensorboard_event_files(self.experiment_name, self._local_dir, file_name)
  201. @multi_process_safe
  202. def upload(self):
  203. if self.save_tensorboard_remote:
  204. self.model_checkpoints_data_interface.save_remote_tensorboard_event_files(self.experiment_name, self._local_dir)
  205. if self.save_logs_remote:
  206. log_file_name = self.log_file_path.split("/")[-1]
  207. self.model_checkpoints_data_interface.save_remote_checkpoints_file(self.experiment_name, self._local_dir, log_file_name)
  208. @multi_process_safe
  209. def flush(self):
  210. self.tensorboard_writer.flush()
  211. @multi_process_safe
  212. def close(self):
  213. if self.system_monitor is not None:
  214. self.system_monitor.close()
  215. logger.info("[CLEANUP] - Successfully stopped system monitoring process")
  216. self.tensorboard_writer.close()
  217. if self.tensor_board_process is not None:
  218. try:
  219. logger.info("[CLEANUP] - Stopping tensorboard process")
  220. process = psutil.Process(self.tensor_board_process.pid)
  221. process.send_signal(signal.SIGTERM)
  222. logger.info("[CLEANUP] - Successfully stopped tensorboard process")
  223. except Exception as ex:
  224. logger.info("[CLEANUP] - Could not stop tensorboard process properly: " + str(ex))
  225. @multi_process_safe
  226. def add_checkpoint(self, tag: str, state_dict: dict, global_step: int = None):
  227. name = f"ckpt_{global_step}.pth" if tag is None else tag
  228. if not name.endswith(".pth"):
  229. name += ".pth"
  230. path = os.path.join(self._local_dir, name)
  231. torch.save(state_dict, path)
  232. if "best" in tag:
  233. logger.info("Checkpoint saved in " + path)
  234. if self.save_checkpoints_remote:
  235. self.model_checkpoints_data_interface.save_remote_checkpoints_file(self.experiment_name, self._local_dir, name)
  236. def add(self, tag: str, obj: Any, global_step: int = None):
  237. pass
  238. def local_dir(self) -> str:
  239. return self._local_dir
  240. @multi_process_safe
  241. def _save_code(self):
  242. for name, code in saved_codes.items():
  243. if not name.endswith("py"):
  244. name = name + ".py"
  245. path = os.path.join(self._local_dir, name)
  246. with open(path, "w") as f:
  247. f.write(code)
  248. self.add_file(name)
  249. code = "\t" + code
  250. 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