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

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

Comments

Loading...