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

#468 Bug/sg 399 external checkpoints fix

Merged
Ghost merged 1 commits into Deci-AI:master from deci-ai:bug/SG-399_external_checkpoints_fix
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
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
  1. import os
  2. import sys
  3. import socket
  4. import time
  5. from dataclasses import dataclass
  6. from multiprocessing import Process
  7. from pathlib import Path
  8. from typing import Tuple, Union, Dict, Sequence
  9. import random
  10. import inspect
  11. from super_gradients.common.abstractions.abstract_logger import get_logger
  12. from treelib import Tree
  13. from termcolor import colored
  14. import torch
  15. from torch.utils.tensorboard import SummaryWriter
  16. from super_gradients.training.exceptions.dataset_exceptions import UnsupportedBatchItemsFormat
  17. from super_gradients.common.data_types.enum import MultiGPUMode
  18. # TODO: These utils should move to sg_trainer package as internal (private) helper functions
  19. IS_BETTER_COLOR = {True: "green", False: "red"}
  20. IS_GREATER_SYMBOLS = {True: "↗", False: "↘"}
  21. logger = get_logger(__name__)
  22. @dataclass
  23. class MonitoredValue:
  24. """Store a value and some indicators relative to its past iterations.
  25. The value can be a metric/loss, and the iteration can be epochs/batch.
  26. """
  27. name: str
  28. greater_is_better: bool
  29. current: float = None
  30. previous: float = None
  31. best: float = None
  32. change_from_previous: float = None
  33. change_from_best: float = None
  34. @property
  35. def is_better_than_previous(self):
  36. if self.greater_is_better is None or self.change_from_best is None:
  37. return None
  38. elif self.greater_is_better:
  39. return self.change_from_previous >= 0
  40. else:
  41. return self.change_from_previous < 0
  42. @property
  43. def is_best_value(self):
  44. if self.greater_is_better is None or self.change_from_best is None:
  45. return None
  46. elif self.greater_is_better:
  47. return self.change_from_best >= 0
  48. else:
  49. return self.change_from_best < 0
  50. def update_monitored_value(previous_monitored_value: MonitoredValue, new_value: float) -> MonitoredValue:
  51. """Update the given ValueToMonitor object (could be a loss or a metric) with the new value
  52. :param previous_monitored_value: The stats about the value that is monitored throughout epochs.
  53. :param new_value: The value of the current epoch that will be used to update previous_monitored_value
  54. :return:
  55. """
  56. previous_value, previous_best_value = previous_monitored_value.current, previous_monitored_value.best
  57. name, greater_is_better = previous_monitored_value.name, previous_monitored_value.greater_is_better
  58. if previous_best_value is None:
  59. previous_best_value = previous_value
  60. elif greater_is_better:
  61. previous_best_value = max(previous_value, previous_best_value)
  62. else:
  63. previous_best_value = min(previous_value, previous_best_value)
  64. if previous_value is None:
  65. change_from_previous = None
  66. change_from_best = None
  67. else:
  68. change_from_previous = new_value - previous_value
  69. change_from_best = new_value - previous_best_value
  70. return MonitoredValue(name=name, current=new_value, previous=previous_value, best=previous_best_value,
  71. change_from_previous=change_from_previous, change_from_best=change_from_best,
  72. greater_is_better=greater_is_better)
  73. def update_monitored_values_dict(monitored_values_dict: Dict[str, MonitoredValue],
  74. new_values_dict: Dict[str, float]) -> Dict[str, MonitoredValue]:
  75. """Update the given ValueToMonitor object (could be a loss or a metric) with the new value
  76. :param monitored_values_dict: Dict mapping value names to their stats throughout epochs.
  77. :param new_values_dict: Dict mapping value names to their new (i.e. current epoch) value.
  78. :return: Updated monitored_values_dict
  79. """
  80. for monitored_value_name in monitored_values_dict.keys():
  81. monitored_values_dict[monitored_value_name] = update_monitored_value(
  82. new_value=new_values_dict[monitored_value_name],
  83. previous_monitored_value=monitored_values_dict[monitored_value_name],
  84. )
  85. return monitored_values_dict
  86. def display_epoch_summary(epoch: int, n_digits: int,
  87. train_monitored_values: Dict[str, MonitoredValue],
  88. valid_monitored_values: Dict[str, MonitoredValue]) -> None:
  89. """Display a summary of loss/metric of interest, for a given epoch.
  90. :param epoch: the number of epoch.
  91. :param n_digits: number of digits to display on screen for float values
  92. :param train_monitored_values: mapping of loss/metric with their stats that will be displayed
  93. :param valid_monitored_values: mapping of loss/metric with their stats that will be displayed
  94. :return:
  95. """
  96. def _format_to_str(val: float) -> str:
  97. return str(round(val, n_digits))
  98. def _generate_tree(value_name: str, monitored_value: MonitoredValue) -> Tree:
  99. """Generate a tree that represents the stats of a given loss/metric."""
  100. current = _format_to_str(monitored_value.current)
  101. root_id = str(hash(f"{value_name} = {current}")) + str(random.random())
  102. tree = Tree()
  103. tree.create_node(tag=f"{value_name.capitalize()} = {current}", identifier=root_id)
  104. if monitored_value.previous is not None:
  105. previous = _format_to_str(monitored_value.previous)
  106. best = _format_to_str(monitored_value.best)
  107. change_from_previous = _format_to_str(monitored_value.change_from_previous)
  108. change_from_best = _format_to_str(monitored_value.change_from_best)
  109. diff_with_prev_colored = colored(
  110. text=f"{IS_GREATER_SYMBOLS[monitored_value.change_from_previous > 0]} {change_from_previous}",
  111. color=IS_BETTER_COLOR[monitored_value.is_better_than_previous]
  112. )
  113. diff_with_best_colored = colored(
  114. text=f"{IS_GREATER_SYMBOLS[monitored_value.change_from_best > 0]} {change_from_best}",
  115. color=IS_BETTER_COLOR[monitored_value.is_best_value]
  116. )
  117. tree.create_node(
  118. tag=f"Epoch N-1 = {previous:6} ({diff_with_prev_colored:8})",
  119. identifier=f"0_previous_{root_id}",
  120. parent=root_id
  121. )
  122. tree.create_node(
  123. tag=f"Best until now = {best:6} ({diff_with_best_colored:8})",
  124. identifier=f"1_best_{root_id}",
  125. parent=root_id
  126. )
  127. return tree
  128. train_tree = Tree()
  129. train_tree.create_node("Training", "Training")
  130. for name, value in train_monitored_values.items():
  131. train_tree.paste('Training', new_tree=_generate_tree(name, monitored_value=value))
  132. valid_tree = Tree()
  133. valid_tree.create_node("Validation", "Validation")
  134. for name, value in valid_monitored_values.items():
  135. valid_tree.paste('Validation', new_tree=_generate_tree(name, monitored_value=value))
  136. summary_tree = Tree()
  137. summary_tree.create_node(f"SUMMARY OF EPOCH {epoch}", "Summary")
  138. summary_tree.paste("Summary", train_tree)
  139. summary_tree.paste("Summary", valid_tree)
  140. summary_tree.show()
  141. def try_port(port):
  142. """
  143. try_port - Helper method for tensorboard port binding
  144. :param port:
  145. :return:
  146. """
  147. sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  148. is_port_available = False
  149. try:
  150. sock.bind(("localhost", port))
  151. is_port_available = True
  152. except Exception as ex:
  153. print('Port ' + str(port) + ' is in use' + str(ex))
  154. sock.close()
  155. return is_port_available
  156. def launch_tensorboard_process(checkpoints_dir_path: str, sleep_postpone: bool = True, port: int = None) -> Tuple[Process, int]:
  157. """
  158. launch_tensorboard_process - Default behavior is to scan all free ports from 6006-6016 and try using them
  159. unless port is defined by the user
  160. :param checkpoints_dir_path:
  161. :param sleep_postpone:
  162. :param port:
  163. :return: tuple of tb process, port
  164. """
  165. logdir_path = str(Path(checkpoints_dir_path).parent.absolute())
  166. tb_cmd = 'tensorboard --logdir=' + logdir_path + ' --bind_all'
  167. if port is not None:
  168. tb_ports = [port]
  169. else:
  170. tb_ports = range(6006, 6016)
  171. for tb_port in tb_ports:
  172. if not try_port(tb_port):
  173. continue
  174. else:
  175. print('Starting Tensor-Board process on port: ' + str(tb_port))
  176. tensor_board_process = Process(target=os.system, args=([tb_cmd + ' --port=' + str(tb_port)]))
  177. tensor_board_process.daemon = True
  178. tensor_board_process.start()
  179. # LET THE TENSORBOARD PROCESS START
  180. if sleep_postpone:
  181. time.sleep(3)
  182. return tensor_board_process, tb_port
  183. # RETURNING IRRELEVANT VALUES
  184. print('Failed to initialize Tensor-Board process on port: ' + ', '.join(map(str, tb_ports)))
  185. return None, -1
  186. def init_summary_writer(tb_dir, checkpoint_loaded, user_prompt=False):
  187. """Remove previous tensorboard files from directory and launch a tensor board process"""
  188. # If the training is from scratch, Walk through destination folder and delete existing tensorboard logs
  189. user = ''
  190. if not checkpoint_loaded:
  191. for filename in os.listdir(tb_dir):
  192. if 'events' in filename:
  193. if not user_prompt:
  194. logger.debug('"{}" will not be deleted'.format(filename))
  195. continue
  196. while True:
  197. # Verify with user before deleting old tensorboard files
  198. user = input('\nOLDER TENSORBOARD FILES EXISTS IN EXPERIMENT FOLDER:\n"{}"\n'
  199. 'DO YOU WANT TO DELETE THEM? [y/n]'
  200. .format(filename)) if (user != 'n' or user != 'y') else user
  201. if user == 'y':
  202. os.remove('{}/{}'.format(tb_dir, filename))
  203. print('DELETED: {}!'.format(filename))
  204. break
  205. elif user == 'n':
  206. print('"{}" will not be deleted'.format(filename))
  207. break
  208. print('Unknown answer...')
  209. # Launch a tensorboard process
  210. return SummaryWriter(tb_dir)
  211. def add_log_to_file(filename, results_titles_list, results_values_list, epoch, max_epochs):
  212. """Add a message to the log file"""
  213. # -Note: opening and closing the file every time is in-efficient. It is done for experimental purposes
  214. with open(filename, 'a') as f:
  215. f.write('\nEpoch (%d/%d) - ' % (epoch, max_epochs))
  216. for result_title, result_value in zip(results_titles_list, results_values_list):
  217. if isinstance(result_value, torch.Tensor):
  218. result_value = result_value.item()
  219. f.write(result_title + ': ' + str(result_value) + '\t')
  220. def write_training_results(writer, results_titles_list, results_values_list, epoch):
  221. """Stores the training and validation loss and accuracy for current epoch in a tensorboard file"""
  222. for res_key, res_val in zip(results_titles_list, results_values_list):
  223. # USE ONLY LOWER-CASE LETTERS AND REPLACE SPACES WITH '_' TO AVOID MANY TITLES FOR THE SAME KEY
  224. corrected_res_key = res_key.lower().replace(' ', '_')
  225. writer.add_scalar(corrected_res_key, res_val, epoch)
  226. writer.flush()
  227. def write_hpms(writer, hpmstructs=[], special_conf={}):
  228. """Stores the training and dataset hyper params in the tensorboard file"""
  229. hpm_string = ""
  230. for hpm in hpmstructs:
  231. for key, val in hpm.__dict__.items():
  232. hpm_string += '{}: {} \n '.format(key, val)
  233. for key, val in special_conf.items():
  234. hpm_string += '{}: {} \n '.format(key, val)
  235. writer.add_text("Hyper_parameters", hpm_string)
  236. writer.flush()
  237. # TODO: This should probably move into datasets/datasets_utils.py?
  238. def unpack_batch_items(batch_items: Union[tuple, torch.Tensor]):
  239. """
  240. Adds support for unpacking batch items in train/validation loop.
  241. @param batch_items: (Union[tuple, torch.Tensor]) returned by the data loader, which is expected to be in one of
  242. the following formats:
  243. 1. torch.Tensor or tuple, s.t inputs = batch_items[0], targets = batch_items[1] and len(batch_items) = 2
  244. 2. tuple: (inputs, targets, additional_batch_items)
  245. where inputs are fed to the network, targets are their corresponding labels and additional_batch_items is a
  246. dictionary (format {additional_batch_item_i_name: additional_batch_item_i ...}) which can be accessed through
  247. the phase context under the attribute additional_batch_item_i_name, using a phase callback.
  248. @return: inputs, target, additional_batch_items
  249. """
  250. additional_batch_items = {}
  251. if len(batch_items) == 2:
  252. inputs, target = batch_items
  253. elif len(batch_items) == 3:
  254. inputs, target, additional_batch_items = batch_items
  255. else:
  256. raise UnsupportedBatchItemsFormat()
  257. return inputs, target, additional_batch_items
  258. def log_uncaught_exceptions(logger):
  259. """
  260. Makes logger log uncaught exceptions
  261. @param logger: logging.Logger
  262. @return: None
  263. """
  264. def handle_exception(exc_type, exc_value, exc_traceback):
  265. if issubclass(exc_type, KeyboardInterrupt):
  266. sys.__excepthook__(exc_type, exc_value, exc_traceback)
  267. return
  268. logger.error("Uncaught exception", exc_info=(exc_type, exc_value, exc_traceback))
  269. sys.excepthook = handle_exception
  270. def parse_args(cfg, arg_names: Union[Sequence[str], callable]) -> dict:
  271. """
  272. parse args from a config.
  273. unlike get_param(), in this case only parameters that appear in the config will override default params from the function's signature
  274. """
  275. if not isinstance(arg_names, Sequence):
  276. arg_names = get_callable_param_names(arg_names)
  277. kwargs_dict = {}
  278. for arg_name in arg_names:
  279. if hasattr(cfg, arg_name) and getattr(cfg, arg_name) is not None:
  280. kwargs_dict[arg_name] = getattr(cfg, arg_name)
  281. return kwargs_dict
  282. def get_callable_param_names(obj: callable) -> Tuple[str]:
  283. """Get the param names of a given callable (function, class, ...)
  284. :param obj: Object to inspect
  285. :return: Param names of that object
  286. """
  287. return tuple(inspect.signature(obj).parameters)
  288. def log_main_training_params(gpu_mode: MultiGPUMode, num_gpus: int, batch_size: int, batch_accumulate: int, len_train_set: int):
  289. """Log training parameters"""
  290. msg = "TRAINING PARAMETERS:\n" \
  291. f" - Mode: {gpu_mode.name if gpu_mode else 'Single GPU'}\n"\
  292. f" - Number of GPUs: {num_gpus:<10} ({torch.cuda.device_count()} available on the machine)\n" \
  293. f" - Dataset size: {len_train_set:<10} (len(train_set))\n" \
  294. f" - Batch size per GPU: {batch_size:<10} (batch_size)\n" \
  295. f" - Batch Accumulate: {batch_accumulate:<10} (batch_accumulate)\n" \
  296. f" - Total batch size: {num_gpus * batch_size:<10} (num_gpus * batch_size)\n" \
  297. f" - Effective Batch size: {num_gpus * batch_size * batch_accumulate:<10} (num_gpus * batch_size * batch_accumulate)\n" \
  298. f" - Iterations per epoch: {int(len_train_set / (num_gpus * batch_size)):<10} (len(train_set) / total_batch_size)\n" \
  299. f" - Gradient updates per epoch: {int(len_train_set / (num_gpus * batch_size * batch_accumulate)):<10} (len(train_set) / effective_batch_size)\n"
  300. logger.info(msg)
Discard
Tip!

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