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

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

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

Comments

Loading...