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
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
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
  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, Callable
  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.common.environment.device_utils import device_config
  17. from super_gradients.training.exceptions.dataset_exceptions import UnsupportedBatchItemsFormat
  18. from super_gradients.common.data_types.enum import MultiGPUMode
  19. from enum import Enum
  20. class IncreaseType(Enum):
  21. """Type of increase compared to previous value, i.e. if the value is greater, smaller or the same.
  22. Difference with "improvement":
  23. If a loss goes from 1 to 0.5, the value is smaller (decreased), but the result is better (improvement).
  24. For accuracy from 1 to 0.5, the value is smaller, but this time the result decreased, because greater is better.
  25. """
  26. NONE = "none"
  27. IS_GREATER = "greater"
  28. IS_SMALLER = "smaller"
  29. IS_EQUAL = "equal"
  30. def to_symbol(self) -> str:
  31. """Get the symbol representing the current increase type"""
  32. if self == IncreaseType.NONE:
  33. return ""
  34. elif self == IncreaseType.IS_GREATER:
  35. return "↗"
  36. elif self == IncreaseType.IS_SMALLER:
  37. return "↘"
  38. else:
  39. return "="
  40. class ImprovementType(Enum):
  41. """Type of improvement compared to previous value, i.e. if the value is better, worse or the same.
  42. Difference with "increase":
  43. If a loss goes from 1 to 0.5, the value is smaller (decreased), but the result is better (improvement).
  44. For accuracy from 1 to 0.5, the value is smaller, but this time the result decreased, because greater is better.
  45. """
  46. IS_BETTER = "better"
  47. IS_WORSE = "worse"
  48. IS_SAME = "same"
  49. NONE = "none"
  50. def to_color(self) -> Union[str, None]:
  51. """Get the color representing the current improvement type"""
  52. if self == ImprovementType.IS_SAME:
  53. return "white"
  54. elif self == ImprovementType.IS_BETTER:
  55. return "green"
  56. elif self == ImprovementType.IS_WORSE:
  57. return "red"
  58. else:
  59. return None
  60. logger = get_logger(__name__)
  61. @dataclass
  62. class MonitoredValue:
  63. """Store a value and some indicators relative to its past iterations.
  64. The value can be a metric/loss, and the iteration can be epochs/batch.
  65. :param name: Name of the metric
  66. :param greater_is_better: True, a greater value is considered better.
  67. ex: (greater_is_better=True) For Accuracy 1 is greater and therefore better than 0.4
  68. ex: (greater_is_better=False) For Loss 1 is greater and therefore worse than 0.4
  69. None when unknown
  70. :param current: Current value of the metric
  71. :param previous: Value of the metric in previous iteration
  72. :param best: Value of the metric in best iteration (best according to greater_is_better)
  73. :param change_from_previous: Change compared to previous iteration value
  74. :param change_from_best: Change compared to best iteration value
  75. """
  76. name: str
  77. greater_is_better: bool = None
  78. current: float = None
  79. previous: float = None
  80. best: float = None
  81. change_from_previous: float = None
  82. change_from_best: float = None
  83. @property
  84. def has_increased_from_previous(self) -> IncreaseType:
  85. """Type of increase compared to previous value, i.e. if the value is greater, smaller or the same."""
  86. return self._get_increase_type(self.change_from_previous)
  87. @property
  88. def has_improved_from_previous(self) -> ImprovementType:
  89. """Type of improvement compared to previous value, i.e. if the value is better, worse or the same."""
  90. return self._get_improvement_type(delta=self.change_from_previous)
  91. @property
  92. def has_increased_from_best(self) -> IncreaseType:
  93. """Type of increase compared to best value, i.e. if the value is greater, smaller or the same."""
  94. return self._get_increase_type(self.change_from_best)
  95. @property
  96. def has_improved_from_best(self) -> ImprovementType:
  97. """Type of improvement compared to best value, i.e. if the value is better, worse or the same."""
  98. return self._get_improvement_type(delta=self.change_from_best)
  99. def _get_increase_type(self, delta: float) -> IncreaseType:
  100. """Type of increase, i.e. if the value is greater, smaller or the same."""
  101. if self.change_from_best is None:
  102. return IncreaseType.NONE
  103. if delta > 0:
  104. return IncreaseType.IS_GREATER
  105. elif delta < 0:
  106. return IncreaseType.IS_SMALLER
  107. else:
  108. return IncreaseType.IS_EQUAL
  109. def _get_improvement_type(self, delta: float) -> ImprovementType:
  110. """Type of improvement, i.e. if value is better, worse or the same."""
  111. if self.greater_is_better is None or self.change_from_best is None:
  112. return ImprovementType.NONE
  113. has_increased, has_decreased = delta > 0, delta < 0
  114. if has_increased and self.greater_is_better or has_decreased and not self.greater_is_better:
  115. return ImprovementType.IS_BETTER
  116. elif has_increased and not self.greater_is_better or has_decreased and self.greater_is_better:
  117. return ImprovementType.IS_WORSE
  118. else:
  119. return ImprovementType.IS_SAME
  120. def update_monitored_value(previous_monitored_value: MonitoredValue, new_value: float) -> MonitoredValue:
  121. """Update the given ValueToMonitor object (could be a loss or a metric) with the new value
  122. :param previous_monitored_value: The stats about the value that is monitored throughout epochs.
  123. :param new_value: The value of the current epoch that will be used to update previous_monitored_value
  124. :return:
  125. """
  126. previous_value, previous_best_value = previous_monitored_value.current, previous_monitored_value.best
  127. name, greater_is_better = previous_monitored_value.name, previous_monitored_value.greater_is_better
  128. if previous_best_value is None:
  129. previous_best_value = previous_value
  130. elif greater_is_better:
  131. previous_best_value = max(previous_value, previous_best_value)
  132. else:
  133. previous_best_value = min(previous_value, previous_best_value)
  134. if previous_value is None:
  135. change_from_previous = None
  136. change_from_best = None
  137. else:
  138. change_from_previous = new_value - previous_value
  139. change_from_best = new_value - previous_best_value
  140. return MonitoredValue(
  141. name=name,
  142. current=new_value,
  143. previous=previous_value,
  144. best=previous_best_value,
  145. change_from_previous=change_from_previous,
  146. change_from_best=change_from_best,
  147. greater_is_better=greater_is_better,
  148. )
  149. def update_monitored_values_dict(monitored_values_dict: Dict[str, MonitoredValue], new_values_dict: Dict[str, float]) -> Dict[str, MonitoredValue]:
  150. """Update the given ValueToMonitor object (could be a loss or a metric) with the new value
  151. :param monitored_values_dict: Dict mapping value names to their stats throughout epochs.
  152. :param new_values_dict: Dict mapping value names to their new (i.e. current epoch) value.
  153. :return: Updated monitored_values_dict
  154. """
  155. for monitored_value_name in monitored_values_dict.keys():
  156. monitored_values_dict[monitored_value_name] = update_monitored_value(
  157. new_value=new_values_dict[monitored_value_name],
  158. previous_monitored_value=monitored_values_dict[monitored_value_name],
  159. )
  160. return monitored_values_dict
  161. def display_epoch_summary(
  162. epoch: int, n_digits: int, train_monitored_values: Dict[str, MonitoredValue], valid_monitored_values: Dict[str, MonitoredValue]
  163. ) -> None:
  164. """Display a summary of loss/metric of interest, for a given epoch.
  165. :param epoch: the number of epoch.
  166. :param n_digits: number of digits to display on screen for float values
  167. :param train_monitored_values: mapping of loss/metric with their stats that will be displayed
  168. :param valid_monitored_values: mapping of loss/metric with their stats that will be displayed
  169. :return:
  170. """
  171. def _format_to_str(val: float) -> str:
  172. return str(round(val, n_digits))
  173. def _generate_tree(value_name: str, monitored_value: MonitoredValue) -> Tree:
  174. """Generate a tree that represents the stats of a given loss/metric."""
  175. current = _format_to_str(monitored_value.current)
  176. root_id = str(hash(f"{value_name} = {current}")) + str(random.random())
  177. tree = Tree()
  178. tree.create_node(tag=f"{value_name.capitalize()} = {current}", identifier=root_id)
  179. if monitored_value.previous is not None:
  180. previous = _format_to_str(monitored_value.previous)
  181. best = _format_to_str(monitored_value.best)
  182. change_from_previous = _format_to_str(monitored_value.change_from_previous)
  183. change_from_best = _format_to_str(monitored_value.change_from_best)
  184. diff_with_prev_colored = colored(
  185. text=f"{monitored_value.has_increased_from_previous.to_symbol()} {change_from_previous}",
  186. color=monitored_value.has_improved_from_previous.to_color(),
  187. )
  188. diff_with_best_colored = colored(
  189. text=f"{monitored_value.has_increased_from_best.to_symbol()} {change_from_best}", color=monitored_value.has_improved_from_best.to_color()
  190. )
  191. tree.create_node(tag=f"Epoch N-1 = {previous:6} ({diff_with_prev_colored:8})", identifier=f"0_previous_{root_id}", parent=root_id)
  192. tree.create_node(tag=f"Best until now = {best:6} ({diff_with_best_colored:8})", identifier=f"1_best_{root_id}", parent=root_id)
  193. return tree
  194. train_tree = Tree()
  195. train_tree.create_node("Training", "Training")
  196. for name, value in train_monitored_values.items():
  197. train_tree.paste("Training", new_tree=_generate_tree(name, monitored_value=value))
  198. valid_tree = Tree()
  199. valid_tree.create_node("Validation", "Validation")
  200. for name, value in valid_monitored_values.items():
  201. valid_tree.paste("Validation", new_tree=_generate_tree(name, monitored_value=value))
  202. summary_tree = Tree()
  203. summary_tree.create_node(f"SUMMARY OF EPOCH {epoch}", "Summary")
  204. summary_tree.paste("Summary", train_tree)
  205. summary_tree.paste("Summary", valid_tree)
  206. summary_tree.show()
  207. def try_port(port):
  208. """
  209. try_port - Helper method for tensorboard port binding
  210. :param port:
  211. :return:
  212. """
  213. sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  214. is_port_available = False
  215. try:
  216. sock.bind(("localhost", port))
  217. is_port_available = True
  218. except Exception as ex:
  219. print("Port " + str(port) + " is in use" + str(ex))
  220. sock.close()
  221. return is_port_available
  222. def launch_tensorboard_process(checkpoints_dir_path: str, sleep_postpone: bool = True, port: int = None) -> Tuple[Process, int]:
  223. """
  224. launch_tensorboard_process - Default behavior is to scan all free ports from 6006-6016 and try using them
  225. unless port is defined by the user
  226. :param checkpoints_dir_path:
  227. :param sleep_postpone:
  228. :param port:
  229. :return: tuple of tb process, port
  230. """
  231. logdir_path = str(Path(checkpoints_dir_path).parent.absolute())
  232. tb_cmd = "tensorboard --logdir=" + logdir_path + " --bind_all"
  233. if port is not None:
  234. tb_ports = [port]
  235. else:
  236. tb_ports = range(6006, 6016)
  237. for tb_port in tb_ports:
  238. if not try_port(tb_port):
  239. continue
  240. else:
  241. print("Starting Tensor-Board process on port: " + str(tb_port))
  242. tensor_board_process = Process(target=os.system, args=([tb_cmd + " --port=" + str(tb_port)]))
  243. tensor_board_process.daemon = True
  244. tensor_board_process.start()
  245. # LET THE TENSORBOARD PROCESS START
  246. if sleep_postpone:
  247. time.sleep(3)
  248. return tensor_board_process, tb_port
  249. # RETURNING IRRELEVANT VALUES
  250. print("Failed to initialize Tensor-Board process on port: " + ", ".join(map(str, tb_ports)))
  251. return None, -1
  252. def init_summary_writer(tb_dir, checkpoint_loaded, user_prompt=False):
  253. """Remove previous tensorboard files from directory and launch a tensor board process"""
  254. # If the training is from scratch, Walk through destination folder and delete existing tensorboard logs
  255. user = ""
  256. if not checkpoint_loaded:
  257. for filename in os.listdir(tb_dir):
  258. if "events" in filename:
  259. if not user_prompt:
  260. logger.debug('"{}" will not be deleted'.format(filename))
  261. continue
  262. while True:
  263. # Verify with user before deleting old tensorboard files
  264. user = (
  265. input('\nOLDER TENSORBOARD FILES EXISTS IN EXPERIMENT FOLDER:\n"{}"\n' "DO YOU WANT TO DELETE THEM? [y/n]".format(filename))
  266. if (user != "n" or user != "y")
  267. else user
  268. )
  269. if user == "y":
  270. os.remove("{}/{}".format(tb_dir, filename))
  271. print("DELETED: {}!".format(filename))
  272. break
  273. elif user == "n":
  274. print('"{}" will not be deleted'.format(filename))
  275. break
  276. print("Unknown answer...")
  277. # Launch a tensorboard process
  278. return SummaryWriter(tb_dir)
  279. def add_log_to_file(filename, results_titles_list, results_values_list, epoch, max_epochs):
  280. """Add a message to the log file"""
  281. # -Note: opening and closing the file every time is in-efficient. It is done for experimental purposes
  282. with open(filename, "a") as f:
  283. f.write("\nEpoch (%d/%d) - " % (epoch, max_epochs))
  284. for result_title, result_value in zip(results_titles_list, results_values_list):
  285. if isinstance(result_value, torch.Tensor):
  286. result_value = result_value.item()
  287. f.write(result_title + ": " + str(result_value) + "\t")
  288. def write_training_results(writer, results_titles_list, results_values_list, epoch):
  289. """Stores the training and validation loss and accuracy for current epoch in a tensorboard file"""
  290. for res_key, res_val in zip(results_titles_list, results_values_list):
  291. # USE ONLY LOWER-CASE LETTERS AND REPLACE SPACES WITH '_' TO AVOID MANY TITLES FOR THE SAME KEY
  292. corrected_res_key = res_key.lower().replace(" ", "_")
  293. writer.add_scalar(corrected_res_key, res_val, epoch)
  294. writer.flush()
  295. def write_hpms(writer, hpmstructs=[], special_conf={}):
  296. """Stores the training and dataset hyper params in the tensorboard file"""
  297. hpm_string = ""
  298. for hpm in hpmstructs:
  299. for key, val in hpm.__dict__.items():
  300. hpm_string += "{}: {} \n ".format(key, val)
  301. for key, val in special_conf.items():
  302. hpm_string += "{}: {} \n ".format(key, val)
  303. writer.add_text("Hyper_parameters", hpm_string)
  304. writer.flush()
  305. # TODO: This should probably move into datasets/datasets_utils.py?
  306. def unpack_batch_items(batch_items: Union[tuple, torch.Tensor]):
  307. """
  308. Adds support for unpacking batch items in train/validation loop.
  309. @param batch_items: (Union[tuple, torch.Tensor]) returned by the data loader, which is expected to be in one of
  310. the following formats:
  311. 1. torch.Tensor or tuple, s.t inputs = batch_items[0], targets = batch_items[1] and len(batch_items) = 2
  312. 2. tuple: (inputs, targets, additional_batch_items)
  313. where inputs are fed to the network, targets are their corresponding labels and additional_batch_items is a
  314. dictionary (format {additional_batch_item_i_name: additional_batch_item_i ...}) which can be accessed through
  315. the phase context under the attribute additional_batch_item_i_name, using a phase callback.
  316. @return: inputs, target, additional_batch_items
  317. """
  318. additional_batch_items = {}
  319. if len(batch_items) == 2:
  320. inputs, target = batch_items
  321. elif len(batch_items) == 3:
  322. inputs, target, additional_batch_items = batch_items
  323. else:
  324. raise UnsupportedBatchItemsFormat()
  325. return inputs, target, additional_batch_items
  326. def log_uncaught_exceptions(logger):
  327. """
  328. Makes logger log uncaught exceptions
  329. @param logger: logging.Logger
  330. @return: None
  331. """
  332. def log_exceptook(excepthook: Callable) -> Callable:
  333. """Wrapping function that logs exceptions that are not KeyboardInterrupt"""
  334. def handle_exception(exc_type, exc_value, exc_traceback):
  335. if not issubclass(exc_type, KeyboardInterrupt):
  336. logger.error("Uncaught exception", exc_info=(exc_type, exc_value, exc_traceback))
  337. excepthook(exc_type, exc_value, exc_traceback)
  338. return
  339. return handle_exception
  340. sys.excepthook = log_exceptook(sys.excepthook)
  341. def parse_args(cfg, arg_names: Union[Sequence[str], callable]) -> dict:
  342. """
  343. parse args from a config.
  344. unlike get_param(), in this case only parameters that appear in the config will override default params from the function's signature
  345. """
  346. if not isinstance(arg_names, Sequence):
  347. arg_names = get_callable_param_names(arg_names)
  348. kwargs_dict = {}
  349. for arg_name in arg_names:
  350. if hasattr(cfg, arg_name) and getattr(cfg, arg_name) is not None:
  351. kwargs_dict[arg_name] = getattr(cfg, arg_name)
  352. return kwargs_dict
  353. def get_callable_param_names(obj: callable) -> Tuple[str]:
  354. """Get the param names of a given callable (function, class, ...)
  355. :param obj: Object to inspect
  356. :return: Param names of that object
  357. """
  358. return tuple(inspect.signature(obj).parameters)
  359. def log_main_training_params(multi_gpu: MultiGPUMode, num_gpus: int, batch_size: int, batch_accumulate: int, len_train_set: int):
  360. """Log training parameters"""
  361. msg = (
  362. "TRAINING PARAMETERS:\n"
  363. f" - Mode: {multi_gpu.name if multi_gpu else 'Single GPU'}\n"
  364. f" - Number of GPUs: {num_gpus if 'cuda' in device_config.device else 0:<10} ({torch.cuda.device_count()} available on the machine)\n"
  365. f" - Dataset size: {len_train_set:<10} (len(train_set))\n"
  366. f" - Batch size per GPU: {batch_size:<10} (batch_size)\n"
  367. f" - Batch Accumulate: {batch_accumulate:<10} (batch_accumulate)\n"
  368. f" - Total batch size: {num_gpus * batch_size:<10} (num_gpus * batch_size)\n"
  369. f" - Effective Batch size: {num_gpus * batch_size * batch_accumulate:<10} (num_gpus * batch_size * batch_accumulate)\n"
  370. f" - Iterations per epoch: {int(len_train_set / (num_gpus * batch_size)):<10} (len(train_set) / total_batch_size)\n"
  371. f" - Gradient updates per epoch: {int(len_train_set / (num_gpus * batch_size * batch_accumulate)):<10} (len(train_set) / effective_batch_size)\n"
  372. )
  373. logger.info(msg)
Discard
Tip!

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