forked from jankrepl/deepdow
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtest_callbacks.py
336 lines (258 loc) · 9.96 KB
/
test_callbacks.py
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
"""Collection of tests focused on the callbacks module."""
import datetime
import pathlib
import pandas as pd
import pytest
from deepdow.callbacks import (
BenchmarkCallback,
Callback,
EarlyStoppingCallback,
EarlyStoppingException,
ModelCheckpointCallback,
MLFlowCallback,
ProgressBarCallback,
TensorBoardCallback,
ValidationCallback,
)
ALL_METHODS = [
"on_train_begin",
"on_epoch_begin",
"on_batch_begin",
"on_train_interrupt",
"on_batch_end",
"on_epoch_end",
"on_train_end",
]
ALL_CALLBACKS = [
BenchmarkCallback,
Callback,
MLFlowCallback,
ProgressBarCallback,
TensorBoardCallback,
ValidationCallback,
]
@pytest.mark.parametrize("lookbacks", [None, [2, 3]])
def test_benchmark(run_dummy, metadata_dummy, lookbacks):
cb = BenchmarkCallback(lookbacks)
cb.run = run_dummy
run_dummy.callbacks = [] # make sure there are no default callbacks
run_dummy.callbacks.append(cb)
for method_name in ALL_METHODS:
getattr(run_dummy, method_name)(metadata_dummy)
assert isinstance(run_dummy.history.metrics_per_epoch(-1), pd.DataFrame)
assert len(run_dummy.history.metrics["epoch"].unique()) == 1
class TestEarlyStoppingCallback:
def test_error(self, run_dummy, metadata_dummy):
dataloader_name = list(run_dummy.val_dataloaders.keys())[0]
metric_name = list(run_dummy.metrics.keys())[0]
cb_wrong_dataloader = EarlyStoppingCallback(
dataloader_name="fake", metric_name=metric_name
)
cb_wrong_metric = EarlyStoppingCallback(
dataloader_name=dataloader_name, metric_name="fake"
)
cb_wrong_dataloader.run = run_dummy
cb_wrong_metric.run = run_dummy
with pytest.raises(ValueError):
cb_wrong_dataloader.on_train_begin(metadata_dummy)
with pytest.raises(ValueError):
cb_wrong_metric.on_train_begin(metadata_dummy)
def test_basic(self, run_dummy, metadata_dummy):
dataloader_name = list(run_dummy.val_dataloaders.keys())[0]
metric_name = list(run_dummy.metrics.keys())[0]
cb = EarlyStoppingCallback(
dataloader_name=dataloader_name,
metric_name=metric_name,
patience=0,
)
cb.run = run_dummy
cb_val = ValidationCallback()
cb_val.run = run_dummy
run_dummy.callbacks = [
cb_val,
cb,
] # make sure there are no default callbacks
with pytest.raises(EarlyStoppingException):
for method_name in ALL_METHODS:
getattr(run_dummy, method_name)(metadata_dummy)
cb.on_train_interrupt({"exception": EarlyStoppingException()})
class TestMLFlowCallback:
@pytest.mark.parametrize(
"log_benchmarks", [True, False], ids=["log_bmarks", "dont_log_bmarks"]
)
def test_independent(
self, run_dummy, metadata_dummy, tmpdir, log_benchmarks
):
with pytest.raises(ValueError):
MLFlowCallback(
run_name="name",
run_id="some_id",
log_benchmarks=log_benchmarks,
mlflow_path=pathlib.Path(str(tmpdir)),
)
cb = MLFlowCallback(
mlflow_path=pathlib.Path(str(tmpdir)),
experiment_name="test",
log_benchmarks=log_benchmarks,
)
cb.run = run_dummy
run_dummy.callbacks = [cb] # make sure there are no default callbacks
for method_name in ALL_METHODS:
getattr(run_dummy, method_name)(metadata_dummy)
def test_benchmarks(self, run_dummy, metadata_dummy, tmpdir):
cb = MLFlowCallback(
mlflow_path=pathlib.Path(str(tmpdir)),
experiment_name="test",
log_benchmarks=True,
)
cb_bm = BenchmarkCallback()
cb.run = run_dummy
cb_bm.run = run_dummy
run_dummy.callbacks = [
cb_bm,
cb,
] # make sure there are no default callbacks
for method_name in ALL_METHODS:
getattr(run_dummy, method_name)(metadata_dummy)
def test_validation(self, run_dummy, metadata_dummy, tmpdir):
cb = MLFlowCallback(
mlflow_path=pathlib.Path(str(tmpdir)),
experiment_name="test",
log_benchmarks=False,
)
cb_val = ValidationCallback()
cb.run = run_dummy
cb_val.run = run_dummy
run_dummy.callbacks = [
cb_val,
cb,
] # make sure there are no default callbacks
for method_name in ALL_METHODS:
getattr(run_dummy, method_name)(metadata_dummy)
class TestModelCheckpointCallback(Callback):
def test_error(self, run_dummy, metadata_dummy, tmpdir):
dataloader_name = list(run_dummy.val_dataloaders.keys())[0]
metric_name = list(run_dummy.metrics.keys())[0]
folder_path = pathlib.Path(str(tmpdir))
some_file_path = folder_path / "some_file.txt"
some_file_path.touch()
with pytest.raises(NotADirectoryError):
ModelCheckpointCallback(
folder_path=some_file_path,
dataloader_name=dataloader_name,
metric_name=metric_name,
)
cb_wrong_dataloader = ModelCheckpointCallback(
folder_path, dataloader_name="fake", metric_name=metric_name
)
cb_wrong_metric = ModelCheckpointCallback(
folder_path, dataloader_name=dataloader_name, metric_name="fake"
)
cb_wrong_dataloader.run = run_dummy
cb_wrong_metric.run = run_dummy
with pytest.raises(ValueError):
cb_wrong_dataloader.on_train_begin(metadata_dummy)
with pytest.raises(ValueError):
cb_wrong_metric.on_train_begin(metadata_dummy)
def test_basic(self, run_dummy, metadata_dummy, tmpdir):
dataloader_name = list(run_dummy.val_dataloaders.keys())[0]
metric_name = list(run_dummy.metrics.keys())[0]
cb = ModelCheckpointCallback(
folder_path=pathlib.Path(str(tmpdir)),
dataloader_name=dataloader_name,
metric_name=metric_name,
verbose=True,
)
cb.run = run_dummy
cb_val = ValidationCallback()
cb_val.run = run_dummy
run_dummy.callbacks = [
cb_val,
cb,
] # make sure there are no default callbacks
for method_name in ALL_METHODS:
getattr(run_dummy, method_name)(metadata_dummy)
cb.on_train_interrupt({"exception": EarlyStoppingException()})
class TestProgressBarCallback:
@pytest.mark.parametrize("output", ["stderr", "stdout"])
def test_independent(self, run_dummy, metadata_dummy, output):
with pytest.raises(ValueError):
ProgressBarCallback(output="{}_fake".format(output))
cb = ProgressBarCallback(output=output)
cb.run = run_dummy
run_dummy.callbacks = [cb] # make sure there are no default callbacks
for method_name in ALL_METHODS:
getattr(run_dummy, method_name)(metadata_dummy)
def test_validation(self, run_dummy, metadata_dummy):
cb = ProgressBarCallback()
cb_val = ValidationCallback()
cb.run = run_dummy
cb_val.run = run_dummy
run_dummy.callbacks = [
cb_val,
cb,
] # make sure there are no default callbacks
for method_name in ALL_METHODS:
getattr(run_dummy, method_name)(metadata_dummy)
class TestTensorBoardCallback:
@pytest.mark.parametrize(
"ts_type", ["single_inside", "single_outside", "all"]
)
def test_independent(self, run_dummy, metadata_dummy, tmpdir, ts_type):
if ts_type == "single_inside":
ts = metadata_dummy["timestamps"][0]
elif ts_type == "single_outside":
ts = datetime.datetime.now()
elif ts_type == "all":
ts = None
else:
ValueError()
cb = TensorBoardCallback(log_dir=pathlib.Path(str(tmpdir)), ts=ts)
cb.run = run_dummy
run_dummy.callbacks = [cb] # make sure there are no default callbacks
for method_name in ALL_METHODS:
if method_name == "on_batch_end":
run_dummy.network(
metadata_dummy["X_batch"]
) # let the forward hook take effect
getattr(run_dummy, method_name)(metadata_dummy)
@pytest.mark.parametrize(
"bm_available",
[True, False],
ids=["bmarks_available", "bmarks_unavailable"],
)
def test_benchmark(self, run_dummy, metadata_dummy, bm_available, tmpdir):
cb = TensorBoardCallback(
log_benchmarks=True, log_dir=pathlib.Path(str(tmpdir))
)
cb_bm = BenchmarkCallback()
cb.run = run_dummy
cb_bm.run = run_dummy
run_dummy.callbacks = (
[cb_bm, cb] if bm_available else [cb]
) # make sure there are no default callbacks
for method_name in ALL_METHODS:
getattr(run_dummy, method_name)(metadata_dummy)
def test_validation(self, run_dummy, metadata_dummy, tmpdir):
cb = TensorBoardCallback(log_dir=pathlib.Path(str(tmpdir)))
cb_val = ValidationCallback()
cb.run = run_dummy
cb_val.run = run_dummy
run_dummy.callbacks = [
cb_val,
cb,
] # make sure there are no default callbacks
for method_name in ALL_METHODS:
getattr(run_dummy, method_name)(metadata_dummy)
@pytest.mark.parametrize("lookbacks", [None, [2, 3]])
def test_validation(run_dummy, metadata_dummy, lookbacks):
cb = ValidationCallback(lookbacks=lookbacks)
cb.run = run_dummy
run_dummy.callbacks = [cb] # make sure there are no default callbacks
for method_name in ALL_METHODS:
getattr(run_dummy, method_name)(metadata_dummy)
assert isinstance(
run_dummy.history.metrics_per_epoch(metadata_dummy["epoch"]),
pd.DataFrame,
)
assert len(run_dummy.history.metrics["epoch"].unique()) == 1