2020-02-25 19:52:39 +00:00
|
|
|
import argparse
|
|
|
|
from abc import ABC, abstractmethod
|
2020-03-04 14:33:39 +00:00
|
|
|
from argparse import Namespace
|
2019-09-27 16:05:29 +00:00
|
|
|
from functools import wraps
|
2020-02-25 19:52:39 +00:00
|
|
|
from typing import Union, Optional, Dict, Iterable, Any, Callable, List
|
2019-09-27 16:05:29 +00:00
|
|
|
|
2020-03-14 17:02:05 +00:00
|
|
|
import torch
|
|
|
|
|
2019-09-27 16:05:29 +00:00
|
|
|
|
2020-02-25 19:52:39 +00:00
|
|
|
def rank_zero_only(fn: Callable):
|
2019-12-08 00:25:12 +00:00
|
|
|
"""Decorate a logger method to run it only on the process with rank 0.
|
2019-09-27 16:05:29 +00:00
|
|
|
|
2020-02-25 19:52:39 +00:00
|
|
|
Args:
|
|
|
|
fn: Function to decorate
|
2019-09-27 16:05:29 +00:00
|
|
|
"""
|
|
|
|
|
|
|
|
@wraps(fn)
|
|
|
|
def wrapped_fn(self, *args, **kwargs):
|
|
|
|
if self.rank == 0:
|
|
|
|
fn(self, *args, **kwargs)
|
|
|
|
|
|
|
|
return wrapped_fn
|
|
|
|
|
|
|
|
|
2019-12-08 00:25:12 +00:00
|
|
|
class LightningLoggerBase(ABC):
|
|
|
|
"""Base class for experiment loggers."""
|
2019-09-27 16:05:29 +00:00
|
|
|
|
|
|
|
def __init__(self):
|
|
|
|
self._rank = 0
|
|
|
|
|
2019-12-08 00:25:12 +00:00
|
|
|
@property
|
2020-02-25 19:52:39 +00:00
|
|
|
@abstractmethod
|
|
|
|
def experiment(self) -> Any:
|
|
|
|
"""Return the experiment object associated with this logger"""
|
2019-12-08 00:25:12 +00:00
|
|
|
|
2020-02-25 19:52:39 +00:00
|
|
|
@abstractmethod
|
|
|
|
def log_metrics(self, metrics: Dict[str, float], step: Optional[int] = None):
|
2019-12-04 11:57:10 +00:00
|
|
|
"""Record metrics.
|
2019-09-27 16:05:29 +00:00
|
|
|
|
2020-02-25 19:52:39 +00:00
|
|
|
Args:
|
|
|
|
metrics: Dictionary with metric names as keys and measured quantities as values
|
|
|
|
step: Step number at which the metrics should be recorded
|
2019-09-27 16:05:29 +00:00
|
|
|
"""
|
|
|
|
|
2020-03-14 17:02:05 +00:00
|
|
|
@staticmethod
|
|
|
|
def _convert_params(params: Union[Dict[str, Any], Namespace]) -> Dict[str, Any]:
|
2020-03-04 14:33:39 +00:00
|
|
|
# in case converting from namespace
|
|
|
|
if isinstance(params, Namespace):
|
|
|
|
params = vars(params)
|
2020-03-05 04:02:19 +00:00
|
|
|
|
|
|
|
if params is None:
|
|
|
|
params = {}
|
|
|
|
|
2020-03-04 14:33:39 +00:00
|
|
|
return params
|
|
|
|
|
2020-03-19 13:15:47 +00:00
|
|
|
@staticmethod
|
|
|
|
def _flatten_dict(params: Dict[str, Any], delimiter: str = '/') -> Dict[str, Any]:
|
|
|
|
"""Flatten hierarchical dict e.g. {'a': {'b': 'c'}} -> {'a/b': 'c'}.
|
|
|
|
|
|
|
|
Args:
|
|
|
|
params: Dictionary contains hparams
|
|
|
|
delimiter: Delimiter to express the hierarchy. Defaults to '/'.
|
|
|
|
|
|
|
|
Returns:
|
|
|
|
Flatten dict.
|
|
|
|
|
|
|
|
Examples:
|
|
|
|
>>> LightningLoggerBase._flatten_dict({'a': {'b': 'c'}})
|
|
|
|
{'a/b': 'c'}
|
|
|
|
>>> LightningLoggerBase._flatten_dict({'a': {'b': 123}})
|
|
|
|
{'a/b': 123}
|
|
|
|
"""
|
|
|
|
|
|
|
|
def _dict_generator(input_dict, prefixes=None):
|
|
|
|
prefixes = prefixes[:] if prefixes else []
|
|
|
|
if isinstance(input_dict, dict):
|
|
|
|
for key, value in input_dict.items():
|
|
|
|
if isinstance(value, (dict, Namespace)):
|
|
|
|
value = vars(value) if isinstance(value, Namespace) else value
|
|
|
|
for d in _dict_generator(value, prefixes + [key]):
|
|
|
|
yield d
|
|
|
|
else:
|
|
|
|
yield prefixes + [key, value if value is not None else str(None)]
|
|
|
|
else:
|
|
|
|
yield prefixes + [input_dict if input_dict is None else str(input_dict)]
|
|
|
|
|
|
|
|
return {delimiter.join(keys): val for *keys, val in _dict_generator(params)}
|
|
|
|
|
2020-03-14 17:02:05 +00:00
|
|
|
@staticmethod
|
|
|
|
def _sanitize_params(params: Dict[str, Any]) -> Dict[str, Any]:
|
|
|
|
"""Returns params with non-primitvies converted to strings for logging
|
|
|
|
|
|
|
|
>>> params = {"float": 0.3,
|
|
|
|
... "int": 1,
|
|
|
|
... "string": "abc",
|
|
|
|
... "bool": True,
|
|
|
|
... "list": [1, 2, 3],
|
|
|
|
... "namespace": Namespace(foo=3),
|
|
|
|
... "layer": torch.nn.BatchNorm1d}
|
|
|
|
>>> import pprint
|
|
|
|
>>> pprint.pprint(LightningLoggerBase._sanitize_params(params)) # doctest: +NORMALIZE_WHITESPACE
|
|
|
|
{'bool': True,
|
|
|
|
'float': 0.3,
|
|
|
|
'int': 1,
|
|
|
|
'layer': "<class 'torch.nn.modules.batchnorm.BatchNorm1d'>",
|
|
|
|
'list': '[1, 2, 3]',
|
|
|
|
'namespace': 'Namespace(foo=3)',
|
|
|
|
'string': 'abc'}
|
|
|
|
"""
|
|
|
|
return {k: v if type(v) in [bool, int, float, str, torch.Tensor] else str(v) for k, v in params.items()}
|
|
|
|
|
2020-02-25 19:52:39 +00:00
|
|
|
@abstractmethod
|
|
|
|
def log_hyperparams(self, params: argparse.Namespace):
|
2019-12-08 00:25:12 +00:00
|
|
|
"""Record hyperparameters.
|
2019-09-27 16:05:29 +00:00
|
|
|
|
2020-02-25 19:52:39 +00:00
|
|
|
Args:
|
|
|
|
params: argparse.Namespace containing the hyperparameters
|
2019-09-27 16:05:29 +00:00
|
|
|
"""
|
|
|
|
|
2020-03-04 14:33:39 +00:00
|
|
|
def save(self) -> None:
|
2019-12-08 00:25:12 +00:00
|
|
|
"""Save log data."""
|
2020-02-25 19:52:39 +00:00
|
|
|
pass
|
2019-09-27 16:05:29 +00:00
|
|
|
|
2020-03-04 14:33:39 +00:00
|
|
|
def finalize(self, status: str) -> None:
|
2019-12-08 00:25:12 +00:00
|
|
|
"""Do any processing that is necessary to finalize an experiment.
|
2019-09-27 16:05:29 +00:00
|
|
|
|
2020-02-25 19:52:39 +00:00
|
|
|
Args:
|
|
|
|
status: Status that the experiment finished with (e.g. success, failed, aborted)
|
2019-09-27 16:05:29 +00:00
|
|
|
"""
|
2020-02-25 19:52:39 +00:00
|
|
|
pass
|
2019-09-27 16:05:29 +00:00
|
|
|
|
2020-03-04 14:33:39 +00:00
|
|
|
def close(self) -> None:
|
2019-12-08 00:25:12 +00:00
|
|
|
"""Do any cleanup that is necessary to close an experiment."""
|
2020-02-25 19:52:39 +00:00
|
|
|
pass
|
2019-09-27 16:05:29 +00:00
|
|
|
|
|
|
|
@property
|
2020-02-25 19:52:39 +00:00
|
|
|
def rank(self) -> int:
|
2019-12-08 00:25:12 +00:00
|
|
|
"""Process rank. In general, metrics should only be logged by the process with rank 0."""
|
2019-09-27 16:05:29 +00:00
|
|
|
return self._rank
|
|
|
|
|
|
|
|
@rank.setter
|
2020-03-04 14:33:39 +00:00
|
|
|
def rank(self, value: int) -> None:
|
2019-12-08 00:25:12 +00:00
|
|
|
"""Set the process rank."""
|
2019-09-27 16:05:29 +00:00
|
|
|
self._rank = value
|
|
|
|
|
2019-11-05 15:41:59 +00:00
|
|
|
@property
|
2020-02-25 19:52:39 +00:00
|
|
|
@abstractmethod
|
|
|
|
def name(self) -> str:
|
2019-12-08 00:25:12 +00:00
|
|
|
"""Return the experiment name."""
|
2019-11-05 15:41:59 +00:00
|
|
|
|
2019-09-27 16:05:29 +00:00
|
|
|
@property
|
2020-02-25 19:52:39 +00:00
|
|
|
@abstractmethod
|
|
|
|
def version(self) -> Union[int, str]:
|
2019-12-08 00:25:12 +00:00
|
|
|
"""Return the experiment version."""
|
2020-02-25 19:52:39 +00:00
|
|
|
|
|
|
|
|
|
|
|
class LoggerCollection(LightningLoggerBase):
|
|
|
|
"""The `LoggerCollection` class is used to iterate all logging actions over the given `logger_iterable`.
|
|
|
|
|
|
|
|
Args:
|
|
|
|
logger_iterable: An iterable collection of loggers
|
|
|
|
"""
|
|
|
|
|
|
|
|
def __init__(self, logger_iterable: Iterable[LightningLoggerBase]):
|
|
|
|
super().__init__()
|
|
|
|
self._logger_iterable = logger_iterable
|
|
|
|
|
2020-02-27 20:54:06 +00:00
|
|
|
def __getitem__(self, index: int) -> LightningLoggerBase:
|
|
|
|
return [logger for logger in self._logger_iterable][index]
|
|
|
|
|
2020-02-25 19:52:39 +00:00
|
|
|
@property
|
|
|
|
def experiment(self) -> List[Any]:
|
2020-03-03 01:49:14 +00:00
|
|
|
return [logger.experiment for logger in self._logger_iterable]
|
2020-02-25 19:52:39 +00:00
|
|
|
|
2020-03-04 14:33:39 +00:00
|
|
|
def log_metrics(self, metrics: Dict[str, float], step: Optional[int] = None) -> None:
|
2020-02-25 19:52:39 +00:00
|
|
|
[logger.log_metrics(metrics, step) for logger in self._logger_iterable]
|
|
|
|
|
2020-03-04 14:33:39 +00:00
|
|
|
def log_hyperparams(self, params: Union[Dict[str, Any], Namespace]) -> None:
|
2020-02-25 19:52:39 +00:00
|
|
|
[logger.log_hyperparams(params) for logger in self._logger_iterable]
|
|
|
|
|
2020-03-04 14:33:39 +00:00
|
|
|
def save(self) -> None:
|
2020-02-25 19:52:39 +00:00
|
|
|
[logger.save() for logger in self._logger_iterable]
|
|
|
|
|
2020-03-04 14:33:39 +00:00
|
|
|
def finalize(self, status: str) -> None:
|
2020-02-25 19:52:39 +00:00
|
|
|
[logger.finalize(status) for logger in self._logger_iterable]
|
|
|
|
|
2020-03-04 14:33:39 +00:00
|
|
|
def close(self) -> None:
|
2020-02-25 19:52:39 +00:00
|
|
|
[logger.close() for logger in self._logger_iterable]
|
|
|
|
|
2020-03-03 01:49:14 +00:00
|
|
|
@LightningLoggerBase.rank.setter
|
2020-03-04 14:33:39 +00:00
|
|
|
def rank(self, value: int) -> None:
|
2020-02-25 19:52:39 +00:00
|
|
|
self._rank = value
|
|
|
|
for logger in self._logger_iterable:
|
|
|
|
logger.rank = value
|
|
|
|
|
|
|
|
@property
|
|
|
|
def name(self) -> str:
|
|
|
|
return '_'.join([str(logger.name) for logger in self._logger_iterable])
|
|
|
|
|
|
|
|
@property
|
|
|
|
def version(self) -> str:
|
|
|
|
return '_'.join([str(logger.version) for logger in self._logger_iterable])
|