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
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
  1. import copy
  2. import os
  3. import time
  4. from enum import Enum
  5. import math
  6. import numpy as np
  7. import onnx
  8. import onnxruntime
  9. import torch
  10. import signal
  11. from typing import List
  12. from super_gradients.common.abstractions.abstract_logger import get_logger
  13. from super_gradients.training.utils.detection_utils import DetectionVisualization, DetectionPostPredictionCallback
  14. from super_gradients.training.utils.segmentation_utils import BinarySegmentationVisualization
  15. import cv2
  16. logger = get_logger(__name__)
  17. try:
  18. from deci_lab_client.client import DeciPlatformClient
  19. from deci_lab_client.models import ModelBenchmarkState
  20. _imported_deci_lab_failure = None
  21. except (ImportError, NameError, ModuleNotFoundError) as import_err:
  22. logger.debug("Failed to import deci_lab_client")
  23. _imported_deci_lab_failure = import_err
  24. class Phase(Enum):
  25. PRE_TRAINING = "PRE_TRAINING"
  26. TRAIN_BATCH_END = "TRAIN_BATCH_END"
  27. TRAIN_BATCH_STEP = "TRAIN_BATCH_STEP"
  28. TRAIN_EPOCH_START = "TRAIN_EPOCH_START"
  29. TRAIN_EPOCH_END = "TRAIN_EPOCH_END"
  30. VALIDATION_BATCH_END = "VALIDATION_BATCH_END"
  31. VALIDATION_EPOCH_END = "VALIDATION_EPOCH_END"
  32. VALIDATION_END_BEST_EPOCH = "VALIDATION_END_BEST_EPOCH"
  33. TEST_BATCH_END = "TEST_BATCH_END"
  34. TEST_END = "TEST_END"
  35. POST_TRAINING = "POST_TRAINING"
  36. class ContextSgMethods:
  37. """
  38. Class for delegating Trainer's methods, so that only the relevant ones are ("phase wise") are accessible.
  39. """
  40. def __init__(self, **methods):
  41. for attr, attr_val in methods.items():
  42. setattr(self, attr, attr_val)
  43. class PhaseContext:
  44. """
  45. Represents the input for phase callbacks, and is constantly updated after callback calls.
  46. """
  47. def __init__(
  48. self,
  49. epoch=None,
  50. batch_idx=None,
  51. optimizer=None,
  52. metrics_dict=None,
  53. inputs=None,
  54. preds=None,
  55. target=None,
  56. metrics_compute_fn=None,
  57. loss_avg_meter=None,
  58. loss_log_items=None,
  59. criterion=None,
  60. device=None,
  61. experiment_name=None,
  62. ckpt_dir=None,
  63. net=None,
  64. lr_warmup_epochs=None,
  65. sg_logger=None,
  66. train_loader=None,
  67. valid_loader=None,
  68. training_params=None,
  69. ddp_silent_mode=None,
  70. checkpoint_params=None,
  71. architecture=None,
  72. arch_params=None,
  73. metric_idx_in_results_tuple=None,
  74. metric_to_watch=None,
  75. valid_metrics=None,
  76. context_methods=None,
  77. ema_model=None,
  78. ):
  79. self.epoch = epoch
  80. self.batch_idx = batch_idx
  81. self.optimizer = optimizer
  82. self.inputs = inputs
  83. self.preds = preds
  84. self.target = target
  85. self.metrics_dict = metrics_dict
  86. self.metrics_compute_fn = metrics_compute_fn
  87. self.loss_avg_meter = loss_avg_meter
  88. self.loss_log_items = loss_log_items
  89. self.criterion = criterion
  90. self.device = device
  91. self.stop_training = False
  92. self.experiment_name = experiment_name
  93. self.ckpt_dir = ckpt_dir
  94. self.net = net
  95. self.lr_warmup_epochs = lr_warmup_epochs
  96. self.sg_logger = sg_logger
  97. self.train_loader = train_loader
  98. self.valid_loader = valid_loader
  99. self.training_params = training_params
  100. self.ddp_silent_mode = ddp_silent_mode
  101. self.checkpoint_params = checkpoint_params
  102. self.architecture = architecture
  103. self.arch_params = arch_params
  104. self.metric_to_watch = metric_to_watch
  105. self.valid_metrics = valid_metrics
  106. self.context_methods = context_methods
  107. self.ema_model = ema_model
  108. def update_context(self, **kwargs):
  109. for attr, attr_val in kwargs.items():
  110. setattr(self, attr, attr_val)
  111. class PhaseCallback:
  112. def __init__(self, phase: Phase):
  113. self.phase = phase
  114. def __call__(self, *args, **kwargs):
  115. raise NotImplementedError
  116. def __repr__(self):
  117. return self.__class__.__name__
  118. class ModelConversionCheckCallback(PhaseCallback):
  119. """
  120. Pre-training callback that verifies model conversion to onnx given specified conversion parameters.
  121. The model is converted, then inference is applied with onnx runtime.
  122. Use this callback wit hthe same args as DeciPlatformCallback to prevent conversion fails at the end of training.
  123. Attributes:
  124. model_meta_data: (ModelMetadata) model's meta-data object.
  125. The following parameters may be passed as kwargs in order to control the conversion to onnx:
  126. :param opset_version (default=11)
  127. :param do_constant_folding (default=True)
  128. :param dynamic_axes (default=
  129. {'input': {0: 'batch_size'},
  130. # Variable length axes
  131. 'output': {0: 'batch_size'}}
  132. )
  133. :param input_names (default=["input"])
  134. :param output_names (default=["output"])
  135. :param rtol (default=1e-03)
  136. :param atol (default=1e-05)
  137. """
  138. def __init__(self, model_meta_data, **kwargs):
  139. super(ModelConversionCheckCallback, self).__init__(phase=Phase.PRE_TRAINING)
  140. self.model_meta_data = model_meta_data
  141. self.opset_version = kwargs.get("opset_version", 10)
  142. self.do_constant_folding = kwargs.get("do_constant_folding", None) if kwargs.get("do_constant_folding", None) else True
  143. self.input_names = kwargs.get("input_names") or ["input"]
  144. self.output_names = kwargs.get("output_names") or ["output"]
  145. self.dynamic_axes = kwargs.get("dynamic_axes") or {"input": {0: "batch_size"}, "output": {0: "batch_size"}}
  146. self.rtol = kwargs.get("rtol", 1e-03)
  147. self.atol = kwargs.get("atol", 1e-05)
  148. def __call__(self, context: PhaseContext):
  149. model = copy.deepcopy(context.net.module)
  150. model = model.cpu()
  151. model.eval() # Put model into eval mode
  152. if hasattr(model, "prep_model_for_conversion"):
  153. model.prep_model_for_conversion(input_size=self.model_meta_data.input_dimensions)
  154. x = torch.randn(self.model_meta_data.primary_batch_size, *self.model_meta_data.input_dimensions, requires_grad=False)
  155. tmp_model_path = os.path.join(context.ckpt_dir, self.model_meta_data.name + "_tmp.onnx")
  156. with torch.no_grad():
  157. torch_out = model(x)
  158. torch.onnx.export(
  159. model, # Model being run
  160. x, # Model input (or a tuple for multiple inputs)
  161. tmp_model_path, # Where to save the model (can be a file or file-like object)
  162. export_params=True, # Store the trained parameter weights inside the model file
  163. opset_version=self.opset_version,
  164. do_constant_folding=self.do_constant_folding,
  165. input_names=self.input_names,
  166. output_names=self.output_names,
  167. dynamic_axes=self.dynamic_axes,
  168. )
  169. onnx_model = onnx.load(tmp_model_path)
  170. onnx.checker.check_model(onnx_model)
  171. ort_session = onnxruntime.InferenceSession(tmp_model_path, providers=["CUDAExecutionProvider", "CPUExecutionProvider"])
  172. # compute ONNX Runtime output prediction
  173. ort_inputs = {ort_session.get_inputs()[0].name: x.cpu().numpy()}
  174. ort_outs = ort_session.run(None, ort_inputs)
  175. # TODO: Ideally we don't want to check this but have the certainty of just calling torch_out.cpu()
  176. if isinstance(torch_out, List) or isinstance(torch_out, tuple):
  177. torch_out = torch_out[0]
  178. # compare ONNX Runtime and PyTorch results
  179. np.testing.assert_allclose(torch_out.cpu().numpy(), ort_outs[0], rtol=self.rtol, atol=self.atol)
  180. os.remove(tmp_model_path)
  181. logger.info("Exported model has been tested with ONNXRuntime, and the result looks good!")
  182. class DeciLabUploadCallback(PhaseCallback):
  183. """
  184. Post-training callback for uploading and optimizing a model.
  185. Attributes:
  186. model_meta_data: (ModelMetadata) model's meta-data object.
  187. optimization_request_form: (dict) optimization request form object.
  188. ckpt_name: (str) default="ckpt_best" refers to the filename of the checkpoint, inside the checkpoint directory.
  189. The following parameters may be passed as kwargs in order to control the conversion to onnx:
  190. :param opset_version
  191. :param do_constant_folding
  192. :param dynamic_axes
  193. :param input_names
  194. :param output_names
  195. """
  196. def __init__(self, model_meta_data, optimization_request_form, ckpt_name="ckpt_best.pth", **kwargs):
  197. super().__init__(phase=Phase.POST_TRAINING)
  198. if _imported_deci_lab_failure is not None:
  199. raise _imported_deci_lab_failure
  200. self.model_meta_data = model_meta_data
  201. self.optimization_request_form = optimization_request_form
  202. self.conversion_kwargs = kwargs
  203. self.ckpt_name = ckpt_name
  204. self.platform_client = DeciPlatformClient("api.deci.ai", 443, https=True)
  205. self.platform_client.login(token=os.getenv("DECI_PLATFORM_TOKEN"))
  206. @staticmethod
  207. def log_optimization_failed():
  208. logger.info("We couldn't finish your model optimization. Visit https://console.deci.ai for details")
  209. def upload_model(self, model):
  210. """
  211. This function will upload the trained model to the Deci Lab
  212. Args:
  213. model: The resulting model from the training process
  214. """
  215. self.platform_client.add_model(
  216. add_model_request=self.model_meta_data,
  217. optimization_request=self.optimization_request_form,
  218. local_loaded_model=model,
  219. )
  220. def get_optimization_status(self, optimized_model_name: str):
  221. """
  222. This function will do fetch the optimized version of the trained model and check on its benchmark status.
  223. The status will be checked against the server every 30 seconds and the process will timeout after 30 minutes
  224. or log about the successful optimization - whichever happens first.
  225. Args:
  226. optimized_model_name (str): Optimized model name
  227. Returns:
  228. bool: whether or not the optimized model has been benchmarked
  229. """
  230. def handler(_signum, _frame):
  231. logger.error("Process timed out. Visit https://console.deci.ai for details")
  232. return False
  233. signal.signal(signal.SIGALRM, handler)
  234. signal.alarm(1800)
  235. finished = False
  236. while not finished:
  237. optimized_model = self.platform_client.get_model_by_name(name=optimized_model_name).data
  238. if optimized_model.benchmark_state not in [ModelBenchmarkState.IN_PROGRESS, ModelBenchmarkState.PENDING]:
  239. finished = True
  240. else:
  241. time.sleep(30)
  242. signal.alarm(0)
  243. return True
  244. def __call__(self, context: PhaseContext):
  245. """
  246. This function will attempt to upload the trained model and schedule an optimization for it.
  247. Args:
  248. context (PhaseContext): Training phase context
  249. Returns:
  250. bool: whether or not the optimized model has been benchmarked
  251. """
  252. try:
  253. model = copy.deepcopy(context.net)
  254. model_state_dict_path = os.path.join(context.ckpt_dir, self.ckpt_name)
  255. model_state_dict = torch.load(model_state_dict_path)["net"]
  256. model.load_state_dict(state_dict=model_state_dict)
  257. model = model.module.cpu()
  258. if hasattr(model, "prep_model_for_conversion"):
  259. model.prep_model_for_conversion(input_size=self.model_meta_data.input_dimensions)
  260. self.upload_model(model=model)
  261. model_name = self.model_meta_data.name
  262. logger.info(f"Successfully added {model_name} to the model repository")
  263. optimized_model_name = f"{model_name}_1_1"
  264. logger.info("We'll wait for the scheduled optimization to finish. Please don't close this window")
  265. success = self.get_optimization_status(optimized_model_name=optimized_model_name)
  266. if success:
  267. logger.info("Successfully finished your model optimization. Visit https://console.deci.ai for details")
  268. else:
  269. DeciLabUploadCallback.log_optimization_failed()
  270. except Exception as ex:
  271. DeciLabUploadCallback.log_optimization_failed()
  272. logger.error(ex)
  273. class LRCallbackBase(PhaseCallback):
  274. """
  275. Base class for hard coded learning rate scheduling regimes, implemented as callbacks.
  276. """
  277. def __init__(self, phase, initial_lr, update_param_groups, train_loader_len, net, training_params, **kwargs):
  278. super(LRCallbackBase, self).__init__(phase)
  279. self.initial_lr = initial_lr
  280. self.lr = initial_lr
  281. self.update_param_groups = update_param_groups
  282. self.train_loader_len = train_loader_len
  283. self.net = net
  284. self.training_params = training_params
  285. def __call__(self, context: PhaseContext, **kwargs):
  286. if self.is_lr_scheduling_enabled(context):
  287. self.perform_scheduling(context)
  288. def is_lr_scheduling_enabled(self, context: PhaseContext):
  289. """
  290. Predicate that controls whether to perform lr scheduling based on values in context.
  291. @param context: PhaseContext: current phase's context.
  292. @return: bool, whether to apply lr scheduling or not.
  293. """
  294. raise NotImplementedError
  295. def perform_scheduling(self, context: PhaseContext):
  296. """
  297. Performs lr scheduling based on values in context.
  298. @param context: PhaseContext: current phase's context.
  299. """
  300. raise NotImplementedError
  301. def update_lr(self, optimizer, epoch, batch_idx=None):
  302. if self.update_param_groups:
  303. param_groups = self.net.module.update_param_groups(optimizer.param_groups, self.lr, epoch, batch_idx, self.training_params, self.train_loader_len)
  304. optimizer.param_groups = param_groups
  305. else:
  306. # UPDATE THE OPTIMIZERS PARAMETER
  307. for param_group in optimizer.param_groups:
  308. param_group["lr"] = self.lr
  309. class WarmupLRCallback(LRCallbackBase):
  310. """
  311. LR scheduling callback for linear step warmup.
  312. LR climbs from warmup_initial_lr with even steps to initial lr. When warmup_initial_lr is None- LR climb starts from
  313. initial_lr/(1+warmup_epochs).
  314. """
  315. def __init__(self, **kwargs):
  316. super(WarmupLRCallback, self).__init__(Phase.TRAIN_EPOCH_START, **kwargs)
  317. self.warmup_initial_lr = self.training_params.warmup_initial_lr or self.initial_lr / (self.training_params.lr_warmup_epochs + 1)
  318. self.warmup_step_size = (self.initial_lr - self.warmup_initial_lr) / self.training_params.lr_warmup_epochs
  319. def perform_scheduling(self, context):
  320. self.lr = self.warmup_initial_lr + context.epoch * self.warmup_step_size
  321. self.update_lr(context.optimizer, context.epoch, None)
  322. def is_lr_scheduling_enabled(self, context):
  323. return self.training_params.lr_warmup_epochs >= context.epoch
  324. class StepLRCallback(LRCallbackBase):
  325. """
  326. Hard coded step learning rate scheduling (i.e at specific milestones).
  327. """
  328. def __init__(self, lr_updates, lr_decay_factor, step_lr_update_freq=None, **kwargs):
  329. super(StepLRCallback, self).__init__(Phase.TRAIN_EPOCH_END, **kwargs)
  330. if step_lr_update_freq and len(lr_updates):
  331. raise ValueError("Only one of [lr_updates, step_lr_update_freq] should be passed to StepLRCallback constructor")
  332. if step_lr_update_freq:
  333. max_epochs = self.training_params.max_epochs - self.training_params.lr_cooldown_epochs
  334. warmup_epochs = self.training_params.lr_warmup_epochs
  335. lr_updates = [
  336. int(np.ceil(step_lr_update_freq * x)) for x in range(1, max_epochs) if warmup_epochs <= int(np.ceil(step_lr_update_freq * x)) < max_epochs
  337. ]
  338. elif self.training_params.lr_cooldown_epochs > 0:
  339. logger.warning("Specific lr_updates were passed along with cooldown_epochs > 0," " cooldown will have no effect.")
  340. self.lr_updates = lr_updates
  341. self.lr_decay_factor = lr_decay_factor
  342. def perform_scheduling(self, context):
  343. num_updates_passed = [x for x in self.lr_updates if x <= context.epoch]
  344. self.lr = self.initial_lr * self.lr_decay_factor ** len(num_updates_passed)
  345. self.update_lr(context.optimizer, context.epoch, None)
  346. def is_lr_scheduling_enabled(self, context):
  347. return self.training_params.lr_warmup_epochs <= context.epoch
  348. class ExponentialLRCallback(LRCallbackBase):
  349. """
  350. Exponential decay learning rate scheduling. Decays the learning rate by `lr_decay_factor` every epoch.
  351. """
  352. def __init__(self, lr_decay_factor: float, **kwargs):
  353. super().__init__(phase=Phase.TRAIN_BATCH_STEP, **kwargs)
  354. self.lr_decay_factor = lr_decay_factor
  355. def perform_scheduling(self, context):
  356. effective_epoch = context.epoch - self.training_params.lr_warmup_epochs
  357. current_iter = self.train_loader_len * effective_epoch + context.batch_idx
  358. self.lr = self.initial_lr * self.lr_decay_factor ** (current_iter / self.train_loader_len)
  359. self.update_lr(context.optimizer, context.epoch, context.batch_idx)
  360. def is_lr_scheduling_enabled(self, context):
  361. post_warmup_epochs = self.training_params.max_epochs - self.training_params.lr_cooldown_epochs
  362. return self.training_params.lr_warmup_epochs <= context.epoch < post_warmup_epochs
  363. class PolyLRCallback(LRCallbackBase):
  364. """
  365. Hard coded polynomial decay learning rate scheduling (i.e at specific milestones).
  366. """
  367. def __init__(self, max_epochs, **kwargs):
  368. super(PolyLRCallback, self).__init__(Phase.TRAIN_BATCH_STEP, **kwargs)
  369. self.max_epochs = max_epochs
  370. def perform_scheduling(self, context):
  371. effective_epoch = context.epoch - self.training_params.lr_warmup_epochs
  372. effective_max_epochs = self.max_epochs - self.training_params.lr_warmup_epochs - self.training_params.lr_cooldown_epochs
  373. current_iter = (self.train_loader_len * effective_epoch + context.batch_idx) / self.training_params.batch_accumulate
  374. max_iter = self.train_loader_len * effective_max_epochs / self.training_params.batch_accumulate
  375. self.lr = self.initial_lr * pow((1.0 - (current_iter / max_iter)), 0.9)
  376. self.update_lr(context.optimizer, context.epoch, context.batch_idx)
  377. def is_lr_scheduling_enabled(self, context):
  378. post_warmup_epochs = self.training_params.max_epochs - self.training_params.lr_cooldown_epochs
  379. return self.training_params.lr_warmup_epochs <= context.epoch < post_warmup_epochs
  380. class CosineLRCallback(LRCallbackBase):
  381. """
  382. Hard coded step Cosine anealing learning rate scheduling.
  383. """
  384. def __init__(self, max_epochs, cosine_final_lr_ratio, **kwargs):
  385. super(CosineLRCallback, self).__init__(Phase.TRAIN_BATCH_STEP, **kwargs)
  386. self.max_epochs = max_epochs
  387. self.cosine_final_lr_ratio = cosine_final_lr_ratio
  388. def perform_scheduling(self, context):
  389. effective_epoch = context.epoch - self.training_params.lr_warmup_epochs
  390. effective_max_epochs = self.max_epochs - self.training_params.lr_warmup_epochs - self.training_params.lr_cooldown_epochs
  391. current_iter = self.train_loader_len * effective_epoch + context.batch_idx
  392. max_iter = self.train_loader_len * effective_max_epochs
  393. lr = 0.5 * self.initial_lr * (1.0 + math.cos(current_iter / (max_iter + 1) * math.pi))
  394. # the cosine starts from initial_lr and reaches initial_lr * cosine_final_lr_ratio in last epoch
  395. self.lr = lr * (1 - self.cosine_final_lr_ratio) + (self.initial_lr * self.cosine_final_lr_ratio)
  396. self.update_lr(context.optimizer, context.epoch, context.batch_idx)
  397. def is_lr_scheduling_enabled(self, context):
  398. post_warmup_epochs = self.training_params.max_epochs - self.training_params.lr_cooldown_epochs
  399. return self.training_params.lr_warmup_epochs <= context.epoch < post_warmup_epochs
  400. class FunctionLRCallback(LRCallbackBase):
  401. """
  402. Hard coded rate scheduling for user defined lr scheduling function.
  403. """
  404. def __init__(self, max_epochs, lr_schedule_function, **kwargs):
  405. super(FunctionLRCallback, self).__init__(Phase.TRAIN_BATCH_STEP, **kwargs)
  406. assert callable(self.lr_schedule_function), "self.lr_function must be callable"
  407. self.lr_schedule_function = lr_schedule_function
  408. self.max_epochs = max_epochs
  409. def is_lr_scheduling_enabled(self, context):
  410. post_warmup_epochs = self.training_params.max_epochs - self.training_params.lr_cooldown_epochs
  411. return self.training_params.lr_warmup_epochs <= context.epoch < post_warmup_epochs
  412. def perform_scheduling(self, context):
  413. effective_epoch = context.epoch - self.training_params.lr_warmup_epochs
  414. effective_max_epochs = self.max_epochs - self.training_params.lr_warmup_epochs - self.training_params.lr_cooldown_epochs
  415. self.lr = self.lr_schedule_function(
  416. initial_lr=self.initial_lr,
  417. epoch=effective_epoch,
  418. iter=context.batch_idx,
  419. max_epoch=effective_max_epochs,
  420. iters_per_epoch=self.train_loader_len,
  421. )
  422. self.update_lr(context.optimizer, context.epoch, context.batch_idx)
  423. class IllegalLRSchedulerMetric(Exception):
  424. """Exception raised illegal combination of training parameters.
  425. Attributes:
  426. message -- explanation of the error
  427. """
  428. def __init__(self, metric_name, metrics_dict):
  429. self.message = "Illegal metric name: " + metric_name + ". Expected one of metics_dics keys: " + str(metrics_dict.keys())
  430. super().__init__(self.message)
  431. class LRSchedulerCallback(PhaseCallback):
  432. """
  433. Learning rate scheduler callback.
  434. Attributes:
  435. scheduler: torch.optim._LRScheduler, the learning rate scheduler to be called step() with.
  436. metric_name: str, (default=None) the metric name for ReduceLROnPlateau learning rate scheduler.
  437. When passing __call__ a metrics_dict, with a key=self.metric_name, the value of that metric will monitored
  438. for ReduceLROnPlateau (i.e step(metrics_dict[self.metric_name]).
  439. """
  440. def __init__(self, scheduler, phase, metric_name=None):
  441. super(LRSchedulerCallback, self).__init__(phase)
  442. self.scheduler = scheduler
  443. self.metric_name = metric_name
  444. def __call__(self, context: PhaseContext):
  445. if context.lr_warmup_epochs <= context.epoch:
  446. if self.metric_name and self.metric_name in context.metrics_dict.keys():
  447. self.scheduler.step(context.metrics_dict[self.metric_name])
  448. elif self.metric_name is None:
  449. self.scheduler.step()
  450. else:
  451. raise IllegalLRSchedulerMetric(self.metric_name, context.metrics_dict)
  452. def __repr__(self):
  453. return "LRSchedulerCallback: " + repr(self.scheduler)
  454. class MetricsUpdateCallback(PhaseCallback):
  455. def __init__(self, phase: Phase):
  456. super(MetricsUpdateCallback, self).__init__(phase)
  457. def __call__(self, context: PhaseContext):
  458. context.metrics_compute_fn.update(**context.__dict__)
  459. if context.criterion is not None:
  460. context.loss_avg_meter.update(context.loss_log_items, len(context.inputs))
  461. class KDModelMetricsUpdateCallback(MetricsUpdateCallback):
  462. def __init__(self, phase: Phase):
  463. super().__init__(phase=phase)
  464. def __call__(self, context: PhaseContext):
  465. metrics_compute_fn_kwargs = {k: v.student_output if k == "preds" else v for k, v in context.__dict__.items()}
  466. context.metrics_compute_fn.update(**metrics_compute_fn_kwargs)
  467. if context.criterion is not None:
  468. context.loss_avg_meter.update(context.loss_log_items, len(context.inputs))
  469. class PhaseContextTestCallback(PhaseCallback):
  470. """
  471. A callback that saves the phase context the for testing.
  472. """
  473. def __init__(self, phase: Phase):
  474. super(PhaseContextTestCallback, self).__init__(phase)
  475. self.context = None
  476. def __call__(self, context: PhaseContext):
  477. self.context = context
  478. class DetectionVisualizationCallback(PhaseCallback):
  479. """
  480. A callback that adds a visualization of a batch of detection predictions to context.sg_logger
  481. Attributes:
  482. freq: frequency (in epochs) to perform this callback.
  483. batch_idx: batch index to perform visualization for.
  484. classes: class list of the dataset.
  485. last_img_idx_in_batch: Last image index to add to log. (default=-1, will take entire batch).
  486. """
  487. def __init__(
  488. self,
  489. phase: Phase,
  490. freq: int,
  491. post_prediction_callback: DetectionPostPredictionCallback,
  492. classes: list,
  493. batch_idx: int = 0,
  494. last_img_idx_in_batch: int = -1,
  495. ):
  496. super(DetectionVisualizationCallback, self).__init__(phase)
  497. self.freq = freq
  498. self.post_prediction_callback = post_prediction_callback
  499. self.batch_idx = batch_idx
  500. self.classes = classes
  501. self.last_img_idx_in_batch = last_img_idx_in_batch
  502. def __call__(self, context: PhaseContext):
  503. if context.epoch % self.freq == 0 and context.batch_idx == self.batch_idx:
  504. # SOME CALCULATIONS ARE IN-PLACE IN NMS, SO CLONE THE PREDICTIONS
  505. preds = (context.preds[0].clone(), None)
  506. preds = self.post_prediction_callback(preds)
  507. batch_imgs = DetectionVisualization.visualize_batch(context.inputs, preds, context.target, self.batch_idx, self.classes)
  508. batch_imgs = [cv2.cvtColor(image, cv2.COLOR_BGR2RGB) for image in batch_imgs]
  509. batch_imgs = np.stack(batch_imgs)
  510. tag = "batch_" + str(self.batch_idx) + "_images"
  511. context.sg_logger.add_images(tag=tag, images=batch_imgs[: self.last_img_idx_in_batch], global_step=context.epoch, data_format="NHWC")
  512. class BinarySegmentationVisualizationCallback(PhaseCallback):
  513. """
  514. A callback that adds a visualization of a batch of segmentation predictions to context.sg_logger
  515. Attributes:
  516. freq: frequency (in epochs) to perform this callback.
  517. batch_idx: batch index to perform visualization for.
  518. last_img_idx_in_batch: Last image index to add to log. (default=-1, will take entire batch).
  519. """
  520. def __init__(self, phase: Phase, freq: int, batch_idx: int = 0, last_img_idx_in_batch: int = -1):
  521. super(BinarySegmentationVisualizationCallback, self).__init__(phase)
  522. self.freq = freq
  523. self.batch_idx = batch_idx
  524. self.last_img_idx_in_batch = last_img_idx_in_batch
  525. def __call__(self, context: PhaseContext):
  526. if context.epoch % self.freq == 0 and context.batch_idx == self.batch_idx:
  527. if isinstance(context.preds, tuple):
  528. preds = context.preds[0].clone()
  529. else:
  530. preds = context.preds.clone()
  531. batch_imgs = BinarySegmentationVisualization.visualize_batch(context.inputs, preds, context.target, self.batch_idx)
  532. batch_imgs = [cv2.cvtColor(image, cv2.COLOR_BGR2RGB) for image in batch_imgs]
  533. batch_imgs = np.stack(batch_imgs)
  534. tag = "batch_" + str(self.batch_idx) + "_images"
  535. context.sg_logger.add_images(tag=tag, images=batch_imgs[: self.last_img_idx_in_batch], global_step=context.epoch, data_format="NHWC")
  536. class TrainingStageSwitchCallbackBase(PhaseCallback):
  537. """
  538. TrainingStageSwitchCallback
  539. A phase callback that is called at a specific epoch (epoch start) to support multi-stage training.
  540. It does so by manipulating the objects inside the context.
  541. Attributes:
  542. next_stage_start_epoch: int, the epoch idx to apply the stage change.
  543. """
  544. def __init__(self, next_stage_start_epoch: int):
  545. super(TrainingStageSwitchCallbackBase, self).__init__(phase=Phase.TRAIN_EPOCH_START)
  546. self.next_stage_start_epoch = next_stage_start_epoch
  547. def __call__(self, context: PhaseContext):
  548. if context.epoch == self.next_stage_start_epoch:
  549. self.apply_stage_change(context)
  550. def apply_stage_change(self, context: PhaseContext):
  551. """
  552. This method is called when the callback is fired on the next_stage_start_epoch,
  553. and holds the stage change logic that should be applied to the context's objects.
  554. :param context: PhaseContext, context of current phase
  555. """
  556. raise NotImplementedError
  557. class YoloXTrainingStageSwitchCallback(TrainingStageSwitchCallbackBase):
  558. """
  559. YoloXTrainingStageSwitchCallback
  560. Training stage switch for YoloX training.
  561. Disables mosaic, and manipulates YoloX loss to use L1.
  562. """
  563. def __init__(self, next_stage_start_epoch: int = 285):
  564. super(YoloXTrainingStageSwitchCallback, self).__init__(next_stage_start_epoch=next_stage_start_epoch)
  565. def apply_stage_change(self, context: PhaseContext):
  566. for transform in context.train_loader.dataset.transforms:
  567. if hasattr(transform, "close"):
  568. transform.close()
  569. iter(context.train_loader)
  570. context.criterion.use_l1 = True
  571. class CallbackHandler:
  572. """
  573. Runs all callbacks who's phase attribute equals to the given phase.
  574. Attributes:
  575. callbacks: List[PhaseCallback]. Callbacks to be run.
  576. """
  577. def __init__(self, callbacks):
  578. self.callbacks = callbacks
  579. def __call__(self, phase: Phase, context: PhaseContext):
  580. for callback in self.callbacks:
  581. if callback.phase == phase:
  582. callback(context)
  583. class TestLRCallback(PhaseCallback):
  584. """
  585. Phase callback that collects the learning rates in lr_placeholder at the end of each epoch (used for testing). In
  586. the case of multiple parameter groups (i.e multiple learning rates) the learning rate is collected from the first
  587. one. The phase is VALIDATION_EPOCH_END to ensure all lr updates have been performed before calling this callback.
  588. """
  589. def __init__(self, lr_placeholder):
  590. super(TestLRCallback, self).__init__(Phase.VALIDATION_EPOCH_END)
  591. self.lr_placeholder = lr_placeholder
  592. def __call__(self, context: PhaseContext):
  593. self.lr_placeholder.append(context.optimizer.param_groups[0]["lr"])
Discard
Tip!

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