2020-04-16 16:04:12 +00:00
|
|
|
"""
|
|
|
|
TensorBoard
|
|
|
|
-----------
|
|
|
|
"""
|
|
|
|
|
2020-02-25 19:52:39 +00:00
|
|
|
import csv
|
2019-12-08 04:25:37 +00:00
|
|
|
import os
|
2020-01-16 12:22:29 +00:00
|
|
|
from argparse import Namespace
|
2020-03-04 14:33:39 +00:00
|
|
|
from typing import Optional, Dict, Union, Any
|
2020-02-25 19:52:39 +00:00
|
|
|
from warnings import warn
|
2019-12-08 04:25:37 +00:00
|
|
|
|
|
|
|
import torch
|
2020-02-25 19:52:39 +00:00
|
|
|
from pkg_resources import parse_version
|
2019-12-08 04:25:37 +00:00
|
|
|
from torch.utils.tensorboard import SummaryWriter
|
|
|
|
|
2020-04-07 10:39:54 +00:00
|
|
|
from pytorch_lightning import _logger as log
|
2020-04-24 21:21:00 +00:00
|
|
|
from pytorch_lightning.loggers.base import LightningLoggerBase
|
|
|
|
from pytorch_lightning.utilities import rank_zero_only
|
2019-12-08 04:25:37 +00:00
|
|
|
|
|
|
|
|
2019-12-08 15:59:25 +00:00
|
|
|
class TensorBoardLogger(LightningLoggerBase):
|
2020-01-17 11:03:31 +00:00
|
|
|
r"""
|
2020-04-16 16:04:12 +00:00
|
|
|
Log to local file system in `TensorBoard <https://www.tensorflow.org/tensorboard>`_ format.
|
|
|
|
Implemented using :class:`~torch.utils.tensorboard.SummaryWriter`. Logs are saved to
|
|
|
|
``os.path.join(save_dir, name, version)``. This is the default logger in Lightning, it comes
|
|
|
|
preinstalled.
|
2020-02-11 04:55:22 +00:00
|
|
|
|
2020-03-19 13:14:29 +00:00
|
|
|
Example:
|
2020-04-16 16:04:12 +00:00
|
|
|
>>> from pytorch_lightning import Trainer
|
|
|
|
>>> from pytorch_lightning.loggers import TensorBoardLogger
|
|
|
|
>>> logger = TensorBoardLogger("tb_logs", name="my_model")
|
|
|
|
>>> trainer = Trainer(logger=logger)
|
2019-12-08 04:25:37 +00:00
|
|
|
|
2020-01-17 11:03:31 +00:00
|
|
|
Args:
|
2020-03-20 19:49:01 +00:00
|
|
|
save_dir: Save directory
|
2020-04-16 16:04:12 +00:00
|
|
|
name: Experiment name. Defaults to ``'default'``. If it is the empty string then no per-experiment
|
2020-02-10 14:07:17 +00:00
|
|
|
subdirectory is used.
|
2020-03-20 19:49:01 +00:00
|
|
|
version: Experiment version. If version is not specified the logger inspects the save
|
2020-02-10 14:07:17 +00:00
|
|
|
directory for existing versions, then automatically assigns the next available version.
|
|
|
|
If it is a string then it is used as the run-specific subdirectory name,
|
2020-04-16 16:04:12 +00:00
|
|
|
otherwise ``'version_${version}'`` is used.
|
2020-03-20 19:49:01 +00:00
|
|
|
\**kwargs: Other arguments are passed directly to the :class:`SummaryWriter` constructor.
|
2019-12-08 04:25:37 +00:00
|
|
|
|
|
|
|
"""
|
2020-01-16 12:22:29 +00:00
|
|
|
NAME_CSV_TAGS = 'meta_tags.csv'
|
2019-12-08 04:25:37 +00:00
|
|
|
|
2020-04-15 00:32:33 +00:00
|
|
|
def __init__(self,
|
|
|
|
save_dir: str,
|
|
|
|
name: Optional[str] = "default",
|
|
|
|
version: Optional[Union[int, str]] = None,
|
|
|
|
**kwargs):
|
2019-12-08 04:25:37 +00:00
|
|
|
super().__init__()
|
|
|
|
self.save_dir = save_dir
|
|
|
|
self._name = name
|
2019-12-08 15:59:25 +00:00
|
|
|
self._version = version
|
2019-12-08 04:25:37 +00:00
|
|
|
|
|
|
|
self._experiment = None
|
2020-01-16 12:22:29 +00:00
|
|
|
self.tags = {}
|
2020-04-15 00:32:33 +00:00
|
|
|
self._kwargs = kwargs
|
2019-12-08 04:25:37 +00:00
|
|
|
|
2020-02-10 14:07:17 +00:00
|
|
|
@property
|
2020-02-25 19:52:39 +00:00
|
|
|
def root_dir(self) -> str:
|
2020-02-10 14:07:17 +00:00
|
|
|
"""
|
|
|
|
Parent directory for all tensorboard checkpoint subdirectories.
|
2020-04-16 16:04:12 +00:00
|
|
|
If the experiment name parameter is ``None`` or the empty string, no experiment subdirectory is used
|
|
|
|
and the checkpoint will be saved in "save_dir/version_dir"
|
2020-02-10 14:07:17 +00:00
|
|
|
"""
|
|
|
|
if self.name is None or len(self.name) == 0:
|
|
|
|
return self.save_dir
|
|
|
|
else:
|
|
|
|
return os.path.join(self.save_dir, self.name)
|
|
|
|
|
|
|
|
@property
|
2020-02-25 19:52:39 +00:00
|
|
|
def log_dir(self) -> str:
|
2020-02-10 14:07:17 +00:00
|
|
|
"""
|
2020-04-16 16:04:12 +00:00
|
|
|
The directory for this run's tensorboard checkpoint. By default, it is named
|
|
|
|
``'version_${self.version}'`` but it can be overridden by passing a string value
|
|
|
|
for the constructor's version parameter instead of ``None`` or an int.
|
2020-02-10 14:07:17 +00:00
|
|
|
"""
|
|
|
|
# create a pseudo standard path ala test-tube
|
|
|
|
version = self.version if isinstance(self.version, str) else f"version_{self.version}"
|
|
|
|
log_dir = os.path.join(self.root_dir, version)
|
|
|
|
return log_dir
|
|
|
|
|
2019-12-08 04:25:37 +00:00
|
|
|
@property
|
2020-02-25 19:52:39 +00:00
|
|
|
def experiment(self) -> SummaryWriter:
|
2020-01-17 11:03:31 +00:00
|
|
|
r"""
|
2020-04-16 16:04:12 +00:00
|
|
|
Actual tensorboard object. To use TensorBoard features in your
|
|
|
|
:class:`~pytorch_lightning.core.lightning.LightningModule` do the following.
|
2020-01-17 11:03:31 +00:00
|
|
|
|
2020-04-16 16:04:12 +00:00
|
|
|
Example::
|
2020-01-17 11:03:31 +00:00
|
|
|
|
2020-04-16 16:04:12 +00:00
|
|
|
self.logger.experiment.some_tensorboard_function()
|
2020-01-17 11:03:31 +00:00
|
|
|
|
2020-04-16 16:04:12 +00:00
|
|
|
"""
|
2019-12-08 04:25:37 +00:00
|
|
|
if self._experiment is not None:
|
|
|
|
return self._experiment
|
|
|
|
|
2020-02-10 14:07:17 +00:00
|
|
|
os.makedirs(self.root_dir, exist_ok=True)
|
2020-04-15 00:32:33 +00:00
|
|
|
self._experiment = SummaryWriter(log_dir=self.log_dir, **self._kwargs)
|
2019-12-08 04:25:37 +00:00
|
|
|
return self._experiment
|
|
|
|
|
|
|
|
@rank_zero_only
|
2020-04-27 07:47:35 +00:00
|
|
|
def log_hyperparams(self, params: Union[Dict[str, Any], Namespace],
|
2020-04-27 07:44:26 +00:00
|
|
|
metrics: Optional[Dict[str, Any]] = None) -> None:
|
2020-03-04 14:33:39 +00:00
|
|
|
params = self._convert_params(params)
|
2020-03-19 13:15:47 +00:00
|
|
|
params = self._flatten_dict(params)
|
2020-03-14 17:02:05 +00:00
|
|
|
sanitized_params = self._sanitize_params(params)
|
2020-01-16 12:22:29 +00:00
|
|
|
|
2019-12-08 04:25:37 +00:00
|
|
|
if parse_version(torch.__version__) < parse_version("1.3.0"):
|
|
|
|
warn(
|
2019-12-08 15:59:25 +00:00
|
|
|
f"Hyperparameter logging is not available for Torch version {torch.__version__}."
|
|
|
|
" Skipping log_hyperparams. Upgrade to Torch 1.3.0 or above to enable"
|
|
|
|
" hyperparameter logging."
|
2019-12-08 04:25:37 +00:00
|
|
|
)
|
2020-01-16 12:22:29 +00:00
|
|
|
else:
|
2020-02-02 14:31:45 +00:00
|
|
|
from torch.utils.tensorboard.summary import hparams
|
2020-05-12 11:25:12 +00:00
|
|
|
|
2020-04-27 07:44:26 +00:00
|
|
|
if metrics is None:
|
|
|
|
metrics = {}
|
|
|
|
exp, ssi, sei = hparams(sanitized_params, metrics)
|
2020-02-02 14:31:45 +00:00
|
|
|
writer = self.experiment._get_file_writer()
|
|
|
|
writer.add_summary(exp)
|
|
|
|
writer.add_summary(ssi)
|
|
|
|
writer.add_summary(sei)
|
2020-03-14 17:02:05 +00:00
|
|
|
|
2020-05-12 11:25:12 +00:00
|
|
|
if metrics:
|
|
|
|
# necessary for hparam comparison with metrics
|
|
|
|
self.log_metrics(metrics)
|
|
|
|
|
2020-01-16 12:22:29 +00:00
|
|
|
# some alternative should be added
|
2020-03-14 17:02:05 +00:00
|
|
|
self.tags.update(sanitized_params)
|
2019-12-08 04:25:37 +00:00
|
|
|
|
|
|
|
@rank_zero_only
|
2020-03-04 14:33:39 +00:00
|
|
|
def log_metrics(self, metrics: Dict[str, float], step: Optional[int] = None) -> None:
|
2019-12-08 04:25:37 +00:00
|
|
|
for k, v in metrics.items():
|
|
|
|
if isinstance(v, torch.Tensor):
|
|
|
|
v = v.item()
|
2019-12-08 15:59:25 +00:00
|
|
|
self.experiment.add_scalar(k, v, step)
|
2019-12-08 04:25:37 +00:00
|
|
|
|
|
|
|
@rank_zero_only
|
2020-03-04 14:33:39 +00:00
|
|
|
def save(self) -> None:
|
2020-04-15 00:32:33 +00:00
|
|
|
super().save()
|
2019-12-08 15:59:25 +00:00
|
|
|
try:
|
|
|
|
self.experiment.flush()
|
|
|
|
except AttributeError:
|
|
|
|
# you are using PT version (<v1.2) which does not have implemented flush
|
|
|
|
self.experiment._get_file_writer().flush()
|
2019-12-08 04:25:37 +00:00
|
|
|
|
2020-02-10 14:07:17 +00:00
|
|
|
dir_path = self.log_dir
|
2020-01-16 12:22:29 +00:00
|
|
|
if not os.path.isdir(dir_path):
|
|
|
|
dir_path = self.save_dir
|
2020-01-29 19:52:23 +00:00
|
|
|
|
2020-01-16 12:22:29 +00:00
|
|
|
# prepare the file path
|
|
|
|
meta_tags_path = os.path.join(dir_path, self.NAME_CSV_TAGS)
|
2020-01-29 19:52:23 +00:00
|
|
|
|
2020-01-16 12:22:29 +00:00
|
|
|
# save the metatags file
|
2020-01-29 19:52:23 +00:00
|
|
|
with open(meta_tags_path, 'w', newline='') as csvfile:
|
|
|
|
fieldnames = ['key', 'value']
|
|
|
|
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
|
|
|
|
writer.writerow({'key': 'key', 'value': 'value'})
|
|
|
|
for k, v in self.tags.items():
|
|
|
|
writer.writerow({'key': k, 'value': v})
|
2020-01-16 12:22:29 +00:00
|
|
|
|
2019-12-08 04:25:37 +00:00
|
|
|
@rank_zero_only
|
2020-03-04 14:33:39 +00:00
|
|
|
def finalize(self, status: str) -> None:
|
2019-12-08 04:25:37 +00:00
|
|
|
self.save()
|
|
|
|
|
|
|
|
@property
|
2020-02-25 19:52:39 +00:00
|
|
|
def name(self) -> str:
|
2019-12-08 04:25:37 +00:00
|
|
|
return self._name
|
|
|
|
|
|
|
|
@property
|
2020-02-25 19:52:39 +00:00
|
|
|
def version(self) -> int:
|
2019-12-08 04:25:37 +00:00
|
|
|
if self._version is None:
|
|
|
|
self._version = self._get_next_version()
|
|
|
|
return self._version
|
|
|
|
|
|
|
|
def _get_next_version(self):
|
|
|
|
root_dir = os.path.join(self.save_dir, self.name)
|
2020-04-07 10:39:54 +00:00
|
|
|
|
|
|
|
if not os.path.isdir(root_dir):
|
|
|
|
log.warning('Missing logger folder: %s', root_dir)
|
|
|
|
return 0
|
|
|
|
|
2020-01-18 12:17:54 +00:00
|
|
|
existing_versions = []
|
|
|
|
for d in os.listdir(root_dir):
|
|
|
|
if os.path.isdir(os.path.join(root_dir, d)) and d.startswith("version_"):
|
|
|
|
existing_versions.append(int(d.split("_")[1]))
|
|
|
|
|
2019-12-08 04:25:37 +00:00
|
|
|
if len(existing_versions) == 0:
|
|
|
|
return 0
|
2020-02-01 23:44:05 +00:00
|
|
|
|
|
|
|
return max(existing_versions) + 1
|