lightning/tests/tests_pytorch/loggers/test_all.py

342 lines
13 KiB
Python
Raw Normal View History

2020-10-13 11:18:07 +00:00
# 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 contextlib
import inspect
import pickle
from unittest import mock
from unittest.mock import ANY
import pytest
import torch
from pytorch_lightning import Callback, Trainer
from pytorch_lightning.demos.boring_classes import BoringModel
from pytorch_lightning.loggers import (
CometLogger,
2021-06-09 13:07:02 +00:00
CSVLogger,
MLFlowLogger,
NeptuneLogger,
TensorBoardLogger,
WandbLogger,
)
from pytorch_lightning.loggers.logger import DummyExperiment
from tests_pytorch.helpers.runif import RunIf
from tests_pytorch.loggers.test_comet import _patch_comet_atexit
from tests_pytorch.loggers.test_mlflow import mock_mlflow_run_creation
from tests_pytorch.loggers.test_neptune import create_neptune_mock
LOGGER_CTX_MANAGERS = (
mock.patch("pytorch_lightning.loggers.comet.comet_ml"),
mock.patch("pytorch_lightning.loggers.comet.CometOfflineExperiment"),
mock.patch("pytorch_lightning.loggers.mlflow.mlflow"),
mock.patch("pytorch_lightning.loggers.mlflow.MlflowClient"),
mock.patch("pytorch_lightning.loggers.neptune.neptune", new_callable=create_neptune_mock),
mock.patch("pytorch_lightning.loggers.neptune._NEPTUNE_AVAILABLE", return_value=True),
mock.patch("pytorch_lightning.loggers.wandb.wandb"),
mock.patch("pytorch_lightning.loggers.wandb.Run", new=mock.Mock),
)
ALL_LOGGER_CLASSES = (
CometLogger,
CSVLogger,
MLFlowLogger,
NeptuneLogger,
TensorBoardLogger,
WandbLogger,
)
ALL_LOGGER_CLASSES_WO_NEPTUNE = tuple(filter(lambda cls: cls is not NeptuneLogger, ALL_LOGGER_CLASSES))
ALL_LOGGER_CLASSES_WO_NEPTUNE_WANDB = tuple(filter(lambda cls: cls is not WandbLogger, ALL_LOGGER_CLASSES_WO_NEPTUNE))
2020-04-15 15:14:29 +00:00
def _get_logger_args(logger_class, save_dir):
logger_args = {}
if "save_dir" in inspect.getfullargspec(logger_class).args:
2020-04-15 15:14:29 +00:00
logger_args.update(save_dir=str(save_dir))
if "offline_mode" in inspect.getfullargspec(logger_class).args:
2020-04-15 15:14:29 +00:00
logger_args.update(offline_mode=True)
if "offline" in inspect.getfullargspec(logger_class).args:
logger_args.update(offline=True)
if issubclass(logger_class, NeptuneLogger):
logger_args.update(mode="offline")
2020-04-15 15:14:29 +00:00
return logger_args
2021-05-19 19:50:58 +00:00
def _instantiate_logger(logger_class, save_dir, **override_kwargs):
args = _get_logger_args(logger_class, save_dir)
args.update(**override_kwargs)
logger = logger_class(**args)
return logger
@pytest.mark.parametrize("logger_class", ALL_LOGGER_CLASSES)
def test_loggers_fit_test_all(tmpdir, monkeypatch, logger_class):
"""Verify that basic functionality of all loggers."""
with contextlib.ExitStack() as stack:
for mgr in LOGGER_CTX_MANAGERS:
stack.enter_context(mgr)
_test_loggers_fit_test(tmpdir, logger_class)
def _test_loggers_fit_test(tmpdir, logger_class):
class CustomModel(BoringModel):
def training_step(self, batch, batch_idx):
output = self.layer(batch)
loss = self.loss(batch, output)
self.log("train_some_val", loss)
return {"loss": loss}
def validation_epoch_end(self, outputs) -> None:
avg_val_loss = torch.stack([x["x"] for x in outputs]).mean()
self.log_dict({"early_stop_on": avg_val_loss, "val_loss": avg_val_loss**0.5})
def test_epoch_end(self, outputs) -> None:
avg_test_loss = torch.stack([x["y"] for x in outputs]).mean()
self.log("test_loss", avg_test_loss)
class StoreHistoryLogger(logger_class):
2021-04-27 20:23:55 +00:00
def __init__(self, *args, **kwargs) -> None:
super().__init__(*args, **kwargs)
self.history = []
def log_metrics(self, metrics, step):
super().log_metrics(metrics, step)
self.history.append((step, metrics))
2020-04-15 15:14:29 +00:00
logger_args = _get_logger_args(logger_class, tmpdir)
logger = StoreHistoryLogger(**logger_args)
if logger_class == WandbLogger:
# required mocks for Trainer
logger.experiment.id = "foo"
logger.experiment.name = "bar"
if logger_class == CometLogger:
logger.experiment.id = "foo"
logger.experiment.project_name = "bar"
Mocking Loggers Part 5/5 (final) (#3926) * base * add xfail * new test * import * missing import * xfail if not installed include mkpatch fix test * mock comet comet mocks fix test remove dep undo merge duplication * line * line * convert doctest * doctest * docs * prune Results usage in notebooks (#3911) * notebooks * notebooks * revamp entire metrics (#3868) * removed metric Co-authored-by: Teddy Koker <teddy.koker@gmail.com> * added new metrics Co-authored-by: Teddy Koker teddy.koker@gmail.com * pep8 Co-authored-by: Teddy Koker teddy.koker@gmail.com * pep8 Co-authored-by: Teddy Koker <teddy.koker@gmail.com> * docs Co-authored-by: Teddy Koker <teddy.koker@gmail.com> * docs Co-authored-by: Teddy Koker <teddy.koker@gmail.com> * win ddp tests skip Co-authored-by: Teddy Koker <teddy.koker@gmail.com> * win ddp tests skip Co-authored-by: Teddy Koker <teddy.koker@gmail.com> * win ddp tests skip Co-authored-by: Teddy Koker <teddy.koker@gmail.com> * win ddp tests skip Co-authored-by: Teddy Koker <teddy.koker@gmail.com> * reset in compute, cache compute Co-authored-by: Teddy Koker <teddy.koker@gmail.com> * reduce_ops handling Co-authored-by: Teddy Koker <teddy.koker@gmail.com> * sync -> sync_dist, type annotations Co-authored-by: Teddy Koker <teddy.koker@gmail.com> * wip docs Co-authored-by: Teddy Koker <teddy.koker@gmail.com> * mean squared error * docstring * added mean ___ error metrics * added mean ___ error metrics * seperated files * accuracy doctest * gpu fix * remove unnecessary mixin * metric and accuracy docstring Co-authored-by: Teddy Koker <teddy.koker@gmail.com> * metric docs Co-authored-by: Teddy Koker <teddy.koker@gmail.com> * pep8, changelog Co-authored-by: Teddy Koker <teddy.koker@gmail.com> * refactor dist utils, pep8 * refactor dist utils, pep8 Co-authored-by: Teddy Koker <teddy.koker@gmail.com> * Callback docs with autosummary (#3908) * callback docs with autosummary * do not show private methods * callback base docstring * skip some docker builds (temporally pass) (#3913) * skip some docker builds * todos * skip * use badges only with push (#3914) * testtube * mock test tube * mock mlflow * remove mlflow * clean up * test * test * test * test * test * test * code blocks * remove import * codeblock * logger * wandb causes stall Co-authored-by: William Falcon <waf2107@columbia.edu> Co-authored-by: Jirka Borovec <Borda@users.noreply.github.com> Co-authored-by: Ananya Harsh Jha <ananya@pytorchlightning.ai> Co-authored-by: Teddy Koker <teddy.koker@gmail.com> Co-authored-by: Jeff Yang <ydcjeff@outlook.com>
2020-10-07 03:49:06 +00:00
if logger_class == MLFlowLogger:
logger = mock_mlflow_run_creation(logger, experiment_id="foo", run_id="bar")
model = CustomModel()
trainer = Trainer(
max_epochs=1,
logger=logger,
limit_train_batches=1,
limit_val_batches=1,
log_every_n_steps=1,
default_root_dir=tmpdir,
)
trainer.fit(model)
trainer.test()
log_metric_names = [(s, sorted(m.keys())) for s, m in logger.history]
if logger_class == TensorBoardLogger:
expected = [
(0, ["epoch", "train_some_val"]),
(0, ["early_stop_on", "epoch", "val_loss"]),
(1, ["epoch", "test_loss"]),
]
assert log_metric_names == expected
else:
expected = [
(0, ["epoch", "train_some_val"]),
(0, ["early_stop_on", "epoch", "val_loss"]),
(1, ["epoch", "test_loss"]),
]
assert log_metric_names == expected
@pytest.mark.parametrize(
"logger_class", ALL_LOGGER_CLASSES_WO_NEPTUNE
) # WandbLogger and NeptuneLogger get tested separately
def test_loggers_pickle_all(tmpdir, monkeypatch, logger_class):
"""Test that the logger objects can be pickled.
This test only makes sense if the packages are installed.
"""
_patch_comet_atexit(monkeypatch)
try:
_test_loggers_pickle(tmpdir, monkeypatch, logger_class)
except (ImportError, ModuleNotFoundError):
pytest.xfail(f"pickle test requires {logger_class.__class__} dependencies to be installed.")
def _test_loggers_pickle(tmpdir, monkeypatch, logger_class):
"""Verify that pickling trainer with logger works."""
2020-10-05 03:23:58 +00:00
_patch_comet_atexit(monkeypatch)
2020-04-15 15:14:29 +00:00
logger_args = _get_logger_args(logger_class, tmpdir)
logger = logger_class(**logger_args)
# this can cause pickle error if the experiment object is not picklable
# the logger needs to remove it from the state before pickle
_ = logger.experiment
# logger also has to avoid adding un-picklable attributes to self in .save
logger.log_metrics({"a": 1})
logger.save()
2020-04-27 11:41:30 +00:00
# test pickling loggers
pickle.dumps(logger)
trainer = Trainer(max_epochs=1, logger=logger)
pkl_bytes = pickle.dumps(trainer)
trainer2 = pickle.loads(pkl_bytes)
trainer2.logger.log_metrics({"acc": 1.0})
2022-02-17 01:27:51 +00:00
# make sure we restored properly
assert trainer2.logger.name == logger.name
assert trainer2.logger.save_dir == logger.save_dir
@pytest.mark.parametrize(
"extra_params",
[
pytest.param(dict(max_epochs=1, auto_scale_batch_size=True), id="Batch-size-Finder"),
pytest.param(dict(max_epochs=3, auto_lr_find=True), id="LR-Finder"),
],
)
def test_logger_reset_correctly(tmpdir, extra_params):
"""Test that the tuners do not alter the logger reference."""
class CustomModel(BoringModel):
def __init__(self, lr=0.1, batch_size=1):
super().__init__()
self.save_hyperparameters()
model = CustomModel()
trainer = Trainer(default_root_dir=tmpdir, **extra_params)
logger1 = trainer.logger
trainer.tune(model)
logger2 = trainer.logger
logger3 = model.logger
assert logger1 == logger2, "Finder altered the logger of trainer"
assert logger2 == logger3, "Finder altered the logger of model"
class RankZeroLoggerCheck(Callback):
# this class has to be defined outside the test function, otherwise we get pickle error
# due to the way ddp process is launched
def on_train_batch_start(self, trainer, pl_module, batch, batch_idx):
is_dummy = isinstance(trainer.logger.experiment, DummyExperiment)
if trainer.is_global_zero:
assert not is_dummy
else:
assert is_dummy
assert pl_module.logger.experiment.something(foo="bar") is None
@pytest.mark.parametrize("logger_class", ALL_LOGGER_CLASSES_WO_NEPTUNE_WANDB)
@RunIf(skip_windows=True)
Mocking Loggers Part 5/5 (final) (#3926) * base * add xfail * new test * import * missing import * xfail if not installed include mkpatch fix test * mock comet comet mocks fix test remove dep undo merge duplication * line * line * convert doctest * doctest * docs * prune Results usage in notebooks (#3911) * notebooks * notebooks * revamp entire metrics (#3868) * removed metric Co-authored-by: Teddy Koker <teddy.koker@gmail.com> * added new metrics Co-authored-by: Teddy Koker teddy.koker@gmail.com * pep8 Co-authored-by: Teddy Koker teddy.koker@gmail.com * pep8 Co-authored-by: Teddy Koker <teddy.koker@gmail.com> * docs Co-authored-by: Teddy Koker <teddy.koker@gmail.com> * docs Co-authored-by: Teddy Koker <teddy.koker@gmail.com> * win ddp tests skip Co-authored-by: Teddy Koker <teddy.koker@gmail.com> * win ddp tests skip Co-authored-by: Teddy Koker <teddy.koker@gmail.com> * win ddp tests skip Co-authored-by: Teddy Koker <teddy.koker@gmail.com> * win ddp tests skip Co-authored-by: Teddy Koker <teddy.koker@gmail.com> * reset in compute, cache compute Co-authored-by: Teddy Koker <teddy.koker@gmail.com> * reduce_ops handling Co-authored-by: Teddy Koker <teddy.koker@gmail.com> * sync -> sync_dist, type annotations Co-authored-by: Teddy Koker <teddy.koker@gmail.com> * wip docs Co-authored-by: Teddy Koker <teddy.koker@gmail.com> * mean squared error * docstring * added mean ___ error metrics * added mean ___ error metrics * seperated files * accuracy doctest * gpu fix * remove unnecessary mixin * metric and accuracy docstring Co-authored-by: Teddy Koker <teddy.koker@gmail.com> * metric docs Co-authored-by: Teddy Koker <teddy.koker@gmail.com> * pep8, changelog Co-authored-by: Teddy Koker <teddy.koker@gmail.com> * refactor dist utils, pep8 * refactor dist utils, pep8 Co-authored-by: Teddy Koker <teddy.koker@gmail.com> * Callback docs with autosummary (#3908) * callback docs with autosummary * do not show private methods * callback base docstring * skip some docker builds (temporally pass) (#3913) * skip some docker builds * todos * skip * use badges only with push (#3914) * testtube * mock test tube * mock mlflow * remove mlflow * clean up * test * test * test * test * test * test * code blocks * remove import * codeblock * logger * wandb causes stall Co-authored-by: William Falcon <waf2107@columbia.edu> Co-authored-by: Jirka Borovec <Borda@users.noreply.github.com> Co-authored-by: Ananya Harsh Jha <ananya@pytorchlightning.ai> Co-authored-by: Teddy Koker <teddy.koker@gmail.com> Co-authored-by: Jeff Yang <ydcjeff@outlook.com>
2020-10-07 03:49:06 +00:00
def test_logger_created_on_rank_zero_only(tmpdir, monkeypatch, logger_class):
"""Test that loggers get replaced by dummy loggers on global rank > 0."""
2020-10-05 03:23:58 +00:00
_patch_comet_atexit(monkeypatch)
Mocking Loggers Part 5/5 (final) (#3926) * base * add xfail * new test * import * missing import * xfail if not installed include mkpatch fix test * mock comet comet mocks fix test remove dep undo merge duplication * line * line * convert doctest * doctest * docs * prune Results usage in notebooks (#3911) * notebooks * notebooks * revamp entire metrics (#3868) * removed metric Co-authored-by: Teddy Koker <teddy.koker@gmail.com> * added new metrics Co-authored-by: Teddy Koker teddy.koker@gmail.com * pep8 Co-authored-by: Teddy Koker teddy.koker@gmail.com * pep8 Co-authored-by: Teddy Koker <teddy.koker@gmail.com> * docs Co-authored-by: Teddy Koker <teddy.koker@gmail.com> * docs Co-authored-by: Teddy Koker <teddy.koker@gmail.com> * win ddp tests skip Co-authored-by: Teddy Koker <teddy.koker@gmail.com> * win ddp tests skip Co-authored-by: Teddy Koker <teddy.koker@gmail.com> * win ddp tests skip Co-authored-by: Teddy Koker <teddy.koker@gmail.com> * win ddp tests skip Co-authored-by: Teddy Koker <teddy.koker@gmail.com> * reset in compute, cache compute Co-authored-by: Teddy Koker <teddy.koker@gmail.com> * reduce_ops handling Co-authored-by: Teddy Koker <teddy.koker@gmail.com> * sync -> sync_dist, type annotations Co-authored-by: Teddy Koker <teddy.koker@gmail.com> * wip docs Co-authored-by: Teddy Koker <teddy.koker@gmail.com> * mean squared error * docstring * added mean ___ error metrics * added mean ___ error metrics * seperated files * accuracy doctest * gpu fix * remove unnecessary mixin * metric and accuracy docstring Co-authored-by: Teddy Koker <teddy.koker@gmail.com> * metric docs Co-authored-by: Teddy Koker <teddy.koker@gmail.com> * pep8, changelog Co-authored-by: Teddy Koker <teddy.koker@gmail.com> * refactor dist utils, pep8 * refactor dist utils, pep8 Co-authored-by: Teddy Koker <teddy.koker@gmail.com> * Callback docs with autosummary (#3908) * callback docs with autosummary * do not show private methods * callback base docstring * skip some docker builds (temporally pass) (#3913) * skip some docker builds * todos * skip * use badges only with push (#3914) * testtube * mock test tube * mock mlflow * remove mlflow * clean up * test * test * test * test * test * test * code blocks * remove import * codeblock * logger * wandb causes stall Co-authored-by: William Falcon <waf2107@columbia.edu> Co-authored-by: Jirka Borovec <Borda@users.noreply.github.com> Co-authored-by: Ananya Harsh Jha <ananya@pytorchlightning.ai> Co-authored-by: Teddy Koker <teddy.koker@gmail.com> Co-authored-by: Jeff Yang <ydcjeff@outlook.com>
2020-10-07 03:49:06 +00:00
try:
_test_logger_created_on_rank_zero_only(tmpdir, logger_class)
Mocking Loggers Part 5/5 (final) (#3926) * base * add xfail * new test * import * missing import * xfail if not installed include mkpatch fix test * mock comet comet mocks fix test remove dep undo merge duplication * line * line * convert doctest * doctest * docs * prune Results usage in notebooks (#3911) * notebooks * notebooks * revamp entire metrics (#3868) * removed metric Co-authored-by: Teddy Koker <teddy.koker@gmail.com> * added new metrics Co-authored-by: Teddy Koker teddy.koker@gmail.com * pep8 Co-authored-by: Teddy Koker teddy.koker@gmail.com * pep8 Co-authored-by: Teddy Koker <teddy.koker@gmail.com> * docs Co-authored-by: Teddy Koker <teddy.koker@gmail.com> * docs Co-authored-by: Teddy Koker <teddy.koker@gmail.com> * win ddp tests skip Co-authored-by: Teddy Koker <teddy.koker@gmail.com> * win ddp tests skip Co-authored-by: Teddy Koker <teddy.koker@gmail.com> * win ddp tests skip Co-authored-by: Teddy Koker <teddy.koker@gmail.com> * win ddp tests skip Co-authored-by: Teddy Koker <teddy.koker@gmail.com> * reset in compute, cache compute Co-authored-by: Teddy Koker <teddy.koker@gmail.com> * reduce_ops handling Co-authored-by: Teddy Koker <teddy.koker@gmail.com> * sync -> sync_dist, type annotations Co-authored-by: Teddy Koker <teddy.koker@gmail.com> * wip docs Co-authored-by: Teddy Koker <teddy.koker@gmail.com> * mean squared error * docstring * added mean ___ error metrics * added mean ___ error metrics * seperated files * accuracy doctest * gpu fix * remove unnecessary mixin * metric and accuracy docstring Co-authored-by: Teddy Koker <teddy.koker@gmail.com> * metric docs Co-authored-by: Teddy Koker <teddy.koker@gmail.com> * pep8, changelog Co-authored-by: Teddy Koker <teddy.koker@gmail.com> * refactor dist utils, pep8 * refactor dist utils, pep8 Co-authored-by: Teddy Koker <teddy.koker@gmail.com> * Callback docs with autosummary (#3908) * callback docs with autosummary * do not show private methods * callback base docstring * skip some docker builds (temporally pass) (#3913) * skip some docker builds * todos * skip * use badges only with push (#3914) * testtube * mock test tube * mock mlflow * remove mlflow * clean up * test * test * test * test * test * test * code blocks * remove import * codeblock * logger * wandb causes stall Co-authored-by: William Falcon <waf2107@columbia.edu> Co-authored-by: Jirka Borovec <Borda@users.noreply.github.com> Co-authored-by: Ananya Harsh Jha <ananya@pytorchlightning.ai> Co-authored-by: Teddy Koker <teddy.koker@gmail.com> Co-authored-by: Jeff Yang <ydcjeff@outlook.com>
2020-10-07 03:49:06 +00:00
except (ImportError, ModuleNotFoundError):
pytest.xfail(f"multi-process test requires {logger_class.__class__} dependencies to be installed.")
Mocking Loggers Part 5/5 (final) (#3926) * base * add xfail * new test * import * missing import * xfail if not installed include mkpatch fix test * mock comet comet mocks fix test remove dep undo merge duplication * line * line * convert doctest * doctest * docs * prune Results usage in notebooks (#3911) * notebooks * notebooks * revamp entire metrics (#3868) * removed metric Co-authored-by: Teddy Koker <teddy.koker@gmail.com> * added new metrics Co-authored-by: Teddy Koker teddy.koker@gmail.com * pep8 Co-authored-by: Teddy Koker teddy.koker@gmail.com * pep8 Co-authored-by: Teddy Koker <teddy.koker@gmail.com> * docs Co-authored-by: Teddy Koker <teddy.koker@gmail.com> * docs Co-authored-by: Teddy Koker <teddy.koker@gmail.com> * win ddp tests skip Co-authored-by: Teddy Koker <teddy.koker@gmail.com> * win ddp tests skip Co-authored-by: Teddy Koker <teddy.koker@gmail.com> * win ddp tests skip Co-authored-by: Teddy Koker <teddy.koker@gmail.com> * win ddp tests skip Co-authored-by: Teddy Koker <teddy.koker@gmail.com> * reset in compute, cache compute Co-authored-by: Teddy Koker <teddy.koker@gmail.com> * reduce_ops handling Co-authored-by: Teddy Koker <teddy.koker@gmail.com> * sync -> sync_dist, type annotations Co-authored-by: Teddy Koker <teddy.koker@gmail.com> * wip docs Co-authored-by: Teddy Koker <teddy.koker@gmail.com> * mean squared error * docstring * added mean ___ error metrics * added mean ___ error metrics * seperated files * accuracy doctest * gpu fix * remove unnecessary mixin * metric and accuracy docstring Co-authored-by: Teddy Koker <teddy.koker@gmail.com> * metric docs Co-authored-by: Teddy Koker <teddy.koker@gmail.com> * pep8, changelog Co-authored-by: Teddy Koker <teddy.koker@gmail.com> * refactor dist utils, pep8 * refactor dist utils, pep8 Co-authored-by: Teddy Koker <teddy.koker@gmail.com> * Callback docs with autosummary (#3908) * callback docs with autosummary * do not show private methods * callback base docstring * skip some docker builds (temporally pass) (#3913) * skip some docker builds * todos * skip * use badges only with push (#3914) * testtube * mock test tube * mock mlflow * remove mlflow * clean up * test * test * test * test * test * test * code blocks * remove import * codeblock * logger * wandb causes stall Co-authored-by: William Falcon <waf2107@columbia.edu> Co-authored-by: Jirka Borovec <Borda@users.noreply.github.com> Co-authored-by: Ananya Harsh Jha <ananya@pytorchlightning.ai> Co-authored-by: Teddy Koker <teddy.koker@gmail.com> Co-authored-by: Jeff Yang <ydcjeff@outlook.com>
2020-10-07 03:49:06 +00:00
def _test_logger_created_on_rank_zero_only(tmpdir, logger_class):
logger_args = _get_logger_args(logger_class, tmpdir)
logger = logger_class(**logger_args)
model = BoringModel()
trainer = Trainer(
logger=logger,
default_root_dir=tmpdir,
strategy="ddp_spawn",
2022-01-16 16:12:18 +00:00
accelerator="cpu",
devices=2,
max_steps=1,
callbacks=[RankZeroLoggerCheck()],
)
trainer.fit(model)
assert trainer.state.finished, f"Training failed with {trainer.state}"
def test_logger_with_prefix_all(tmpdir, monkeypatch):
"""Test that prefix is added at the beginning of the metric keys."""
prefix = "tmp"
# Comet
with mock.patch("pytorch_lightning.loggers.comet.comet_ml"), mock.patch(
"pytorch_lightning.loggers.comet.CometOfflineExperiment"
):
_patch_comet_atexit(monkeypatch)
2021-05-19 19:50:58 +00:00
logger = _instantiate_logger(CometLogger, save_dir=tmpdir, prefix=prefix)
logger.log_metrics({"test": 1.0}, step=0)
logger.experiment.log_metrics.assert_called_once_with({"tmp-test": 1.0}, epoch=None, step=0)
# MLflow
with mock.patch("pytorch_lightning.loggers.mlflow.mlflow"), mock.patch(
"pytorch_lightning.loggers.mlflow.MlflowClient"
):
2021-05-19 19:50:58 +00:00
logger = _instantiate_logger(MLFlowLogger, save_dir=tmpdir, prefix=prefix)
logger.log_metrics({"test": 1.0}, step=0)
logger.experiment.log_metric.assert_called_once_with(ANY, "tmp-test", 1.0, ANY, 0)
# Neptune
with mock.patch("pytorch_lightning.loggers.neptune.neptune"), mock.patch(
"pytorch_lightning.loggers.neptune._NEPTUNE_AVAILABLE", return_value=True
):
Adapt `NeptuneLogger` to new `neptune-client` api (#6867) * Initial split to NeptuneLegacyLogger and NeptuneLogger * Adapt NeptuneLogger to neptune-pytorch-lightning repo version * Fix stylecheck and tests * Fix style and PR suggestions * Expect Run object in NeptuneLogger.init * Model checkpoint support and restructured tests * Reformat code - use " instead of ' * Fix logging INTEGRATION_VERSION_KEY * Update CHANGELOG.md * Fix stylecheck * Remove NeptuneLegacyLogger * updated neptune-related docstrings * PR suggestions * update CODEOWERS file * move import logic to imports.py * minor neptune.py improvements * formatting fixes and minor updates * Fix generation of docs * formatting fixes and minor updates * fix * PR fixes vol. 2 * define return type of _dict_paths method * bump required version of `neptune-client` * Enable log_* functions * Update pytorch_lightning/loggers/neptune.py Co-authored-by: Adrian Wälchli <aedu.waelchli@gmail.com> * Revert "Enable log_* functions" This reverts commit 050a436899b7f3582c0455dc27b171335b85a3a5. * Make global helper lists internal * Logger's `name` and `version` methods return proper results * Initialize Run and its name and id at logger init level * Make _init_run_instance static * Add pre-commit hook code changes. * Fix blacken-docs check * Fix neptune doctests and test_all * added docs comment about neptune-specific syntax * added docs comment about neptune-specific syntax in the loggers.rst * fix * Add pickling test * added myself to neptune codeowners * Enable some of deprecated log_* functions * Restore _run_instance for unpickled logger * Add `step` parameter to log_* functions * Fix stylecheck * Fix checkstyle * Fix checkstyle * Update pytorch_lightning/loggers/neptune.py Co-authored-by: thomas chaton <thomas@grid.ai> * Fix tests * Fix stylecheck * fixed project name * Fix windows tests * Fix stylechecks * Fix neptune docs tests * docformatter fixes * De-duplicate legacy_kwargs_msg * Update .github/CODEOWNERS Co-authored-by: Adrian Wälchli <aedu.waelchli@gmail.com> Co-authored-by: kamil-kaczmarek <kamil.kaczmarek@neptune.ml> Co-authored-by: Adrian Wälchli <aedu.waelchli@gmail.com> Co-authored-by: thomas chaton <thomas@grid.ai>
2021-09-10 16:48:58 +00:00
logger = _instantiate_logger(NeptuneLogger, api_key="test", project="project", save_dir=tmpdir, prefix=prefix)
assert logger.experiment.__getitem__.call_count == 2
logger.log_metrics({"test": 1.0}, step=0)
assert logger.experiment.__getitem__.call_count == 3
Adapt `NeptuneLogger` to new `neptune-client` api (#6867) * Initial split to NeptuneLegacyLogger and NeptuneLogger * Adapt NeptuneLogger to neptune-pytorch-lightning repo version * Fix stylecheck and tests * Fix style and PR suggestions * Expect Run object in NeptuneLogger.init * Model checkpoint support and restructured tests * Reformat code - use " instead of ' * Fix logging INTEGRATION_VERSION_KEY * Update CHANGELOG.md * Fix stylecheck * Remove NeptuneLegacyLogger * updated neptune-related docstrings * PR suggestions * update CODEOWERS file * move import logic to imports.py * minor neptune.py improvements * formatting fixes and minor updates * Fix generation of docs * formatting fixes and minor updates * fix * PR fixes vol. 2 * define return type of _dict_paths method * bump required version of `neptune-client` * Enable log_* functions * Update pytorch_lightning/loggers/neptune.py Co-authored-by: Adrian Wälchli <aedu.waelchli@gmail.com> * Revert "Enable log_* functions" This reverts commit 050a436899b7f3582c0455dc27b171335b85a3a5. * Make global helper lists internal * Logger's `name` and `version` methods return proper results * Initialize Run and its name and id at logger init level * Make _init_run_instance static * Add pre-commit hook code changes. * Fix blacken-docs check * Fix neptune doctests and test_all * added docs comment about neptune-specific syntax * added docs comment about neptune-specific syntax in the loggers.rst * fix * Add pickling test * added myself to neptune codeowners * Enable some of deprecated log_* functions * Restore _run_instance for unpickled logger * Add `step` parameter to log_* functions * Fix stylecheck * Fix checkstyle * Fix checkstyle * Update pytorch_lightning/loggers/neptune.py Co-authored-by: thomas chaton <thomas@grid.ai> * Fix tests * Fix stylecheck * fixed project name * Fix windows tests * Fix stylechecks * Fix neptune docs tests * docformatter fixes * De-duplicate legacy_kwargs_msg * Update .github/CODEOWNERS Co-authored-by: Adrian Wälchli <aedu.waelchli@gmail.com> Co-authored-by: kamil-kaczmarek <kamil.kaczmarek@neptune.ml> Co-authored-by: Adrian Wälchli <aedu.waelchli@gmail.com> Co-authored-by: thomas chaton <thomas@grid.ai>
2021-09-10 16:48:58 +00:00
logger.experiment.__getitem__.assert_called_with("tmp/test")
logger.experiment.__getitem__().log.assert_called_once_with(1.0)
# TensorBoard
with mock.patch("pytorch_lightning.loggers.tensorboard.SummaryWriter"):
2021-05-19 19:50:58 +00:00
logger = _instantiate_logger(TensorBoardLogger, save_dir=tmpdir, prefix=prefix)
logger.log_metrics({"test": 1.0}, step=0)
logger.experiment.add_scalar.assert_called_once_with("tmp-test", 1.0, 0)
# WandB
with mock.patch("pytorch_lightning.loggers.wandb.wandb") as wandb, mock.patch(
"pytorch_lightning.loggers.wandb.Run", new=mock.Mock
):
2021-05-19 19:50:58 +00:00
logger = _instantiate_logger(WandbLogger, save_dir=tmpdir, prefix=prefix)
wandb.run = None
wandb.init().step = 0
logger.log_metrics({"test": 1.0}, step=0)
logger.experiment.log.assert_called_once_with({"tmp-test": 1.0, "trainer/global_step": 0})
def test_logger_default_name(tmpdir):
"""Test that the default logger name is lightning_logs."""
# CSV
logger = CSVLogger(save_dir=tmpdir)
assert logger.name == "lightning_logs"
# TensorBoard
with mock.patch("pytorch_lightning.loggers.tensorboard.SummaryWriter"):
logger = _instantiate_logger(TensorBoardLogger, save_dir=tmpdir)
assert logger.name == "lightning_logs"
# MLflow
with mock.patch("pytorch_lightning.loggers.mlflow.mlflow"), mock.patch(
"pytorch_lightning.loggers.mlflow.MlflowClient"
) as mlflow_client:
mlflow_client().get_experiment_by_name.return_value = None
logger = _instantiate_logger(MLFlowLogger, save_dir=tmpdir)
_ = logger.experiment
logger._mlflow_client.create_experiment.assert_called_with(name="lightning_logs", artifact_location=ANY)
# on MLFLowLogger `name` refers to the experiment id
# assert logger.experiment.get_experiment(logger.name).name == "lightning_logs"