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

sg_trainer.py 96 KB

You have to be logged in to leave a comment. Sign In
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
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
  1. import inspect
  2. import os
  3. from copy import deepcopy
  4. from pathlib import Path
  5. from typing import Union, Tuple, Mapping, Dict, Any
  6. import hydra
  7. import numpy as np
  8. import torch
  9. from omegaconf import DictConfig
  10. from omegaconf import OmegaConf
  11. from piptools.scripts.sync import _get_installed_distributions
  12. from torch import nn
  13. from torch.cuda.amp import GradScaler, autocast
  14. from torch.utils.data import DataLoader, SequentialSampler
  15. from torch.utils.data.distributed import DistributedSampler
  16. from torchmetrics import MetricCollection
  17. from tqdm import tqdm
  18. from super_gradients.common.environment.checkpoints_dir_utils import get_checkpoints_dir_path, get_ckpt_local_path
  19. from super_gradients.module_interfaces import HasPreprocessingParams, HasPredict
  20. from super_gradients.training.utils.sg_trainer_utils import get_callable_param_names
  21. from super_gradients.common.abstractions.abstract_logger import get_logger
  22. from super_gradients.common.sg_loggers.abstract_sg_logger import AbstractSGLogger
  23. from super_gradients.common.sg_loggers.base_sg_logger import BaseSGLogger
  24. from super_gradients.common.data_types.enum import MultiGPUMode, StrictLoad, EvaluationType
  25. from super_gradients.common.decorators.factory_decorator import resolve_param
  26. from super_gradients.common.factories.callbacks_factory import CallbacksFactory
  27. from super_gradients.common.factories.list_factory import ListFactory
  28. from super_gradients.common.factories.losses_factory import LossesFactory
  29. from super_gradients.common.factories.metrics_factory import MetricsFactory
  30. from super_gradients.training import utils as core_utils, models, dataloaders
  31. from super_gradients.training.datasets.samplers import RepeatAugSampler
  32. from super_gradients.training.exceptions.sg_trainer_exceptions import UnsupportedOptimizerFormat
  33. from super_gradients.training.metrics.metric_utils import (
  34. get_metrics_titles,
  35. get_metrics_results_tuple,
  36. get_logging_values,
  37. get_metrics_dict,
  38. get_train_loop_description_dict,
  39. )
  40. from super_gradients.training.models import SgModule, get_model_name
  41. from super_gradients.common.registry.registry import ARCHITECTURES, SG_LOGGERS
  42. from super_gradients.training.pretrained_models import PRETRAINED_NUM_CLASSES
  43. from super_gradients.training.utils import sg_trainer_utils, get_param
  44. from super_gradients.training.utils.distributed_training_utils import (
  45. MultiGPUModeAutocastWrapper,
  46. reduce_results_tuple_for_ddp,
  47. compute_precise_bn_stats,
  48. setup_device,
  49. get_gpu_mem_utilization,
  50. get_world_size,
  51. get_local_rank,
  52. require_ddp_setup,
  53. get_device_ids,
  54. is_ddp_subprocess,
  55. wait_for_the_master,
  56. DDPNotSetupException,
  57. )
  58. from super_gradients.training.utils.ema import ModelEMA
  59. from super_gradients.training.utils.optimizer_utils import build_optimizer
  60. from super_gradients.training.utils.sg_trainer_utils import MonitoredValue, log_main_training_params
  61. from super_gradients.training.utils.utils import fuzzy_idx_in_list
  62. from super_gradients.training.utils.weight_averaging_utils import ModelWeightAveraging
  63. from super_gradients.training.metrics import Accuracy, Top5
  64. from super_gradients.training.utils import random_seed
  65. from super_gradients.training.utils.checkpoint_utils import (
  66. read_ckpt_state_dict,
  67. load_checkpoint_to_model,
  68. load_pretrained_weights,
  69. )
  70. from super_gradients.training.datasets.datasets_utils import DatasetStatisticsTensorboardLogger
  71. from super_gradients.training.utils.callbacks import (
  72. CallbackHandler,
  73. Phase,
  74. PhaseContext,
  75. MetricsUpdateCallback,
  76. ContextSgMethods,
  77. LRCallbackBase,
  78. )
  79. from super_gradients.common.registry.registry import LR_SCHEDULERS_CLS_DICT, LR_WARMUP_CLS_DICT
  80. from super_gradients.common.environment.device_utils import device_config
  81. from super_gradients.training.utils import HpmStruct
  82. from super_gradients.common.environment.cfg_utils import load_experiment_cfg, add_params_to_cfg
  83. from super_gradients.common.factories.pre_launch_callbacks_factory import PreLaunchCallbacksFactory
  84. from super_gradients.training.params import TrainingParams
  85. logger = get_logger(__name__)
  86. class Trainer:
  87. """
  88. SuperGradient Model - Base Class for Sg Models
  89. Methods
  90. -------
  91. train(max_epochs : int, initial_epoch : int, save_model : bool)
  92. the main function used for the training, h.p. updating, logging etc.
  93. predict(idx : int)
  94. returns the predictions and label of the current inputs
  95. test(epoch : int, idx : int, save : bool):
  96. returns the test loss, accuracy and runtime
  97. """
  98. def __init__(self, experiment_name: str, device: str = None, multi_gpu: Union[MultiGPUMode, str] = None, ckpt_root_dir: str = None):
  99. """
  100. :param experiment_name: Used for logging and loading purposes
  101. :param device: If equal to 'cpu' runs on the CPU otherwise on GPU
  102. :param multi_gpu: If True, runs on all available devices
  103. otherwise saves the Checkpoints Locally
  104. checkpoint from cloud service, otherwise overwrites the local checkpoints file
  105. :param ckpt_root_dir: Local root directory path where all experiment logging directories will
  106. reside. When none is give, it is assumed that
  107. pkg_resources.resource_filename('checkpoints', "") exists and will be used.
  108. """
  109. # This should later me removed
  110. if device is not None or multi_gpu is not None:
  111. raise KeyError(
  112. "Trainer does not accept anymore 'device' and 'multi_gpu' as argument. "
  113. "Both should instead be passed to "
  114. "super_gradients.setup_device(device=..., multi_gpu=..., num_gpus=...)"
  115. )
  116. if require_ddp_setup():
  117. raise DDPNotSetupException()
  118. # SET THE EMPTY PROPERTIES
  119. self.net, self.architecture, self.arch_params, self.dataset_interface = None, None, None, None
  120. self.train_loader, self.valid_loader = None, None
  121. self.ema = None
  122. self.ema_model = None
  123. self.sg_logger = None
  124. self.update_param_groups = None
  125. self.criterion = None
  126. self.training_params = None
  127. self.scaler = None
  128. self.phase_callbacks = None
  129. self.checkpoint_params = None
  130. self.pre_prediction_callback = None
  131. # SET THE DEFAULT PROPERTIES
  132. self.half_precision = False
  133. self.load_checkpoint = False
  134. self.load_backbone = False
  135. self.load_weights_only = False
  136. self.ddp_silent_mode = is_ddp_subprocess()
  137. self.model_weight_averaging = None
  138. self.average_model_checkpoint_filename = "average_model.pth"
  139. self.start_epoch = 0
  140. self.best_metric = np.inf
  141. self.external_checkpoint_path = None
  142. self.strict_load = StrictLoad.ON
  143. self.load_ema_as_net = False
  144. self.ckpt_best_name = "ckpt_best.pth"
  145. self._first_backward = True
  146. # METRICS
  147. self.loss_logging_items_names = None
  148. self.train_metrics = None
  149. self.valid_metrics = None
  150. self.greater_metric_to_watch_is_better = None
  151. self.metric_to_watch = None
  152. self.greater_train_metrics_is_better: Dict[str, bool] = {} # For each metric, indicates if greater is better
  153. self.greater_valid_metrics_is_better: Dict[str, bool] = {}
  154. # SETTING THE PROPERTIES FROM THE CONSTRUCTOR
  155. self.experiment_name = experiment_name
  156. self.ckpt_name = None
  157. self.checkpoints_dir_path = get_checkpoints_dir_path(experiment_name, ckpt_root_dir)
  158. self.phase_callback_handler: CallbackHandler = None
  159. # SET THE DEFAULTS
  160. # TODO: SET DEFAULT TRAINING PARAMS FOR EACH TASK
  161. default_results_titles = ["Train Loss", "Train Acc", "Train Top5", "Valid Loss", "Valid Acc", "Valid Top5"]
  162. self.results_titles = default_results_titles
  163. default_train_metrics, default_valid_metrics = MetricCollection([Accuracy(), Top5()]), MetricCollection([Accuracy(), Top5()])
  164. self.train_metrics, self.valid_metrics = default_train_metrics, default_valid_metrics
  165. self.train_monitored_values = {}
  166. self.valid_monitored_values = {}
  167. self.max_train_batches = None
  168. self.max_valid_batches = None
  169. self._epoch_start_logging_values = {}
  170. @property
  171. def device(self) -> str:
  172. return device_config.device
  173. @classmethod
  174. def train_from_config(cls, cfg: Union[DictConfig, dict]) -> Tuple[nn.Module, Tuple]:
  175. """
  176. Trains according to cfg recipe configuration.
  177. :param cfg: The parsed DictConfig from yaml recipe files or a dictionary
  178. :return: the model and the output of trainer.train(...) (i.e results tuple)
  179. """
  180. setup_device(
  181. device=core_utils.get_param(cfg, "device"),
  182. multi_gpu=core_utils.get_param(cfg, "multi_gpu"),
  183. num_gpus=core_utils.get_param(cfg, "num_gpus"),
  184. )
  185. # INSTANTIATE ALL OBJECTS IN CFG
  186. cfg = hydra.utils.instantiate(cfg)
  187. # TRIGGER CFG MODIFYING CALLBACKS
  188. cfg = cls._trigger_cfg_modifying_callbacks(cfg)
  189. trainer = Trainer(experiment_name=cfg.experiment_name, ckpt_root_dir=cfg.ckpt_root_dir)
  190. # BUILD NETWORK
  191. model = models.get(
  192. model_name=cfg.architecture,
  193. num_classes=cfg.arch_params.num_classes,
  194. arch_params=cfg.arch_params,
  195. strict_load=cfg.checkpoint_params.strict_load,
  196. pretrained_weights=cfg.checkpoint_params.pretrained_weights,
  197. checkpoint_path=cfg.checkpoint_params.checkpoint_path,
  198. load_backbone=cfg.checkpoint_params.load_backbone,
  199. )
  200. # INSTANTIATE DATA LOADERS
  201. train_dataloader = dataloaders.get(
  202. name=get_param(cfg, "train_dataloader"),
  203. dataset_params=cfg.dataset_params.train_dataset_params,
  204. dataloader_params=cfg.dataset_params.train_dataloader_params,
  205. )
  206. val_dataloader = dataloaders.get(
  207. name=get_param(cfg, "val_dataloader"),
  208. dataset_params=cfg.dataset_params.val_dataset_params,
  209. dataloader_params=cfg.dataset_params.val_dataloader_params,
  210. )
  211. recipe_logged_cfg = {"recipe_config": OmegaConf.to_container(cfg, resolve=True)}
  212. # TRAIN
  213. res = trainer.train(
  214. model=model,
  215. train_loader=train_dataloader,
  216. valid_loader=val_dataloader,
  217. training_params=cfg.training_hyperparams,
  218. additional_configs_to_log=recipe_logged_cfg,
  219. )
  220. return model, res
  221. @classmethod
  222. def _trigger_cfg_modifying_callbacks(cls, cfg):
  223. pre_launch_cbs = get_param(cfg, "pre_launch_callbacks_list", list())
  224. pre_launch_cbs = ListFactory(PreLaunchCallbacksFactory()).get(pre_launch_cbs)
  225. for plcb in pre_launch_cbs:
  226. cfg = plcb(cfg)
  227. return cfg
  228. @classmethod
  229. def resume_experiment(cls, experiment_name: str, ckpt_root_dir: str = None) -> Tuple[nn.Module, Tuple]:
  230. """
  231. Resume a training that was run using our recipes.
  232. :param experiment_name: Name of the experiment to resume
  233. :param ckpt_root_dir: Directory including the checkpoints
  234. """
  235. logger.info("Resume training using the checkpoint recipe, ignoring the current recipe")
  236. cfg = load_experiment_cfg(experiment_name, ckpt_root_dir)
  237. add_params_to_cfg(cfg, params=["training_hyperparams.resume=True"])
  238. return cls.train_from_config(cfg)
  239. @classmethod
  240. def evaluate_from_recipe(cls, cfg: DictConfig) -> Tuple[nn.Module, Tuple]:
  241. """
  242. Evaluate according to a cfg recipe configuration.
  243. Note: This script does NOT run training, only validation.
  244. Please make sure that the config refers to a PRETRAINED MODEL either from one of your checkpoint or from pretrained weights from model zoo.
  245. :param cfg: The parsed DictConfig from yaml recipe files or a dictionary
  246. """
  247. setup_device(
  248. device=core_utils.get_param(cfg, "device"),
  249. multi_gpu=core_utils.get_param(cfg, "multi_gpu"),
  250. num_gpus=core_utils.get_param(cfg, "num_gpus"),
  251. )
  252. # INSTANTIATE ALL OBJECTS IN CFG
  253. cfg = hydra.utils.instantiate(cfg)
  254. trainer = Trainer(experiment_name=cfg.experiment_name, ckpt_root_dir=cfg.ckpt_root_dir)
  255. # INSTANTIATE DATA LOADERS
  256. val_dataloader = dataloaders.get(
  257. name=cfg.val_dataloader, dataset_params=cfg.dataset_params.val_dataset_params, dataloader_params=cfg.dataset_params.val_dataloader_params
  258. )
  259. if cfg.checkpoint_params.pretrained_weights is None and cfg.checkpoint_params.checkpoint_path is None:
  260. logger.info(
  261. "checkpoint_params.checkpoint_path was not provided, " "so the recipe will be evaluated using checkpoints_dir/training_hyperparams.ckpt_name"
  262. )
  263. checkpoints_dir = Path(get_checkpoints_dir_path(experiment_name=cfg.experiment_name, ckpt_root_dir=cfg.ckpt_root_dir))
  264. cfg.checkpoint_params.checkpoint_path = str(checkpoints_dir / cfg.training_hyperparams.ckpt_name)
  265. logger.info(f"Evaluating checkpoint: {cfg.checkpoint_params.checkpoint_path}")
  266. # BUILD NETWORK
  267. model = models.get(
  268. model_name=cfg.architecture,
  269. num_classes=cfg.arch_params.num_classes,
  270. arch_params=cfg.arch_params,
  271. strict_load=cfg.checkpoint_params.strict_load,
  272. pretrained_weights=cfg.checkpoint_params.pretrained_weights,
  273. checkpoint_path=cfg.checkpoint_params.checkpoint_path,
  274. load_backbone=cfg.checkpoint_params.load_backbone,
  275. )
  276. # TEST
  277. valid_metrics_dict = trainer.test(model=model, test_loader=val_dataloader, test_metrics_list=cfg.training_hyperparams.valid_metrics_list)
  278. results = ["Validate Results"]
  279. results += [f" - {metric:10}: {value}" for metric, value in valid_metrics_dict.items()]
  280. logger.info("\n".join(results))
  281. return model, valid_metrics_dict
  282. @classmethod
  283. def evaluate_checkpoint(cls, experiment_name: str, ckpt_name: str = "ckpt_latest.pth", ckpt_root_dir: str = None) -> None:
  284. """
  285. Evaluate a checkpoint resulting from one of your previous experiment, using the same parameters (dataset, valid_metrics,...)
  286. as used during the training of the experiment
  287. Note:
  288. The parameters will be unchanged even if the recipe used for that experiment was changed since then.
  289. This is to ensure that validation of the experiment will remain exactly the same as during training.
  290. Example, evaluate the checkpoint "average_model.pth" from experiment "my_experiment_name":
  291. >> evaluate_checkpoint(experiment_name="my_experiment_name", ckpt_name="average_model.pth")
  292. :param experiment_name: Name of the experiment to validate
  293. :param ckpt_name: Name of the checkpoint to test ("ckpt_latest.pth", "average_model.pth" or "ckpt_best.pth" for instance)
  294. :param ckpt_root_dir: Directory including the checkpoints
  295. """
  296. logger.info("Evaluate checkpoint")
  297. cfg = load_experiment_cfg(experiment_name, ckpt_root_dir)
  298. add_params_to_cfg(cfg, params=["training_hyperparams.resume=True", f"ckpt_name={ckpt_name}"])
  299. cls.evaluate_from_recipe(cfg)
  300. def _set_dataset_params(self):
  301. self.dataset_params = {
  302. "train_dataset_params": self.train_loader.dataset.dataset_params if hasattr(self.train_loader.dataset, "dataset_params") else None,
  303. "train_dataloader_params": self.train_loader.dataloader_params if hasattr(self.train_loader, "dataloader_params") else None,
  304. "valid_dataset_params": self.valid_loader.dataset.dataset_params if hasattr(self.valid_loader.dataset, "dataset_params") else None,
  305. "valid_dataloader_params": self.valid_loader.dataloader_params if hasattr(self.valid_loader, "dataloader_params") else None,
  306. }
  307. self.dataset_params = HpmStruct(**self.dataset_params)
  308. def _net_to_device(self):
  309. """
  310. Manipulates self.net according to device.multi_gpu
  311. """
  312. self.net.to(device_config.device)
  313. # FOR MULTI-GPU TRAINING (not distributed)
  314. sync_bn = core_utils.get_param(self.training_params, "sync_bn", default_val=False)
  315. if device_config.multi_gpu == MultiGPUMode.DATA_PARALLEL:
  316. self.net = torch.nn.DataParallel(self.net, device_ids=get_device_ids())
  317. elif device_config.multi_gpu == MultiGPUMode.DISTRIBUTED_DATA_PARALLEL:
  318. if sync_bn:
  319. if not self.ddp_silent_mode:
  320. logger.info("DDP - Using Sync Batch Norm... Training time will be affected accordingly")
  321. self.net = torch.nn.SyncBatchNorm.convert_sync_batchnorm(self.net).to(device_config.device)
  322. local_rank = int(device_config.device.split(":")[1])
  323. self.net = torch.nn.parallel.DistributedDataParallel(self.net, device_ids=[local_rank], output_device=local_rank, find_unused_parameters=True)
  324. else:
  325. self.net = core_utils.WrappedModel(self.net)
  326. def _train_epoch(self, epoch: int, silent_mode: bool = False) -> tuple:
  327. """
  328. train_epoch - A single epoch training procedure
  329. :param optimizer: The optimizer for the network
  330. :param epoch: The current epoch
  331. :param silent_mode: No verbosity
  332. """
  333. # SET THE MODEL IN training STATE
  334. self.net.train()
  335. # THE DISABLE FLAG CONTROLS WHETHER THE PROGRESS BAR IS SILENT OR PRINTS THE LOGS
  336. with tqdm(self.train_loader, bar_format="{l_bar}{bar:10}{r_bar}", dynamic_ncols=True, disable=silent_mode) as progress_bar_train_loader:
  337. progress_bar_train_loader.set_description(f"Train epoch {epoch}")
  338. # RESET/INIT THE METRIC LOGGERS
  339. self._reset_metrics()
  340. self.train_metrics.to(device_config.device)
  341. loss_avg_meter = core_utils.utils.AverageMeter()
  342. context = PhaseContext(
  343. epoch=epoch,
  344. optimizer=self.optimizer,
  345. metrics_compute_fn=self.train_metrics,
  346. loss_avg_meter=loss_avg_meter,
  347. criterion=self.criterion,
  348. device=device_config.device,
  349. lr_warmup_epochs=self.training_params.lr_warmup_epochs,
  350. sg_logger=self.sg_logger,
  351. train_loader=self.train_loader,
  352. context_methods=self._get_context_methods(Phase.TRAIN_BATCH_END),
  353. ddp_silent_mode=self.ddp_silent_mode,
  354. )
  355. for batch_idx, batch_items in enumerate(progress_bar_train_loader):
  356. batch_items = core_utils.tensor_container_to_device(batch_items, device_config.device, non_blocking=True)
  357. inputs, targets, additional_batch_items = sg_trainer_utils.unpack_batch_items(batch_items)
  358. if self.pre_prediction_callback is not None:
  359. inputs, targets = self.pre_prediction_callback(inputs, targets, batch_idx)
  360. context.update_context(batch_idx=batch_idx, inputs=inputs, target=targets, **additional_batch_items)
  361. self.phase_callback_handler.on_train_batch_start(context)
  362. # AUTOCAST IS ENABLED ONLY IF self.training_params.mixed_precision - IF enabled=False AUTOCAST HAS NO EFFECT
  363. with autocast(enabled=self.training_params.mixed_precision):
  364. # FORWARD PASS TO GET NETWORK'S PREDICTIONS
  365. outputs = self.net(inputs)
  366. # COMPUTE THE LOSS FOR BACK PROP + EXTRA METRICS COMPUTED DURING THE LOSS FORWARD PASS
  367. loss, loss_log_items = self._get_losses(outputs, targets)
  368. context.update_context(preds=outputs, loss_log_items=loss_log_items)
  369. self.phase_callback_handler.on_train_batch_loss_end(context)
  370. if not self.ddp_silent_mode and batch_idx == 0:
  371. self._epoch_start_logging_values = self._get_epoch_start_logging_values()
  372. self._backward_step(loss, epoch, batch_idx, context)
  373. # COMPUTE THE RUNNING USER METRICS AND LOSS RUNNING ITEMS. RESULT TUPLE IS THEIR CONCATENATION.
  374. logging_values = loss_avg_meter.average + get_metrics_results_tuple(self.train_metrics)
  375. gpu_memory_utilization = get_gpu_mem_utilization() / 1e9 if torch.cuda.is_available() else 0
  376. # RENDER METRICS PROGRESS
  377. pbar_message_dict = get_train_loop_description_dict(
  378. logging_values, self.train_metrics, self.loss_logging_items_names, gpu_mem=gpu_memory_utilization
  379. )
  380. progress_bar_train_loader.set_postfix(**pbar_message_dict)
  381. self.phase_callback_handler.on_train_batch_end(context)
  382. if self.max_train_batches is not None and self.max_train_batches - 1 <= batch_idx:
  383. break
  384. self.train_monitored_values = sg_trainer_utils.update_monitored_values_dict(
  385. monitored_values_dict=self.train_monitored_values, new_values_dict=pbar_message_dict
  386. )
  387. return logging_values
  388. def _get_losses(self, outputs: torch.Tensor, targets: torch.Tensor) -> Tuple[torch.Tensor, tuple]:
  389. # GET THE OUTPUT OF THE LOSS FUNCTION
  390. loss = self.criterion(outputs, targets)
  391. if isinstance(loss, tuple):
  392. loss, loss_logging_items = loss
  393. # IF ITS NOT A TUPLE THE LOGGING ITEMS CONTAIN ONLY THE LOSS FOR BACKPROP (USER DEFINED LOSS RETURNS SCALAR)
  394. else:
  395. loss_logging_items = loss.unsqueeze(0).detach()
  396. # ON FIRST BACKWARD, DERRIVE THE LOGGING TITLES.
  397. if self.loss_logging_items_names is None or self._first_backward:
  398. self._init_loss_logging_names(loss_logging_items)
  399. if self.metric_to_watch:
  400. self._init_monitored_items()
  401. self._first_backward = False
  402. if len(loss_logging_items) != len(self.loss_logging_items_names):
  403. raise ValueError(
  404. "Loss output length must match loss_logging_items_names. Got "
  405. + str(len(loss_logging_items))
  406. + ", and "
  407. + str(len(self.loss_logging_items_names))
  408. )
  409. # RETURN AND THE LOSS LOGGING ITEMS COMPUTED DURING LOSS FORWARD PASS
  410. return loss, loss_logging_items
  411. def _init_monitored_items(self):
  412. self.metric_idx_in_results_tuple = fuzzy_idx_in_list(self.metric_to_watch, self.loss_logging_items_names + get_metrics_titles(self.valid_metrics))
  413. # Instantiate the values to monitor (loss/metric)
  414. for loss_name in self.loss_logging_items_names:
  415. self.train_monitored_values[loss_name] = MonitoredValue(name=loss_name, greater_is_better=False)
  416. self.valid_monitored_values[loss_name] = MonitoredValue(name=loss_name, greater_is_better=False)
  417. for metric_name in get_metrics_titles(self.train_metrics):
  418. self.train_monitored_values[metric_name] = MonitoredValue(name=metric_name, greater_is_better=self.greater_train_metrics_is_better.get(metric_name))
  419. for metric_name in get_metrics_titles(self.valid_metrics):
  420. self.valid_monitored_values[metric_name] = MonitoredValue(name=metric_name, greater_is_better=self.greater_valid_metrics_is_better.get(metric_name))
  421. self.results_titles = ["Train_" + t for t in self.loss_logging_items_names + get_metrics_titles(self.train_metrics)] + [
  422. "Valid_" + t for t in self.loss_logging_items_names + get_metrics_titles(self.valid_metrics)
  423. ]
  424. if self.training_params.average_best_models:
  425. self.model_weight_averaging = ModelWeightAveraging(
  426. ckpt_dir=self.checkpoints_dir_path,
  427. greater_is_better=self.greater_metric_to_watch_is_better,
  428. metric_to_watch=self.metric_to_watch,
  429. metric_idx=self.metric_idx_in_results_tuple,
  430. load_checkpoint=self.load_checkpoint,
  431. )
  432. def _backward_step(self, loss: torch.Tensor, epoch: int, batch_idx: int, context: PhaseContext, *args, **kwargs) -> None:
  433. """
  434. Run backprop on the loss and perform a step
  435. :param loss: The value computed by the loss function
  436. :param optimizer: An object that can perform a gradient step and zeroize model gradient
  437. :param epoch: number of epoch the training is on
  438. :param batch_idx: Zero-based number of iteration inside the current epoch
  439. :param context: current phase context
  440. :return:
  441. """
  442. # SCALER IS ENABLED ONLY IF self.training_params.mixed_precision=True
  443. self.scaler.scale(loss).backward()
  444. self.phase_callback_handler.on_train_batch_backward_end(context)
  445. # ACCUMULATE GRADIENT FOR X BATCHES BEFORE OPTIMIZING
  446. local_step = batch_idx + 1
  447. global_step = local_step + len(self.train_loader) * epoch
  448. total_steps = len(self.train_loader) * self.max_epochs
  449. if global_step % self.batch_accumulate == 0:
  450. self.phase_callback_handler.on_train_batch_gradient_step_start(context)
  451. # APPLY GRADIENT CLIPPING IF REQUIRED
  452. if self.training_params.clip_grad_norm:
  453. self.scaler.unscale_(self.optimizer)
  454. torch.nn.utils.clip_grad_norm_(self.net.parameters(), self.training_params.clip_grad_norm)
  455. # SCALER IS ENABLED ONLY IF self.training_params.mixed_precision=True
  456. self.scaler.step(self.optimizer)
  457. self.scaler.update()
  458. self.optimizer.zero_grad()
  459. if self.ema:
  460. self.ema_model.update(self.net, step=global_step, total_steps=total_steps)
  461. # RUN PHASE CALLBACKS
  462. self.phase_callback_handler.on_train_batch_gradient_step_end(context)
  463. def _save_checkpoint(
  464. self,
  465. optimizer: torch.optim.Optimizer = None,
  466. epoch: int = None,
  467. validation_results_tuple: tuple = None,
  468. context: PhaseContext = None,
  469. ) -> None:
  470. """
  471. Save the current state dict as latest (always), best (if metric was improved), epoch# (if determined in training
  472. params)
  473. """
  474. # WHEN THE validation_results_tuple IS NONE WE SIMPLY SAVE THE state_dict AS LATEST AND Return
  475. if validation_results_tuple is None:
  476. self.sg_logger.add_checkpoint(tag="ckpt_latest_weights_only.pth", state_dict={"net": self.net.state_dict()}, global_step=epoch)
  477. return
  478. # COMPUTE THE CURRENT metric
  479. # IF idx IS A LIST - SUM ALL THE VALUES STORED IN THE LIST'S INDICES
  480. metric = (
  481. validation_results_tuple[self.metric_idx_in_results_tuple]
  482. if isinstance(self.metric_idx_in_results_tuple, int)
  483. else sum([validation_results_tuple[idx] for idx in self.metric_idx_in_results_tuple])
  484. )
  485. # BUILD THE state_dict
  486. state = {"net": self.net.state_dict(), "acc": metric, "epoch": epoch}
  487. if optimizer is not None:
  488. state["optimizer_state_dict"] = optimizer.state_dict()
  489. if self.scaler is not None:
  490. state["scaler_state_dict"] = self.scaler.state_dict()
  491. if self.ema:
  492. state["ema_net"] = self.ema_model.ema.state_dict()
  493. if isinstance(self.net.module, HasPredict) and isinstance(self.valid_loader.dataset, HasPreprocessingParams):
  494. state["processing_params"] = self.valid_loader.dataset.get_dataset_preprocessing_params()
  495. # SAVES CURRENT MODEL AS ckpt_latest
  496. self.sg_logger.add_checkpoint(tag="ckpt_latest.pth", state_dict=state, global_step=epoch)
  497. # SAVE MODEL AT SPECIFIC EPOCHS DETERMINED BY save_ckpt_epoch_list
  498. if epoch in self.training_params.save_ckpt_epoch_list:
  499. self.sg_logger.add_checkpoint(tag=f"ckpt_epoch_{epoch}.pth", state_dict=state, global_step=epoch)
  500. # OVERRIDE THE BEST CHECKPOINT AND best_metric IF metric GOT BETTER THAN THE PREVIOUS BEST
  501. if (metric > self.best_metric and self.greater_metric_to_watch_is_better) or (metric < self.best_metric and not self.greater_metric_to_watch_is_better):
  502. # STORE THE CURRENT metric AS BEST
  503. self.best_metric = metric
  504. self.sg_logger.add_checkpoint(tag=self.ckpt_best_name, state_dict=state, global_step=epoch)
  505. # RUN PHASE CALLBACKS
  506. self.phase_callback_handler.on_validation_end_best_epoch(context)
  507. if isinstance(metric, torch.Tensor):
  508. metric = metric.item()
  509. logger.info("Best checkpoint overriden: validation " + self.metric_to_watch + ": " + str(metric))
  510. if self.training_params.average_best_models:
  511. net_for_averaging = self.ema_model.ema if self.ema else self.net
  512. state["net"] = self.model_weight_averaging.get_average_model(net_for_averaging, validation_results_tuple=validation_results_tuple)
  513. self.sg_logger.add_checkpoint(tag=self.average_model_checkpoint_filename, state_dict=state, global_step=epoch)
  514. def _prep_net_for_train(self) -> None:
  515. if self.arch_params is None:
  516. self._init_arch_params()
  517. # TODO: REMOVE THE BELOW LINE (FOR BACKWARD COMPATIBILITY)
  518. if self.checkpoint_params is None:
  519. self.checkpoint_params = HpmStruct(load_checkpoint=self.training_params.resume)
  520. self._net_to_device()
  521. # SET THE FLAG FOR DIFFERENT PARAMETER GROUP OPTIMIZER UPDATE
  522. self.update_param_groups = hasattr(self.net.module, "update_param_groups")
  523. self.checkpoint = {}
  524. self.strict_load = core_utils.get_param(self.training_params, "resume_strict_load", StrictLoad.ON)
  525. self.load_ema_as_net = False
  526. self.load_checkpoint = core_utils.get_param(self.training_params, "resume", False)
  527. self.external_checkpoint_path = core_utils.get_param(self.training_params, "resume_path")
  528. self.ckpt_name = core_utils.get_param(self.training_params, "ckpt_name", "ckpt_latest.pth")
  529. self.resume_from_remote_sg_logger = core_utils.get_param(self.training_params, "resume_from_remote_sg_logger", False)
  530. self.load_checkpoint = self.load_checkpoint or self.external_checkpoint_path is not None or self.resume_from_remote_sg_logger
  531. def _init_arch_params(self) -> None:
  532. default_arch_params = HpmStruct()
  533. arch_params = getattr(self.net, "arch_params", default_arch_params)
  534. self.arch_params = default_arch_params
  535. if arch_params is not None:
  536. self.arch_params.override(**arch_params.to_dict())
  537. # FIXME - we need to resolve flake8's 'function is too complex' for this function
  538. def train(
  539. self,
  540. model: nn.Module,
  541. training_params: dict = None,
  542. train_loader: DataLoader = None,
  543. valid_loader: DataLoader = None,
  544. additional_configs_to_log: Dict = None,
  545. ): # noqa: C901
  546. """
  547. train - Trains the Model
  548. IMPORTANT NOTE: Additional batch parameters can be added as a third item (optional) if a tuple is returned by
  549. the data loaders, as dictionary. The phase context will hold the additional items, under an attribute with
  550. the same name as the key in this dictionary. Then such items can be accessed through phase callbacks.
  551. :param additional_configs_to_log: Dict, dictionary containing configs that will be added to the training's
  552. sg_logger. Format should be {"Config_title_1": {...}, "Config_title_2":{..}}.
  553. :param model: torch.nn.Module, model to train.
  554. :param train_loader: Dataloader for train set.
  555. :param valid_loader: Dataloader for validation.
  556. :param training_params:
  557. - `resume` : bool (default=False)
  558. Whether to continue training from ckpt with the same experiment name
  559. (i.e resume from CKPT_ROOT_DIR/EXPERIMENT_NAME/CKPT_NAME)
  560. - `ckpt_name` : str (default=ckpt_latest.pth)
  561. The checkpoint (.pth file) filename in CKPT_ROOT_DIR/EXPERIMENT_NAME/ to use when resume=True and
  562. resume_path=None
  563. - `resume_path`: str (default=None)
  564. Explicit checkpoint path (.pth file) to use to resume training.
  565. - `max_epochs` : int
  566. Number of epochs to run training.
  567. - `lr_updates` : list(int)
  568. List of fixed epoch numbers to perform learning rate updates when `lr_mode='step'`.
  569. - `lr_decay_factor` : float
  570. Decay factor to apply to the learning rate at each update when `lr_mode='step'`.
  571. - `lr_mode` : str
  572. Learning rate scheduling policy, one of ['step','poly','cosine','function'].
  573. 'step' refers to constant updates at epoch numbers passed through `lr_updates`. Each update decays the learning rate by `lr_decay_factor`.
  574. 'cosine' refers to the Cosine Anealing policy as mentioned in https://arxiv.org/abs/1608.03983.
  575. The final learning rate ratio is controlled by `cosine_final_lr_ratio` training parameter.
  576. 'poly' refers to the polynomial decrease: in each epoch iteration `self.lr = self.initial_lr * pow((1.0 - (current_iter / max_iter)), 0.9)`
  577. 'function' refers to a user-defined learning rate scheduling function, that is passed through `lr_schedule_function`.
  578. - `lr_schedule_function` : Union[callable,None]
  579. Learning rate scheduling function to be used when `lr_mode` is 'function'.
  580. - `warmup_mode`: Union[str, Type[LRCallbackBase], None]
  581. If not None, define how the learning rate will be increased during the warmup phase.
  582. Currently, only 'warmup_linear_epoch' and `warmup_linear_step` modes are supported.
  583. - `lr_warmup_epochs` : int (default=0)
  584. Number of epochs for learning rate warm up - see https://arxiv.org/pdf/1706.02677.pdf (Section 2.2).
  585. Relevant for `warmup_mode=warmup_linear_epoch`.
  586. When lr_warmup_epochs > 0, the learning rate will be increased linearly from 0 to the `initial_lr`
  587. once per epoch.
  588. - `lr_warmup_steps` : int (default=0)
  589. Number of steps for learning rate warm up - see https://arxiv.org/pdf/1706.02677.pdf (Section 2.2).
  590. Relevant for `warmup_mode=warmup_linear_step`.
  591. When lr_warmup_steps > 0, the learning rate will be increased linearly from 0 to the `initial_lr`
  592. for a total number of steps according to formula: min(lr_warmup_steps, len(train_loader)).
  593. The capping is done to avoid interference of warmup with epoch-based schedulers.
  594. - `cosine_final_lr_ratio` : float (default=0.01)
  595. Final learning rate ratio (only relevant when `lr_mode`='cosine'). The cosine starts from initial_lr and reaches
  596. initial_lr * cosine_final_lr_ratio in last epoch
  597. - `inital_lr` : float
  598. Initial learning rate.
  599. - `loss` : Union[nn.module, str]
  600. Loss function for training.
  601. One of SuperGradient's built in options:
  602. "cross_entropy": LabelSmoothingCrossEntropyLoss,
  603. "mse": MSELoss,
  604. "r_squared_loss": RSquaredLoss,
  605. "detection_loss": YoLoV3DetectionLoss,
  606. "shelfnet_ohem_loss": ShelfNetOHEMLoss,
  607. "shelfnet_se_loss": ShelfNetSemanticEncodingLoss,
  608. "ssd_loss": SSDLoss,
  609. or user defined nn.module loss function.
  610. IMPORTANT: forward(...) should return a (loss, loss_items) tuple where loss is the tensor used
  611. for backprop (i.e what your original loss function returns), and loss_items should be a tensor of
  612. shape (n_items), of values computed during the forward pass which we desire to log over the
  613. entire epoch. For example- the loss itself should always be logged. Another example is a scenario
  614. where the computed loss is the sum of a few components we would like to log- these entries in
  615. loss_items).
  616. IMPORTANT:When dealing with external loss classes, to logg/monitor the loss_items as described
  617. above by specific string name:
  618. Set a "component_names" property in the loss class, whos instance is passed through train_params,
  619. to be a list of strings, of length n_items who's ith element is the name of the ith entry in loss_items.
  620. Then each item will be logged, rendered on tensorboard and "watched" (i.e saving model checkpoints
  621. according to it) under <LOSS_CLASS.__name__>"/"<COMPONENT_NAME>. If a single item is returned rather then a
  622. tuple, it would be logged under <LOSS_CLASS.__name__>. When there is no such attributed, the items
  623. will be named <LOSS_CLASS.__name__>"/"Loss_"<IDX> according to the length of loss_items
  624. For example:
  625. class MyLoss(_Loss):
  626. ...
  627. def forward(self, inputs, targets):
  628. ...
  629. total_loss = comp1 + comp2
  630. loss_items = torch.cat((total_loss.unsqueeze(0),comp1.unsqueeze(0), comp2.unsqueeze(0)).detach()
  631. return total_loss, loss_items
  632. ...
  633. @property
  634. def component_names(self):
  635. return ["total_loss", "my_1st_component", "my_2nd_component"]
  636. Trainer.train(...
  637. train_params={"loss":MyLoss(),
  638. ...
  639. "metric_to_watch": "MyLoss/my_1st_component"}
  640. This will write to log and monitor MyLoss/total_loss, MyLoss/my_1st_component,
  641. MyLoss/my_2nd_component.
  642. For example:
  643. class MyLoss2(_Loss):
  644. ...
  645. def forward(self, inputs, targets):
  646. ...
  647. total_loss = comp1 + comp2
  648. loss_items = torch.cat((total_loss.unsqueeze(0),comp1.unsqueeze(0), comp2.unsqueeze(0)).detach()
  649. return total_loss, loss_items
  650. ...
  651. Trainer.train(...
  652. train_params={"loss":MyLoss(),
  653. ...
  654. "metric_to_watch": "MyLoss2/loss_0"}
  655. This will write to log and monitor MyLoss2/loss_0, MyLoss2/loss_1, MyLoss2/loss_2
  656. as they have been named by their positional index in loss_items.
  657. Since running logs will save the loss_items in some internal state, it is recommended that
  658. loss_items are detached from their computational graph for memory efficiency.
  659. - `optimizer` : Union[str, torch.optim.Optimizer]
  660. Optimization algorithm. One of ['Adam','SGD','RMSProp'] corresponding to the torch.optim
  661. optimzers implementations, or any object that implements torch.optim.Optimizer.
  662. - `criterion_params` : dict
  663. Loss function parameters.
  664. - `optimizer_params` : dict
  665. When `optimizer` is one of ['Adam','SGD','RMSProp'], it will be initialized with optimizer_params.
  666. (see https://pytorch.org/docs/stable/optim.html for the full list of
  667. parameters for each optimizer).
  668. - `train_metrics_list` : list(torchmetrics.Metric)
  669. Metrics to log during training. For more information on torchmetrics see
  670. https://torchmetrics.rtfd.io/en/latest/.
  671. - `valid_metrics_list` : list(torchmetrics.Metric)
  672. Metrics to log during validation/testing. For more information on torchmetrics see
  673. https://torchmetrics.rtfd.io/en/latest/.
  674. - `loss_logging_items_names` : list(str)
  675. The list of names/titles for the outputs returned from the loss functions forward pass (reminder-
  676. the loss function should return the tuple (loss, loss_items)). These names will be used for
  677. logging their values.
  678. - `metric_to_watch` : str (default="Accuracy")
  679. will be the metric which the model checkpoint will be saved according to, and can be set to any
  680. of the following:
  681. a metric name (str) of one of the metric objects from the valid_metrics_list
  682. a "metric_name" if some metric in valid_metrics_list has an attribute component_names which
  683. is a list referring to the names of each entry in the output metric (torch tensor of size n)
  684. one of "loss_logging_items_names" i.e which will correspond to an item returned during the
  685. loss function's forward pass (see loss docs abov).
  686. At the end of each epoch, if a new best metric_to_watch value is achieved, the models checkpoint
  687. is saved in YOUR_PYTHON_PATH/checkpoints/ckpt_best.pth
  688. - `greater_metric_to_watch_is_better` : bool
  689. When choosing a model's checkpoint to be saved, the best achieved model is the one that maximizes the
  690. metric_to_watch when this parameter is set to True, and a one that minimizes it otherwise.
  691. - `ema` : bool (default=False)
  692. Whether to use Model Exponential Moving Average (see
  693. https://github.com/rwightman/pytorch-image-models ema implementation)
  694. - `batch_accumulate` : int (default=1)
  695. Number of batches to accumulate before every backward pass.
  696. - `ema_params` : dict
  697. Parameters for the ema model.
  698. - `zero_weight_decay_on_bias_and_bn` : bool (default=False)
  699. Whether to apply weight decay on batch normalization parameters or not (ignored when the passed
  700. optimizer has already been initialized).
  701. - `load_opt_params` : bool (default=True)
  702. Whether to load the optimizers parameters as well when loading a model's checkpoint.
  703. - `run_validation_freq` : int (default=1)
  704. The frequency in which validation is performed during training (i.e the validation is ran every
  705. `run_validation_freq` epochs.
  706. - `save_model` : bool (default=True)
  707. Whether to save the model checkpoints.
  708. - `silent_mode` : bool
  709. Silents the print outs.
  710. - `mixed_precision` : bool
  711. Whether to use mixed precision or not.
  712. - `save_ckpt_epoch_list` : list(int) (default=[])
  713. List of fixed epoch indices the user wishes to save checkpoints in.
  714. - `average_best_models` : bool (default=False)
  715. If set, a snapshot dictionary file and the average model will be saved / updated at every epoch
  716. and evaluated only when training is completed. The snapshot file will only be deleted upon
  717. completing the training. The snapshot dict will be managed on cpu.
  718. - `precise_bn` : bool (default=False)
  719. Whether to use precise_bn calculation during the training.
  720. - `precise_bn_batch_size` : int (default=None)
  721. The effective batch size we want to calculate the batchnorm on. For example, if we are training a model
  722. on 8 gpus, with a batch of 128 on each gpu, a good rule of thumb would be to give it 8192
  723. (ie: effective_batch_size * num_gpus = batch_per_gpu * num_gpus * num_gpus).
  724. If precise_bn_batch_size is not provided in the training_params, the latter heuristic will be taken.
  725. - `seed` : int (default=42)
  726. Random seed to be set for torch, numpy, and random. When using DDP each process will have it's seed
  727. set to seed + rank.
  728. - `log_installed_packages` : bool (default=False)
  729. When set, the list of all installed packages (and their versions) will be written to the tensorboard
  730. and logfile (useful when trying to reproduce results).
  731. - `dataset_statistics` : bool (default=False)
  732. Enable a statistic analysis of the dataset. If set to True the dataset will be analyzed and a report
  733. will be added to the tensorboard along with some sample images from the dataset. Currently only
  734. detection datasets are supported for analysis.
  735. - `sg_logger` : Union[AbstractSGLogger, str] (defauls=base_sg_logger)
  736. Define the SGLogger object for this training process. The SGLogger handles all disk writes, logs, TensorBoard, remote logging
  737. and remote storage. By overriding the default base_sg_logger, you can change the storage location, support external monitoring and logging
  738. or support remote storage.
  739. - `sg_logger_params` : dict
  740. SGLogger parameters
  741. - `clip_grad_norm` : float
  742. Defines a maximal L2 norm of the gradients. Values which exceed the given value will be clipped
  743. - `lr_cooldown_epochs` : int (default=0)
  744. Number of epochs to cooldown LR (i.e the last epoch from scheduling view point=max_epochs-cooldown).
  745. - `pre_prediction_callback` : Callable (default=None)
  746. When not None, this callback will be applied to images and targets, and returning them to be used
  747. for the forward pass, and further computations. Args for this callable should be in the order
  748. (inputs, targets, batch_idx) returning modified_inputs, modified_targets
  749. - `ckpt_best_name` : str (default='ckpt_best.pth')
  750. The best checkpoint (according to metric_to_watch) will be saved under this filename in the checkpoints directory.
  751. - `max_train_batches`: int, for debug- when not None- will break out of inner train loop (i.e iterating over
  752. train_loader) when reaching this number of batches. Usefull for debugging (default=None).
  753. - `max_valid_batches`: int, for debug- when not None- will break out of inner valid loop (i.e iterating over
  754. valid_loader) when reaching this number of batches. Usefull for debugging (default=None).
  755. - `resume_from_remote_sg_logger`: bool (default=False), bool (default=False), When true, ckpt_name (checkpoint filename
  756. to resume i.e ckpt_latest.pth bydefault) will be downloaded into the experiment checkpoints directory
  757. prior to loading weights, then training is resumed from that checkpoint. The source is unique to
  758. every logger, and currently supported for WandB loggers only.
  759. IMPORTANT: Only works for experiments that were ran with sg_logger_params.save_checkpoints_remote=True.
  760. IMPORTANT: For WandB loggers, one must also pass the run id through the wandb_id arg in sg_logger_params.
  761. :return:
  762. """
  763. global logger
  764. if training_params is None:
  765. training_params = dict()
  766. self.train_loader = train_loader if train_loader is not None else self.train_loader
  767. self.valid_loader = valid_loader if valid_loader is not None else self.valid_loader
  768. if self.train_loader is None:
  769. raise ValueError("No `train_loader` found. Please provide a value for `train_loader`")
  770. if self.valid_loader is None:
  771. raise ValueError("No `valid_loader` found. Please provide a value for `valid_loader`")
  772. if hasattr(self.train_loader, "batch_sampler") and self.train_loader.batch_sampler is not None:
  773. batch_size = self.train_loader.batch_sampler.batch_size
  774. else:
  775. batch_size = self.train_loader.batch_size
  776. if len(self.train_loader.dataset) % batch_size != 0 and not self.train_loader.drop_last:
  777. logger.warning("Train dataset size % batch_size != 0 and drop_last=False, this might result in smaller " "last batch.")
  778. self._set_dataset_params()
  779. if device_config.multi_gpu == MultiGPUMode.DISTRIBUTED_DATA_PARALLEL:
  780. # Note: the dataloader uses sampler of the batch_sampler when it is not None.
  781. train_sampler = self.train_loader.batch_sampler.sampler if self.train_loader.batch_sampler is not None else self.train_loader.sampler
  782. if isinstance(train_sampler, SequentialSampler):
  783. raise ValueError(
  784. "You are using a SequentialSampler on you training dataloader, while working on DDP. "
  785. "This cancels the DDP benefits since it makes each process iterate through the entire dataset"
  786. )
  787. if not isinstance(train_sampler, (DistributedSampler, RepeatAugSampler)):
  788. logger.warning(
  789. "The training sampler you are using might not support DDP. "
  790. "If it doesnt, please use one of the following sampler: DistributedSampler, RepeatAugSampler"
  791. )
  792. self.training_params = TrainingParams()
  793. self.training_params.override(**training_params)
  794. self.net = model
  795. self._prep_net_for_train()
  796. if not self.ddp_silent_mode:
  797. self._initialize_sg_logger_objects(additional_configs_to_log)
  798. self._load_checkpoint_to_model()
  799. # SET RANDOM SEED
  800. random_seed(is_ddp=device_config.multi_gpu == MultiGPUMode.DISTRIBUTED_DATA_PARALLEL, device=device_config.device, seed=self.training_params.seed)
  801. silent_mode = self.training_params.silent_mode or self.ddp_silent_mode
  802. # METRICS
  803. self._set_train_metrics(train_metrics_list=self.training_params.train_metrics_list)
  804. self._set_valid_metrics(valid_metrics_list=self.training_params.valid_metrics_list)
  805. # Store the metric to follow (loss\accuracy) and initialize as the worst value
  806. self.metric_to_watch = self.training_params.metric_to_watch
  807. self.greater_metric_to_watch_is_better = self.training_params.greater_metric_to_watch_is_better
  808. # Allowing loading instantiated loss or string
  809. if isinstance(self.training_params.loss, str):
  810. self.criterion = LossesFactory().get({self.training_params.loss: self.training_params.criterion_params})
  811. elif isinstance(self.training_params.loss, Mapping):
  812. self.criterion = LossesFactory().get(self.training_params.loss)
  813. elif isinstance(self.training_params.loss, nn.Module):
  814. self.criterion = self.training_params.loss
  815. self.criterion.to(device_config.device)
  816. self.max_epochs = self.training_params.max_epochs
  817. self.ema = self.training_params.ema
  818. self.precise_bn = self.training_params.precise_bn
  819. self.precise_bn_batch_size = self.training_params.precise_bn_batch_size
  820. self.batch_accumulate = self.training_params.batch_accumulate
  821. num_batches = len(self.train_loader)
  822. if self.ema:
  823. self.ema_model = self._instantiate_ema_model(self.training_params.ema_params)
  824. self.ema_model.updates = self.start_epoch * num_batches // self.batch_accumulate
  825. if self.load_checkpoint:
  826. if "ema_net" in self.checkpoint.keys():
  827. self.ema_model.ema.load_state_dict(self.checkpoint["ema_net"])
  828. else:
  829. self.ema = False
  830. logger.warning("[Warning] Checkpoint does not include EMA weights, continuing training without EMA.")
  831. self.run_validation_freq = self.training_params.run_validation_freq
  832. validation_results_tuple = (0, 0)
  833. inf_time = 0
  834. timer = core_utils.Timer(device_config.device)
  835. # IF THE LR MODE IS NOT DEFAULT TAKE IT FROM THE TRAINING PARAMS
  836. self.lr_mode = self.training_params.lr_mode
  837. load_opt_params = self.training_params.load_opt_params
  838. self.phase_callbacks = self.training_params.phase_callbacks or []
  839. self.phase_callbacks = ListFactory(CallbacksFactory()).get(self.phase_callbacks)
  840. if self.lr_mode is not None:
  841. sg_lr_callback_cls = LR_SCHEDULERS_CLS_DICT[self.lr_mode]
  842. self.phase_callbacks.append(
  843. sg_lr_callback_cls(
  844. train_loader_len=len(self.train_loader),
  845. net=self.net,
  846. training_params=self.training_params,
  847. update_param_groups=self.update_param_groups,
  848. **self.training_params.to_dict(),
  849. )
  850. )
  851. warmup_mode = self.training_params.warmup_mode
  852. warmup_callback_cls = None
  853. if isinstance(warmup_mode, str):
  854. warmup_callback_cls = LR_WARMUP_CLS_DICT[warmup_mode]
  855. elif isinstance(warmup_mode, type) and issubclass(warmup_mode, LRCallbackBase):
  856. warmup_callback_cls = warmup_mode
  857. elif warmup_mode is not None:
  858. pass
  859. else:
  860. raise RuntimeError("warmup_mode has to be either a name of a mode (str) or a subclass of PhaseCallback")
  861. if warmup_callback_cls is not None:
  862. self.phase_callbacks.append(
  863. warmup_callback_cls(
  864. train_loader_len=len(self.train_loader),
  865. net=self.net,
  866. training_params=self.training_params,
  867. update_param_groups=self.update_param_groups,
  868. **self.training_params.to_dict(),
  869. )
  870. )
  871. self._add_metrics_update_callback(Phase.TRAIN_BATCH_END)
  872. self._add_metrics_update_callback(Phase.VALIDATION_BATCH_END)
  873. self.phase_callback_handler = CallbackHandler(callbacks=self.phase_callbacks)
  874. if not self.ddp_silent_mode:
  875. if self.training_params.dataset_statistics:
  876. dataset_statistics_logger = DatasetStatisticsTensorboardLogger(self.sg_logger)
  877. dataset_statistics_logger.analyze(self.train_loader, all_classes=self.classes, title="Train-set", anchors=self.net.module.arch_params.anchors)
  878. dataset_statistics_logger.analyze(self.valid_loader, all_classes=self.classes, title="val-set")
  879. sg_trainer_utils.log_uncaught_exceptions(logger)
  880. if not self.load_checkpoint or self.load_weights_only:
  881. # WHEN STARTING TRAINING FROM SCRATCH, DO NOT LOAD OPTIMIZER PARAMS (EVEN IF LOADING BACKBONE)
  882. self.start_epoch = 0
  883. self._reset_best_metric()
  884. load_opt_params = False
  885. if isinstance(self.training_params.optimizer, str) or (
  886. inspect.isclass(self.training_params.optimizer) and issubclass(self.training_params.optimizer, torch.optim.Optimizer)
  887. ):
  888. self.optimizer = build_optimizer(net=self.net, lr=self.training_params.initial_lr, training_params=self.training_params)
  889. elif isinstance(self.training_params.optimizer, torch.optim.Optimizer):
  890. self.optimizer = self.training_params.optimizer
  891. else:
  892. raise UnsupportedOptimizerFormat()
  893. # VERIFY GRADIENT CLIPPING VALUE
  894. if self.training_params.clip_grad_norm is not None and self.training_params.clip_grad_norm <= 0:
  895. raise TypeError("Params", "Invalid clip_grad_norm")
  896. if self.load_checkpoint and load_opt_params:
  897. self.optimizer.load_state_dict(self.checkpoint["optimizer_state_dict"])
  898. self.pre_prediction_callback = CallbacksFactory().get(self.training_params.pre_prediction_callback)
  899. self._initialize_mixed_precision(self.training_params.mixed_precision)
  900. self.ckpt_best_name = self.training_params.ckpt_best_name
  901. if self.training_params.max_train_batches is not None:
  902. if self.training_params.max_train_batches > len(self.train_loader):
  903. logger.warning("max_train_batches is greater than len(self.train_loader) and will have no effect.")
  904. elif self.training_params.max_train_batches <= 0:
  905. raise ValueError("max_train_batches must be positive.")
  906. if self.training_params.max_valid_batches is not None:
  907. if self.training_params.max_valid_batches > len(self.valid_loader):
  908. logger.warning("max_valid_batches is greater than len(self.valid_loader) and will have no effect.")
  909. elif self.training_params.max_valid_batches <= 0:
  910. raise ValueError("max_valid_batches must be positive.")
  911. self.max_train_batches = self.training_params.max_train_batches
  912. self.max_valid_batches = self.training_params.max_valid_batches
  913. # STATE ATTRIBUTE SET HERE FOR SUBSEQUENT TRAIN() CALLS
  914. self._first_backward = True
  915. context = PhaseContext(
  916. optimizer=self.optimizer,
  917. net=self.net,
  918. experiment_name=self.experiment_name,
  919. ckpt_dir=self.checkpoints_dir_path,
  920. criterion=self.criterion,
  921. lr_warmup_epochs=self.training_params.lr_warmup_epochs,
  922. sg_logger=self.sg_logger,
  923. train_loader=self.train_loader,
  924. valid_loader=self.valid_loader,
  925. training_params=self.training_params,
  926. ddp_silent_mode=self.ddp_silent_mode,
  927. checkpoint_params=self.checkpoint_params,
  928. architecture=self.architecture,
  929. arch_params=self.arch_params,
  930. metric_to_watch=self.metric_to_watch,
  931. device=device_config.device,
  932. context_methods=self._get_context_methods(Phase.PRE_TRAINING),
  933. ema_model=self.ema_model,
  934. )
  935. self.phase_callback_handler.on_training_start(context)
  936. first_batch = next(iter(self.train_loader))
  937. inputs, _, _ = sg_trainer_utils.unpack_batch_items(first_batch)
  938. log_main_training_params(
  939. multi_gpu=device_config.multi_gpu,
  940. num_gpus=get_world_size(),
  941. batch_size=len(inputs),
  942. batch_accumulate=self.batch_accumulate,
  943. train_dataset_length=len(self.train_loader.dataset),
  944. train_dataloader_len=len(self.train_loader),
  945. )
  946. self._set_net_preprocessing_from_valid_loader()
  947. try:
  948. # HEADERS OF THE TRAINING PROGRESS
  949. if not silent_mode:
  950. logger.info(f"Started training for {self.max_epochs - self.start_epoch} epochs ({self.start_epoch}/" f"{self.max_epochs - 1})\n")
  951. for epoch in range(self.start_epoch, self.max_epochs):
  952. if context.stop_training:
  953. logger.info("Request to stop training has been received, stopping training")
  954. break
  955. # Phase.TRAIN_EPOCH_START
  956. # RUN PHASE CALLBACKS
  957. context.update_context(epoch=epoch)
  958. self.phase_callback_handler.on_train_loader_start(context)
  959. # IN DDP- SET_EPOCH WILL CAUSE EVERY PROCESS TO BE EXPOSED TO THE ENTIRE DATASET BY SHUFFLING WITH A
  960. # DIFFERENT SEED EACH EPOCH START
  961. if (
  962. device_config.multi_gpu == MultiGPUMode.DISTRIBUTED_DATA_PARALLEL
  963. and hasattr(self.train_loader, "sampler")
  964. and hasattr(self.train_loader.sampler, "set_epoch")
  965. ):
  966. self.train_loader.sampler.set_epoch(epoch)
  967. train_metrics_tuple = self._train_epoch(epoch=epoch, silent_mode=silent_mode)
  968. # Phase.TRAIN_EPOCH_END
  969. # RUN PHASE CALLBACKS
  970. train_metrics_dict = get_metrics_dict(train_metrics_tuple, self.train_metrics, self.loss_logging_items_names)
  971. context.update_context(metrics_dict=train_metrics_dict)
  972. self.phase_callback_handler.on_train_loader_end(context)
  973. # CALCULATE PRECISE BATCHNORM STATS
  974. if self.precise_bn:
  975. compute_precise_bn_stats(
  976. model=self.net, loader=self.train_loader, precise_bn_batch_size=self.precise_bn_batch_size, num_gpus=get_world_size()
  977. )
  978. if self.ema:
  979. compute_precise_bn_stats(
  980. model=self.ema_model.ema,
  981. loader=self.train_loader,
  982. precise_bn_batch_size=self.precise_bn_batch_size,
  983. num_gpus=get_world_size(),
  984. )
  985. # model switch - we replace self.net.module with the ema model for the testing and saving part
  986. # and then switch it back before the next training epoch
  987. if self.ema:
  988. self.ema_model.update_attr(self.net)
  989. keep_model = self.net
  990. self.net = self.ema_model.ema
  991. # RUN TEST ON VALIDATION SET EVERY self.run_validation_freq EPOCHS
  992. if (epoch + 1) % self.run_validation_freq == 0:
  993. self.phase_callback_handler.on_validation_loader_start(context)
  994. timer.start()
  995. validation_results_tuple = self._validate_epoch(epoch=epoch, silent_mode=silent_mode)
  996. inf_time = timer.stop()
  997. # Phase.VALIDATION_EPOCH_END
  998. # RUN PHASE CALLBACKS
  999. valid_metrics_dict = get_metrics_dict(validation_results_tuple, self.valid_metrics, self.loss_logging_items_names)
  1000. context.update_context(metrics_dict=valid_metrics_dict)
  1001. self.phase_callback_handler.on_validation_loader_end(context)
  1002. if self.ema:
  1003. self.net = keep_model
  1004. if not self.ddp_silent_mode:
  1005. # SAVING AND LOGGING OCCURS ONLY IN THE MAIN PROCESS (IN CASES THERE ARE SEVERAL PROCESSES - DDP)
  1006. self._write_to_disk_operations(
  1007. train_metrics=train_metrics_tuple,
  1008. validation_results=validation_results_tuple,
  1009. lr_dict=self._epoch_start_logging_values,
  1010. inf_time=inf_time,
  1011. epoch=epoch,
  1012. context=context,
  1013. )
  1014. self.sg_logger.upload()
  1015. # Evaluating the average model and removing snapshot averaging file if training is completed
  1016. if self.training_params.average_best_models:
  1017. self._validate_final_average_model(cleanup_snapshots_pkl_file=True)
  1018. except KeyboardInterrupt:
  1019. logger.info(
  1020. "\n[MODEL TRAINING EXECUTION HAS BEEN INTERRUPTED]... Please wait until SOFT-TERMINATION process "
  1021. "finishes and saves all of the Model Checkpoints and log files before terminating..."
  1022. )
  1023. logger.info("For HARD Termination - Stop the process again")
  1024. finally:
  1025. if device_config.multi_gpu == MultiGPUMode.DISTRIBUTED_DATA_PARALLEL:
  1026. # CLEAN UP THE MULTI-GPU PROCESS GROUP WHEN DONE
  1027. if torch.distributed.is_initialized() and self.training_params.kill_ddp_pgroup_on_end:
  1028. torch.distributed.destroy_process_group()
  1029. # PHASE.TRAIN_END
  1030. self.phase_callback_handler.on_training_end(context)
  1031. if not self.ddp_silent_mode:
  1032. self.sg_logger.close()
  1033. def _set_net_preprocessing_from_valid_loader(self):
  1034. if isinstance(self.net.module, HasPredict) and isinstance(self.valid_loader.dataset, HasPreprocessingParams):
  1035. try:
  1036. self.net.module.set_dataset_processing_params(**self.valid_loader.dataset.get_dataset_preprocessing_params())
  1037. except Exception as e:
  1038. logger.warning(
  1039. f"Could not set preprocessing pipeline from the validation dataset:\n {e}.\n Before calling"
  1040. "predict make sure to call set_dataset_processing_params."
  1041. )
  1042. def _reset_best_metric(self):
  1043. self.best_metric = -1 * np.inf if self.greater_metric_to_watch_is_better else np.inf
  1044. def _reset_metrics(self):
  1045. for metric in ("train_metrics", "valid_metrics", "test_metrics"):
  1046. if hasattr(self, metric) and getattr(self, metric) is not None:
  1047. getattr(self, metric).reset()
  1048. @resolve_param("train_metrics_list", ListFactory(MetricsFactory()))
  1049. def _set_train_metrics(self, train_metrics_list):
  1050. self.train_metrics = MetricCollection(train_metrics_list)
  1051. for metric_name, metric in self.train_metrics.items():
  1052. if hasattr(metric, "greater_component_is_better"):
  1053. self.greater_train_metrics_is_better.update(metric.greater_component_is_better)
  1054. elif hasattr(metric, "greater_is_better"):
  1055. self.greater_train_metrics_is_better[metric_name] = metric.greater_is_better
  1056. else:
  1057. self.greater_train_metrics_is_better[metric_name] = None
  1058. @resolve_param("valid_metrics_list", ListFactory(MetricsFactory()))
  1059. def _set_valid_metrics(self, valid_metrics_list):
  1060. self.valid_metrics = MetricCollection(valid_metrics_list)
  1061. for metric_name, metric in self.valid_metrics.items():
  1062. if hasattr(metric, "greater_component_is_better"):
  1063. self.greater_valid_metrics_is_better.update(metric.greater_component_is_better)
  1064. elif hasattr(metric, "greater_is_better"):
  1065. self.greater_valid_metrics_is_better[metric_name] = metric.greater_is_better
  1066. else:
  1067. self.greater_valid_metrics_is_better[metric_name] = None
  1068. @resolve_param("test_metrics_list", ListFactory(MetricsFactory()))
  1069. def _set_test_metrics(self, test_metrics_list):
  1070. self.test_metrics = MetricCollection(test_metrics_list)
  1071. def _initialize_mixed_precision(self, mixed_precision_enabled: bool):
  1072. # SCALER IS ALWAYS INITIALIZED BUT IS DISABLED IF MIXED PRECISION WAS NOT SET
  1073. self.scaler = GradScaler(enabled=mixed_precision_enabled)
  1074. if mixed_precision_enabled:
  1075. assert device_config.device.startswith("cuda"), "mixed precision is not available for CPU"
  1076. if device_config.multi_gpu == MultiGPUMode.DATA_PARALLEL:
  1077. # IN DATAPARALLEL MODE WE NEED TO WRAP THE FORWARD FUNCTION OF OUR MODEL SO IT WILL RUN WITH AUTOCAST.
  1078. # BUT SINCE THE MODULE IS CLONED TO THE DEVICES ON EACH FORWARD CALL OF A DATAPARALLEL MODEL,
  1079. # WE HAVE TO REGISTER THE WRAPPER BEFORE EVERY FORWARD CALL
  1080. def hook(module, _):
  1081. module.forward = MultiGPUModeAutocastWrapper(module.forward)
  1082. self.net.module.register_forward_pre_hook(hook=hook)
  1083. if self.load_checkpoint:
  1084. scaler_state_dict = core_utils.get_param(self.checkpoint, "scaler_state_dict")
  1085. if scaler_state_dict is None:
  1086. logger.warning("Mixed Precision - scaler state_dict not found in loaded model. This may case issues " "with loss scaling")
  1087. else:
  1088. self.scaler.load_state_dict(scaler_state_dict)
  1089. def _validate_final_average_model(self, cleanup_snapshots_pkl_file=False):
  1090. """
  1091. Testing the averaged model by loading the last saved average checkpoint and running test.
  1092. Will be loaded to each of DDP processes
  1093. :param cleanup_pkl_file: a flag for deleting the 10 best snapshots dictionary
  1094. """
  1095. logger.info("RUNNING ADDITIONAL TEST ON THE AVERAGED MODEL...")
  1096. keep_state_dict = deepcopy(self.net.state_dict())
  1097. # SETTING STATE DICT TO THE AVERAGE MODEL FOR EVALUATION
  1098. average_model_ckpt_path = os.path.join(self.checkpoints_dir_path, self.average_model_checkpoint_filename)
  1099. local_rank = get_local_rank()
  1100. # WAIT FOR MASTER RANK TO SAVE THE CKPT BEFORE WE TRY TO READ IT.
  1101. with wait_for_the_master(local_rank):
  1102. average_model_sd = read_ckpt_state_dict(average_model_ckpt_path)["net"]
  1103. self.net.load_state_dict(average_model_sd)
  1104. # testing the averaged model and save instead of best model if needed
  1105. averaged_model_results_tuple = self._validate_epoch(epoch=self.max_epochs)
  1106. # Reverting the current model
  1107. self.net.load_state_dict(keep_state_dict)
  1108. if not self.ddp_silent_mode:
  1109. average_model_tb_titles = ["Averaged Model " + x for x in self.results_titles[-1 * len(averaged_model_results_tuple) :]]
  1110. write_struct = ""
  1111. for ind, title in enumerate(average_model_tb_titles):
  1112. write_struct += "%s: %.3f \n " % (title, averaged_model_results_tuple[ind])
  1113. self.sg_logger.add_scalar(title, averaged_model_results_tuple[ind], global_step=self.max_epochs)
  1114. self.sg_logger.add_text("Averaged_Model_Performance", write_struct, self.max_epochs)
  1115. if cleanup_snapshots_pkl_file:
  1116. self.model_weight_averaging.cleanup()
  1117. @property
  1118. def get_arch_params(self):
  1119. return self.arch_params.to_dict()
  1120. @property
  1121. def get_structure(self):
  1122. return self.net.module.structure
  1123. @property
  1124. def get_architecture(self):
  1125. return self.architecture
  1126. def set_experiment_name(self, experiment_name):
  1127. self.experiment_name = experiment_name
  1128. def _re_build_model(self, arch_params={}):
  1129. """
  1130. arch_params : dict
  1131. Architecture H.P. e.g.: block, num_blocks, num_classes, etc.
  1132. :return:
  1133. """
  1134. if "num_classes" not in arch_params.keys():
  1135. if self.dataset_interface is None:
  1136. raise Exception("Error", "Number of classes not defined in arch params and dataset is not defined")
  1137. else:
  1138. arch_params["num_classes"] = len(self.classes)
  1139. self.arch_params = core_utils.HpmStruct(**arch_params)
  1140. self.classes = self.arch_params.num_classes
  1141. self.net = self._instantiate_net(self.architecture, self.arch_params, self.checkpoint_params)
  1142. # save the architecture for neural architecture search
  1143. if hasattr(self.net, "structure"):
  1144. self.architecture = self.net.structure
  1145. self.net.to(device_config.device)
  1146. if device_config.multi_gpu == MultiGPUMode.DISTRIBUTED_DATA_PARALLEL:
  1147. logger.warning("Warning: distributed training is not supported in re_build_model()")
  1148. self.net = torch.nn.DataParallel(self.net, device_ids=get_device_ids()) if device_config.multi_gpu else core_utils.WrappedModel(self.net)
  1149. @property
  1150. def get_module(self):
  1151. return self.net
  1152. def set_module(self, module):
  1153. self.net = module
  1154. def _switch_device(self, new_device):
  1155. device_config.device = new_device
  1156. self.net.to(device_config.device)
  1157. # FIXME - we need to resolve flake8's 'function is too complex' for this function
  1158. def _load_checkpoint_to_model(self): # noqa: C901 - too complex
  1159. """
  1160. Copies the source checkpoint to a local folder and loads the checkpoint's data to the model using the
  1161. attributes:
  1162. strict: See StrictLoad class documentation for details.
  1163. load_backbone: loads the provided checkpoint to self.net.backbone instead of self.net
  1164. NOTE: 'acc', 'epoch', 'optimizer_state_dict' and the logs are NOT loaded if self.zeroize_prev_train_params
  1165. is True
  1166. """
  1167. with wait_for_the_master(get_local_rank()):
  1168. if self.resume_from_remote_sg_logger and not self.ddp_silent_mode:
  1169. self.sg_logger.download_remote_ckpt(ckpt_name=self.ckpt_name)
  1170. if self.load_checkpoint or self.external_checkpoint_path:
  1171. # GET LOCAL PATH TO THE CHECKPOINT FILE FIRST
  1172. ckpt_root_dir = str(Path(self.checkpoints_dir_path).parent)
  1173. ckpt_local_path = get_ckpt_local_path(
  1174. ckpt_root_dir=ckpt_root_dir,
  1175. experiment_name=self.experiment_name,
  1176. ckpt_name=self.ckpt_name,
  1177. external_checkpoint_path=self.external_checkpoint_path,
  1178. )
  1179. # LOAD CHECKPOINT TO MODEL
  1180. self.checkpoint = load_checkpoint_to_model(
  1181. ckpt_local_path=ckpt_local_path,
  1182. load_backbone=self.load_backbone,
  1183. net=self.net,
  1184. strict=self.strict_load.value if isinstance(self.strict_load, StrictLoad) else self.strict_load,
  1185. load_weights_only=self.load_weights_only,
  1186. load_ema_as_net=self.load_ema_as_net,
  1187. )
  1188. if "ema_net" in self.checkpoint.keys():
  1189. logger.warning(
  1190. "[WARNING] Main network has been loaded from checkpoint but EMA network exists as "
  1191. "well. It "
  1192. " will only be loaded during validation when training with ema=True. "
  1193. )
  1194. # UPDATE TRAINING PARAMS IF THEY EXIST & WE ARE NOT LOADING AN EXTERNAL MODEL's WEIGHTS
  1195. self.best_metric = self.checkpoint["acc"] if "acc" in self.checkpoint.keys() else -1
  1196. self.start_epoch = self.checkpoint["epoch"] if "epoch" in self.checkpoint.keys() else 0
  1197. def _prep_for_test(
  1198. self, test_loader: torch.utils.data.DataLoader = None, loss=None, test_metrics_list=None, loss_logging_items_names=None, test_phase_callbacks=None
  1199. ):
  1200. """Run commands that are common to all models"""
  1201. # SET THE MODEL IN evaluation STATE
  1202. self.net.eval()
  1203. # IF SPECIFIED IN THE FUNCTION CALL - OVERRIDE THE self ARGUMENTS
  1204. self.test_loader = test_loader or self.test_loader
  1205. self.criterion = loss or self.criterion
  1206. self.loss_logging_items_names = loss_logging_items_names or self.loss_logging_items_names
  1207. self.phase_callbacks = test_phase_callbacks or self.phase_callbacks
  1208. if self.phase_callbacks is None:
  1209. self.phase_callbacks = []
  1210. if test_metrics_list:
  1211. self._set_test_metrics(test_metrics_list)
  1212. self._add_metrics_update_callback(Phase.TEST_BATCH_END)
  1213. self.phase_callback_handler = CallbackHandler(self.phase_callbacks)
  1214. # WHEN TESTING WITHOUT A LOSS FUNCTION- CREATE EPOCH HEADERS FOR PRINTS
  1215. if self.criterion is None:
  1216. self.loss_logging_items_names = []
  1217. if self.test_metrics is None:
  1218. raise ValueError(
  1219. "Metrics are required to perform test. Pass them through test_metrics_list arg when "
  1220. "calling test or through training_params when calling train(...)"
  1221. )
  1222. if self.test_loader is None:
  1223. raise ValueError("Test dataloader is required to perform test. Make sure to either pass it through " "test_loader arg.")
  1224. # RESET METRIC RUNNERS
  1225. self._reset_metrics()
  1226. self.test_metrics.to(device_config.device)
  1227. if self.arch_params is None:
  1228. self._init_arch_params()
  1229. self._net_to_device()
  1230. def _add_metrics_update_callback(self, phase: Phase):
  1231. """
  1232. Adds MetricsUpdateCallback to be fired at phase
  1233. :param phase: Phase for the metrics callback to be fired at
  1234. """
  1235. self.phase_callbacks.append(MetricsUpdateCallback(phase))
  1236. def _initialize_sg_logger_objects(self, additional_configs_to_log: Dict = None):
  1237. """Initialize object that collect, write to disk, monitor and store remotely all training outputs"""
  1238. sg_logger = core_utils.get_param(self.training_params, "sg_logger")
  1239. # OVERRIDE SOME PARAMETERS TO MAKE SURE THEY MATCH THE TRAINING PARAMETERS
  1240. general_sg_logger_params = {
  1241. "experiment_name": self.experiment_name,
  1242. "storage_location": "local",
  1243. "resumed": self.load_checkpoint,
  1244. "training_params": self.training_params,
  1245. "checkpoints_dir_path": self.checkpoints_dir_path,
  1246. }
  1247. if sg_logger is None:
  1248. raise RuntimeError("sg_logger must be defined in training params (see default_training_params)")
  1249. if isinstance(sg_logger, AbstractSGLogger):
  1250. self.sg_logger = sg_logger
  1251. elif isinstance(sg_logger, str):
  1252. sg_logger_cls = SG_LOGGERS.get(sg_logger)
  1253. if sg_logger_cls is None:
  1254. raise RuntimeError(f"sg_logger={sg_logger} not registered in SuperGradients. Available {list(SG_LOGGERS.keys())}")
  1255. sg_logger_params = core_utils.get_param(self.training_params, "sg_logger_params", {})
  1256. if issubclass(sg_logger_cls, BaseSGLogger):
  1257. sg_logger_params = {**sg_logger_params, **general_sg_logger_params}
  1258. # Some sg_logger require model_name, but not all of them.
  1259. if "model_name" in get_callable_param_names(sg_logger_cls.__init__):
  1260. if sg_logger_params.get("model_name") is None:
  1261. # Use the model name used in `models.get(...)` if relevant
  1262. sg_logger_params["model_name"] = get_model_name(self.net.module)
  1263. if sg_logger_params["model_name"] is None:
  1264. raise ValueError(
  1265. f'`model_name` is required to use `training_hyperparams.sg_logger="{sg_logger}"`.\n'
  1266. 'Please set `training_hyperparams.sg_logger_params.model_name="<your-model-name>"`.\n'
  1267. "Note that specifying `model_name` is not required when the model was loaded using `models.get(...)`."
  1268. )
  1269. self.sg_logger = sg_logger_cls(**sg_logger_params)
  1270. else:
  1271. raise RuntimeError("sg_logger can be either an sg_logger name (str) or an instance of AbstractSGLogger")
  1272. if not isinstance(self.sg_logger, BaseSGLogger):
  1273. logger.warning(
  1274. "WARNING! Using a user-defined sg_logger: files will not be automatically written to disk!\n"
  1275. "Please make sure the provided sg_logger writes to disk or compose your sg_logger to BaseSGLogger"
  1276. )
  1277. # IN CASE SG_LOGGER UPDATED THE DIR PATH
  1278. self.checkpoints_dir_path = self.sg_logger.local_dir()
  1279. hyper_param_config = self._get_hyper_param_config()
  1280. if additional_configs_to_log is not None:
  1281. hyper_param_config["additional_configs_to_log"] = additional_configs_to_log
  1282. self.sg_logger.add_config("hyper_params", hyper_param_config)
  1283. self.sg_logger.flush()
  1284. def _get_hyper_param_config(self):
  1285. """
  1286. Creates a training hyper param config for logging.
  1287. """
  1288. additional_log_items = {
  1289. "initial_LR": self.training_params.initial_lr,
  1290. "num_devices": get_world_size(),
  1291. "multi_gpu": str(device_config.multi_gpu),
  1292. "device_type": torch.cuda.get_device_name(0) if torch.cuda.is_available() else "cpu",
  1293. }
  1294. # ADD INSTALLED PACKAGE LIST + THEIR VERSIONS
  1295. if self.training_params.log_installed_packages:
  1296. pkg_list = list(map(lambda pkg: str(pkg), _get_installed_distributions()))
  1297. additional_log_items["installed_packages"] = pkg_list
  1298. hyper_param_config = {
  1299. "arch_params": self.arch_params.__dict__,
  1300. "checkpoint_params": self.checkpoint_params.__dict__,
  1301. "training_hyperparams": self.training_params.__dict__,
  1302. "dataset_params": self.dataset_params.__dict__,
  1303. "additional_log_items": additional_log_items,
  1304. }
  1305. return hyper_param_config
  1306. def _write_to_disk_operations(self, train_metrics: tuple, validation_results: tuple, lr_dict: dict, inf_time: float, epoch: int, context: PhaseContext):
  1307. """Run the various logging operations, e.g.: log file, Tensorboard, save checkpoint etc."""
  1308. # STORE VALUES IN A TENSORBOARD FILE
  1309. train_results = list(train_metrics) + list(validation_results) + [inf_time]
  1310. all_titles = self.results_titles + ["Inference Time"]
  1311. result_dict = {all_titles[i]: train_results[i] for i in range(len(train_results))}
  1312. self.sg_logger.add_scalars(tag_scalar_dict=result_dict, global_step=epoch)
  1313. self.sg_logger.add_scalars(tag_scalar_dict=lr_dict, global_step=epoch)
  1314. # SAVE THE CHECKPOINT
  1315. if self.training_params.save_model:
  1316. self._save_checkpoint(self.optimizer, epoch + 1, validation_results, context)
  1317. def _get_epoch_start_logging_values(self) -> dict:
  1318. """Get all the values that should be logged at the start of each epoch.
  1319. This is useful for values like Learning Rate that can change over an epoch."""
  1320. lrs = [self.optimizer.param_groups[i]["lr"] for i in range(len(self.optimizer.param_groups))]
  1321. lr_titles = ["LR/Param_group_" + str(i) for i in range(len(self.optimizer.param_groups))] if len(self.optimizer.param_groups) > 1 else ["LR"]
  1322. lr_dict = {lr_titles[i]: lrs[i] for i in range(len(lrs))}
  1323. return lr_dict
  1324. def test(
  1325. self,
  1326. model: nn.Module = None,
  1327. test_loader: torch.utils.data.DataLoader = None,
  1328. loss: torch.nn.modules.loss._Loss = None,
  1329. silent_mode: bool = False,
  1330. test_metrics_list=None,
  1331. loss_logging_items_names=None,
  1332. metrics_progress_verbose=False,
  1333. test_phase_callbacks=None,
  1334. use_ema_net=True,
  1335. ) -> tuple:
  1336. """
  1337. Evaluates the model on given dataloader and metrics.
  1338. :param model: model to perfrom test on. When none is given, will try to use self.net (defalut=None).
  1339. :param test_loader: dataloader to perform test on.
  1340. :param test_metrics_list: (list(torchmetrics.Metric)) metrics list for evaluation.
  1341. :param silent_mode: (bool) controls verbosity
  1342. :param metrics_progress_verbose: (bool) controls the verbosity of metrics progress (default=False). Slows down the program.
  1343. :param use_ema_net (bool) whether to perform test on self.ema_model.ema (when self.ema_model.ema exists,
  1344. otherwise self.net will be tested) (default=True)
  1345. :return: results tuple (tuple) containing the loss items and metric values.
  1346. All of the above args will override Trainer's corresponding attribute when not equal to None. Then evaluation
  1347. is ran on self.test_loader with self.test_metrics.
  1348. """
  1349. self.net = model or self.net
  1350. # IN CASE TRAINING WAS PERFROMED BEFORE TEST- MAKE SURE TO TEST THE EMA MODEL (UNLESS SPECIFIED OTHERWISE BY
  1351. # use_ema_net)
  1352. if use_ema_net and self.ema_model is not None:
  1353. keep_model = self.net
  1354. self.net = self.ema_model.ema
  1355. self._prep_for_test(
  1356. test_loader=test_loader,
  1357. loss=loss,
  1358. test_metrics_list=test_metrics_list,
  1359. loss_logging_items_names=loss_logging_items_names,
  1360. test_phase_callbacks=test_phase_callbacks,
  1361. )
  1362. context = PhaseContext(
  1363. criterion=self.criterion,
  1364. device=self.device,
  1365. sg_logger=self.sg_logger,
  1366. context_methods=self._get_context_methods(Phase.TEST_BATCH_END),
  1367. )
  1368. if test_metrics_list:
  1369. context.update_context(test_metrics=self.test_metrics)
  1370. self.phase_callback_handler.on_test_loader_start(context)
  1371. test_results = self.evaluate(
  1372. data_loader=self.test_loader,
  1373. metrics=self.test_metrics,
  1374. evaluation_type=EvaluationType.TEST,
  1375. silent_mode=silent_mode,
  1376. metrics_progress_verbose=metrics_progress_verbose,
  1377. )
  1378. self.phase_callback_handler.on_test_loader_end(context)
  1379. # SWITCH BACK BETWEEN NETS SO AN ADDITIONAL TRAINING CAN BE DONE AFTER TEST
  1380. if use_ema_net and self.ema_model is not None:
  1381. self.net = keep_model
  1382. self._first_backward = True
  1383. test_results = get_metrics_dict(test_results, self.test_metrics, self.loss_logging_items_names)
  1384. return test_results
  1385. def _validate_epoch(self, epoch: int, silent_mode: bool = False) -> tuple:
  1386. """
  1387. Runs evaluation on self.valid_loader, with self.valid_metrics.
  1388. :param epoch: (int) epoch idx
  1389. :param silent_mode: (bool) controls verbosity
  1390. :return: results tuple (tuple) containing the loss items and metric values.
  1391. """
  1392. self.net.eval()
  1393. self._reset_metrics()
  1394. self.valid_metrics.to(device_config.device)
  1395. return self.evaluate(
  1396. data_loader=self.valid_loader, metrics=self.valid_metrics, evaluation_type=EvaluationType.VALIDATION, epoch=epoch, silent_mode=silent_mode
  1397. )
  1398. def evaluate(
  1399. self,
  1400. data_loader: torch.utils.data.DataLoader,
  1401. metrics: MetricCollection,
  1402. evaluation_type: EvaluationType,
  1403. epoch: int = None,
  1404. silent_mode: bool = False,
  1405. metrics_progress_verbose: bool = False,
  1406. ):
  1407. """
  1408. Evaluates the model on given dataloader and metrics.
  1409. :param data_loader: dataloader to perform evaluataion on
  1410. :param metrics: (MetricCollection) metrics for evaluation
  1411. :param evaluation_type: (EvaluationType) controls which phase callbacks will be used (for example, on batch end,
  1412. when evaluation_type=EvaluationType.VALIDATION the Phase.VALIDATION_BATCH_END callbacks will be triggered)
  1413. :param epoch: (int) epoch idx
  1414. :param silent_mode: (bool) controls verbosity
  1415. :param metrics_progress_verbose: (bool) controls the verbosity of metrics progress (default=False).
  1416. Slows down the program significantly.
  1417. :return: results tuple (tuple) containing the loss items and metric values.
  1418. """
  1419. # THE DISABLE FLAG CONTROLS WHETHER THE PROGRESS BAR IS SILENT OR PRINTS THE LOGS
  1420. loss_avg_meter = core_utils.utils.AverageMeter()
  1421. logging_values = None
  1422. lr_warmup_epochs = self.training_params.lr_warmup_epochs if self.training_params else None
  1423. context = PhaseContext(
  1424. epoch=epoch,
  1425. metrics_compute_fn=metrics,
  1426. loss_avg_meter=loss_avg_meter,
  1427. criterion=self.criterion,
  1428. device=device_config.device,
  1429. lr_warmup_epochs=lr_warmup_epochs,
  1430. sg_logger=self.sg_logger,
  1431. context_methods=self._get_context_methods(Phase.VALIDATION_BATCH_END),
  1432. )
  1433. with tqdm(data_loader, bar_format="{l_bar}{bar:10}{r_bar}", dynamic_ncols=True, disable=silent_mode) as progress_bar_data_loader:
  1434. if not silent_mode:
  1435. # PRINT TITLES
  1436. pbar_start_msg = f"Validation epoch {epoch}" if evaluation_type == EvaluationType.VALIDATION else "Test"
  1437. progress_bar_data_loader.set_description(pbar_start_msg)
  1438. with torch.no_grad():
  1439. for batch_idx, batch_items in enumerate(progress_bar_data_loader):
  1440. batch_items = core_utils.tensor_container_to_device(batch_items, device_config.device, non_blocking=True)
  1441. inputs, targets, additional_batch_items = sg_trainer_utils.unpack_batch_items(batch_items)
  1442. # TRIGGER PHASE CALLBACKS CORRESPONDING TO THE EVALUATION TYPE
  1443. context.update_context(batch_idx=batch_idx, inputs=inputs, target=targets, **additional_batch_items)
  1444. if evaluation_type == EvaluationType.VALIDATION:
  1445. self.phase_callback_handler.on_validation_batch_start(context)
  1446. else:
  1447. self.phase_callback_handler.on_test_batch_start(context)
  1448. output = self.net(inputs)
  1449. context.update_context(preds=output)
  1450. if self.criterion is not None:
  1451. # STORE THE loss_items ONLY, THE 1ST RETURNED VALUE IS THE loss FOR BACKPROP DURING TRAINING
  1452. loss_tuple = self._get_losses(output, targets)[1].cpu()
  1453. context.update_context(loss_log_items=loss_tuple)
  1454. # TRIGGER PHASE CALLBACKS CORRESPONDING TO THE EVALUATION TYPE
  1455. if evaluation_type == EvaluationType.VALIDATION:
  1456. self.phase_callback_handler.on_validation_batch_end(context)
  1457. else:
  1458. self.phase_callback_handler.on_test_batch_end(context)
  1459. # COMPUTE METRICS IF PROGRESS VERBOSITY IS SET
  1460. if metrics_progress_verbose and not silent_mode:
  1461. # COMPUTE THE RUNNING USER METRICS AND LOSS RUNNING ITEMS. RESULT TUPLE IS THEIR CONCATENATION.
  1462. logging_values = get_logging_values(loss_avg_meter, metrics, self.criterion)
  1463. pbar_message_dict = get_train_loop_description_dict(logging_values, metrics, self.loss_logging_items_names)
  1464. progress_bar_data_loader.set_postfix(**pbar_message_dict)
  1465. if evaluation_type == EvaluationType.VALIDATION and self.max_valid_batches is not None and self.max_valid_batches - 1 <= batch_idx:
  1466. break
  1467. # NEED TO COMPUTE METRICS FOR THE FIRST TIME IF PROGRESS VERBOSITY IS NOT SET
  1468. if not metrics_progress_verbose:
  1469. # COMPUTE THE RUNNING USER METRICS AND LOSS RUNNING ITEMS. RESULT TUPLE IS THEIR CONCATENATION.
  1470. logging_values = get_logging_values(loss_avg_meter, metrics, self.criterion)
  1471. pbar_message_dict = get_train_loop_description_dict(logging_values, metrics, self.loss_logging_items_names)
  1472. progress_bar_data_loader.set_postfix(**pbar_message_dict)
  1473. # TODO: SUPPORT PRINTING AP PER CLASS- SINCE THE METRICS ARE NOT HARD CODED ANYMORE (as done in
  1474. # calc_batch_prediction_accuracy_per_class in metric_utils.py), THIS IS ONLY RELEVANT WHEN CHOOSING
  1475. # DETECTIONMETRICS, WHICH ALREADY RETURN THE METRICS VALUEST HEMSELVES AND NOT THE ITEMS REQUIRED FOR SUCH
  1476. # COMPUTATION. ALSO REMOVE THE BELOW LINES BY IMPLEMENTING CRITERION AS A TORCHMETRIC.
  1477. if device_config.multi_gpu == MultiGPUMode.DISTRIBUTED_DATA_PARALLEL:
  1478. logging_values = reduce_results_tuple_for_ddp(logging_values, next(self.net.parameters()).device)
  1479. pbar_message_dict = get_train_loop_description_dict(logging_values, metrics, self.loss_logging_items_names)
  1480. self.valid_monitored_values = sg_trainer_utils.update_monitored_values_dict(
  1481. monitored_values_dict=self.valid_monitored_values, new_values_dict=pbar_message_dict
  1482. )
  1483. if not silent_mode and evaluation_type == EvaluationType.VALIDATION:
  1484. progress_bar_data_loader.write("===========================================================")
  1485. sg_trainer_utils.display_epoch_summary(
  1486. epoch=context.epoch, n_digits=4, train_monitored_values=self.train_monitored_values, valid_monitored_values=self.valid_monitored_values
  1487. )
  1488. progress_bar_data_loader.write("===========================================================")
  1489. return logging_values
  1490. def _instantiate_net(
  1491. self, architecture: Union[torch.nn.Module, SgModule.__class__, str], arch_params: dict, checkpoint_params: dict, *args, **kwargs
  1492. ) -> tuple:
  1493. """
  1494. Instantiates nn.Module according to architecture and arch_params, and handles pretrained weights and the required
  1495. module manipulation (i.e head replacement).
  1496. :param architecture: String, torch.nn.Module or uninstantiated SgModule class describing the netowrks architecture.
  1497. :param arch_params: Architecture's parameters passed to networks c'tor.
  1498. :param checkpoint_params: checkpoint loading related parameters dictionary with 'pretrained_weights' key,
  1499. s.t it's value is a string describing the dataset of the pretrained weights (for example "imagenent").
  1500. :return: instantiated netowrk i.e torch.nn.Module, architecture_class (will be none when architecture is not str)
  1501. """
  1502. pretrained_weights = core_utils.get_param(checkpoint_params, "pretrained_weights", default_val=None)
  1503. if pretrained_weights is not None:
  1504. num_classes_new_head = arch_params.num_classes
  1505. arch_params.num_classes = PRETRAINED_NUM_CLASSES[pretrained_weights]
  1506. if isinstance(architecture, str):
  1507. architecture_cls = ARCHITECTURES[architecture]
  1508. net = architecture_cls(arch_params=arch_params)
  1509. elif isinstance(architecture, SgModule.__class__):
  1510. net = architecture(arch_params)
  1511. else:
  1512. net = architecture
  1513. if pretrained_weights:
  1514. load_pretrained_weights(net, architecture, pretrained_weights)
  1515. if num_classes_new_head != arch_params.num_classes:
  1516. net.replace_head(new_num_classes=num_classes_new_head)
  1517. arch_params.num_classes = num_classes_new_head
  1518. return net
  1519. def _instantiate_ema_model(self, ema_params: Mapping[str, Any]) -> ModelEMA:
  1520. """Instantiate ema model for standard SgModule.
  1521. :param decay_type: (str) The decay climb schedule. See EMA_DECAY_FUNCTIONS for more details.
  1522. :param decay: The maximum decay value. As the training process advances, the decay will climb towards this value
  1523. according to decay_type schedule. See EMA_DECAY_FUNCTIONS for more details.
  1524. :param kwargs: Additional parameters for the decay function. See EMA_DECAY_FUNCTIONS for more details.
  1525. """
  1526. logger.info(f"Using EMA with params {ema_params}")
  1527. return ModelEMA.from_params(self.net, **ema_params)
  1528. @property
  1529. def get_net(self):
  1530. """
  1531. Getter for network.
  1532. :return: torch.nn.Module, self.net
  1533. """
  1534. return self.net
  1535. def set_net(self, net: torch.nn.Module):
  1536. """
  1537. Setter for network.
  1538. :param net: torch.nn.Module, value to set net
  1539. :return:
  1540. """
  1541. self.net = net
  1542. def set_ckpt_best_name(self, ckpt_best_name):
  1543. """
  1544. Setter for best checkpoint filename.
  1545. :param ckpt_best_name: str, value to set ckpt_best_name
  1546. """
  1547. self.ckpt_best_name = ckpt_best_name
  1548. def set_ema(self, val: bool):
  1549. """
  1550. Setter for self.ema
  1551. :param val: bool, value to set ema
  1552. """
  1553. self.ema = val
  1554. def _get_context_methods(self, phase: Phase) -> ContextSgMethods:
  1555. """
  1556. Returns ContextSgMethods holding the methods that should be accessible through phase callbacks to the user at
  1557. the specific phase
  1558. :param phase: Phase, controls what methods should be returned.
  1559. :return: ContextSgMethods holding methods from self.
  1560. """
  1561. if phase in [
  1562. Phase.PRE_TRAINING,
  1563. Phase.TRAIN_EPOCH_START,
  1564. Phase.TRAIN_EPOCH_END,
  1565. Phase.VALIDATION_EPOCH_END,
  1566. Phase.VALIDATION_EPOCH_END,
  1567. Phase.POST_TRAINING,
  1568. Phase.VALIDATION_END_BEST_EPOCH,
  1569. ]:
  1570. context_methods = ContextSgMethods(
  1571. get_net=self.get_net,
  1572. set_net=self.set_net,
  1573. set_ckpt_best_name=self.set_ckpt_best_name,
  1574. reset_best_metric=self._reset_best_metric,
  1575. validate_epoch=self._validate_epoch,
  1576. set_ema=self.set_ema,
  1577. )
  1578. else:
  1579. context_methods = ContextSgMethods()
  1580. return context_methods
  1581. def _init_loss_logging_names(self, loss_logging_items):
  1582. criterion_name = self.criterion.__class__.__name__
  1583. component_names = None
  1584. if hasattr(self.criterion, "component_names"):
  1585. component_names = self.criterion.component_names
  1586. elif len(loss_logging_items) > 1:
  1587. component_names = ["loss_" + str(i) for i in range(len(loss_logging_items))]
  1588. if component_names is not None:
  1589. self.loss_logging_items_names = [criterion_name + "/" + component_name for component_name in component_names]
  1590. if self.metric_to_watch in component_names:
  1591. self.metric_to_watch = criterion_name + "/" + self.metric_to_watch
  1592. else:
  1593. self.loss_logging_items_names = [criterion_name]
Tip!

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

Comments

Loading...