Skip to content

Commit c336881

Browse files
authored
Added fix to ensure that custom logged metrics within test_epoch_end are appended to the result object even without step reduced metrics (#4251)
1 parent 10a5b58 commit c336881

File tree

2 files changed

+36
-0
lines changed

2 files changed

+36
-0
lines changed

pytorch_lightning/trainer/connectors/logger_connector.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -173,6 +173,9 @@ def _log_on_evaluation_epoch_end_metrics(self, epoch_logs):
173173
# now we log all of them
174174
for dl_idx, dl_metrics in enumerate(step_metrics):
175175
if len(dl_metrics) == 0:
176+
# Ensure custom logged metrics are included if not included with step metrics
177+
if len(epoch_logger_metrics) > 0:
178+
self.eval_loop_results.append(epoch_logger_metrics)
176179
continue
177180

178181
reduced_epoch_metrics = dl_metrics[0].__class__.reduce_on_epoch_end(dl_metrics)

tests/trainer/logging/test_eval_loop_logging_1_0.py

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -311,6 +311,39 @@ def validation_epoch_end(self, outputs) -> None:
311311
assert len(logged_val) == 6
312312

313313

314+
@pytest.mark.parametrize(['batches', 'log_interval', 'max_epochs'], [(1, 1, 1), (64, 32, 2)])
315+
def test_eval_epoch_only_logging(tmpdir, batches, log_interval, max_epochs):
316+
"""
317+
Tests that only test_epoch_end can be used to log, and we return them in the results.
318+
"""
319+
os.environ['PL_DEV_DEBUG'] = '1'
320+
321+
class TestModel(BoringModel):
322+
def test_epoch_end(self, outputs):
323+
self.log('c', torch.tensor(2), on_epoch=True, prog_bar=True, logger=True)
324+
self.log('d/e/f', 2)
325+
326+
model = TestModel()
327+
328+
trainer = Trainer(
329+
default_root_dir=tmpdir,
330+
limit_train_batches=batches,
331+
limit_val_batches=batches,
332+
max_epochs=max_epochs,
333+
log_every_n_steps=log_interval,
334+
weights_summary=None,
335+
)
336+
trainer.fit(model)
337+
results = trainer.test(model)
338+
339+
expected_result_metrics = {
340+
'c': torch.tensor(2),
341+
'd/e/f': 2,
342+
}
343+
for result in results:
344+
assert result == expected_result_metrics
345+
346+
314347
def test_monitor_val_epoch_end(tmpdir):
315348
epoch_min_loss_override = 0
316349
model = SimpleModule()

0 commit comments

Comments
 (0)