Skip to content

Commit a659904

Browse files
Raalskycarmoccarohitgr7
authored andcommitted
Fixed NeptuneLogger when using DDP (#11030)
Co-authored-by: Carlos Mocholí <[email protected]> Co-authored-by: Rohit Gupta <[email protected]>
1 parent 8b2c39b commit a659904

File tree

5 files changed

+86
-55
lines changed

5 files changed

+86
-55
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/).
88

99
### Fixed
1010

11+
- Fixed `NeptuneLogger` when using DDP ([#11030](https://github.com/PyTorchLightning/pytorch-lightning/pull/11030))
1112
- Fixed a bug to disable logging hyperparameters in logger if there are no hparams ([#11105](https://github.com/PyTorchLightning/pytorch-lightning/issues/11105))
1213
- Fixed an issue when torch-scripting a `LightningModule` after training with `Trainer(sync_batchnorm=True)` ([#11078](https://github.com/PyTorchLightning/pytorch-lightning/pull/11078))
1314
- Fixed an `AttributeError` occuring when using a `CombinedLoader` (multiple dataloaders) for prediction ([#11111](https://github.com/PyTorchLightning/pytorch-lightning/pull/11111))

environment.yml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -51,4 +51,4 @@ dependencies:
5151
- mlflow>=1.0.0
5252
- comet_ml>=3.1.12
5353
- wandb>=0.8.21
54-
- neptune-client>=0.4.109
54+
- neptune-client>=0.10.0

pytorch_lightning/loggers/neptune.py

Lines changed: 76 additions & 50 deletions
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,7 @@
4444
from neptune.new.types import File as NeptuneFile
4545
except ModuleNotFoundError:
4646
import neptune
47-
from neptune.exceptions import NeptuneLegacyProjectException
47+
from neptune.exceptions import NeptuneLegacyProjectException, NeptuneOfflineModeFetchException
4848
from neptune.run import Run
4949
from neptune.types import File as NeptuneFile
5050
else:
@@ -266,51 +266,64 @@ def __init__(
266266
prefix: str = "training",
267267
**neptune_run_kwargs,
268268
):
269-
270269
# verify if user passed proper init arguments
271270
self._verify_input_arguments(api_key, project, name, run, neptune_run_kwargs)
271+
if neptune is None:
272+
raise ModuleNotFoundError(
273+
"You want to use the `Neptune` logger which is not installed yet, install it with"
274+
" `pip install neptune-client`."
275+
)
272276

273277
super().__init__()
274278
self._log_model_checkpoints = log_model_checkpoints
275279
self._prefix = prefix
280+
self._run_name = name
281+
self._project_name = project
282+
self._api_key = api_key
283+
self._run_instance = run
284+
self._neptune_run_kwargs = neptune_run_kwargs
285+
self._run_short_id = None
276286

277-
self._run_instance = self._init_run_instance(api_key, project, name, run, neptune_run_kwargs)
287+
if self._run_instance is not None:
288+
self._retrieve_run_data()
278289

279-
self._run_short_id = self.run._short_id # skipcq: PYL-W0212
290+
# make sure that we've log integration version for outside `Run` instances
291+
self._run_instance[_INTEGRATION_VERSION_KEY] = __version__
292+
293+
def _retrieve_run_data(self):
280294
try:
281-
self.run.wait()
295+
self._run_instance.wait()
296+
self._run_short_id = self.run._short_id # skipcq: PYL-W0212
282297
self._run_name = self._run_instance["sys/name"].fetch()
283298
except NeptuneOfflineModeFetchException:
284299
self._run_name = "offline-name"
285300

286-
def _init_run_instance(self, api_key, project, name, run, neptune_run_kwargs) -> Run:
287-
if run is not None:
288-
run_instance = run
289-
else:
290-
try:
291-
run_instance = neptune.init(
292-
project=project,
293-
api_token=api_key,
294-
name=name,
295-
**neptune_run_kwargs,
296-
)
297-
except NeptuneLegacyProjectException as e:
298-
raise TypeError(
299-
f"""Project {project} has not been migrated to the new structure.
300-
You can still integrate it with the Neptune logger using legacy Python API
301-
available as part of neptune-contrib package:
302-
- https://docs-legacy.neptune.ai/integrations/pytorch_lightning.html\n
303-
"""
304-
) from e
305-
306-
# make sure that we've log integration version for both newly created and outside `Run` instances
307-
run_instance[_INTEGRATION_VERSION_KEY] = __version__
308-
309-
# keep api_key and project, they will be required when resuming Run for pickled logger
310-
self._api_key = api_key
311-
self._project_name = run_instance._project_name # skipcq: PYL-W0212
301+
@property
302+
def _neptune_init_args(self):
303+
args = {}
304+
# Backward compatibility in case of previous version retrieval
305+
try:
306+
args = self._neptune_run_kwargs
307+
except AttributeError:
308+
pass
309+
310+
if self._project_name is not None:
311+
args["project"] = self._project_name
312+
313+
if self._api_key is not None:
314+
args["api_token"] = self._api_key
312315

313-
return run_instance
316+
if self._run_short_id is not None:
317+
args["run"] = self._run_short_id
318+
319+
# Backward compatibility in case of previous version retrieval
320+
try:
321+
if self._run_name is not None:
322+
args["name"] = self._run_name
323+
except AttributeError:
324+
pass
325+
326+
return args
314327

315328
def _construct_path_with_prefix(self, *keys) -> str:
316329
"""Return sequence of keys joined by `LOGGER_JOIN_CHAR`, started with `_prefix` if defined."""
@@ -379,7 +392,7 @@ def __getstate__(self):
379392

380393
def __setstate__(self, state):
381394
self.__dict__ = state
382-
self._run_instance = neptune.init(project=self._project_name, api_token=self._api_key, run=self._run_short_id)
395+
self._run_instance = neptune.init(**self._neptune_init_args)
383396

384397
@property
385398
@rank_zero_experiment
@@ -412,8 +425,23 @@ def training_step(self, batch, batch_idx):
412425
return self.run
413426

414427
@property
428+
@rank_zero_experiment
415429
def run(self) -> Run:
416-
return self._run_instance
430+
try:
431+
if not self._run_instance:
432+
self._run_instance = neptune.init(**self._neptune_init_args)
433+
self._retrieve_run_data()
434+
# make sure that we've log integration version for newly created
435+
self._run_instance[_INTEGRATION_VERSION_KEY] = __version__
436+
437+
return self._run_instance
438+
except NeptuneLegacyProjectException as e:
439+
raise TypeError(
440+
f"Project {self._project_name} has not been migrated to the new structure."
441+
" You can still integrate it with the Neptune logger using legacy Python API"
442+
" available as part of neptune-contrib package:"
443+
" https://docs-legacy.neptune.ai/integrations/pytorch_lightning.html\n"
444+
) from e
417445

418446
@rank_zero_only
419447
def log_hyperparams(self, params: Union[Dict[str, Any], Namespace]) -> None: # skipcq: PYL-W0221
@@ -473,13 +501,13 @@ def log_metrics(self, metrics: Dict[str, Union[torch.Tensor, float]], step: Opti
473501

474502
for key, val in metrics.items():
475503
# `step` is ignored because Neptune expects strictly increasing step values which
476-
# Lighting does not always guarantee.
477-
self.experiment[key].log(val)
504+
# Lightning does not always guarantee.
505+
self.run[key].log(val)
478506

479507
@rank_zero_only
480508
def finalize(self, status: str) -> None:
481509
if status:
482-
self.experiment[self._construct_path_with_prefix("status")] = status
510+
self.run[self._construct_path_with_prefix("status")] = status
483511

484512
super().finalize(status)
485513

@@ -493,12 +521,14 @@ def save_dir(self) -> Optional[str]:
493521
"""
494522
return os.path.join(os.getcwd(), ".neptune")
495523

524+
@rank_zero_only
496525
def log_model_summary(self, model, max_depth=-1):
497526
model_str = str(ModelSummary(model=model, max_depth=max_depth))
498-
self.experiment[self._construct_path_with_prefix("model/summary")] = neptune.types.File.from_content(
527+
self.run[self._construct_path_with_prefix("model/summary")] = neptune.types.File.from_content(
499528
content=model_str, extension="txt"
500529
)
501530

531+
@rank_zero_only
502532
def after_save_checkpoint(self, checkpoint_callback: "ReferenceType[ModelCheckpoint]") -> None:
503533
"""Automatically log checkpointed model. Called after model checkpoint callback saves a new checkpoint.
504534
@@ -515,35 +545,33 @@ def after_save_checkpoint(self, checkpoint_callback: "ReferenceType[ModelCheckpo
515545
if checkpoint_callback.last_model_path:
516546
model_last_name = self._get_full_model_name(checkpoint_callback.last_model_path, checkpoint_callback)
517547
file_names.add(model_last_name)
518-
self.experiment[f"{checkpoints_namespace}/{model_last_name}"].upload(checkpoint_callback.last_model_path)
548+
self.run[f"{checkpoints_namespace}/{model_last_name}"].upload(checkpoint_callback.last_model_path)
519549

520550
# save best k models
521551
for key in checkpoint_callback.best_k_models.keys():
522552
model_name = self._get_full_model_name(key, checkpoint_callback)
523553
file_names.add(model_name)
524-
self.experiment[f"{checkpoints_namespace}/{model_name}"].upload(key)
554+
self.run[f"{checkpoints_namespace}/{model_name}"].upload(key)
525555

526556
# log best model path and checkpoint
527557
if checkpoint_callback.best_model_path:
528-
self.experiment[
529-
self._construct_path_with_prefix("model/best_model_path")
530-
] = checkpoint_callback.best_model_path
558+
self.run[self._construct_path_with_prefix("model/best_model_path")] = checkpoint_callback.best_model_path
531559

532560
model_name = self._get_full_model_name(checkpoint_callback.best_model_path, checkpoint_callback)
533561
file_names.add(model_name)
534-
self.experiment[f"{checkpoints_namespace}/{model_name}"].upload(checkpoint_callback.best_model_path)
562+
self.run[f"{checkpoints_namespace}/{model_name}"].upload(checkpoint_callback.best_model_path)
535563

536564
# remove old models logged to experiment if they are not part of best k models at this point
537-
if self.experiment.exists(checkpoints_namespace):
538-
exp_structure = self.experiment.get_structure()
565+
if self.run.exists(checkpoints_namespace):
566+
exp_structure = self.run.get_structure()
539567
uploaded_model_names = self._get_full_model_names_from_exp_structure(exp_structure, checkpoints_namespace)
540568

541569
for file_to_drop in list(uploaded_model_names - file_names):
542-
del self.experiment[f"{checkpoints_namespace}/{file_to_drop}"]
570+
del self.run[f"{checkpoints_namespace}/{file_to_drop}"]
543571

544572
# log best model score
545573
if checkpoint_callback.best_model_score:
546-
self.experiment[self._construct_path_with_prefix("model/best_model_score")] = (
574+
self.run[self._construct_path_with_prefix("model/best_model_score")] = (
547575
checkpoint_callback.best_model_score.cpu().detach().numpy()
548576
)
549577

@@ -637,13 +665,11 @@ def log_artifact(self, artifact: str, destination: Optional[str] = None) -> None
637665
self._signal_deprecated_api_usage("log_artifact", f"logger.run['{key}].log('path_to_file')")
638666
self.run[key].log(destination)
639667

640-
@rank_zero_only
641668
def set_property(self, *args, **kwargs):
642669
self._signal_deprecated_api_usage(
643670
"log_artifact", f"logger.run['{self._prefix}/{self.PARAMETERS_KEY}/key'].log(value)", raise_exception=True
644671
)
645672

646-
@rank_zero_only
647673
def append_tags(self, *args, **kwargs):
648674
self._signal_deprecated_api_usage(
649675
"append_tags", "logger.run['sys/tags'].add(['foo', 'bar'])", raise_exception=True

tests/loggers/test_all.py

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,8 @@ def _get_logger_args(logger_class, save_dir):
4747
logger_args.update(offline_mode=True)
4848
if "offline" in inspect.getfullargspec(logger_class).args:
4949
logger_args.update(offline=True)
50+
if issubclass(logger_class, NeptuneLogger):
51+
logger_args.update(mode="offline")
5052
return logger_args
5153

5254

@@ -320,7 +322,9 @@ def on_train_batch_start(self, trainer, pl_module, batch, batch_idx):
320322

321323

322324
@RunIf(skip_windows=True, skip_49370=True, skip_hanging_spawn=True)
323-
@pytest.mark.parametrize("logger_class", [CometLogger, CSVLogger, MLFlowLogger, TensorBoardLogger, TestTubeLogger])
325+
@pytest.mark.parametrize(
326+
"logger_class", [CometLogger, CSVLogger, MLFlowLogger, NeptuneLogger, TensorBoardLogger, TestTubeLogger]
327+
)
324328
def test_logger_created_on_rank_zero_only(tmpdir, monkeypatch, logger_class):
325329
"""Test that loggers get replaced by dummy loggers on global rank > 0."""
326330
_patch_comet_atexit(monkeypatch)

tests/loggers/test_neptune.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -77,7 +77,7 @@ def tmpdir_unittest_fixture(request, tmpdir):
7777
class TestNeptuneLogger(unittest.TestCase):
7878
def test_neptune_online(self, neptune):
7979
logger = NeptuneLogger(api_key="test", project="project")
80-
created_run_mock = logger._run_instance
80+
created_run_mock = logger.run
8181

8282
self.assertEqual(logger._run_instance, created_run_mock)
8383
self.assertEqual(logger.name, "Run test name")
@@ -109,7 +109,7 @@ def test_neptune_pickling(self, neptune):
109109
pickled_logger = pickle.dumps(logger)
110110
unpickled = pickle.loads(pickled_logger)
111111

112-
neptune.init.assert_called_once_with(project="test-project", api_token=None, run="TEST-42")
112+
neptune.init.assert_called_once_with(name="Test name", run=unpickleable_run._short_id)
113113
self.assertIsNotNone(unpickled.experiment)
114114

115115
@patch("pytorch_lightning.loggers.neptune.Run", Run)
@@ -360,7 +360,7 @@ def test_legacy_functions(self, neptune, neptune_file_mock, warnings_mock):
360360
logger = NeptuneLogger(api_key="test", project="project")
361361

362362
# test deprecated functions which will be shut down in pytorch-lightning 1.7.0
363-
attr_mock = logger._run_instance.__getitem__
363+
attr_mock = logger.run.__getitem__
364364
attr_mock.reset_mock()
365365
fake_image = {}
366366

0 commit comments

Comments
 (0)