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

#307 Hotfix/sg 000 fix image loading new detectiondataset

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

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