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

#378 Feature/sg 281 add kd notebook

Merged
Ghost merged 1 commits into Deci-AI:master from deci-ai:feature/SG-281-add_kd_notebook
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
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
  1. import inspect
  2. import os
  3. import sys
  4. from copy import deepcopy
  5. from typing import Union, Tuple, Mapping, List, Any
  6. import hydra
  7. import numpy as np
  8. import torch
  9. from omegaconf import DictConfig
  10. from torch import nn
  11. from torch.utils.data import DataLoader, DistributedSampler
  12. from torch.cuda.amp import GradScaler, autocast
  13. from torchmetrics import MetricCollection
  14. from tqdm import tqdm
  15. from piptools.scripts.sync import _get_installed_distributions
  16. from super_gradients.common.factories.callbacks_factory import CallbacksFactory
  17. from super_gradients.common.data_types.enum import MultiGPUMode, StrictLoad, EvaluationType
  18. from super_gradients.training.models.all_architectures import ARCHITECTURES
  19. from super_gradients.common.decorators.factory_decorator import resolve_param
  20. from super_gradients.common.environment import env_helpers
  21. from super_gradients.common.abstractions.abstract_logger import get_logger
  22. from super_gradients.common.factories.list_factory import ListFactory
  23. from super_gradients.common.factories.losses_factory import LossesFactory
  24. from super_gradients.common.factories.metrics_factory import MetricsFactory
  25. from super_gradients.common.sg_loggers import SG_LOGGERS
  26. from super_gradients.common.sg_loggers.abstract_sg_logger import AbstractSGLogger
  27. from super_gradients.common.sg_loggers.base_sg_logger import BaseSGLogger
  28. from super_gradients.training import utils as core_utils, models, dataloaders
  29. from super_gradients.training.models import SgModule
  30. from super_gradients.training.pretrained_models import PRETRAINED_NUM_CLASSES
  31. from super_gradients.training.utils import sg_trainer_utils
  32. from super_gradients.training.utils.quantization_utils import QATCallback
  33. from super_gradients.training.utils.sg_trainer_utils import MonitoredValue, parse_args
  34. from super_gradients.training.exceptions.sg_trainer_exceptions import UnsupportedOptimizerFormat, \
  35. IllegalDataloaderInitialization, GPUModeNotSetupError
  36. from super_gradients.training.losses import LOSSES
  37. from super_gradients.training.metrics.metric_utils import get_metrics_titles, get_metrics_results_tuple, \
  38. get_logging_values, \
  39. get_metrics_dict, get_train_loop_description_dict
  40. from super_gradients.training.params import TrainingParams
  41. from super_gradients.training.utils.detection_utils import DetectionPostPredictionCallback
  42. from super_gradients.training.utils.distributed_training_utils import MultiGPUModeAutocastWrapper, \
  43. reduce_results_tuple_for_ddp, compute_precise_bn_stats, setup_gpu_mode, require_gpu_setup
  44. from super_gradients.training.utils.ema import ModelEMA
  45. from super_gradients.training.utils.optimizer_utils import build_optimizer
  46. from super_gradients.training.utils.weight_averaging_utils import ModelWeightAveraging
  47. from super_gradients.training.metrics import Accuracy, Top5
  48. from super_gradients.training.utils import random_seed
  49. from super_gradients.training.utils.checkpoint_utils import get_ckpt_local_path, read_ckpt_state_dict, \
  50. load_checkpoint_to_model, load_pretrained_weights
  51. from super_gradients.training.datasets.datasets_utils import DatasetStatisticsTensorboardLogger
  52. from super_gradients.training.utils.callbacks import CallbackHandler, Phase, LR_SCHEDULERS_CLS_DICT, PhaseContext, \
  53. MetricsUpdateCallback, LR_WARMUP_CLS_DICT, ContextSgMethods, LRCallbackBase
  54. from super_gradients.common.environment import environment_config
  55. from super_gradients.training.utils import HpmStruct
  56. from super_gradients.training.datasets.samplers.infinite_sampler import InfiniteSampler
  57. logger = get_logger(__name__)
  58. class Trainer:
  59. """
  60. SuperGradient Model - Base Class for Sg Models
  61. Methods
  62. -------
  63. train(max_epochs : int, initial_epoch : int, save_model : bool)
  64. the main function used for the training, h.p. updating, logging etc.
  65. predict(idx : int)
  66. returns the predictions and label of the current inputs
  67. test(epoch : int, idx : int, save : bool):
  68. returns the test loss, accuracy and runtime
  69. """
  70. def __init__(self, experiment_name: str, device: str = None, multi_gpu: Union[MultiGPUMode, str] = MultiGPUMode.OFF,
  71. model_checkpoints_location: str = 'local',
  72. overwrite_local_checkpoint: bool = True, ckpt_name: str = 'ckpt_latest.pth',
  73. post_prediction_callback: DetectionPostPredictionCallback = None, ckpt_root_dir: str = None,
  74. train_loader: DataLoader = None, valid_loader: DataLoader = None, test_loader: DataLoader = None,
  75. classes: List[Any] = None):
  76. """
  77. :param experiment_name: Used for logging and loading purposes
  78. :param device: If equal to 'cpu' runs on the CPU otherwise on GPU
  79. :param multi_gpu: If True, runs on all available devices
  80. :param model_checkpoints_location: If set to 's3' saves the Checkpoints in AWS S3
  81. otherwise saves the Checkpoints Locally
  82. :param overwrite_local_checkpoint: If set to False keeps the current local checkpoint when importing
  83. checkpoint from cloud service, otherwise overwrites the local checkpoints file
  84. :param ckpt_name: The Checkpoint to Load
  85. :param ckpt_root_dir: Local root directory path where all experiment logging directories will
  86. reside. When none is give, it is assumed that
  87. pkg_resources.resource_filename('checkpoints', "") exists and will be used.
  88. :param train_loader: Training set Dataloader instead of using DatasetInterface, must pass "valid_loader"
  89. and "classes" along with it
  90. :param valid_loader: Validation set Dataloader
  91. :param test_loader: Test set Dataloader
  92. :param classes: List of class labels
  93. """
  94. # SET THE EMPTY PROPERTIES
  95. self.net, self.architecture, self.arch_params, self.dataset_interface = None, None, None, None
  96. self.device, self.multi_gpu = None, None
  97. self.ema = None
  98. self.ema_model = None
  99. self.sg_logger = None
  100. self.update_param_groups = None
  101. self.post_prediction_callback = None
  102. self.criterion = None
  103. self.training_params = None
  104. self.scaler = None
  105. self.phase_callbacks = None
  106. self.checkpoint_params = None
  107. self.pre_prediction_callback = None
  108. # SET THE DEFAULT PROPERTIES
  109. self.half_precision = False
  110. self.load_checkpoint = False
  111. self.load_backbone = False
  112. self.load_weights_only = False
  113. self.ddp_silent_mode = False
  114. self.source_ckpt_folder_name = None
  115. self.model_weight_averaging = None
  116. self.average_model_checkpoint_filename = 'average_model.pth'
  117. self.start_epoch = 0
  118. self.best_metric = np.inf
  119. self.external_checkpoint_path = None
  120. self.strict_load = StrictLoad.ON
  121. self.load_ema_as_net = False
  122. self.ckpt_best_name = 'ckpt_best.pth'
  123. self.enable_qat = False
  124. self.qat_params = {}
  125. self._infinite_train_loader = False
  126. # DETERMINE THE LOCATION OF THE LOSS AND ACCURACY IN THE RESULTS TUPLE OUTPUTED BY THE TEST
  127. self.loss_idx_in_results_tuple, self.acc_idx_in_results_tuple = None, None
  128. # METRICS
  129. self.loss_logging_items_names = None
  130. self.train_metrics = None
  131. self.valid_metrics = None
  132. self.greater_metric_to_watch_is_better = None
  133. # SETTING THE PROPERTIES FROM THE CONSTRUCTOR
  134. self.experiment_name = experiment_name
  135. self.ckpt_name = ckpt_name
  136. self.overwrite_local_checkpoint = overwrite_local_checkpoint
  137. self.model_checkpoints_location = model_checkpoints_location
  138. self._set_dataset_properties(classes, test_loader, train_loader, valid_loader)
  139. # CREATING THE LOGGING DIR BASED ON THE INPUT PARAMS TO PREVENT OVERWRITE OF LOCAL VERSION
  140. if ckpt_root_dir:
  141. self.checkpoints_dir_path = os.path.join(ckpt_root_dir, self.experiment_name)
  142. elif os.path.exists(environment_config.PKG_CHECKPOINTS_DIR):
  143. self.checkpoints_dir_path = os.path.join(environment_config.PKG_CHECKPOINTS_DIR, self.experiment_name)
  144. else:
  145. raise ValueError("Illegal checkpoints directory: pass ckpt_root_dir that exists, or add 'checkpoints' to"
  146. "resources.")
  147. # INITIALIZE THE DEVICE FOR THE MODEL
  148. self._initialize_device(requested_device=device, requested_multi_gpu=multi_gpu)
  149. self.post_prediction_callback = post_prediction_callback
  150. # SET THE DEFAULTS
  151. # TODO: SET DEFAULT TRAINING PARAMS FOR EACH TASK
  152. default_results_titles = ['Train Loss', 'Train Acc', 'Train Top5', 'Valid Loss', 'Valid Acc', 'Valid Top5']
  153. self.results_titles = default_results_titles
  154. self.loss_idx_in_results_tuple, self.acc_idx_in_results_tuple = 0, 1
  155. default_train_metrics, default_valid_metrics = MetricCollection([Accuracy(), Top5()]), MetricCollection(
  156. [Accuracy(), Top5()])
  157. default_loss_logging_items_names = ["Loss"]
  158. self.train_metrics, self.valid_metrics = default_train_metrics, default_valid_metrics
  159. self.loss_logging_items_names = default_loss_logging_items_names
  160. self.train_monitored_values = {}
  161. self.valid_monitored_values = {}
  162. @classmethod
  163. def train_from_config(cls, cfg: Union[DictConfig, dict]) -> None:
  164. """
  165. Trains according to cfg recipe configuration.
  166. @param cfg: The parsed DictConfig from yaml recipe files or a dictionary
  167. @return: output of trainer.train(...) (i.e results tuple)
  168. """
  169. setup_gpu_mode(gpu_mode=core_utils.get_param(cfg, 'multi_gpu', MultiGPUMode.OFF),
  170. num_gpus=core_utils.get_param(cfg, 'num_gpus'))
  171. # INSTANTIATE ALL OBJECTS IN CFG
  172. cfg = hydra.utils.instantiate(cfg)
  173. kwargs = parse_args(cfg, cls.__init__)
  174. trainer = Trainer(**kwargs)
  175. # INSTANTIATE DATA LOADERS
  176. train_dataloader = dataloaders.get(name=cfg.train_dataloader,
  177. dataset_params=cfg.dataset_params.train_dataset_params,
  178. dataloader_params=cfg.dataset_params.train_dataloader_params)
  179. val_dataloader = dataloaders.get(name=cfg.val_dataloader,
  180. dataset_params=cfg.dataset_params.val_dataset_params,
  181. dataloader_params=cfg.dataset_params.val_dataloader_params)
  182. # BUILD NETWORK
  183. model = models.get(model_name=cfg.architecture,
  184. num_classes=cfg.arch_params.num_classes,
  185. arch_params=cfg.arch_params,
  186. strict_load=cfg.checkpoint_params.strict_load,
  187. pretrained_weights=cfg.checkpoint_params.pretrained_weights,
  188. checkpoint_path=cfg.checkpoint_params.checkpoint_path,
  189. load_backbone=cfg.checkpoint_params.load_backbone
  190. )
  191. # TRAIN
  192. trainer.train(model=model,
  193. train_loader=train_dataloader,
  194. valid_loader=val_dataloader,
  195. training_params=cfg.training_hyperparams)
  196. def _set_dataset_properties(self, classes, test_loader, train_loader, valid_loader):
  197. if any([train_loader, valid_loader, classes]) and not all([train_loader, valid_loader, classes]):
  198. raise IllegalDataloaderInitialization()
  199. dataset_params = {"batch_size": train_loader.batch_size if train_loader else None,
  200. "val_batch_size": valid_loader.batch_size if valid_loader else None,
  201. "test_batch_size": test_loader.batch_size if test_loader else None,
  202. "dataset_dir": None,
  203. "s3_link": None}
  204. if train_loader and self.multi_gpu == MultiGPUMode.DISTRIBUTED_DATA_PARALLEL:
  205. if not all([isinstance(train_loader.sampler, DistributedSampler),
  206. isinstance(valid_loader.sampler, DistributedSampler),
  207. test_loader is None or isinstance(test_loader.sampler, DistributedSampler)]):
  208. logger.warning(
  209. "DDP training was selected but the dataloader samplers are not of type DistributedSamplers")
  210. self.dataset_params, self.train_loader, self.valid_loader, self.test_loader, self.classes = \
  211. HpmStruct(**dataset_params), train_loader, valid_loader, test_loader, classes
  212. def _set_ckpt_loading_attributes(self):
  213. """
  214. Sets checkpoint loading related attributes according to self.checkpoint_params
  215. """
  216. self.checkpoint = {}
  217. self.strict_load = core_utils.get_param(self.checkpoint_params, 'strict_load', default_val=StrictLoad.ON)
  218. self.load_ema_as_net = core_utils.get_param(self.checkpoint_params, 'load_ema_as_net', default_val=False)
  219. self.source_ckpt_folder_name = core_utils.get_param(self.checkpoint_params, 'source_ckpt_folder_name')
  220. self.load_checkpoint = core_utils.get_param(self.checkpoint_params, 'load_checkpoint', default_val=False)
  221. self.load_backbone = core_utils.get_param(self.checkpoint_params, 'load_backbone', default_val=False)
  222. self.external_checkpoint_path = core_utils.get_param(self.checkpoint_params, 'external_checkpoint_path')
  223. if self.load_checkpoint or self.external_checkpoint_path:
  224. self.load_weights_only = core_utils.get_param(self.checkpoint_params, 'load_weights_only',
  225. default_val=False)
  226. self.ckpt_name = core_utils.get_param(self.checkpoint_params, 'ckpt_name', default_val=self.ckpt_name)
  227. def _net_to_device(self):
  228. """
  229. Manipulates self.net according to self.multi_gpu
  230. """
  231. self.net.to(self.device)
  232. # FOR MULTI-GPU TRAINING (not distributed)
  233. self.arch_params.sync_bn = core_utils.get_param(self.arch_params, 'sync_bn', default_val=False)
  234. if self.multi_gpu == MultiGPUMode.DATA_PARALLEL:
  235. self.net = torch.nn.DataParallel(self.net, device_ids=self.device_ids)
  236. elif self.multi_gpu == MultiGPUMode.DISTRIBUTED_DATA_PARALLEL:
  237. if self.arch_params.sync_bn:
  238. if not self.ddp_silent_mode:
  239. logger.info('DDP - Using Sync Batch Norm... Training time will be affected accordingly')
  240. self.net = torch.nn.SyncBatchNorm.convert_sync_batchnorm(self.net).to(self.device)
  241. local_rank = int(self.device.split(':')[1])
  242. self.net = torch.nn.parallel.DistributedDataParallel(self.net,
  243. device_ids=[local_rank],
  244. output_device=local_rank,
  245. find_unused_parameters=True)
  246. else:
  247. self.net = core_utils.WrappedModel(self.net)
  248. def _train_epoch(self, epoch: int, silent_mode: bool = False) -> tuple:
  249. """
  250. train_epoch - A single epoch training procedure
  251. :param optimizer: The optimizer for the network
  252. :param epoch: The current epoch
  253. :param silent_mode: No verbosity
  254. """
  255. # SET THE MODEL IN training STATE
  256. self.net.train()
  257. # THE DISABLE FLAG CONTROLS WHETHER THE PROGRESS BAR IS SILENT OR PRINTS THE LOGS
  258. progress_bar_train_loader = tqdm(self.train_loader, bar_format="{l_bar}{bar:10}{r_bar}", dynamic_ncols=True,
  259. disable=silent_mode)
  260. progress_bar_train_loader.set_description(f"Train epoch {epoch}")
  261. # RESET/INIT THE METRIC LOGGERS
  262. self._reset_metrics()
  263. self.train_metrics.to(self.device)
  264. loss_avg_meter = core_utils.utils.AverageMeter()
  265. context = PhaseContext(epoch=epoch,
  266. optimizer=self.optimizer,
  267. metrics_compute_fn=self.train_metrics,
  268. loss_avg_meter=loss_avg_meter,
  269. criterion=self.criterion,
  270. device=self.device,
  271. lr_warmup_epochs=self.training_params.lr_warmup_epochs,
  272. sg_logger=self.sg_logger,
  273. train_loader=self.train_loader,
  274. context_methods=self._get_context_methods(Phase.TRAIN_BATCH_END),
  275. ddp_silent_mode=self.ddp_silent_mode)
  276. for batch_idx, batch_items in enumerate(progress_bar_train_loader):
  277. batch_items = core_utils.tensor_container_to_device(batch_items, self.device, non_blocking=True)
  278. inputs, targets, additional_batch_items = sg_trainer_utils.unpack_batch_items(batch_items)
  279. if self.pre_prediction_callback is not None:
  280. inputs, targets = self.pre_prediction_callback(inputs, targets, batch_idx)
  281. # AUTOCAST IS ENABLED ONLY IF self.training_params.mixed_precision - IF enabled=False AUTOCAST HAS NO EFFECT
  282. with autocast(enabled=self.training_params.mixed_precision):
  283. # FORWARD PASS TO GET NETWORK'S PREDICTIONS
  284. outputs = self.net(inputs)
  285. # COMPUTE THE LOSS FOR BACK PROP + EXTRA METRICS COMPUTED DURING THE LOSS FORWARD PASS
  286. loss, loss_log_items = self._get_losses(outputs, targets)
  287. context.update_context(batch_idx=batch_idx,
  288. inputs=inputs,
  289. preds=outputs,
  290. target=targets,
  291. loss_log_items=loss_log_items,
  292. **additional_batch_items)
  293. self.phase_callback_handler(Phase.TRAIN_BATCH_END, context)
  294. # LOG LR THAT WILL BE USED IN CURRENT EPOCH AND AFTER FIRST WARMUP/LR_SCHEDULER UPDATE BEFORE WEIGHT UPDATE
  295. if not self.ddp_silent_mode and batch_idx == 0:
  296. self._write_lrs(epoch)
  297. self._backward_step(loss, epoch, batch_idx, context)
  298. # COMPUTE THE RUNNING USER METRICS AND LOSS RUNNING ITEMS. RESULT TUPLE IS THEIR CONCATENATION.
  299. logging_values = loss_avg_meter.average + get_metrics_results_tuple(self.train_metrics)
  300. gpu_memory_utilization = torch.cuda.memory_cached() / 1E9 if torch.cuda.is_available() else 0
  301. # RENDER METRICS PROGRESS
  302. pbar_message_dict = get_train_loop_description_dict(logging_values,
  303. self.train_metrics,
  304. self.loss_logging_items_names,
  305. gpu_mem=gpu_memory_utilization)
  306. progress_bar_train_loader.set_postfix(**pbar_message_dict)
  307. # TODO: ITERATE BY MAX ITERS
  308. # FOR INFINITE SAMPLERS WE MUST BREAK WHEN REACHING LEN ITERATIONS.
  309. if self._infinite_train_loader and batch_idx == len(self.train_loader) - 1:
  310. break
  311. if not self.ddp_silent_mode:
  312. self.sg_logger.upload()
  313. self.train_monitored_values = sg_trainer_utils.update_monitored_values_dict(
  314. monitored_values_dict=self.train_monitored_values, new_values_dict=pbar_message_dict)
  315. return logging_values
  316. def _get_losses(self, outputs: torch.Tensor, targets: torch.Tensor) -> Tuple[torch.Tensor, tuple]:
  317. # GET THE OUTPUT OF THE LOSS FUNCTION
  318. loss = self.criterion(outputs, targets)
  319. if isinstance(loss, tuple):
  320. loss, loss_logging_items = loss
  321. # IF ITS NOT A TUPLE THE LOGGING ITEMS CONTAIN ONLY THE LOSS FOR BACKPROP (USER DEFINED LOSS RETURNS SCALAR)
  322. else:
  323. loss_logging_items = loss.unsqueeze(0).detach()
  324. if len(loss_logging_items) != len(self.loss_logging_items_names):
  325. raise ValueError("Loss output length must match loss_logging_items_names. Got " + str(
  326. len(loss_logging_items)) + ', and ' + str(len(self.loss_logging_items_names)))
  327. # RETURN AND THE LOSS LOGGING ITEMS COMPUTED DURING LOSS FORWARD PASS
  328. return loss, loss_logging_items
  329. def _backward_step(self, loss: torch.Tensor, epoch: int, batch_idx: int, context: PhaseContext, *args, **kwargs):
  330. """
  331. Run backprop on the loss and perform a step
  332. :param loss: The value computed by the loss function
  333. :param optimizer: An object that can perform a gradient step and zeroize model gradient
  334. :param epoch: number of epoch the training is on
  335. :param batch_idx: number of iteration inside the current epoch
  336. :param context: current phase context
  337. :return:
  338. """
  339. # SCALER IS ENABLED ONLY IF self.training_params.mixed_precision=True
  340. self.scaler.scale(loss).backward()
  341. # APPLY GRADIENT CLIPPING IF REQUIRED
  342. if self.training_params.clip_grad_norm:
  343. torch.nn.utils.clip_grad_norm_(self.net.parameters(), self.training_params.clip_grad_norm)
  344. # ACCUMULATE GRADIENT FOR X BATCHES BEFORE OPTIMIZING
  345. integrated_batches_num = batch_idx + len(self.train_loader) * epoch + 1
  346. if integrated_batches_num % self.batch_accumulate == 0:
  347. # SCALER IS ENABLED ONLY IF self.training_params.mixed_precision=True
  348. self.scaler.step(self.optimizer)
  349. self.scaler.update()
  350. self.optimizer.zero_grad()
  351. if self.ema:
  352. self.ema_model.update(self.net, integrated_batches_num / (len(self.train_loader) * self.max_epochs))
  353. # RUN PHASE CALLBACKS
  354. self.phase_callback_handler(Phase.TRAIN_BATCH_STEP, context)
  355. def _save_checkpoint(self, optimizer=None, epoch: int = None, validation_results_tuple: tuple = None,
  356. context: PhaseContext = None):
  357. """
  358. Save the current state dict as latest (always), best (if metric was improved), epoch# (if determined in training
  359. params)
  360. """
  361. # WHEN THE validation_results_tuple IS NONE WE SIMPLY SAVE THE state_dict AS LATEST AND Return
  362. if validation_results_tuple is None:
  363. self.sg_logger.add_checkpoint(tag='ckpt_latest_weights_only.pth', state_dict={'net': self.net.state_dict()},
  364. global_step=epoch)
  365. return
  366. # COMPUTE THE CURRENT metric
  367. # IF idx IS A LIST - SUM ALL THE VALUES STORED IN THE LIST'S INDICES
  368. metric = validation_results_tuple[self.metric_idx_in_results_tuple] if isinstance(
  369. self.metric_idx_in_results_tuple, int) else \
  370. sum([validation_results_tuple[idx] for idx in self.metric_idx_in_results_tuple])
  371. # BUILD THE state_dict
  372. state = {'net': self.net.state_dict(), 'acc': metric, 'epoch': epoch}
  373. if optimizer is not None:
  374. state['optimizer_state_dict'] = optimizer.state_dict()
  375. if self.scaler is not None:
  376. state['scaler_state_dict'] = self.scaler.state_dict()
  377. if self.ema:
  378. state['ema_net'] = self.ema_model.ema.state_dict()
  379. # SAVES CURRENT MODEL AS ckpt_latest
  380. self.sg_logger.add_checkpoint(tag='ckpt_latest.pth', state_dict=state, global_step=epoch)
  381. # SAVE MODEL AT SPECIFIC EPOCHS DETERMINED BY save_ckpt_epoch_list
  382. if epoch in self.training_params.save_ckpt_epoch_list:
  383. self.sg_logger.add_checkpoint(tag=f'ckpt_epoch_{epoch}.pth', state_dict=state, global_step=epoch)
  384. # OVERRIDE THE BEST CHECKPOINT AND best_metric IF metric GOT BETTER THAN THE PREVIOUS BEST
  385. if (metric > self.best_metric and self.greater_metric_to_watch_is_better) or (
  386. metric < self.best_metric and not self.greater_metric_to_watch_is_better):
  387. # STORE THE CURRENT metric AS BEST
  388. self.best_metric = metric
  389. self._save_best_checkpoint(epoch, state)
  390. # RUN PHASE CALLBACKS
  391. self.phase_callback_handler(Phase.VALIDATION_END_BEST_EPOCH, context)
  392. if isinstance(metric, torch.Tensor):
  393. metric = metric.item()
  394. logger.info("Best checkpoint overriden: validation " + self.metric_to_watch + ": " + str(metric))
  395. if self.training_params.average_best_models:
  396. net_for_averaging = self.ema_model.ema if self.ema else self.net
  397. averaged_model_sd = self.model_weight_averaging.get_average_model(net_for_averaging,
  398. validation_results_tuple=validation_results_tuple)
  399. self.sg_logger.add_checkpoint(tag=self.average_model_checkpoint_filename,
  400. state_dict={'net': averaged_model_sd}, global_step=epoch)
  401. def _save_best_checkpoint(self, epoch, state):
  402. self.sg_logger.add_checkpoint(tag=self.ckpt_best_name, state_dict=state, global_step=epoch)
  403. def _prep_net_for_train(self):
  404. if self.arch_params is None:
  405. self._init_arch_params()
  406. # TODO: REMOVE THE BELOW LINE (FOR BACKWARD COMPATIBILITY)
  407. if self.checkpoint_params is None:
  408. self.checkpoint_params = HpmStruct(load_checkpoint=self.training_params.resume)
  409. self._net_to_device()
  410. # SET THE FLAG FOR DIFFERENT PARAMETER GROUP OPTIMIZER UPDATE
  411. self.update_param_groups = hasattr(self.net.module, 'update_param_groups')
  412. self.checkpoint = {}
  413. self.strict_load = core_utils.get_param(self.training_params, "resume_strict_load", StrictLoad.ON)
  414. self.load_ema_as_net = False
  415. self.load_checkpoint = core_utils.get_param(self.training_params, "resume", False)
  416. self.external_checkpoint_path = core_utils.get_param(self.training_params, "resume_path")
  417. self._load_checkpoint_to_model()
  418. def _init_arch_params(self):
  419. default_arch_params = HpmStruct(sync_bn=False)
  420. arch_params = getattr(self.net, "arch_params", default_arch_params)
  421. self.arch_params = default_arch_params
  422. if arch_params is not None:
  423. self.arch_params.override(**arch_params.to_dict())
  424. # FIXME - we need to resolve flake8's 'function is too complex' for this function
  425. def train(self, model: nn.Module = None, training_params: dict = None, train_loader: DataLoader = None,
  426. valid_loader: DataLoader = None): # noqa: C901
  427. """
  428. train - Trains the Model
  429. IMPORTANT NOTE: Additional batch parameters can be added as a third item (optional) if a tuple is returned by
  430. the data loaders, as dictionary. The phase context will hold the additional items, under an attribute with
  431. the same name as the key in this dictionary. Then such items can be accessed through phase callbacks.
  432. :param model: torch.nn.Module, model to train. When none is given will attempt to use self.net
  433. (SEE BUILD_MODEL DEPRECATION) (default=None).
  434. :param train_loader: Dataloader for train set.
  435. :param valid_loader: Dataloader for validation.
  436. :param training_params:
  437. - `max_epochs` : int
  438. Number of epochs to run training.
  439. - `lr_updates` : list(int)
  440. List of fixed epoch numbers to perform learning rate updates when `lr_mode='step'`.
  441. - `lr_decay_factor` : float
  442. Decay factor to apply to the learning rate at each update when `lr_mode='step'`.
  443. - `lr_mode` : str
  444. Learning rate scheduling policy, one of ['step','poly','cosine','function']. 'step' refers to
  445. constant updates at epoch numbers passed through `lr_updates`. 'cosine' refers to Cosine Anealing
  446. policy as mentioned in https://arxiv.org/abs/1608.03983. 'poly' refers to polynomial decrease i.e
  447. in each epoch iteration `self.lr = self.initial_lr * pow((1.0 - (current_iter / max_iter)),
  448. 0.9)` 'function' refers to user defined learning rate scheduling function, that is passed through
  449. `lr_schedule_function`.
  450. - `lr_schedule_function` : Union[callable,None]
  451. Learning rate scheduling function to be used when `lr_mode` is 'function'.
  452. - `lr_warmup_epochs` : int (default=0)
  453. Number of epochs for learning rate warm up - see https://arxiv.org/pdf/1706.02677.pdf (Section 2.2).
  454. - `cosine_final_lr_ratio` : float (default=0.01)
  455. Final learning rate ratio (only relevant when `lr_mode`='cosine'). The cosine starts from initial_lr and reaches
  456. initial_lr * cosine_final_lr_ratio in last epoch
  457. - `inital_lr` : float
  458. Initial learning rate.
  459. - `loss` : Union[nn.module, str]
  460. Loss function for training.
  461. One of SuperGradient's built in options:
  462. "cross_entropy": LabelSmoothingCrossEntropyLoss,
  463. "mse": MSELoss,
  464. "r_squared_loss": RSquaredLoss,
  465. "detection_loss": YoLoV3DetectionLoss,
  466. "shelfnet_ohem_loss": ShelfNetOHEMLoss,
  467. "shelfnet_se_loss": ShelfNetSemanticEncodingLoss,
  468. "ssd_loss": SSDLoss,
  469. or user defined nn.module loss function.
  470. IMPORTANT: forward(...) should return a (loss, loss_items) tuple where loss is the tensor used
  471. for backprop (i.e what your original loss function returns), and loss_items should be a tensor of
  472. shape (n_items), of values computed during the forward pass which we desire to log over the
  473. entire epoch. For example- the loss itself should always be logged. Another example is a scenario
  474. where the computed loss is the sum of a few components we would like to log- these entries in
  475. loss_items).
  476. When training, set the loss_logging_items_names parameter in train_params to be a list of
  477. strings, of length n_items who's ith element is the name of the ith entry in loss_items. Then
  478. each item will be logged, rendered on tensorboard and "watched" (i.e saving model checkpoints
  479. according to it).
  480. Since running logs will save the loss_items in some internal state, it is recommended that
  481. loss_items are detached from their computational graph for memory efficiency.
  482. - `optimizer` : Union[str, torch.optim.Optimizer]
  483. Optimization algorithm. One of ['Adam','SGD','RMSProp'] corresponding to the torch.optim
  484. optimzers implementations, or any object that implements torch.optim.Optimizer.
  485. - `criterion_params` : dict
  486. Loss function parameters.
  487. - `optimizer_params` : dict
  488. When `optimizer` is one of ['Adam','SGD','RMSProp'], it will be initialized with optimizer_params.
  489. (see https://pytorch.org/docs/stable/optim.html for the full list of
  490. parameters for each optimizer).
  491. - `train_metrics_list` : list(torchmetrics.Metric)
  492. Metrics to log during training. For more information on torchmetrics see
  493. https://torchmetrics.rtfd.io/en/latest/.
  494. - `valid_metrics_list` : list(torchmetrics.Metric)
  495. Metrics to log during validation/testing. For more information on torchmetrics see
  496. https://torchmetrics.rtfd.io/en/latest/.
  497. - `loss_logging_items_names` : list(str)
  498. The list of names/titles for the outputs returned from the loss functions forward pass (reminder-
  499. the loss function should return the tuple (loss, loss_items)). These names will be used for
  500. logging their values.
  501. - `metric_to_watch` : str (default="Accuracy")
  502. will be the metric which the model checkpoint will be saved according to, and can be set to any
  503. of the following:
  504. a metric name (str) of one of the metric objects from the valid_metrics_list
  505. a "metric_name" if some metric in valid_metrics_list has an attribute component_names which
  506. is a list referring to the names of each entry in the output metric (torch tensor of size n)
  507. one of "loss_logging_items_names" i.e which will correspond to an item returned during the
  508. loss function's forward pass.
  509. At the end of each epoch, if a new best metric_to_watch value is achieved, the models checkpoint
  510. is saved in YOUR_PYTHON_PATH/checkpoints/ckpt_best.pth
  511. - `greater_metric_to_watch_is_better` : bool
  512. When choosing a model's checkpoint to be saved, the best achieved model is the one that maximizes the
  513. metric_to_watch when this parameter is set to True, and a one that minimizes it otherwise.
  514. - `ema` : bool (default=False)
  515. Whether to use Model Exponential Moving Average (see
  516. https://github.com/rwightman/pytorch-image-models ema implementation)
  517. - `batch_accumulate` : int (default=1)
  518. Number of batches to accumulate before every backward pass.
  519. - `ema_params` : dict
  520. Parameters for the ema model.
  521. - `zero_weight_decay_on_bias_and_bn` : bool (default=False)
  522. Whether to apply weight decay on batch normalization parameters or not (ignored when the passed
  523. optimizer has already been initialized).
  524. - `load_opt_params` : bool (default=True)
  525. Whether to load the optimizers parameters as well when loading a model's checkpoint.
  526. - `run_validation_freq` : int (default=1)
  527. The frequency in which validation is performed during training (i.e the validation is ran every
  528. `run_validation_freq` epochs.
  529. - `save_model` : bool (default=True)
  530. Whether to save the model checkpoints.
  531. - `silent_mode` : bool
  532. Silents the print outs.
  533. - `mixed_precision` : bool
  534. Whether to use mixed precision or not.
  535. - `save_ckpt_epoch_list` : list(int) (default=[])
  536. List of fixed epoch indices the user wishes to save checkpoints in.
  537. - `average_best_models` : bool (default=False)
  538. If set, a snapshot dictionary file and the average model will be saved / updated at every epoch
  539. and evaluated only when training is completed. The snapshot file will only be deleted upon
  540. completing the training. The snapshot dict will be managed on cpu.
  541. - `precise_bn` : bool (default=False)
  542. Whether to use precise_bn calculation during the training.
  543. - `precise_bn_batch_size` : int (default=None)
  544. The effective batch size we want to calculate the batchnorm on. For example, if we are training a model
  545. on 8 gpus, with a batch of 128 on each gpu, a good rule of thumb would be to give it 8192
  546. (ie: effective_batch_size * num_gpus = batch_per_gpu * num_gpus * num_gpus).
  547. If precise_bn_batch_size is not provided in the training_params, the latter heuristic will be taken.
  548. - `seed` : int (default=42)
  549. Random seed to be set for torch, numpy, and random. When using DDP each process will have it's seed
  550. set to seed + rank.
  551. - `log_installed_packages` : bool (default=False)
  552. When set, the list of all installed packages (and their versions) will be written to the tensorboard
  553. and logfile (useful when trying to reproduce results).
  554. - `dataset_statistics` : bool (default=False)
  555. Enable a statistic analysis of the dataset. If set to True the dataset will be analyzed and a report
  556. will be added to the tensorboard along with some sample images from the dataset. Currently only
  557. detection datasets are supported for analysis.
  558. - `save_full_train_log` : bool (default=False)
  559. When set, a full log (of all super_gradients modules, including uncaught exceptions from any other
  560. module) of the training will be saved in the checkpoint directory under full_train_log.log
  561. - `sg_logger` : Union[AbstractSGLogger, str] (defauls=base_sg_logger)
  562. Define the SGLogger object for this training process. The SGLogger handles all disk writes, logs, TensorBoard, remote logging
  563. and remote storage. By overriding the default base_sg_logger, you can change the storage location, support external monitoring and logging
  564. or support remote storage.
  565. - `sg_logger_params` : dict
  566. SGLogger parameters
  567. - `clip_grad_norm` : float
  568. Defines a maximal L2 norm of the gradients. Values which exceed the given value will be clipped
  569. - `lr_cooldown_epochs` : int (default=0)
  570. Number of epochs to cooldown LR (i.e the last epoch from scheduling view point=max_epochs-cooldown).
  571. - `pre_prediction_callback` : Callable (default=None)
  572. When not None, this callback will be applied to images and targets, and returning them to be used
  573. for the forward pass, and further computations. Args for this callable should be in the order
  574. (inputs, targets, batch_idx) returning modified_inputs, modified_targets
  575. - `ckpt_best_name` : str (default='ckpt_best.pth')
  576. The best checkpoint (according to metric_to_watch) will be saved under this filename in the checkpoints directory.
  577. - `enable_qat`: bool (default=False)
  578. Adds a QATCallback to the phase callbacks, that triggers quantization aware training starting from
  579. qat_params["start_epoch"]
  580. - `qat_params`: dict-like object with the following key/values:
  581. start_epoch: int, first epoch to start QAT.
  582. quant_modules_calib_method: str, One of [percentile, mse, entropy, max]. Statistics method for amax
  583. computation of the quantized modules (default=percentile).
  584. per_channel_quant_modules: bool, whether quant modules should be per channel (default=False).
  585. calibrate: bool, whether to perfrom calibration (default=False).
  586. calibrated_model_path: str, path to a calibrated checkpoint (default=None).
  587. calib_data_loader: torch.utils.data.DataLoader, data loader of the calibration dataset. When None,
  588. context.train_loader will be used (default=None).
  589. num_calib_batches: int, number of batches to collect the statistics from.
  590. percentile: float, percentile value to use when Trainer,quant_modules_calib_method='percentile'.
  591. Discarded when other methods are used (Default=99.99).
  592. :return:
  593. """
  594. global logger
  595. if training_params is None:
  596. training_params = dict()
  597. self.train_loader = train_loader or self.train_loader
  598. self.valid_loader = valid_loader or self.valid_loader
  599. self.training_params = TrainingParams()
  600. self.training_params.override(**training_params)
  601. if self.net is None:
  602. self.net = model
  603. self._prep_net_for_train()
  604. # SET RANDOM SEED
  605. random_seed(is_ddp=self.multi_gpu == MultiGPUMode.DISTRIBUTED_DATA_PARALLEL,
  606. device=self.device, seed=self.training_params.seed)
  607. silent_mode = self.training_params.silent_mode or self.ddp_silent_mode
  608. # METRICS
  609. self._set_train_metrics(train_metrics_list=self.training_params.train_metrics_list)
  610. self._set_valid_metrics(valid_metrics_list=self.training_params.valid_metrics_list)
  611. self.loss_logging_items_names = self.training_params.loss_logging_items_names
  612. self.results_titles = ["Train_" + t for t in
  613. self.loss_logging_items_names + get_metrics_titles(self.train_metrics)] + \
  614. ["Valid_" + t for t in
  615. self.loss_logging_items_names + get_metrics_titles(self.valid_metrics)]
  616. # Store the metric to follow (loss\accuracy) and initialize as the worst value
  617. self.metric_to_watch = self.training_params.metric_to_watch
  618. self.greater_metric_to_watch_is_better = self.training_params.greater_metric_to_watch_is_better
  619. self.metric_idx_in_results_tuple = (self.loss_logging_items_names + get_metrics_titles(self.valid_metrics)).index(self.metric_to_watch)
  620. # Instantiate the values to monitor (loss/metric)
  621. for loss in self.loss_logging_items_names:
  622. self.train_monitored_values[loss] = MonitoredValue(name=loss, greater_is_better=False)
  623. self.valid_monitored_values[loss] = MonitoredValue(name=loss, greater_is_better=False)
  624. self.valid_monitored_values[self.metric_to_watch] = MonitoredValue(name=self.metric_to_watch,
  625. greater_is_better=True)
  626. # Allowing loading instantiated loss or string
  627. if isinstance(self.training_params.loss, str):
  628. criterion_cls = LOSSES[self.training_params.loss]
  629. self.criterion = criterion_cls(**self.training_params.criterion_params)
  630. elif isinstance(self.training_params.loss, Mapping):
  631. self.criterion = LossesFactory().get(self.training_params.loss)
  632. elif isinstance(self.training_params.loss, nn.Module):
  633. self.criterion = self.training_params.loss
  634. self.criterion.to(self.device)
  635. self.max_epochs = self.training_params.max_epochs
  636. self.ema = self.training_params.ema
  637. self.precise_bn = self.training_params.precise_bn
  638. self.precise_bn_batch_size = self.training_params.precise_bn_batch_size
  639. self.batch_accumulate = self.training_params.batch_accumulate
  640. num_batches = len(self.train_loader)
  641. if self.ema:
  642. ema_params = self.training_params.ema_params
  643. logger.info(f'Using EMA with params {ema_params}')
  644. self.ema_model = self._instantiate_ema_model(**ema_params)
  645. self.ema_model.updates = self.start_epoch * num_batches // self.batch_accumulate
  646. if self.load_checkpoint:
  647. if 'ema_net' in self.checkpoint.keys():
  648. self.ema_model.ema.load_state_dict(self.checkpoint['ema_net'])
  649. else:
  650. self.ema = False
  651. logger.warning(
  652. "[Warning] Checkpoint does not include EMA weights, continuing training without EMA.")
  653. self.run_validation_freq = self.training_params.run_validation_freq
  654. validation_results_tuple = (0, 0)
  655. inf_time = 0
  656. timer = core_utils.Timer(self.device)
  657. # IF THE LR MODE IS NOT DEFAULT TAKE IT FROM THE TRAINING PARAMS
  658. self.lr_mode = self.training_params.lr_mode
  659. load_opt_params = self.training_params.load_opt_params
  660. self.phase_callbacks = self.training_params.phase_callbacks or []
  661. self.phase_callbacks = ListFactory(CallbacksFactory()).get(self.phase_callbacks)
  662. if self.lr_mode is not None:
  663. sg_lr_callback_cls = LR_SCHEDULERS_CLS_DICT[self.lr_mode]
  664. self.phase_callbacks.append(sg_lr_callback_cls(train_loader_len=len(self.train_loader),
  665. net=self.net,
  666. training_params=self.training_params,
  667. update_param_groups=self.update_param_groups,
  668. **self.training_params.to_dict()))
  669. if self.training_params.lr_warmup_epochs > 0:
  670. warmup_mode = self.training_params.warmup_mode
  671. if isinstance(warmup_mode, str):
  672. warmup_callback_cls = LR_WARMUP_CLS_DICT[warmup_mode]
  673. elif isinstance(warmup_mode, type) and issubclass(warmup_mode, LRCallbackBase):
  674. warmup_callback_cls = warmup_mode
  675. else:
  676. raise RuntimeError('warmup_mode has to be either a name of a mode (str) or a subclass of PhaseCallback')
  677. self.phase_callbacks.append(warmup_callback_cls(train_loader_len=len(self.train_loader),
  678. net=self.net,
  679. training_params=self.training_params,
  680. update_param_groups=self.update_param_groups,
  681. **self.training_params.to_dict()))
  682. self._add_metrics_update_callback(Phase.TRAIN_BATCH_END)
  683. self._add_metrics_update_callback(Phase.VALIDATION_BATCH_END)
  684. # ADD CALLBACK FOR QAT
  685. self.enable_qat = core_utils.get_param(self.training_params, "enable_qat", False)
  686. if self.enable_qat:
  687. self.qat_params = core_utils.get_param(self.training_params, "qat_params")
  688. if self.qat_params is None:
  689. raise ValueError("Must pass QAT params when enable_qat=True")
  690. self.phase_callbacks.append(QATCallback(**self.qat_params))
  691. self.phase_callback_handler = CallbackHandler(callbacks=self.phase_callbacks)
  692. if not self.ddp_silent_mode:
  693. self._initialize_sg_logger_objects()
  694. if self.training_params.dataset_statistics:
  695. dataset_statistics_logger = DatasetStatisticsTensorboardLogger(self.sg_logger)
  696. dataset_statistics_logger.analyze(self.train_loader, all_classes=self.classes,
  697. title="Train-set", anchors=self.net.module.arch_params.anchors)
  698. dataset_statistics_logger.analyze(self.valid_loader, all_classes=self.classes,
  699. title="val-set")
  700. # AVERAGE BEST 10 MODELS PARAMS
  701. if self.training_params.average_best_models:
  702. self.model_weight_averaging = ModelWeightAveraging(self.checkpoints_dir_path,
  703. greater_is_better=self.greater_metric_to_watch_is_better,
  704. source_ckpt_folder_name=self.source_ckpt_folder_name,
  705. metric_to_watch=self.metric_to_watch,
  706. metric_idx=self.metric_idx_in_results_tuple,
  707. load_checkpoint=self.load_checkpoint,
  708. model_checkpoints_location=self.model_checkpoints_location)
  709. if self.training_params.save_full_train_log and not self.ddp_silent_mode:
  710. logger = get_logger(__name__,
  711. training_log_path=self.sg_logger.log_file_path.replace('.txt', 'full_train_log.log'))
  712. sg_trainer_utils.log_uncaught_exceptions(logger)
  713. if not self.load_checkpoint or self.load_weights_only:
  714. # WHEN STARTING TRAINING FROM SCRATCH, DO NOT LOAD OPTIMIZER PARAMS (EVEN IF LOADING BACKBONE)
  715. self.start_epoch = 0
  716. self._reset_best_metric()
  717. load_opt_params = False
  718. if isinstance(self.training_params.optimizer, str) or \
  719. (inspect.isclass(self.training_params.optimizer) and issubclass(self.training_params.optimizer,
  720. torch.optim.Optimizer)):
  721. self.optimizer = build_optimizer(net=self.net, lr=self.training_params.initial_lr,
  722. training_params=self.training_params)
  723. elif isinstance(self.training_params.optimizer, torch.optim.Optimizer):
  724. self.optimizer = self.training_params.optimizer
  725. else:
  726. raise UnsupportedOptimizerFormat()
  727. # VERIFY GRADIENT CLIPPING VALUE
  728. if self.training_params.clip_grad_norm is not None and self.training_params.clip_grad_norm <= 0:
  729. raise TypeError('Params', 'Invalid clip_grad_norm')
  730. if self.load_checkpoint and load_opt_params:
  731. self.optimizer.load_state_dict(self.checkpoint['optimizer_state_dict'])
  732. self.pre_prediction_callback = CallbacksFactory().get(self.training_params.pre_prediction_callback)
  733. self._initialize_mixed_precision(self.training_params.mixed_precision)
  734. self._infinite_train_loader = (hasattr(self.train_loader, "sampler") and isinstance(self.train_loader.sampler,
  735. InfiniteSampler)) or \
  736. (hasattr(self.train_loader, "batch_sampler") and isinstance(
  737. self.train_loader.batch_sampler.sampler, InfiniteSampler))
  738. self.ckpt_best_name = self.training_params.ckpt_best_name
  739. context = PhaseContext(optimizer=self.optimizer,
  740. net=self.net,
  741. experiment_name=self.experiment_name,
  742. ckpt_dir=self.checkpoints_dir_path,
  743. criterion=self.criterion,
  744. lr_warmup_epochs=self.training_params.lr_warmup_epochs,
  745. sg_logger=self.sg_logger,
  746. train_loader=self.train_loader,
  747. valid_loader=self.valid_loader,
  748. training_params=self.training_params,
  749. ddp_silent_mode=self.ddp_silent_mode,
  750. checkpoint_params=self.checkpoint_params,
  751. architecture=self.architecture,
  752. arch_params=self.arch_params,
  753. metric_idx_in_results_tuple=self.metric_idx_in_results_tuple,
  754. metric_to_watch=self.metric_to_watch,
  755. device=self.device,
  756. context_methods=self._get_context_methods(Phase.PRE_TRAINING),
  757. ema_model=self.ema_model)
  758. self.phase_callback_handler(Phase.PRE_TRAINING, context)
  759. try:
  760. # HEADERS OF THE TRAINING PROGRESS
  761. if not silent_mode:
  762. logger.info(
  763. f'Started training for {self.max_epochs - self.start_epoch} epochs ({self.start_epoch}/'f'{self.max_epochs - 1})\n')
  764. for epoch in range(self.start_epoch, self.max_epochs):
  765. if context.stop_training:
  766. logger.info("Request to stop training has been received, stopping training")
  767. break
  768. # Phase.TRAIN_EPOCH_START
  769. # RUN PHASE CALLBACKS
  770. context.update_context(epoch=epoch)
  771. self.phase_callback_handler(Phase.TRAIN_EPOCH_START, context)
  772. # IN DDP- SET_EPOCH WILL CAUSE EVERY PROCESS TO BE EXPOSED TO THE ENTIRE DATASET BY SHUFFLING WITH A
  773. # DIFFERENT SEED EACH EPOCH START
  774. if self.multi_gpu == MultiGPUMode.DISTRIBUTED_DATA_PARALLEL and hasattr(self.train_loader, "sampler") \
  775. and hasattr(self.train_loader.sampler, "set_epoch"):
  776. self.train_loader.sampler.set_epoch(epoch)
  777. train_metrics_tuple = self._train_epoch(epoch=epoch, silent_mode=silent_mode)
  778. # Phase.TRAIN_EPOCH_END
  779. # RUN PHASE CALLBACKS
  780. train_metrics_dict = get_metrics_dict(train_metrics_tuple, self.train_metrics,
  781. self.loss_logging_items_names)
  782. context.update_context(metrics_dict=train_metrics_dict)
  783. self.phase_callback_handler(Phase.TRAIN_EPOCH_END, context)
  784. # CALCULATE PRECISE BATCHNORM STATS
  785. if self.precise_bn:
  786. compute_precise_bn_stats(model=self.net, loader=self.train_loader,
  787. precise_bn_batch_size=self.precise_bn_batch_size,
  788. num_gpus=self.num_devices)
  789. if self.ema:
  790. compute_precise_bn_stats(model=self.ema_model.ema, loader=self.train_loader,
  791. precise_bn_batch_size=self.precise_bn_batch_size,
  792. num_gpus=self.num_devices)
  793. # model switch - we replace self.net.module with the ema model for the testing and saving part
  794. # and then switch it back before the next training epoch
  795. if self.ema:
  796. self.ema_model.update_attr(self.net)
  797. keep_model = self.net
  798. self.net = self.ema_model.ema
  799. # RUN TEST ON VALIDATION SET EVERY self.run_validation_freq EPOCHS
  800. if (epoch + 1) % self.run_validation_freq == 0:
  801. timer.start()
  802. validation_results_tuple = self._validate_epoch(epoch=epoch, silent_mode=silent_mode)
  803. inf_time = timer.stop()
  804. # Phase.VALIDATION_EPOCH_END
  805. # RUN PHASE CALLBACKS
  806. valid_metrics_dict = get_metrics_dict(validation_results_tuple, self.valid_metrics,
  807. self.loss_logging_items_names)
  808. context.update_context(metrics_dict=valid_metrics_dict)
  809. self.phase_callback_handler(Phase.VALIDATION_EPOCH_END, context)
  810. if self.ema:
  811. self.net = keep_model
  812. if not self.ddp_silent_mode:
  813. # SAVING AND LOGGING OCCURS ONLY IN THE MAIN PROCESS (IN CASES THERE ARE SEVERAL PROCESSES - DDP)
  814. self._write_to_disk_operations(train_metrics_tuple, validation_results_tuple, inf_time, epoch,
  815. context)
  816. # Evaluating the average model and removing snapshot averaging file if training is completed
  817. if self.training_params.average_best_models:
  818. self._validate_final_average_model(cleanup_snapshots_pkl_file=True)
  819. except KeyboardInterrupt:
  820. logger.info(
  821. '\n[MODEL TRAINING EXECUTION HAS BEEN INTERRUPTED]... Please wait until SOFT-TERMINATION process '
  822. 'finishes and saves all of the Model Checkpoints and log files before terminating...')
  823. logger.info('For HARD Termination - Stop the process again')
  824. finally:
  825. if self.multi_gpu == MultiGPUMode.DISTRIBUTED_DATA_PARALLEL:
  826. # CLEAN UP THE MULTI-GPU PROCESS GROUP WHEN DONE
  827. if torch.distributed.is_initialized():
  828. torch.distributed.destroy_process_group()
  829. # PHASE.TRAIN_END
  830. self.phase_callback_handler(Phase.POST_TRAINING, context)
  831. if not self.ddp_silent_mode:
  832. if self.model_checkpoints_location != 'local':
  833. logger.info('[CLEANUP] - Saving Checkpoint files')
  834. self.sg_logger.upload()
  835. self.sg_logger.close()
  836. def _reset_best_metric(self):
  837. self.best_metric = -1 * np.inf if self.greater_metric_to_watch_is_better else np.inf
  838. def _reset_metrics(self):
  839. for metric in ("train_metrics", "valid_metrics", "test_metrics"):
  840. if hasattr(self, metric) and getattr(self, metric) is not None:
  841. getattr(self, metric).reset()
  842. @resolve_param('train_metrics_list', ListFactory(MetricsFactory()))
  843. def _set_train_metrics(self, train_metrics_list):
  844. self.train_metrics = MetricCollection(train_metrics_list)
  845. @resolve_param('valid_metrics_list', ListFactory(MetricsFactory()))
  846. def _set_valid_metrics(self, valid_metrics_list):
  847. self.valid_metrics = MetricCollection(valid_metrics_list)
  848. def _initialize_mixed_precision(self, mixed_precision_enabled: bool):
  849. # SCALER IS ALWAYS INITIALIZED BUT IS DISABLED IF MIXED PRECISION WAS NOT SET
  850. self.scaler = GradScaler(enabled=mixed_precision_enabled)
  851. if mixed_precision_enabled:
  852. assert self.device.startswith('cuda'), "mixed precision is not available for CPU"
  853. if self.multi_gpu == MultiGPUMode.DATA_PARALLEL:
  854. # IN DATAPARALLEL MODE WE NEED TO WRAP THE FORWARD FUNCTION OF OUR MODEL SO IT WILL RUN WITH AUTOCAST.
  855. # BUT SINCE THE MODULE IS CLONED TO THE DEVICES ON EACH FORWARD CALL OF A DATAPARALLEL MODEL,
  856. # WE HAVE TO REGISTER THE WRAPPER BEFORE EVERY FORWARD CALL
  857. def hook(module, _):
  858. module.forward = MultiGPUModeAutocastWrapper(module.forward)
  859. self.net.module.register_forward_pre_hook(hook=hook)
  860. if self.load_checkpoint:
  861. scaler_state_dict = core_utils.get_param(self.checkpoint, 'scaler_state_dict')
  862. if scaler_state_dict is None:
  863. logger.warning(
  864. 'Mixed Precision - scaler state_dict not found in loaded model. This may case issues '
  865. 'with loss scaling')
  866. else:
  867. self.scaler.load_state_dict(scaler_state_dict)
  868. def _validate_final_average_model(self, cleanup_snapshots_pkl_file=False):
  869. """
  870. Testing the averaged model by loading the last saved average checkpoint and running test.
  871. Will be loaded to each of DDP processes
  872. :param cleanup_pkl_file: a flag for deleting the 10 best snapshots dictionary
  873. """
  874. logger.info('RUNNING ADDITIONAL TEST ON THE AVERAGED MODEL...')
  875. keep_state_dict = deepcopy(self.net.state_dict())
  876. # SETTING STATE DICT TO THE AVERAGE MODEL FOR EVALUATION
  877. average_model_ckpt_path = os.path.join(self.checkpoints_dir_path, self.average_model_checkpoint_filename)
  878. average_model_sd = read_ckpt_state_dict(average_model_ckpt_path)['net']
  879. self.net.load_state_dict(average_model_sd)
  880. # testing the averaged model and save instead of best model if needed
  881. averaged_model_results_tuple = self._validate_epoch(epoch=self.max_epochs)
  882. # Reverting the current model
  883. self.net.load_state_dict(keep_state_dict)
  884. if not self.ddp_silent_mode:
  885. # Adding values to sg_logger
  886. # looping over last titles which corresponds to validation (and average model) metrics.
  887. all_titles = self.results_titles[-1 * len(averaged_model_results_tuple):]
  888. result_dict = {all_titles[i]: averaged_model_results_tuple[i] for i in
  889. range(len(averaged_model_results_tuple))}
  890. self.sg_logger.add_scalars(tag_scalar_dict=result_dict, global_step=self.max_epochs)
  891. average_model_tb_titles = ['Averaged Model ' + x for x in
  892. self.results_titles[-1 * len(averaged_model_results_tuple):]]
  893. write_struct = ''
  894. for ind, title in enumerate(average_model_tb_titles):
  895. write_struct += '%s: %.3f \n ' % (title, averaged_model_results_tuple[ind])
  896. self.sg_logger.add_scalar(title, averaged_model_results_tuple[ind], global_step=self.max_epochs)
  897. self.sg_logger.add_text("Averaged_Model_Performance", write_struct, self.max_epochs)
  898. if cleanup_snapshots_pkl_file:
  899. self.model_weight_averaging.cleanup()
  900. @property
  901. def get_arch_params(self):
  902. return self.arch_params.to_dict()
  903. @property
  904. def get_structure(self):
  905. return self.net.module.structure
  906. @property
  907. def get_architecture(self):
  908. return self.architecture
  909. def set_experiment_name(self, experiment_name):
  910. self.experiment_name = experiment_name
  911. def _re_build_model(self, arch_params={}):
  912. """
  913. arch_params : dict
  914. Architecture H.P. e.g.: block, num_blocks, num_classes, etc.
  915. :return:
  916. """
  917. if 'num_classes' not in arch_params.keys():
  918. if self.dataset_interface is None:
  919. raise Exception('Error', 'Number of classes not defined in arch params and dataset is not defined')
  920. else:
  921. arch_params['num_classes'] = len(self.classes)
  922. self.arch_params = core_utils.HpmStruct(**arch_params)
  923. self.classes = self.arch_params.num_classes
  924. self.net = self._instantiate_net(self.architecture, self.arch_params, self.checkpoint_params)
  925. # save the architecture for neural architecture search
  926. if hasattr(self.net, 'structure'):
  927. self.architecture = self.net.structure
  928. self.net.to(self.device)
  929. if self.multi_gpu == MultiGPUMode.DISTRIBUTED_DATA_PARALLEL:
  930. logger.warning("Warning: distributed training is not supported in re_build_model()")
  931. self.net = torch.nn.DataParallel(self.net,
  932. device_ids=self.device_ids) if self.multi_gpu else core_utils.WrappedModel(
  933. self.net)
  934. @property
  935. def get_module(self):
  936. return self.net
  937. def set_module(self, module):
  938. self.net = module
  939. def _initialize_device(self, requested_device: str, requested_multi_gpu: Union[MultiGPUMode, str]):
  940. """
  941. _initialize_device - Initializes the device for the model - Default is CUDA
  942. :param requested_device: Device to initialize ('cuda' / 'cpu')
  943. :param requested_multi_gpu: Get Multiple GPU
  944. """
  945. if isinstance(requested_multi_gpu, str):
  946. requested_multi_gpu = MultiGPUMode(requested_multi_gpu)
  947. # SELECT CUDA DEVICE
  948. if requested_device == 'cuda':
  949. if torch.cuda.is_available():
  950. self.device = 'cuda' # TODO - we may want to set the device number as well i.e. 'cuda:1'
  951. else:
  952. raise RuntimeError('CUDA DEVICE NOT FOUND... EXITING')
  953. if require_gpu_setup(requested_multi_gpu):
  954. raise GPUModeNotSetupError()
  955. # SELECT CPU DEVICE
  956. elif requested_device == 'cpu':
  957. self.device = 'cpu'
  958. self.multi_gpu = False
  959. else:
  960. # SELECT CUDA DEVICE BY DEFAULT IF AVAILABLE
  961. self.device = 'cuda' if torch.cuda.is_available() else 'cpu'
  962. # DEFUALT IS SET TO 1 - IT IS CHANGED IF MULTI-GPU IS USED
  963. self.num_devices = 1
  964. # IN CASE OF MULTIPLE GPUS UPDATE THE LEARNING AND DATA PARAMETERS
  965. # FIXME - CREATE A DISCUSSION ON THESE PARAMETERS - WE MIGHT WANT TO CHANGE THE WAY WE USE THE LR AND
  966. if requested_multi_gpu != MultiGPUMode.OFF:
  967. if 'cuda' in self.device:
  968. # COLLECT THE AVAILABLE GPU AND COUNT THE AVAILABLE GPUS AMOUNT
  969. self.device_ids = list(range(torch.cuda.device_count()))
  970. self.num_devices = len(self.device_ids)
  971. if self.num_devices == 1:
  972. self.multi_gpu = MultiGPUMode.OFF
  973. if requested_multi_gpu != MultiGPUMode.AUTO:
  974. # if AUTO mode was set - do not log a warning
  975. logger.warning(
  976. '\n[WARNING] - Tried running on multiple GPU but only a single GPU is available\n')
  977. else:
  978. if requested_multi_gpu == MultiGPUMode.AUTO:
  979. if env_helpers.is_distributed():
  980. requested_multi_gpu = MultiGPUMode.DISTRIBUTED_DATA_PARALLEL
  981. else:
  982. requested_multi_gpu = MultiGPUMode.DATA_PARALLEL
  983. self.multi_gpu = requested_multi_gpu
  984. if self.multi_gpu == MultiGPUMode.DISTRIBUTED_DATA_PARALLEL:
  985. self._initialize_ddp()
  986. else:
  987. # MULTIPLE GPUS CAN BE ACTIVE ONLY IF A GPU IS AVAILABLE
  988. self.multi_gpu = MultiGPUMode.OFF
  989. logger.warning('\n[WARNING] - Tried running on multiple GPU but none are available => running on CPU\n')
  990. def _initialize_ddp(self):
  991. """
  992. Initialize Distributed Data Parallel
  993. Important note: (1) in distributed training it is customary to specify learning rates and batch sizes per GPU.
  994. Whatever learning rate and schedule you specify will be applied to the each GPU individually.
  995. Since gradients are passed and summed (reduced) from all to all GPUs, the effective batch size is the
  996. batch you specify times the number of GPUs. In the literature there are several "best practices" to set
  997. learning rates and schedules for large batch sizes.
  998. """
  999. logger.info("Distributed training starting...")
  1000. local_rank = environment_config.DDP_LOCAL_RANK
  1001. if not torch.distributed.is_initialized():
  1002. torch.distributed.init_process_group(backend='nccl', init_method='env://')
  1003. if local_rank > 0:
  1004. f = open(os.devnull, 'w')
  1005. sys.stdout = f # silent all printing for non master process
  1006. torch.cuda.set_device(local_rank)
  1007. self.device = 'cuda:%d' % local_rank
  1008. # MAKE ALL HIGHER-RANK GPUS SILENT (DISTRIBUTED MODE)
  1009. self.ddp_silent_mode = local_rank > 0
  1010. if torch.distributed.get_rank() == 0:
  1011. logger.info(f"Training in distributed mode... with {str(torch.distributed.get_world_size())} GPUs")
  1012. def _switch_device(self, new_device):
  1013. self.device = new_device
  1014. self.net.to(self.device)
  1015. # FIXME - we need to resolve flake8's 'function is too complex' for this function
  1016. def _load_checkpoint_to_model(self): # noqa: C901 - too complex
  1017. """
  1018. Copies the source checkpoint to a local folder and loads the checkpoint's data to the model using the
  1019. attributes:
  1020. strict: See StrictLoad class documentation for details.
  1021. load_backbone: loads the provided checkpoint to self.net.backbone instead of self.net
  1022. source_ckpt_folder_name: The folder where the checkpoint is saved. By default uses the self.experiment_name
  1023. NOTE: 'acc', 'epoch', 'optimizer_state_dict' and the logs are NOT loaded if self.zeroize_prev_train_params
  1024. is True
  1025. """
  1026. self._set_ckpt_loading_attributes()
  1027. if self.load_checkpoint or self.external_checkpoint_path:
  1028. # GET LOCAL PATH TO THE CHECKPOINT FILE FIRST
  1029. ckpt_local_path = get_ckpt_local_path(source_ckpt_folder_name=self.source_ckpt_folder_name,
  1030. experiment_name=self.experiment_name,
  1031. ckpt_name=self.ckpt_name,
  1032. model_checkpoints_location=self.model_checkpoints_location,
  1033. external_checkpoint_path=self.external_checkpoint_path,
  1034. overwrite_local_checkpoint=self.overwrite_local_checkpoint,
  1035. load_weights_only=self.load_weights_only)
  1036. # LOAD CHECKPOINT TO MODEL
  1037. self.checkpoint = load_checkpoint_to_model(ckpt_local_path=ckpt_local_path,
  1038. load_backbone=self.load_backbone,
  1039. net=self.net,
  1040. strict=self.strict_load.value if isinstance(self.strict_load,
  1041. StrictLoad) else self.strict_load,
  1042. load_weights_only=self.load_weights_only,
  1043. load_ema_as_net=self.load_ema_as_net)
  1044. if 'ema_net' in self.checkpoint.keys():
  1045. logger.warning("[WARNING] Main network has been loaded from checkpoint but EMA network exists as "
  1046. "well. It "
  1047. " will only be loaded during validation when training with ema=True. ")
  1048. # UPDATE TRAINING PARAMS IF THEY EXIST & WE ARE NOT LOADING AN EXTERNAL MODEL's WEIGHTS
  1049. self.best_metric = self.checkpoint['acc'] if 'acc' in self.checkpoint.keys() else -1
  1050. self.start_epoch = self.checkpoint['epoch'] if 'epoch' in self.checkpoint.keys() else 0
  1051. def _prep_for_test(self, test_loader: torch.utils.data.DataLoader = None, loss=None, post_prediction_callback=None,
  1052. test_metrics_list=None,
  1053. loss_logging_items_names=None, test_phase_callbacks=None):
  1054. """Run commands that are common to all models"""
  1055. # SET THE MODEL IN evaluation STATE
  1056. self.net.eval()
  1057. # IF SPECIFIED IN THE FUNCTION CALL - OVERRIDE THE self ARGUMENTS
  1058. self.test_loader = test_loader or self.test_loader
  1059. self.criterion = loss or self.criterion
  1060. self.post_prediction_callback = post_prediction_callback or self.post_prediction_callback
  1061. self.loss_logging_items_names = loss_logging_items_names or self.loss_logging_items_names
  1062. self.phase_callbacks = test_phase_callbacks or self.phase_callbacks
  1063. if self.phase_callbacks is None:
  1064. self.phase_callbacks = []
  1065. if test_metrics_list:
  1066. self.test_metrics = MetricCollection(test_metrics_list)
  1067. self._add_metrics_update_callback(Phase.TEST_BATCH_END)
  1068. self.phase_callback_handler = CallbackHandler(self.phase_callbacks)
  1069. # WHEN TESTING WITHOUT A LOSS FUNCTION- CREATE EPOCH HEADERS FOR PRINTS
  1070. if self.criterion is None:
  1071. self.loss_logging_items_names = []
  1072. if self.test_metrics is None:
  1073. raise ValueError("Metrics are required to perform test. Pass them through test_metrics_list arg when "
  1074. "calling test or through training_params when calling train(...)")
  1075. if self.test_loader is None:
  1076. raise ValueError("Test dataloader is required to perform test. Make sure to either pass it through "
  1077. "test_loader arg.")
  1078. # RESET METRIC RUNNERS
  1079. self._reset_metrics()
  1080. self.test_metrics.to(self.device)
  1081. if self.arch_params is None:
  1082. self._init_arch_params()
  1083. self._net_to_device()
  1084. def _add_metrics_update_callback(self, phase: Phase):
  1085. """
  1086. Adds MetricsUpdateCallback to be fired at phase
  1087. :param phase: Phase for the metrics callback to be fired at
  1088. """
  1089. self.phase_callbacks.append(MetricsUpdateCallback(phase))
  1090. def _initialize_sg_logger_objects(self):
  1091. """Initialize object that collect, write to disk, monitor and store remotely all training outputs"""
  1092. sg_logger = core_utils.get_param(self.training_params, 'sg_logger')
  1093. # OVERRIDE SOME PARAMETERS TO MAKE SURE THEY MATCH THE TRAINING PARAMETERS
  1094. general_sg_logger_params = {'experiment_name': self.experiment_name,
  1095. 'storage_location': self.model_checkpoints_location,
  1096. 'resumed': self.load_checkpoint,
  1097. 'training_params': self.training_params,
  1098. 'checkpoints_dir_path': self.checkpoints_dir_path}
  1099. if sg_logger is None:
  1100. raise RuntimeError('sg_logger must be defined in training params (see default_training_params)')
  1101. if isinstance(sg_logger, AbstractSGLogger):
  1102. self.sg_logger = sg_logger
  1103. elif isinstance(sg_logger, str):
  1104. sg_logger_params = core_utils.get_param(self.training_params, 'sg_logger_params', {})
  1105. if issubclass(SG_LOGGERS[sg_logger], BaseSGLogger):
  1106. sg_logger_params = {**sg_logger_params, **general_sg_logger_params}
  1107. if sg_logger not in SG_LOGGERS:
  1108. raise RuntimeError('sg_logger not defined in SG_LOGGERS')
  1109. self.sg_logger = SG_LOGGERS[sg_logger](**sg_logger_params)
  1110. else:
  1111. raise RuntimeError('sg_logger can be either an sg_logger name (str) or an instance of AbstractSGLogger')
  1112. if not isinstance(self.sg_logger, BaseSGLogger):
  1113. logger.warning("WARNING! Using a user-defined sg_logger: files will not be automatically written to disk!\n"
  1114. "Please make sure the provided sg_logger writes to disk or compose your sg_logger to BaseSGLogger")
  1115. # IN CASE SG_LOGGER UPDATED THE DIR PATH
  1116. self.checkpoints_dir_path = self.sg_logger.local_dir()
  1117. hyper_param_config = self._get_hyper_param_config()
  1118. self.sg_logger.add_config("hyper_params", hyper_param_config)
  1119. self.sg_logger.flush()
  1120. def _get_hyper_param_config(self):
  1121. """
  1122. Creates a training hyper param config for logging.
  1123. """
  1124. additional_log_items = {'initial_LR': self.training_params.initial_lr,
  1125. 'num_devices': self.num_devices,
  1126. 'multi_gpu': str(self.multi_gpu),
  1127. 'device_type': torch.cuda.get_device_name(0) if torch.cuda.is_available() else 'cpu'}
  1128. # ADD INSTALLED PACKAGE LIST + THEIR VERSIONS
  1129. if self.training_params.log_installed_packages:
  1130. pkg_list = list(map(lambda pkg: str(pkg), _get_installed_distributions()))
  1131. additional_log_items['installed_packages'] = pkg_list
  1132. hyper_param_config = {"arch_params": self.arch_params.__dict__,
  1133. "checkpoint_params": self.checkpoint_params.__dict__,
  1134. "training_hyperparams": self.training_params.__dict__,
  1135. "dataset_params": self.dataset_params.__dict__,
  1136. "additional_log_items": additional_log_items}
  1137. return hyper_param_config
  1138. def _write_to_disk_operations(self, train_metrics: tuple, validation_results: tuple, inf_time: float, epoch: int,
  1139. context: PhaseContext):
  1140. """Run the various logging operations, e.g.: log file, Tensorboard, save checkpoint etc."""
  1141. # STORE VALUES IN A TENSORBOARD FILE
  1142. train_results = list(train_metrics) + list(validation_results) + [inf_time]
  1143. all_titles = self.results_titles + ['Inference Time']
  1144. result_dict = {all_titles[i]: train_results[i] for i in range(len(train_results))}
  1145. self.sg_logger.add_scalars(tag_scalar_dict=result_dict, global_step=epoch)
  1146. # SAVE THE CHECKPOINT
  1147. if self.training_params.save_model:
  1148. self._save_checkpoint(self.optimizer, epoch + 1, validation_results, context)
  1149. def _write_lrs(self, epoch):
  1150. lrs = [self.optimizer.param_groups[i]['lr'] for i in range(len(self.optimizer.param_groups))]
  1151. lr_titles = ['LR/Param_group_' + str(i) for i in range(len(self.optimizer.param_groups))] if len(
  1152. self.optimizer.param_groups) > 1 else ['LR']
  1153. lr_dict = {lr_titles[i]: lrs[i] for i in range(len(lrs))}
  1154. self.sg_logger.add_scalars(tag_scalar_dict=lr_dict, global_step=epoch)
  1155. def test(self, model: nn.Module = None, test_loader: torch.utils.data.DataLoader = None,
  1156. loss: torch.nn.modules.loss._Loss = None, silent_mode: bool = False, test_metrics_list=None,
  1157. loss_logging_items_names=None, metrics_progress_verbose=False, test_phase_callbacks=None,
  1158. use_ema_net=True) -> tuple:
  1159. """
  1160. Evaluates the model on given dataloader and metrics.
  1161. :param model: model to perfrom test on. When none is given, will try to use self.net (defalut=None).
  1162. :param test_loader: dataloader to perform test on.
  1163. :param test_metrics_list: (list(torchmetrics.Metric)) metrics list for evaluation.
  1164. :param silent_mode: (bool) controls verbosity
  1165. :param metrics_progress_verbose: (bool) controls the verbosity of metrics progress (default=False). Slows down the program.
  1166. :param use_ema_net (bool) whether to perform test on self.ema_model.ema (when self.ema_model.ema exists,
  1167. otherwise self.net will be tested) (default=True)
  1168. :return: results tuple (tuple) containing the loss items and metric values.
  1169. All of the above args will override Trainer's corresponding attribute when not equal to None. Then evaluation
  1170. is ran on self.test_loader with self.test_metrics.
  1171. """
  1172. self.net = model or self.net
  1173. # IN CASE TRAINING WAS PERFROMED BEFORE TEST- MAKE SURE TO TEST THE EMA MODEL (UNLESS SPECIFIED OTHERWISE BY
  1174. # use_ema_net)
  1175. if use_ema_net and self.ema_model is not None:
  1176. keep_model = self.net
  1177. self.net = self.ema_model.ema
  1178. self._prep_for_test(test_loader=test_loader,
  1179. loss=loss,
  1180. test_metrics_list=test_metrics_list,
  1181. loss_logging_items_names=loss_logging_items_names,
  1182. test_phase_callbacks=test_phase_callbacks,
  1183. )
  1184. test_results = self.evaluate(data_loader=self.test_loader,
  1185. metrics=self.test_metrics,
  1186. evaluation_type=EvaluationType.TEST,
  1187. silent_mode=silent_mode,
  1188. metrics_progress_verbose=metrics_progress_verbose)
  1189. # SWITCH BACK BETWEEN NETS SO AN ADDITIONAL TRAINING CAN BE DONE AFTER TEST
  1190. if use_ema_net and self.ema_model is not None:
  1191. self.net = keep_model
  1192. return test_results
  1193. def _validate_epoch(self, epoch: int, silent_mode: bool = False) -> tuple:
  1194. """
  1195. Runs evaluation on self.valid_loader, with self.valid_metrics.
  1196. :param epoch: (int) epoch idx
  1197. :param silent_mode: (bool) controls verbosity
  1198. :return: results tuple (tuple) containing the loss items and metric values.
  1199. """
  1200. self.net.eval()
  1201. self._reset_metrics()
  1202. self.valid_metrics.to(self.device)
  1203. return self.evaluate(data_loader=self.valid_loader, metrics=self.valid_metrics,
  1204. evaluation_type=EvaluationType.VALIDATION, epoch=epoch, silent_mode=silent_mode)
  1205. def evaluate(self, data_loader: torch.utils.data.DataLoader, metrics: MetricCollection,
  1206. evaluation_type: EvaluationType, epoch: int = None, silent_mode: bool = False,
  1207. metrics_progress_verbose: bool = False):
  1208. """
  1209. Evaluates the model on given dataloader and metrics.
  1210. :param data_loader: dataloader to perform evaluataion on
  1211. :param metrics: (MetricCollection) metrics for evaluation
  1212. :param evaluation_type: (EvaluationType) controls which phase callbacks will be used (for example, on batch end,
  1213. when evaluation_type=EvaluationType.VALIDATION the Phase.VALIDATION_BATCH_END callbacks will be triggered)
  1214. :param epoch: (int) epoch idx
  1215. :param silent_mode: (bool) controls verbosity
  1216. :param metrics_progress_verbose: (bool) controls the verbosity of metrics progress (default=False).
  1217. Slows down the program significantly.
  1218. :return: results tuple (tuple) containing the loss items and metric values.
  1219. """
  1220. # THE DISABLE FLAG CONTROLS WHETHER THE PROGRESS BAR IS SILENT OR PRINTS THE LOGS
  1221. progress_bar_data_loader = tqdm(data_loader, bar_format="{l_bar}{bar:10}{r_bar}", dynamic_ncols=True,
  1222. disable=silent_mode)
  1223. loss_avg_meter = core_utils.utils.AverageMeter()
  1224. logging_values = None
  1225. loss_tuple = None
  1226. lr_warmup_epochs = self.training_params.lr_warmup_epochs if self.training_params else None
  1227. context = PhaseContext(epoch=epoch,
  1228. metrics_compute_fn=metrics,
  1229. loss_avg_meter=loss_avg_meter,
  1230. criterion=self.criterion,
  1231. device=self.device,
  1232. lr_warmup_epochs=lr_warmup_epochs,
  1233. sg_logger=self.sg_logger,
  1234. context_methods=self._get_context_methods(Phase.VALIDATION_BATCH_END))
  1235. if not silent_mode:
  1236. # PRINT TITLES
  1237. pbar_start_msg = f"Validation epoch {epoch}" if evaluation_type == EvaluationType.VALIDATION else "Test"
  1238. progress_bar_data_loader.set_description(pbar_start_msg)
  1239. with torch.no_grad():
  1240. for batch_idx, batch_items in enumerate(progress_bar_data_loader):
  1241. batch_items = core_utils.tensor_container_to_device(batch_items, self.device, non_blocking=True)
  1242. inputs, targets, additional_batch_items = sg_trainer_utils.unpack_batch_items(batch_items)
  1243. output = self.net(inputs)
  1244. if self.criterion is not None:
  1245. # STORE THE loss_items ONLY, THE 1ST RETURNED VALUE IS THE loss FOR BACKPROP DURING TRAINING
  1246. loss_tuple = self._get_losses(output, targets)[1].cpu()
  1247. context.update_context(batch_idx=batch_idx,
  1248. inputs=inputs,
  1249. preds=output,
  1250. target=targets,
  1251. loss_log_items=loss_tuple,
  1252. **additional_batch_items)
  1253. # TRIGGER PHASE CALLBACKS CORRESPONDING TO THE EVALUATION TYPE
  1254. if evaluation_type == EvaluationType.VALIDATION:
  1255. self.phase_callback_handler(Phase.VALIDATION_BATCH_END, context)
  1256. else:
  1257. self.phase_callback_handler(Phase.TEST_BATCH_END, context)
  1258. # COMPUTE METRICS IF PROGRESS VERBOSITY IS SET
  1259. if metrics_progress_verbose and not silent_mode:
  1260. # COMPUTE THE RUNNING USER METRICS AND LOSS RUNNING ITEMS. RESULT TUPLE IS THEIR CONCATENATION.
  1261. logging_values = get_logging_values(loss_avg_meter, metrics, self.criterion)
  1262. pbar_message_dict = get_train_loop_description_dict(logging_values,
  1263. metrics,
  1264. self.loss_logging_items_names)
  1265. progress_bar_data_loader.set_postfix(**pbar_message_dict)
  1266. # NEED TO COMPUTE METRICS FOR THE FIRST TIME IF PROGRESS VERBOSITY IS NOT SET
  1267. if not metrics_progress_verbose:
  1268. # COMPUTE THE RUNNING USER METRICS AND LOSS RUNNING ITEMS. RESULT TUPLE IS THEIR CONCATENATION.
  1269. logging_values = get_logging_values(loss_avg_meter, metrics, self.criterion)
  1270. pbar_message_dict = get_train_loop_description_dict(logging_values,
  1271. metrics,
  1272. self.loss_logging_items_names)
  1273. progress_bar_data_loader.set_postfix(**pbar_message_dict)
  1274. # TODO: SUPPORT PRINTING AP PER CLASS- SINCE THE METRICS ARE NOT HARD CODED ANYMORE (as done in
  1275. # calc_batch_prediction_accuracy_per_class in metric_utils.py), THIS IS ONLY RELEVANT WHEN CHOOSING
  1276. # DETECTIONMETRICS, WHICH ALREADY RETURN THE METRICS VALUEST HEMSELVES AND NOT THE ITEMS REQUIRED FOR SUCH
  1277. # COMPUTATION. ALSO REMOVE THE BELOW LINES BY IMPLEMENTING CRITERION AS A TORCHMETRIC.
  1278. if self.multi_gpu == MultiGPUMode.DISTRIBUTED_DATA_PARALLEL:
  1279. logging_values = reduce_results_tuple_for_ddp(logging_values, next(self.net.parameters()).device)
  1280. pbar_message_dict = get_train_loop_description_dict(logging_values,
  1281. metrics,
  1282. self.loss_logging_items_names)
  1283. self.valid_monitored_values = sg_trainer_utils.update_monitored_values_dict(
  1284. monitored_values_dict=self.valid_monitored_values, new_values_dict=pbar_message_dict)
  1285. if not silent_mode and evaluation_type == EvaluationType.VALIDATION:
  1286. progress_bar_data_loader.write("===========================================================")
  1287. sg_trainer_utils.display_epoch_summary(epoch=context.epoch, n_digits=4,
  1288. train_monitored_values=self.train_monitored_values,
  1289. valid_monitored_values=self.valid_monitored_values)
  1290. progress_bar_data_loader.write("===========================================================")
  1291. return logging_values
  1292. def _instantiate_net(self, architecture: Union[torch.nn.Module, SgModule.__class__, str], arch_params: dict,
  1293. checkpoint_params: dict, *args, **kwargs) -> tuple:
  1294. """
  1295. Instantiates nn.Module according to architecture and arch_params, and handles pretrained weights and the required
  1296. module manipulation (i.e head replacement).
  1297. :param architecture: String, torch.nn.Module or uninstantiated SgModule class describing the netowrks architecture.
  1298. :param arch_params: Architecture's parameters passed to networks c'tor.
  1299. :param checkpoint_params: checkpoint loading related parameters dictionary with 'pretrained_weights' key,
  1300. s.t it's value is a string describing the dataset of the pretrained weights (for example "imagenent").
  1301. :return: instantiated netowrk i.e torch.nn.Module, architecture_class (will be none when architecture is not str)
  1302. """
  1303. pretrained_weights = core_utils.get_param(checkpoint_params, 'pretrained_weights', default_val=None)
  1304. if pretrained_weights is not None:
  1305. num_classes_new_head = arch_params.num_classes
  1306. arch_params.num_classes = PRETRAINED_NUM_CLASSES[pretrained_weights]
  1307. if isinstance(architecture, str):
  1308. architecture_cls = ARCHITECTURES[architecture]
  1309. net = architecture_cls(arch_params=arch_params)
  1310. elif isinstance(architecture, SgModule.__class__):
  1311. net = architecture(arch_params)
  1312. else:
  1313. net = architecture
  1314. if pretrained_weights:
  1315. load_pretrained_weights(net, architecture, pretrained_weights)
  1316. if num_classes_new_head != arch_params.num_classes:
  1317. net.replace_head(new_num_classes=num_classes_new_head)
  1318. arch_params.num_classes = num_classes_new_head
  1319. return net
  1320. def _instantiate_ema_model(self, decay: float = 0.9999, beta: float = 15, exp_activation: bool = True) -> ModelEMA:
  1321. """Instantiate ema model for standard SgModule.
  1322. :param decay: the maximum decay value. as the training process advances, the decay will climb towards this value
  1323. until the EMA_t+1 = EMA_t * decay + TRAINING_MODEL * (1- decay)
  1324. :param beta: the exponent coefficient. The higher the beta, the sooner in the training the decay will saturate to
  1325. its final value. beta=15 is ~40% of the training process.
  1326. """
  1327. return ModelEMA(self.net, decay, beta, exp_activation)
  1328. @property
  1329. def get_net(self):
  1330. """
  1331. Getter for network.
  1332. :return: torch.nn.Module, self.net
  1333. """
  1334. return self.net
  1335. def set_net(self, net: torch.nn.Module):
  1336. """
  1337. Setter for network.
  1338. :param net: torch.nn.Module, value to set net
  1339. :return:
  1340. """
  1341. self.net = net
  1342. def set_ckpt_best_name(self, ckpt_best_name):
  1343. """
  1344. Setter for best checkpoint filename.
  1345. :param ckpt_best_name: str, value to set ckpt_best_name
  1346. """
  1347. self.ckpt_best_name = ckpt_best_name
  1348. def set_ema(self, val: bool):
  1349. """
  1350. Setter for self.ema
  1351. :param val: bool, value to set ema
  1352. """
  1353. self.ema = val
  1354. def _get_context_methods(self, phase: Phase) -> ContextSgMethods:
  1355. """
  1356. Returns ContextSgMethods holding the methods that should be accessible through phase callbacks to the user at
  1357. the specific phase
  1358. :param phase: Phase, controls what methods should be returned.
  1359. :return: ContextSgMethods holding methods from self.
  1360. """
  1361. if phase in [Phase.PRE_TRAINING, Phase.TRAIN_EPOCH_START, Phase.TRAIN_EPOCH_END, Phase.VALIDATION_EPOCH_END,
  1362. Phase.VALIDATION_EPOCH_END, Phase.POST_TRAINING, Phase.VALIDATION_END_BEST_EPOCH]:
  1363. context_methods = ContextSgMethods(get_net=self.get_net,
  1364. set_net=self.set_net,
  1365. set_ckpt_best_name=self.set_ckpt_best_name,
  1366. reset_best_metric=self._reset_best_metric,
  1367. validate_epoch=self._validate_epoch,
  1368. set_ema=self.set_ema)
  1369. else:
  1370. context_methods = ContextSgMethods()
  1371. return context_methods
Discard
Tip!

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