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 14 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
  1. import os
  2. import unittest
  3. from copy import deepcopy
  4. from torchmetrics import Metric
  5. from super_gradients.training import Trainer
  6. from super_gradients.training.dataloaders.dataloaders import classification_test_dataloader
  7. from super_gradients.training.metrics import Accuracy, Top5
  8. from super_gradients.training.utils.callbacks import PhaseCallback, Phase, PhaseContext
  9. from super_gradients.training.utils.utils import check_models_have_same_weights
  10. from super_gradients.training.models import LeNet
  11. from super_gradients.common.environment.checkpoints_dir_utils import get_checkpoints_dir_path, get_latest_run_id
  12. import torch
  13. class FirstEpochInfoCollector(PhaseCallback):
  14. def __init__(self):
  15. super().__init__(phase=Phase.TRAIN_EPOCH_START)
  16. self.called = False
  17. self.first_epoch = None
  18. self.first_epoch_net = None
  19. def __call__(self, context: PhaseContext):
  20. if not self.called:
  21. self.first_epoch = context.epoch
  22. self.first_epoch_net = deepcopy(context.net)
  23. self.called = True
  24. class DummyEpochMetric(Metric):
  25. """
  26. Dummy metric that returns 10 if epoch is smaller then 3 else 2
  27. """
  28. def __init__(self):
  29. super(DummyEpochMetric, self).__init__()
  30. self.add_state("curr_epoch", default=torch.tensor(0.0))
  31. def update(self, epoch: int):
  32. self.curr_epoch = torch.tensor(epoch)
  33. def compute(self) -> torch.Tensor:
  34. if self.curr_epoch < 3:
  35. return torch.tensor(10)
  36. else:
  37. return torch.tensor(2)
  38. class DummyMetric1(Metric):
  39. """
  40. Dummy metric that always returns 1
  41. """
  42. def __init__(self):
  43. super(DummyMetric1, self).__init__()
  44. self.add_state("curr_val", default=torch.tensor(0.0))
  45. def update(self, epoch: int):
  46. self.curr_val = torch.tensor(1.0)
  47. def compute(self) -> torch.Tensor:
  48. return self.curr_val
  49. class ResumeTrainingTest(unittest.TestCase):
  50. def test_resume_training(self):
  51. train_params = {
  52. "max_epochs": 2,
  53. "lr_updates": [1],
  54. "lr_decay_factor": 0.1,
  55. "lr_mode": "StepLRScheduler",
  56. "lr_warmup_epochs": 0,
  57. "initial_lr": 0.1,
  58. "loss": "CrossEntropyLoss",
  59. "optimizer": "SGD",
  60. "criterion_params": {},
  61. "optimizer_params": {"weight_decay": 1e-4, "momentum": 0.9},
  62. "train_metrics_list": [Accuracy(), Top5()],
  63. "valid_metrics_list": [Accuracy(), Top5()],
  64. "metric_to_watch": "Accuracy",
  65. "greater_metric_to_watch_is_better": True,
  66. }
  67. # Define Model
  68. net = LeNet()
  69. trainer = Trainer("test_resume_training")
  70. trainer.train(model=net, training_params=train_params, train_loader=classification_test_dataloader(), valid_loader=classification_test_dataloader())
  71. # TRAIN FOR 1 MORE EPOCH AND COMPARE THE NET AT THE BEGINNING OF EPOCH 3 AND THE END OF EPOCH NUMBER 2
  72. resume_net = LeNet()
  73. trainer = Trainer("test_resume_training")
  74. first_epoch_cb = FirstEpochInfoCollector()
  75. train_params["resume"] = True
  76. train_params["max_epochs"] = 3
  77. train_params["phase_callbacks"] = [first_epoch_cb]
  78. trainer.train(
  79. model=resume_net, training_params=train_params, train_loader=classification_test_dataloader(), valid_loader=classification_test_dataloader()
  80. )
  81. # ASSERT RELOADED MODEL HAS THE SAME WEIGHTS AS THE MODEL SAVED IN FIRST PART OF TRAINING
  82. self.assertTrue(check_models_have_same_weights(net, first_epoch_cb.first_epoch_net))
  83. # ASSERT WE START FROM THE RIGHT EPOCH NUMBER
  84. self.assertTrue(first_epoch_cb.first_epoch == 2)
  85. def test_resume_run_id_training(self):
  86. ckpt_root_dir = ""
  87. experiment_name = "test_resume_training"
  88. experiment_dir = get_checkpoints_dir_path(ckpt_root_dir=ckpt_root_dir, experiment_name=experiment_name)
  89. original_dir_count = len(os.listdir(experiment_dir))
  90. train_params = {
  91. "max_epochs": 2,
  92. "lr_updates": [1],
  93. "lr_decay_factor": 0.1,
  94. "lr_mode": "StepLRScheduler",
  95. "lr_warmup_epochs": 0,
  96. "initial_lr": 0.1,
  97. "loss": "CrossEntropyLoss",
  98. "optimizer": "SGD",
  99. "criterion_params": {},
  100. "optimizer_params": {"weight_decay": 1e-4, "momentum": 0.9},
  101. "train_metrics_list": [Accuracy(), Top5()],
  102. "valid_metrics_list": [Accuracy(), Top5()],
  103. "metric_to_watch": "Accuracy",
  104. "greater_metric_to_watch_is_better": True,
  105. }
  106. # FIRST TRAINING - Train for 1 epoch
  107. net_v1 = LeNet()
  108. trainer = Trainer(ckpt_root_dir=ckpt_root_dir, experiment_name=experiment_name)
  109. trainer.train(model=net_v1, training_params=train_params, train_loader=classification_test_dataloader(), valid_loader=classification_test_dataloader())
  110. first_run_id = get_latest_run_id(checkpoints_root_dir=ckpt_root_dir, experiment_name=experiment_name)
  111. # Check directory size
  112. self.assertEqual(original_dir_count + 1, len(os.listdir(experiment_dir)), "You should have 1 run folder created only after calling `Trainer.train`.")
  113. # SECOND TRAINING - Train for 1 epoch
  114. net_v2 = LeNet() # We don't want to override the first model
  115. trainer = Trainer(ckpt_root_dir=ckpt_root_dir, experiment_name=experiment_name)
  116. trainer.train(model=net_v2, training_params=train_params, train_loader=classification_test_dataloader(), valid_loader=classification_test_dataloader())
  117. second_run_id = get_latest_run_id(checkpoints_root_dir=ckpt_root_dir, experiment_name=experiment_name)
  118. # Check directory size
  119. self.assertEqual(
  120. original_dir_count + 2, len(os.listdir(experiment_dir)), "You should have 2 run folder created only after calling `Trainer.train` twice."
  121. )
  122. self.assertNotEqual(first_run_id, second_run_id, "First and Second trainings should have different run ids.")
  123. # RESUME
  124. # TRAIN FOR 1 MORE EPOCH AND COMPARE THE NET AT THE BEGINNING OF EPOCH 3 AND THE END OF EPOCH NUMBER 2
  125. first_epoch_cb = FirstEpochInfoCollector()
  126. train_params["run_id"] = first_run_id # Let's run on the first run and make sure it works great
  127. train_params["max_epochs"] = 3
  128. train_params["phase_callbacks"] = [first_epoch_cb]
  129. trainer = Trainer(ckpt_root_dir=ckpt_root_dir, experiment_name=experiment_name)
  130. trainer.train(
  131. model=LeNet(),
  132. training_params=train_params,
  133. train_loader=classification_test_dataloader(),
  134. valid_loader=classification_test_dataloader(),
  135. )
  136. self.assertTrue(check_models_have_same_weights(net_v1, first_epoch_cb.first_epoch_net))
  137. self.assertFalse(check_models_have_same_weights(net_v2, first_epoch_cb.first_epoch_net))
  138. self.assertTrue(first_epoch_cb.first_epoch == 2)
  139. # Resuming should not create a new run
  140. self.assertEqual(
  141. original_dir_count + 2,
  142. len(os.listdir(experiment_dir)),
  143. "You should have only 2 run folder created only after calling `Trainer.train` twice and resuming it once.",
  144. )
  145. def test_resume_external_training(self):
  146. train_params = {
  147. "max_epochs": 2,
  148. "lr_updates": [1],
  149. "lr_decay_factor": 0.1,
  150. "lr_mode": "StepLRScheduler",
  151. "lr_warmup_epochs": 0,
  152. "initial_lr": 0.1,
  153. "loss": "CrossEntropyLoss",
  154. "optimizer": "SGD",
  155. "criterion_params": {},
  156. "optimizer_params": {"weight_decay": 1e-4, "momentum": 0.9},
  157. "train_metrics_list": [Accuracy(), Top5()],
  158. "valid_metrics_list": [Accuracy(), Top5()],
  159. "metric_to_watch": "Accuracy",
  160. "greater_metric_to_watch_is_better": True,
  161. }
  162. # Define Model
  163. net = LeNet()
  164. trainer = Trainer("test_resume_training")
  165. trainer.train(model=net, training_params=train_params, train_loader=classification_test_dataloader(), valid_loader=classification_test_dataloader())
  166. # TRAIN FOR 1 MORE EPOCH AND COMPARE THE NET AT THE BEGINNING OF EPOCH 3 AND THE END OF EPOCH NUMBER 2
  167. resume_net = LeNet()
  168. resume_path = os.path.join(trainer.checkpoints_dir_path, "ckpt_latest.pth")
  169. # SET DIFFERENT EXPERIMENT NAME SO WE LOAD A CHECKPOINT THAT HAS A DIFFERENT PATH FROM THE DEFAULT ONE
  170. trainer = Trainer("test_resume_external_training")
  171. first_epoch_cb = FirstEpochInfoCollector()
  172. train_params["resume_path"] = resume_path
  173. train_params["max_epochs"] = 3
  174. train_params["phase_callbacks"] = [first_epoch_cb]
  175. trainer.train(
  176. model=resume_net, training_params=train_params, train_loader=classification_test_dataloader(), valid_loader=classification_test_dataloader()
  177. )
  178. # ASSERT RELOADED MODEL HAS THE SAME WEIGHTS AS THE MODEL SAVED IN FIRST PART OF TRAINING
  179. self.assertTrue(check_models_have_same_weights(net, first_epoch_cb.first_epoch_net))
  180. # ASSERT WE START FROM THE RIGHT EPOCH NUMBER
  181. self.assertTrue(first_epoch_cb.first_epoch == 2)
  182. def test_resume_external_training_same_dir(self):
  183. ckpt_root_dir = ""
  184. experiment_name = "test_resume_training"
  185. experiment_dir = get_checkpoints_dir_path(ckpt_root_dir=ckpt_root_dir, experiment_name=experiment_name)
  186. original_dir_count = len(os.listdir(experiment_dir))
  187. train_params = {
  188. "max_epochs": 2,
  189. "lr_updates": [1],
  190. "lr_decay_factor": 0.1,
  191. "lr_mode": "StepLRScheduler",
  192. "lr_warmup_epochs": 0,
  193. "initial_lr": 0.1,
  194. "loss": "CrossEntropyLoss",
  195. "optimizer": "SGD",
  196. "criterion_params": {},
  197. "optimizer_params": {"weight_decay": 1e-4, "momentum": 0.9},
  198. "train_metrics_list": [Accuracy(), Top5()],
  199. "valid_metrics_list": [Accuracy(), Top5()],
  200. "metric_to_watch": "Accuracy",
  201. "greater_metric_to_watch_is_better": True,
  202. }
  203. # Train for 1 more epoch
  204. net = LeNet()
  205. trainer = Trainer(ckpt_root_dir=ckpt_root_dir, experiment_name=experiment_name)
  206. trainer.train(model=net, training_params=train_params, train_loader=classification_test_dataloader(), valid_loader=classification_test_dataloader())
  207. # Check directory size
  208. self.assertEqual(original_dir_count + 1, len(os.listdir(experiment_dir)), "You should have 1 run folder created only after calling `Trainer.train`.")
  209. # TRAIN FOR 1 MORE EPOCH AND COMPARE THE NET AT THE BEGINNING OF EPOCH 3 AND THE END OF EPOCH NUMBER 2
  210. resume_net = LeNet()
  211. resume_path = os.path.join(trainer.checkpoints_dir_path, "ckpt_latest.pth")
  212. # SET DIFFERENT EXPERIMENT NAME SO WE LOAD A CHECKPOINT THAT HAS A DIFFERENT PATH FROM THE DEFAULT ONE
  213. trainer = Trainer(ckpt_root_dir=ckpt_root_dir, experiment_name=experiment_dir)
  214. first_epoch_cb = FirstEpochInfoCollector()
  215. train_params["resume_path"] = resume_path
  216. train_params["max_epochs"] = 3
  217. train_params["phase_callbacks"] = [first_epoch_cb]
  218. trainer.train(
  219. model=resume_net, training_params=train_params, train_loader=classification_test_dataloader(), valid_loader=classification_test_dataloader()
  220. )
  221. # ASSERT RELOADED MODEL HAS THE SAME WEIGHTS AS THE MODEL SAVED IN FIRST PART OF TRAINING
  222. self.assertTrue(check_models_have_same_weights(net, first_epoch_cb.first_epoch_net))
  223. # ASSERT WE START FROM THE RIGHT EPOCH NUMBER
  224. self.assertTrue(first_epoch_cb.first_epoch == 2)
  225. # Resuming should create a new run
  226. self.assertEqual(
  227. original_dir_count + 2,
  228. len(os.listdir(experiment_dir)),
  229. "Using resume_path should create a new run folder",
  230. )
  231. def test_resume_training_different_metric_to_watch(self):
  232. """
  233. Tests that if we switch metrics when returning the best_metric
  234. is properly extracted by performing additional test.
  235. We use the dummy epoch metric that will not be optimal in the latest checkpoint on purpose - to check we are
  236. not just using the latest metric.
  237. """
  238. train_params = {
  239. "max_epochs": 4,
  240. "lr_updates": [1],
  241. "lr_decay_factor": 0.1,
  242. "lr_mode": "StepLRScheduler",
  243. "lr_warmup_epochs": 0,
  244. "initial_lr": 0.1,
  245. "loss": "CrossEntropyLoss",
  246. "optimizer": "SGD",
  247. "criterion_params": {},
  248. "optimizer_params": {"weight_decay": 1e-4, "momentum": 0.9},
  249. "train_metrics_list": [],
  250. "valid_metrics_list": [DummyEpochMetric()],
  251. "metric_to_watch": "DummyEpochMetric",
  252. "greater_metric_to_watch_is_better": True,
  253. "average_best_models": False,
  254. }
  255. # Define Model
  256. net = LeNet()
  257. trainer = Trainer("test_resume_training")
  258. trainer.train(model=net, training_params=train_params, train_loader=classification_test_dataloader(), valid_loader=classification_test_dataloader())
  259. # BEST METRIC WILL BE 3 SINCE AT EPOCH 4 IT WILL BE 10 (THIS IS DONE TO CHECK WE ARE NOT TAKING JUST THE LATEST)
  260. self.assertEqual(trainer.best_metric, 10)
  261. # TRAIN FOR 1 MORE EPOCH AND COMPARE THE NET AT THE BEGINNING OF EPOCH 4 AND THE END OF EPOCH NUMBER 3
  262. resume_net = LeNet()
  263. trainer = Trainer("test_resume_training")
  264. train_params["resume"] = True
  265. train_params["max_epochs"] = 5
  266. # CHANGE THE METRIC AND METRIC TO WATCH
  267. train_params["valid_metrics_list"] = [DummyMetric1()]
  268. train_params["metric_to_watch"] = "DummyMetric1"
  269. first_epoch_cb = FirstEpochInfoCollector()
  270. train_params["phase_callbacks"] = [first_epoch_cb]
  271. trainer.train(
  272. model=resume_net, training_params=train_params, train_loader=classification_test_dataloader(), valid_loader=classification_test_dataloader()
  273. )
  274. # ASSERT RELOADED MODEL HAS THE SAME WEIGHTS AS THE MODEL SAVED IN FIRST PART OF TRAINING
  275. self.assertTrue(check_models_have_same_weights(net, first_epoch_cb.first_epoch_net))
  276. # ASSERT WE START FROM THE RIGHT EPOCH NUMBER
  277. self.assertTrue(first_epoch_cb.first_epoch == 4)
  278. # EVEN THOUGH BEST METRIC IS BEFORE RESUME WAS 2 WE ARE SWITCHING METRICS SO THE BEST SHOULD BE 1
  279. self.assertTrue(trainer.best_metric, 1)
  280. if __name__ == "__main__":
  281. unittest.main()
Tip!

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

Comments

Loading...