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

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

Comments

Loading...