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

resume_training_test.py 11 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
  1. import os
  2. import unittest
  3. from copy import deepcopy
  4. from super_gradients.training import Trainer
  5. from super_gradients.training.dataloaders.dataloaders import classification_test_dataloader
  6. from super_gradients.training.metrics import Accuracy, Top5
  7. from super_gradients.training.utils.callbacks import PhaseCallback, Phase, PhaseContext
  8. from super_gradients.training.utils.utils import check_models_have_same_weights
  9. from super_gradients.training.models import LeNet
  10. from super_gradients.common.environment.checkpoints_dir_utils import get_checkpoints_dir_path, get_latest_run_id
  11. class FirstEpochInfoCollector(PhaseCallback):
  12. def __init__(self):
  13. super().__init__(phase=Phase.TRAIN_EPOCH_START)
  14. self.called = False
  15. self.first_epoch = None
  16. self.first_epoch_net = None
  17. def __call__(self, context: PhaseContext):
  18. if not self.called:
  19. self.first_epoch = context.epoch
  20. self.first_epoch_net = deepcopy(context.net)
  21. self.called = True
  22. class ResumeTrainingTest(unittest.TestCase):
  23. def test_resume_training(self):
  24. train_params = {
  25. "max_epochs": 2,
  26. "lr_updates": [1],
  27. "lr_decay_factor": 0.1,
  28. "lr_mode": "step",
  29. "lr_warmup_epochs": 0,
  30. "initial_lr": 0.1,
  31. "loss": "cross_entropy",
  32. "optimizer": "SGD",
  33. "criterion_params": {},
  34. "optimizer_params": {"weight_decay": 1e-4, "momentum": 0.9},
  35. "train_metrics_list": [Accuracy(), Top5()],
  36. "valid_metrics_list": [Accuracy(), Top5()],
  37. "metric_to_watch": "Accuracy",
  38. "greater_metric_to_watch_is_better": True,
  39. }
  40. # Define Model
  41. net = LeNet()
  42. trainer = Trainer("test_resume_training")
  43. trainer.train(model=net, training_params=train_params, train_loader=classification_test_dataloader(), valid_loader=classification_test_dataloader())
  44. # TRAIN FOR 1 MORE EPOCH AND COMPARE THE NET AT THE BEGINNING OF EPOCH 3 AND THE END OF EPOCH NUMBER 2
  45. resume_net = LeNet()
  46. trainer = Trainer("test_resume_training")
  47. first_epoch_cb = FirstEpochInfoCollector()
  48. train_params["resume"] = True
  49. train_params["max_epochs"] = 3
  50. train_params["phase_callbacks"] = [first_epoch_cb]
  51. trainer.train(
  52. model=resume_net, training_params=train_params, train_loader=classification_test_dataloader(), valid_loader=classification_test_dataloader()
  53. )
  54. # ASSERT RELOADED MODEL HAS THE SAME WEIGHTS AS THE MODEL SAVED IN FIRST PART OF TRAINING
  55. self.assertTrue(check_models_have_same_weights(net, first_epoch_cb.first_epoch_net))
  56. # ASSERT WE START FROM THE RIGHT EPOCH NUMBER
  57. self.assertTrue(first_epoch_cb.first_epoch == 2)
  58. def test_resume_run_id_training(self):
  59. ckpt_root_dir = ""
  60. experiment_name = "test_resume_training"
  61. experiment_dir = get_checkpoints_dir_path(ckpt_root_dir=ckpt_root_dir, experiment_name=experiment_name)
  62. original_dir_count = len(os.listdir(experiment_dir))
  63. train_params = {
  64. "max_epochs": 2,
  65. "lr_updates": [1],
  66. "lr_decay_factor": 0.1,
  67. "lr_mode": "step",
  68. "lr_warmup_epochs": 0,
  69. "initial_lr": 0.1,
  70. "loss": "cross_entropy",
  71. "optimizer": "SGD",
  72. "criterion_params": {},
  73. "optimizer_params": {"weight_decay": 1e-4, "momentum": 0.9},
  74. "train_metrics_list": [Accuracy(), Top5()],
  75. "valid_metrics_list": [Accuracy(), Top5()],
  76. "metric_to_watch": "Accuracy",
  77. "greater_metric_to_watch_is_better": True,
  78. }
  79. # FIRST TRAINING - Train for 1 epoch
  80. net_v1 = LeNet()
  81. trainer = Trainer(ckpt_root_dir=ckpt_root_dir, experiment_name=experiment_name)
  82. trainer.train(model=net_v1, training_params=train_params, train_loader=classification_test_dataloader(), valid_loader=classification_test_dataloader())
  83. first_run_id = get_latest_run_id(checkpoints_root_dir=ckpt_root_dir, experiment_name=experiment_name)
  84. # Check directory size
  85. self.assertEqual(original_dir_count + 1, len(os.listdir(experiment_dir)), "You should have 1 run folder created only after calling `Trainer.train`.")
  86. # SECOND TRAINING - Train for 1 epoch
  87. net_v2 = LeNet() # We don't want to override the first model
  88. trainer = Trainer(ckpt_root_dir=ckpt_root_dir, experiment_name=experiment_name)
  89. trainer.train(model=net_v2, training_params=train_params, train_loader=classification_test_dataloader(), valid_loader=classification_test_dataloader())
  90. second_run_id = get_latest_run_id(checkpoints_root_dir=ckpt_root_dir, experiment_name=experiment_name)
  91. # Check directory size
  92. self.assertEqual(
  93. original_dir_count + 2, len(os.listdir(experiment_dir)), "You should have 2 run folder created only after calling `Trainer.train` twice."
  94. )
  95. self.assertNotEqual(first_run_id, second_run_id, "First and Second trainings should have different run ids.")
  96. # RESUME
  97. # TRAIN FOR 1 MORE EPOCH AND COMPARE THE NET AT THE BEGINNING OF EPOCH 3 AND THE END OF EPOCH NUMBER 2
  98. first_epoch_cb = FirstEpochInfoCollector()
  99. train_params["run_id"] = first_run_id # Let's run on the first run and make sure it works great
  100. train_params["max_epochs"] = 3
  101. train_params["phase_callbacks"] = [first_epoch_cb]
  102. trainer = Trainer(ckpt_root_dir=ckpt_root_dir, experiment_name=experiment_name)
  103. trainer.train(
  104. model=LeNet(),
  105. training_params=train_params,
  106. train_loader=classification_test_dataloader(),
  107. valid_loader=classification_test_dataloader(),
  108. )
  109. self.assertTrue(check_models_have_same_weights(net_v1, first_epoch_cb.first_epoch_net))
  110. self.assertFalse(check_models_have_same_weights(net_v2, first_epoch_cb.first_epoch_net))
  111. self.assertTrue(first_epoch_cb.first_epoch == 2)
  112. # Resuming should not create a new run
  113. self.assertEqual(
  114. original_dir_count + 2,
  115. len(os.listdir(experiment_dir)),
  116. "You should have only 2 run folder created only after calling `Trainer.train` twice and resuming it once.",
  117. )
  118. def test_resume_external_training(self):
  119. train_params = {
  120. "max_epochs": 2,
  121. "lr_updates": [1],
  122. "lr_decay_factor": 0.1,
  123. "lr_mode": "step",
  124. "lr_warmup_epochs": 0,
  125. "initial_lr": 0.1,
  126. "loss": "cross_entropy",
  127. "optimizer": "SGD",
  128. "criterion_params": {},
  129. "optimizer_params": {"weight_decay": 1e-4, "momentum": 0.9},
  130. "train_metrics_list": [Accuracy(), Top5()],
  131. "valid_metrics_list": [Accuracy(), Top5()],
  132. "metric_to_watch": "Accuracy",
  133. "greater_metric_to_watch_is_better": True,
  134. }
  135. # Define Model
  136. net = LeNet()
  137. trainer = Trainer("test_resume_training")
  138. trainer.train(model=net, training_params=train_params, train_loader=classification_test_dataloader(), valid_loader=classification_test_dataloader())
  139. # TRAIN FOR 1 MORE EPOCH AND COMPARE THE NET AT THE BEGINNING OF EPOCH 3 AND THE END OF EPOCH NUMBER 2
  140. resume_net = LeNet()
  141. resume_path = os.path.join(trainer.checkpoints_dir_path, "ckpt_latest.pth")
  142. # SET DIFFERENT EXPERIMENT NAME SO WE LOAD A CHECKPOINT THAT HAS A DIFFERENT PATH FROM THE DEFAULT ONE
  143. trainer = Trainer("test_resume_external_training")
  144. first_epoch_cb = FirstEpochInfoCollector()
  145. train_params["resume_path"] = resume_path
  146. train_params["max_epochs"] = 3
  147. train_params["phase_callbacks"] = [first_epoch_cb]
  148. trainer.train(
  149. model=resume_net, training_params=train_params, train_loader=classification_test_dataloader(), valid_loader=classification_test_dataloader()
  150. )
  151. # ASSERT RELOADED MODEL HAS THE SAME WEIGHTS AS THE MODEL SAVED IN FIRST PART OF TRAINING
  152. self.assertTrue(check_models_have_same_weights(net, first_epoch_cb.first_epoch_net))
  153. # ASSERT WE START FROM THE RIGHT EPOCH NUMBER
  154. self.assertTrue(first_epoch_cb.first_epoch == 2)
  155. def test_resume_external_training_same_dir(self):
  156. ckpt_root_dir = ""
  157. experiment_name = "test_resume_training"
  158. experiment_dir = get_checkpoints_dir_path(ckpt_root_dir=ckpt_root_dir, experiment_name=experiment_name)
  159. original_dir_count = len(os.listdir(experiment_dir))
  160. train_params = {
  161. "max_epochs": 2,
  162. "lr_updates": [1],
  163. "lr_decay_factor": 0.1,
  164. "lr_mode": "step",
  165. "lr_warmup_epochs": 0,
  166. "initial_lr": 0.1,
  167. "loss": "cross_entropy",
  168. "optimizer": "SGD",
  169. "criterion_params": {},
  170. "optimizer_params": {"weight_decay": 1e-4, "momentum": 0.9},
  171. "train_metrics_list": [Accuracy(), Top5()],
  172. "valid_metrics_list": [Accuracy(), Top5()],
  173. "metric_to_watch": "Accuracy",
  174. "greater_metric_to_watch_is_better": True,
  175. }
  176. # Train for 1 more epoch
  177. net = LeNet()
  178. trainer = Trainer(ckpt_root_dir=ckpt_root_dir, experiment_name=experiment_name)
  179. trainer.train(model=net, training_params=train_params, train_loader=classification_test_dataloader(), valid_loader=classification_test_dataloader())
  180. # Check directory size
  181. self.assertEqual(original_dir_count + 1, len(os.listdir(experiment_dir)), "You should have 1 run folder created only after calling `Trainer.train`.")
  182. # TRAIN FOR 1 MORE EPOCH AND COMPARE THE NET AT THE BEGINNING OF EPOCH 3 AND THE END OF EPOCH NUMBER 2
  183. resume_net = LeNet()
  184. resume_path = os.path.join(trainer.checkpoints_dir_path, "ckpt_latest.pth")
  185. # SET DIFFERENT EXPERIMENT NAME SO WE LOAD A CHECKPOINT THAT HAS A DIFFERENT PATH FROM THE DEFAULT ONE
  186. trainer = Trainer(ckpt_root_dir=ckpt_root_dir, experiment_name=experiment_dir)
  187. first_epoch_cb = FirstEpochInfoCollector()
  188. train_params["resume_path"] = resume_path
  189. train_params["max_epochs"] = 3
  190. train_params["phase_callbacks"] = [first_epoch_cb]
  191. trainer.train(
  192. model=resume_net, training_params=train_params, train_loader=classification_test_dataloader(), valid_loader=classification_test_dataloader()
  193. )
  194. # ASSERT RELOADED MODEL HAS THE SAME WEIGHTS AS THE MODEL SAVED IN FIRST PART OF TRAINING
  195. self.assertTrue(check_models_have_same_weights(net, first_epoch_cb.first_epoch_net))
  196. # ASSERT WE START FROM THE RIGHT EPOCH NUMBER
  197. self.assertTrue(first_epoch_cb.first_epoch == 2)
  198. # Resuming should create a new run
  199. self.assertEqual(
  200. original_dir_count + 2,
  201. len(os.listdir(experiment_dir)),
  202. "Using resume_path should create a new run folder",
  203. )
  204. if __name__ == "__main__":
  205. unittest.main()
Tip!

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

Comments

Loading...