-
Notifications
You must be signed in to change notification settings - Fork 3.5k
/
Copy pathtest_callback_hook_outputs.py
80 lines (61 loc) · 2.57 KB
/
test_callback_hook_outputs.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
# Copyright The PyTorch Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import pytest
from pytorch_lightning import Callback, Trainer
from tests.helpers.boring_model import BoringModel
@pytest.mark.parametrize("single_cb", [False, True])
def test_train_step_no_return(tmpdir, single_cb: bool):
"""Tests that only training_step can be used."""
class CB(Callback):
def on_train_batch_end(self, trainer, pl_module, outputs, batch, batch_idx):
assert "loss" in outputs
def on_validation_batch_end(self, trainer, pl_module, outputs, batch, batch_idx, dataloader_idx):
assert "x" in outputs
def on_test_batch_end(self, trainer, pl_module, outputs, batch, batch_idx, dataloader_idx):
assert "x" in outputs
class TestModel(BoringModel):
def on_train_batch_end(self, outputs, batch, batch_idx: int) -> None:
assert "loss" in outputs
def on_validation_batch_end(self, outputs, batch, batch_idx: int, dataloader_idx: int) -> None:
assert "x" in outputs
def on_test_batch_end(self, outputs, batch, batch_idx: int, dataloader_idx: int) -> None:
assert "x" in outputs
def training_epoch_end(self, outputs) -> None:
assert len(outputs) == self.trainer.num_training_batches
model = TestModel()
trainer = Trainer(
callbacks=CB() if single_cb else [CB()],
default_root_dir=tmpdir,
limit_train_batches=2,
limit_val_batches=2,
max_epochs=1,
log_every_n_steps=1,
weights_summary=None,
)
assert any(isinstance(c, CB) for c in trainer.callbacks)
trainer.fit(model)
def test_free_memory_on_eval_outputs(tmpdir):
class CB(Callback):
def on_epoch_end(self, trainer, pl_module):
assert len(trainer._evaluation_loop.outputs) == 0
model = BoringModel()
trainer = Trainer(
callbacks=CB(),
default_root_dir=tmpdir,
limit_train_batches=2,
limit_val_batches=2,
max_epochs=1,
weights_summary=None,
)
trainer.fit(model)