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

#475 Feature/sg 000 clean start prints

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

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