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