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

early_stop_test.py 9.0 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
  1. import torch
  2. import torch.nn as nn
  3. import unittest
  4. from super_gradients.training.dataloaders.dataloaders import classification_test_dataloader
  5. from super_gradients.training.utils.early_stopping import EarlyStop
  6. from super_gradients.training.utils.callbacks import Phase
  7. from super_gradients.training.sg_trainer import Trainer
  8. from super_gradients.training.models.classification_models.resnet import ResNet18
  9. from super_gradients.training.metrics import Accuracy, Top5
  10. from torchmetrics.metric import Metric
  11. class MetricTest(Metric):
  12. def __init__(self, metric_values):
  13. super().__init__()
  14. self.metrics_values = metric_values
  15. self.count = 0
  16. def update(self, *args, **kwargs) -> None:
  17. pass
  18. def compute(self):
  19. value = self.metrics_values[self.count]
  20. self.count += 1
  21. return value
  22. class LossTest(nn.Module):
  23. def __init__(self, loss_values):
  24. super(LossTest, self).__init__()
  25. self.loss_values = loss_values
  26. self.count = 0
  27. def forward(self, pred, label):
  28. # double the loss values, one step for training and one for validation
  29. # make returned loss differentiable
  30. loss = (pred * 0).sum() + self.loss_values[self.count // 2]
  31. self.count += 1
  32. return loss, torch.stack([loss]).detach()
  33. class EarlyStopTest(unittest.TestCase):
  34. def setUp(self) -> None:
  35. # batch_size is equal to length of dataset, to have only one step per epoch, to ease the test.
  36. self.net = ResNet18(num_classes=5, arch_params={})
  37. self.max_epochs = 10
  38. self.train_params = {
  39. "max_epochs": self.max_epochs,
  40. "lr_updates": [1],
  41. "lr_decay_factor": 0.1,
  42. "lr_mode": "StepLRScheduler",
  43. "lr_warmup_epochs": 0,
  44. "initial_lr": 0.1,
  45. "loss": "CrossEntropyLoss",
  46. "optimizer": "SGD",
  47. "optimizer_params": {"weight_decay": 1e-4, "momentum": 0.9},
  48. "train_metrics_list": [Accuracy()],
  49. "valid_metrics_list": [Top5()],
  50. "metric_to_watch": "Top5",
  51. "greater_metric_to_watch_is_better": True,
  52. "average_best_models": False,
  53. }
  54. def test_min_mode_patience_metric(self):
  55. """
  56. Test for mode=min metric, test that training stops after no improvement in metric value for amount of `patience`
  57. epochs.
  58. """
  59. trainer = Trainer("early_stop_test")
  60. early_stop_loss = EarlyStop(Phase.VALIDATION_EPOCH_END, monitor="LossTest", mode="min", patience=3, verbose=True)
  61. phase_callbacks = [early_stop_loss]
  62. loss_values = torch.tensor([1.0, 0.8, 0.81, 0.8, 0.9, 0.2, 0.1, 0.3, 0.05, 0.9])
  63. fake_loss = LossTest(loss_values)
  64. train_params = self.train_params.copy()
  65. train_params.update({"loss": fake_loss, "phase_callbacks": phase_callbacks})
  66. trainer.train(
  67. model=self.net, training_params=train_params, train_loader=classification_test_dataloader(), valid_loader=classification_test_dataloader()
  68. )
  69. excepted_end_epoch = 5
  70. # count divided by 2, because loss counter used for both train and eval.
  71. self.assertEqual(excepted_end_epoch, fake_loss.count // 2)
  72. def test_max_mode_patience_metric(self):
  73. """
  74. Test for mode=max metric, test that training stops after no improvement in metric value for amount of `patience`
  75. epochs.
  76. """
  77. trainer = Trainer("early_stop_test")
  78. early_stop_acc = EarlyStop(Phase.VALIDATION_EPOCH_END, monitor="MetricTest", mode="max", patience=3, verbose=True)
  79. phase_callbacks = [early_stop_acc]
  80. metric_values = torch.tensor([0.2, 0.1, 0.3, 0.28, 0.2, 0.1, 0.33, 0.05, 0.9, 0.99])
  81. fake_metric = MetricTest(metric_values)
  82. train_params = self.train_params.copy()
  83. train_params.update({"valid_metrics_list": [fake_metric], "metric_to_watch": "MetricTest", "phase_callbacks": phase_callbacks})
  84. trainer.train(
  85. model=self.net, training_params=train_params, train_loader=classification_test_dataloader(), valid_loader=classification_test_dataloader()
  86. )
  87. excepted_end_epoch = 6
  88. self.assertEqual(excepted_end_epoch, fake_metric.count)
  89. def test_min_mode_threshold_metric(self):
  90. """
  91. Test for mode=min metric, test that training stops after metric value reaches the `threshold` value.
  92. """
  93. trainer = Trainer("early_stop_test")
  94. early_stop_loss = EarlyStop(Phase.VALIDATION_EPOCH_END, monitor="LossTest", mode="min", threshold=0.1, verbose=True)
  95. phase_callbacks = [early_stop_loss]
  96. loss_values = torch.tensor([1.0, 0.8, 0.4, 0.2, 0.09, 0.11, 0.105, 0.3, 0.05, 0.02])
  97. fake_loss = LossTest(loss_values)
  98. train_params = self.train_params.copy()
  99. train_params.update({"loss": fake_loss, "phase_callbacks": phase_callbacks})
  100. trainer.train(
  101. model=self.net, training_params=train_params, train_loader=classification_test_dataloader(), valid_loader=classification_test_dataloader()
  102. )
  103. excepted_end_epoch = 5
  104. # count divided by 2, because loss counter used for both train and eval.
  105. self.assertEqual(excepted_end_epoch, fake_loss.count // 2)
  106. def test_max_mode_threshold_metric(self):
  107. """
  108. Test for mode=max metric, test that training stops after metric value reaches the `threshold` value.
  109. """
  110. trainer = Trainer("early_stop_test")
  111. early_stop_acc = EarlyStop(Phase.VALIDATION_EPOCH_END, monitor="MetricTest", mode="max", threshold=0.94, verbose=True)
  112. phase_callbacks = [early_stop_acc]
  113. metric_values = torch.tensor([0.2, 0.1, 0.6, 0.8, 0.9, 0.92, 0.95, 0.94, 0.948, 0.99])
  114. fake_metric = MetricTest(metric_values)
  115. train_params = self.train_params.copy()
  116. train_params.update({"valid_metrics_list": [fake_metric], "metric_to_watch": "MetricTest", "phase_callbacks": phase_callbacks})
  117. trainer.train(
  118. model=self.net, training_params=train_params, train_loader=classification_test_dataloader(), valid_loader=classification_test_dataloader()
  119. )
  120. excepted_end_epoch = 7
  121. self.assertEqual(excepted_end_epoch, fake_metric.count)
  122. def test_no_finite_stoppage(self):
  123. """
  124. Test that training stops when monitor value is not a finite number. Test case of NaN and Inf values.
  125. """
  126. # test Nan value
  127. trainer = Trainer("early_stop_test")
  128. early_stop_loss = EarlyStop(Phase.VALIDATION_EPOCH_END, monitor="LossTest", mode="min", check_finite=True, verbose=True)
  129. phase_callbacks = [early_stop_loss]
  130. loss_values = torch.tensor([1.0, float("nan"), 0.81, 0.8, 0.9, 0.2, 0.1, 0.3, 0.05, 0.9])
  131. fake_loss = LossTest(loss_values)
  132. train_params = self.train_params.copy()
  133. train_params.update({"loss": fake_loss, "phase_callbacks": phase_callbacks})
  134. trainer.train(
  135. model=self.net, training_params=train_params, train_loader=classification_test_dataloader(), valid_loader=classification_test_dataloader()
  136. )
  137. excepted_end_epoch = 2
  138. self.assertEqual(excepted_end_epoch, fake_loss.count // 2)
  139. # test Inf value
  140. trainer = Trainer("early_stop_test")
  141. early_stop_loss = EarlyStop(Phase.VALIDATION_EPOCH_END, monitor="LossTest", mode="min", patience=3, verbose=True)
  142. phase_callbacks = [early_stop_loss]
  143. loss_values = torch.tensor([1.0, 0.8, float("inf"), 0.8, 0.9, 0.2, 0.1, 0.3, 0.05, 0.9])
  144. fake_loss = LossTest(loss_values)
  145. train_params = self.train_params.copy()
  146. train_params.update({"loss": fake_loss, "phase_callbacks": phase_callbacks})
  147. trainer.train(
  148. model=self.net, training_params=train_params, train_loader=classification_test_dataloader(), valid_loader=classification_test_dataloader()
  149. )
  150. excepted_end_epoch = 3
  151. # count divided by 2, because loss counter used for both train and eval.
  152. self.assertEqual(excepted_end_epoch, fake_loss.count // 2)
  153. def test_min_delta(self):
  154. """
  155. Test for `min_delta` argument, metric value is considered an improvement only if
  156. current_value - min_delta > best_value
  157. """
  158. trainer = Trainer("early_stop_test")
  159. early_stop_acc = EarlyStop(Phase.VALIDATION_EPOCH_END, monitor="MetricTest", mode="max", patience=2, min_delta=0.1, verbose=True)
  160. phase_callbacks = [early_stop_acc]
  161. metric_values = torch.tensor([0.1, 0.2, 0.305, 0.31, 0.34, 0.42, 0.6, 0.8, 0.9, 0.99])
  162. fake_metric = MetricTest(metric_values)
  163. train_params = self.train_params.copy()
  164. train_params.update({"valid_metrics_list": [fake_metric], "metric_to_watch": "MetricTest", "phase_callbacks": phase_callbacks})
  165. trainer.train(
  166. model=self.net, training_params=train_params, train_loader=classification_test_dataloader(), valid_loader=classification_test_dataloader()
  167. )
  168. excepted_end_epoch = 5
  169. self.assertEqual(excepted_end_epoch, fake_metric.count)
  170. if __name__ == "__main__":
  171. unittest.main()
Tip!

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

Comments

Loading...