We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
TensorBoardLogger not saving hparams without metrics
## 🐛 Bug

`log_hyperparams` for `TensorBoardLogger` saves no data with default `metrics=None`, only hparam entries/names show up in sidebar

### To Reproduce

Steps to reproduce the behavior:

```
import pytorch_lightning as pl
logger = pl.loggers.TensorBoardLogger("./test_logs")
test_dict = {"test":0}
logger.log_hyperparams(test_dict)                      ## no data saved
logger.log_hyperparams(test_dict, test_dict)           ## works
logger.log_metrics(test_dict)                          ## works
logger.experiment.add_hparams(test_dict, test_dict)    ## works but saves in a different events file
```

<!-- If you have a code sample, error messages, stack traces, please provide it here as well -->

### Expected behavior
hparams data is saved and viewable via tensorboard with default args

### Proposed solution
For default hparams logging without metrics, add a placeholder metric? I can do a PR if this is appropriate.

--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `pytorch_lightning/loggers/tensorboard.py`
Content:
```
1 # Copyright The PyTorch Lightning team.
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
6 #
7 #     http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14 
15 """
16 TensorBoard
17 -----------
18 """
19 
20 import os
21 from argparse import Namespace
22 from typing import Optional, Dict, Union, Any
23 from warnings import warn
24 
25 import torch
26 from pkg_resources import parse_version
27 from torch.utils.tensorboard import SummaryWriter
28 
29 from pytorch_lightning import _logger as log
30 from pytorch_lightning.core.saving import save_hparams_to_yaml
31 from pytorch_lightning.loggers.base import LightningLoggerBase, rank_zero_experiment
32 from pytorch_lightning.utilities import rank_zero_only, rank_zero_warn
33 from pytorch_lightning.utilities.cloud_io import gfile, makedirs
34 from pytorch_lightning.core.lightning import LightningModule
35 
36 try:
37     from omegaconf import Container, OmegaConf
38 except ImportError:
39     OMEGACONF_AVAILABLE = False
40 else:
41     OMEGACONF_AVAILABLE = True
42 
43 
44 class TensorBoardLogger(LightningLoggerBase):
45     r"""
46     Log to local file system in `TensorBoard <https://www.tensorflow.org/tensorboard>`_ format.
47     Implemented using :class:`~torch.utils.tensorboard.SummaryWriter`. Logs are saved to
48     ``os.path.join(save_dir, name, version)``. This is the default logger in Lightning, it comes
49     preinstalled.
50 
51     Example:
52         >>> from pytorch_lightning import Trainer
53         >>> from pytorch_lightning.loggers import TensorBoardLogger
54         >>> logger = TensorBoardLogger("tb_logs", name="my_model")
55         >>> trainer = Trainer(logger=logger)
56 
57     Args:
58         save_dir: Save directory
59         name: Experiment name. Defaults to ``'default'``. If it is the empty string then no per-experiment
60             subdirectory is used.
61         version: Experiment version. If version is not specified the logger inspects the save
62             directory for existing versions, then automatically assigns the next available version.
63             If it is a string then it is used as the run-specific subdirectory name,
64             otherwise ``'version_${version}'`` is used.
65         log_graph: Adds the computational graph to tensorboard. This requires that
66             the user has defined the `self.example_input_array` attribute in their
67             model.
68         \**kwargs: Other arguments are passed directly to the :class:`SummaryWriter` constructor.
69 
70     """
71     NAME_HPARAMS_FILE = 'hparams.yaml'
72 
73     def __init__(
74         self,
75         save_dir: str,
76         name: Optional[str] = "default",
77         version: Optional[Union[int, str]] = None,
78         log_graph: bool = False,
79         **kwargs
80     ):
81         super().__init__()
82         self._save_dir = save_dir
83         self._name = name or ''
84         self._version = version
85         self._log_graph = log_graph
86 
87         self._experiment = None
88         self.hparams = {}
89         self._kwargs = kwargs
90 
91     @property
92     def root_dir(self) -> str:
93         """
94         Parent directory for all tensorboard checkpoint subdirectories.
95         If the experiment name parameter is ``None`` or the empty string, no experiment subdirectory is used
96         and the checkpoint will be saved in "save_dir/version_dir"
97         """
98         if self.name is None or len(self.name) == 0:
99             return self.save_dir
100         else:
101             return os.path.join(self.save_dir, self.name)
102 
103     @property
104     def log_dir(self) -> str:
105         """
106         The directory for this run's tensorboard checkpoint. By default, it is named
107         ``'version_${self.version}'`` but it can be overridden by passing a string value
108         for the constructor's version parameter instead of ``None`` or an int.
109         """
110         # create a pseudo standard path ala test-tube
111         version = self.version if isinstance(self.version, str) else f"version_{self.version}"
112         log_dir = os.path.join(self.root_dir, version)
113         return log_dir
114 
115     @property
116     def save_dir(self) -> Optional[str]:
117         return self._save_dir
118 
119     @property
120     @rank_zero_experiment
121     def experiment(self) -> SummaryWriter:
122         r"""
123         Actual tensorboard object. To use TensorBoard features in your
124         :class:`~pytorch_lightning.core.lightning.LightningModule` do the following.
125 
126         Example::
127 
128             self.logger.experiment.some_tensorboard_function()
129 
130         """
131         if self._experiment is not None:
132             return self._experiment
133 
134         assert rank_zero_only.rank == 0, 'tried to init log dirs in non global_rank=0'
135         if self.root_dir and not gfile.exists(str(self.root_dir)):
136             makedirs(self.root_dir)
137         self._experiment = SummaryWriter(log_dir=self.log_dir, **self._kwargs)
138         return self._experiment
139 
140     @rank_zero_only
141     def log_hyperparams(self, params: Union[Dict[str, Any], Namespace],
142                         metrics: Optional[Dict[str, Any]] = None) -> None:
143         params = self._convert_params(params)
144 
145         # store params to output
146         if OMEGACONF_AVAILABLE and isinstance(params, Container):
147             self.hparams = OmegaConf.merge(self.hparams, params)
148         else:
149             self.hparams.update(params)
150 
151         # format params into the suitable for tensorboard
152         params = self._flatten_dict(params)
153         params = self._sanitize_params(params)
154 
155         if parse_version(torch.__version__) < parse_version("1.3.0"):
156             warn(
157                 f"Hyperparameter logging is not available for Torch version {torch.__version__}."
158                 " Skipping log_hyperparams. Upgrade to Torch 1.3.0 or above to enable"
159                 " hyperparameter logging."
160             )
161         else:
162             from torch.utils.tensorboard.summary import hparams
163 
164             if metrics is None:
165                 metrics = {}
166             exp, ssi, sei = hparams(params, metrics)
167             writer = self.experiment._get_file_writer()
168             writer.add_summary(exp)
169             writer.add_summary(ssi)
170             writer.add_summary(sei)
171 
172             if metrics:
173                 # necessary for hparam comparison with metrics
174                 self.log_metrics(metrics)
175 
176     @rank_zero_only
177     def log_metrics(self, metrics: Dict[str, float], step: Optional[int] = None) -> None:
178         assert rank_zero_only.rank == 0, 'experiment tried to log from global_rank != 0'
179 
180         for k, v in metrics.items():
181             if isinstance(v, torch.Tensor):
182                 v = v.item()
183             self.experiment.add_scalar(k, v, step)
184 
185     @rank_zero_only
186     def log_graph(self, model: LightningModule, input_array=None):
187         if self._log_graph:
188             if input_array is None:
189                 input_array = model.example_input_array
190 
191             if input_array is not None:
192                 input_array = model.transfer_batch_to_device(input_array, model.device)
193                 self.experiment.add_graph(model, input_array)
194             else:
195                 rank_zero_warn('Could not log computational graph since the'
196                                ' `model.example_input_array` attribute is not set'
197                                ' or `input_array` was not given',
198                                UserWarning)
199 
200     @rank_zero_only
201     def save(self) -> None:
202         super().save()
203         dir_path = self.log_dir
204         if not gfile.isdir(dir_path):
205             dir_path = self.save_dir
206 
207         # prepare the file path
208         hparams_file = os.path.join(dir_path, self.NAME_HPARAMS_FILE)
209 
210         # save the metatags file
211         save_hparams_to_yaml(hparams_file, self.hparams)
212 
213     @rank_zero_only
214     def finalize(self, status: str) -> None:
215         self.save()
216 
217     @property
218     def name(self) -> str:
219         return self._name
220 
221     @property
222     def version(self) -> int:
223         if self._version is None:
224             self._version = self._get_next_version()
225         return self._version
226 
227     def _get_next_version(self):
228         root_dir = os.path.join(self.save_dir, self.name)
229 
230         if not gfile.isdir(root_dir):
231             log.warning('Missing logger folder: %s', root_dir)
232             return 0
233 
234         existing_versions = []
235         for d in gfile.listdir(root_dir):
236             if gfile.isdir(os.path.join(root_dir, d)) and d.startswith("version_"):
237                 existing_versions.append(int(d.split("_")[1]))
238 
239         if len(existing_versions) == 0:
240             return 0
241 
242         return max(existing_versions) + 1
243 
244     def __getstate__(self):
245         state = self.__dict__.copy()
246         state["_experiment"] = None
247         return state
248
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/pytorch_lightning/loggers/tensorboard.py b/pytorch_lightning/loggers/tensorboard.py
--- a/pytorch_lightning/loggers/tensorboard.py
+++ b/pytorch_lightning/loggers/tensorboard.py
@@ -65,6 +65,8 @@
         log_graph: Adds the computational graph to tensorboard. This requires that
             the user has defined the `self.example_input_array` attribute in their
             model.
+        default_hp_metric: Enables a placeholder metric with key `hp_metric` when `log_hyperparams` is
+            called without a metric (otherwise calls to log_hyperparams without a metric are ignored).
         \**kwargs: Other arguments are passed directly to the :class:`SummaryWriter` constructor.
 
     """
@@ -76,6 +78,7 @@
         name: Optional[str] = "default",
         version: Optional[Union[int, str]] = None,
         log_graph: bool = False,
+        default_hp_metric: bool = True,
         **kwargs
     ):
         super().__init__()
@@ -83,6 +86,7 @@
         self._name = name or ''
         self._version = version
         self._log_graph = log_graph
+        self._default_hp_metric = default_hp_metric
 
         self._experiment = None
         self.hparams = {}
@@ -162,16 +166,18 @@
             from torch.utils.tensorboard.summary import hparams
 
             if metrics is None:
-                metrics = {}
-            exp, ssi, sei = hparams(params, metrics)
-            writer = self.experiment._get_file_writer()
-            writer.add_summary(exp)
-            writer.add_summary(ssi)
-            writer.add_summary(sei)
+                if self._default_hp_metric:
+                    metrics = {"hp_metric": -1}
+            elif not isinstance(metrics, dict):
+                metrics = {"hp_metric": metrics}
 
             if metrics:
-                # necessary for hparam comparison with metrics
-                self.log_metrics(metrics)
+                self.log_metrics(metrics, 0)
+                exp, ssi, sei = hparams(params, metrics)
+                writer = self.experiment._get_file_writer()
+                writer.add_summary(exp)
+                writer.add_summary(ssi)
+                writer.add_summary(sei)
 
     @rank_zero_only
     def log_metrics(self, metrics: Dict[str, float], step: Optional[int] = None) -> None:

{"golden_diff": "diff --git a/pytorch_lightning/loggers/tensorboard.py b/pytorch_lightning/loggers/tensorboard.py\n--- a/pytorch_lightning/loggers/tensorboard.py\n+++ b/pytorch_lightning/loggers/tensorboard.py\n@@ -65,6 +65,8 @@\n         log_graph: Adds the computational graph to tensorboard. This requires that\n             the user has defined the `self.example_input_array` attribute in their\n             model.\n+        default_hp_metric: Enables a placeholder metric with key `hp_metric` when `log_hyperparams` is\n+            called without a metric (otherwise calls to log_hyperparams without a metric are ignored).\n         \\**kwargs: Other arguments are passed directly to the :class:`SummaryWriter` constructor.\n \n     \"\"\"\n@@ -76,6 +78,7 @@\n         name: Optional[str] = \"default\",\n         version: Optional[Union[int, str]] = None,\n         log_graph: bool = False,\n+        default_hp_metric: bool = True,\n         **kwargs\n     ):\n         super().__init__()\n@@ -83,6 +86,7 @@\n         self._name = name or ''\n         self._version = version\n         self._log_graph = log_graph\n+        self._default_hp_metric = default_hp_metric\n \n         self._experiment = None\n         self.hparams = {}\n@@ -162,16 +166,18 @@\n             from torch.utils.tensorboard.summary import hparams\n \n             if metrics is None:\n-                metrics = {}\n-            exp, ssi, sei = hparams(params, metrics)\n-            writer = self.experiment._get_file_writer()\n-            writer.add_summary(exp)\n-            writer.add_summary(ssi)\n-            writer.add_summary(sei)\n+                if self._default_hp_metric:\n+                    metrics = {\"hp_metric\": -1}\n+            elif not isinstance(metrics, dict):\n+                metrics = {\"hp_metric\": metrics}\n \n             if metrics:\n-                # necessary for hparam comparison with metrics\n-                self.log_metrics(metrics)\n+                self.log_metrics(metrics, 0)\n+                exp, ssi, sei = hparams(params, metrics)\n+                writer = self.experiment._get_file_writer()\n+                writer.add_summary(exp)\n+                writer.add_summary(ssi)\n+                writer.add_summary(sei)\n \n     @rank_zero_only\n     def log_metrics(self, metrics: Dict[str, float], step: Optional[int] = None) -> None:\n", "issue": "TensorBoardLogger not saving hparams without metrics\n## \ud83d\udc1b Bug\r\n\r\n`log_hyperparams` for `TensorBoardLogger` saves no data with default `metrics=None`, only hparam entries/names show up in sidebar\r\n\r\n### To Reproduce\r\n\r\nSteps to reproduce the behavior:\r\n\r\n```\r\nimport pytorch_lightning as pl\r\nlogger = pl.loggers.TensorBoardLogger(\"./test_logs\")\r\ntest_dict = {\"test\":0}\r\nlogger.log_hyperparams(test_dict)                      ## no data saved\r\nlogger.log_hyperparams(test_dict, test_dict)           ## works\r\nlogger.log_metrics(test_dict)                          ## works\r\nlogger.experiment.add_hparams(test_dict, test_dict)    ## works but saves in a different events file\r\n```\r\n\r\n<!-- If you have a code sample, error messages, stack traces, please provide it here as well -->\r\n\r\n### Expected behavior\r\nhparams data is saved and viewable via tensorboard with default args\r\n\r\n### Proposed solution\r\nFor default hparams logging without metrics, add a placeholder metric? I can do a PR if this is appropriate.\n", "before_files": [{"content": "# Copyright The PyTorch Lightning team.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"\nTensorBoard\n-----------\n\"\"\"\n\nimport os\nfrom argparse import Namespace\nfrom typing import Optional, Dict, Union, Any\nfrom warnings import warn\n\nimport torch\nfrom pkg_resources import parse_version\nfrom torch.utils.tensorboard import SummaryWriter\n\nfrom pytorch_lightning import _logger as log\nfrom pytorch_lightning.core.saving import save_hparams_to_yaml\nfrom pytorch_lightning.loggers.base import LightningLoggerBase, rank_zero_experiment\nfrom pytorch_lightning.utilities import rank_zero_only, rank_zero_warn\nfrom pytorch_lightning.utilities.cloud_io import gfile, makedirs\nfrom pytorch_lightning.core.lightning import LightningModule\n\ntry:\n    from omegaconf import Container, OmegaConf\nexcept ImportError:\n    OMEGACONF_AVAILABLE = False\nelse:\n    OMEGACONF_AVAILABLE = True\n\n\nclass TensorBoardLogger(LightningLoggerBase):\n    r\"\"\"\n    Log to local file system in `TensorBoard <https://www.tensorflow.org/tensorboard>`_ format.\n    Implemented using :class:`~torch.utils.tensorboard.SummaryWriter`. Logs are saved to\n    ``os.path.join(save_dir, name, version)``. This is the default logger in Lightning, it comes\n    preinstalled.\n\n    Example:\n        >>> from pytorch_lightning import Trainer\n        >>> from pytorch_lightning.loggers import TensorBoardLogger\n        >>> logger = TensorBoardLogger(\"tb_logs\", name=\"my_model\")\n        >>> trainer = Trainer(logger=logger)\n\n    Args:\n        save_dir: Save directory\n        name: Experiment name. Defaults to ``'default'``. If it is the empty string then no per-experiment\n            subdirectory is used.\n        version: Experiment version. If version is not specified the logger inspects the save\n            directory for existing versions, then automatically assigns the next available version.\n            If it is a string then it is used as the run-specific subdirectory name,\n            otherwise ``'version_${version}'`` is used.\n        log_graph: Adds the computational graph to tensorboard. This requires that\n            the user has defined the `self.example_input_array` attribute in their\n            model.\n        \\**kwargs: Other arguments are passed directly to the :class:`SummaryWriter` constructor.\n\n    \"\"\"\n    NAME_HPARAMS_FILE = 'hparams.yaml'\n\n    def __init__(\n        self,\n        save_dir: str,\n        name: Optional[str] = \"default\",\n        version: Optional[Union[int, str]] = None,\n        log_graph: bool = False,\n        **kwargs\n    ):\n        super().__init__()\n        self._save_dir = save_dir\n        self._name = name or ''\n        self._version = version\n        self._log_graph = log_graph\n\n        self._experiment = None\n        self.hparams = {}\n        self._kwargs = kwargs\n\n    @property\n    def root_dir(self) -> str:\n        \"\"\"\n        Parent directory for all tensorboard checkpoint subdirectories.\n        If the experiment name parameter is ``None`` or the empty string, no experiment subdirectory is used\n        and the checkpoint will be saved in \"save_dir/version_dir\"\n        \"\"\"\n        if self.name is None or len(self.name) == 0:\n            return self.save_dir\n        else:\n            return os.path.join(self.save_dir, self.name)\n\n    @property\n    def log_dir(self) -> str:\n        \"\"\"\n        The directory for this run's tensorboard checkpoint. By default, it is named\n        ``'version_${self.version}'`` but it can be overridden by passing a string value\n        for the constructor's version parameter instead of ``None`` or an int.\n        \"\"\"\n        # create a pseudo standard path ala test-tube\n        version = self.version if isinstance(self.version, str) else f\"version_{self.version}\"\n        log_dir = os.path.join(self.root_dir, version)\n        return log_dir\n\n    @property\n    def save_dir(self) -> Optional[str]:\n        return self._save_dir\n\n    @property\n    @rank_zero_experiment\n    def experiment(self) -> SummaryWriter:\n        r\"\"\"\n        Actual tensorboard object. To use TensorBoard features in your\n        :class:`~pytorch_lightning.core.lightning.LightningModule` do the following.\n\n        Example::\n\n            self.logger.experiment.some_tensorboard_function()\n\n        \"\"\"\n        if self._experiment is not None:\n            return self._experiment\n\n        assert rank_zero_only.rank == 0, 'tried to init log dirs in non global_rank=0'\n        if self.root_dir and not gfile.exists(str(self.root_dir)):\n            makedirs(self.root_dir)\n        self._experiment = SummaryWriter(log_dir=self.log_dir, **self._kwargs)\n        return self._experiment\n\n    @rank_zero_only\n    def log_hyperparams(self, params: Union[Dict[str, Any], Namespace],\n                        metrics: Optional[Dict[str, Any]] = None) -> None:\n        params = self._convert_params(params)\n\n        # store params to output\n        if OMEGACONF_AVAILABLE and isinstance(params, Container):\n            self.hparams = OmegaConf.merge(self.hparams, params)\n        else:\n            self.hparams.update(params)\n\n        # format params into the suitable for tensorboard\n        params = self._flatten_dict(params)\n        params = self._sanitize_params(params)\n\n        if parse_version(torch.__version__) < parse_version(\"1.3.0\"):\n            warn(\n                f\"Hyperparameter logging is not available for Torch version {torch.__version__}.\"\n                \" Skipping log_hyperparams. Upgrade to Torch 1.3.0 or above to enable\"\n                \" hyperparameter logging.\"\n            )\n        else:\n            from torch.utils.tensorboard.summary import hparams\n\n            if metrics is None:\n                metrics = {}\n            exp, ssi, sei = hparams(params, metrics)\n            writer = self.experiment._get_file_writer()\n            writer.add_summary(exp)\n            writer.add_summary(ssi)\n            writer.add_summary(sei)\n\n            if metrics:\n                # necessary for hparam comparison with metrics\n                self.log_metrics(metrics)\n\n    @rank_zero_only\n    def log_metrics(self, metrics: Dict[str, float], step: Optional[int] = None) -> None:\n        assert rank_zero_only.rank == 0, 'experiment tried to log from global_rank != 0'\n\n        for k, v in metrics.items():\n            if isinstance(v, torch.Tensor):\n                v = v.item()\n            self.experiment.add_scalar(k, v, step)\n\n    @rank_zero_only\n    def log_graph(self, model: LightningModule, input_array=None):\n        if self._log_graph:\n            if input_array is None:\n                input_array = model.example_input_array\n\n            if input_array is not None:\n                input_array = model.transfer_batch_to_device(input_array, model.device)\n                self.experiment.add_graph(model, input_array)\n            else:\n                rank_zero_warn('Could not log computational graph since the'\n                               ' `model.example_input_array` attribute is not set'\n                               ' or `input_array` was not given',\n                               UserWarning)\n\n    @rank_zero_only\n    def save(self) -> None:\n        super().save()\n        dir_path = self.log_dir\n        if not gfile.isdir(dir_path):\n            dir_path = self.save_dir\n\n        # prepare the file path\n        hparams_file = os.path.join(dir_path, self.NAME_HPARAMS_FILE)\n\n        # save the metatags file\n        save_hparams_to_yaml(hparams_file, self.hparams)\n\n    @rank_zero_only\n    def finalize(self, status: str) -> None:\n        self.save()\n\n    @property\n    def name(self) -> str:\n        return self._name\n\n    @property\n    def version(self) -> int:\n        if self._version is None:\n            self._version = self._get_next_version()\n        return self._version\n\n    def _get_next_version(self):\n        root_dir = os.path.join(self.save_dir, self.name)\n\n        if not gfile.isdir(root_dir):\n            log.warning('Missing logger folder: %s', root_dir)\n            return 0\n\n        existing_versions = []\n        for d in gfile.listdir(root_dir):\n            if gfile.isdir(os.path.join(root_dir, d)) and d.startswith(\"version_\"):\n                existing_versions.append(int(d.split(\"_\")[1]))\n\n        if len(existing_versions) == 0:\n            return 0\n\n        return max(existing_versions) + 1\n\n    def __getstate__(self):\n        state = self.__dict__.copy()\n        state[\"_experiment\"] = None\n        return state\n", "path": "pytorch_lightning/loggers/tensorboard.py"}], "after_files": [{"content": "# Copyright The PyTorch Lightning team.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"\nTensorBoard\n-----------\n\"\"\"\n\nimport os\nfrom argparse import Namespace\nfrom typing import Optional, Dict, Union, Any\nfrom warnings import warn\n\nimport torch\nfrom pkg_resources import parse_version\nfrom torch.utils.tensorboard import SummaryWriter\n\nfrom pytorch_lightning import _logger as log\nfrom pytorch_lightning.core.saving import save_hparams_to_yaml\nfrom pytorch_lightning.loggers.base import LightningLoggerBase, rank_zero_experiment\nfrom pytorch_lightning.utilities import rank_zero_only, rank_zero_warn\nfrom pytorch_lightning.utilities.cloud_io import gfile, makedirs\nfrom pytorch_lightning.core.lightning import LightningModule\n\ntry:\n    from omegaconf import Container, OmegaConf\nexcept ImportError:\n    OMEGACONF_AVAILABLE = False\nelse:\n    OMEGACONF_AVAILABLE = True\n\n\nclass TensorBoardLogger(LightningLoggerBase):\n    r\"\"\"\n    Log to local file system in `TensorBoard <https://www.tensorflow.org/tensorboard>`_ format.\n    Implemented using :class:`~torch.utils.tensorboard.SummaryWriter`. Logs are saved to\n    ``os.path.join(save_dir, name, version)``. This is the default logger in Lightning, it comes\n    preinstalled.\n\n    Example:\n        >>> from pytorch_lightning import Trainer\n        >>> from pytorch_lightning.loggers import TensorBoardLogger\n        >>> logger = TensorBoardLogger(\"tb_logs\", name=\"my_model\")\n        >>> trainer = Trainer(logger=logger)\n\n    Args:\n        save_dir: Save directory\n        name: Experiment name. Defaults to ``'default'``. If it is the empty string then no per-experiment\n            subdirectory is used.\n        version: Experiment version. If version is not specified the logger inspects the save\n            directory for existing versions, then automatically assigns the next available version.\n            If it is a string then it is used as the run-specific subdirectory name,\n            otherwise ``'version_${version}'`` is used.\n        log_graph: Adds the computational graph to tensorboard. This requires that\n            the user has defined the `self.example_input_array` attribute in their\n            model.\n        default_hp_metric: Enables a placeholder metric with key `hp_metric` when `log_hyperparams` is\n            called without a metric (otherwise calls to log_hyperparams without a metric are ignored).\n        \\**kwargs: Other arguments are passed directly to the :class:`SummaryWriter` constructor.\n\n    \"\"\"\n    NAME_HPARAMS_FILE = 'hparams.yaml'\n\n    def __init__(\n        self,\n        save_dir: str,\n        name: Optional[str] = \"default\",\n        version: Optional[Union[int, str]] = None,\n        log_graph: bool = False,\n        default_hp_metric: bool = True,\n        **kwargs\n    ):\n        super().__init__()\n        self._save_dir = save_dir\n        self._name = name or ''\n        self._version = version\n        self._log_graph = log_graph\n        self._default_hp_metric = default_hp_metric\n\n        self._experiment = None\n        self.hparams = {}\n        self._kwargs = kwargs\n\n    @property\n    def root_dir(self) -> str:\n        \"\"\"\n        Parent directory for all tensorboard checkpoint subdirectories.\n        If the experiment name parameter is ``None`` or the empty string, no experiment subdirectory is used\n        and the checkpoint will be saved in \"save_dir/version_dir\"\n        \"\"\"\n        if self.name is None or len(self.name) == 0:\n            return self.save_dir\n        else:\n            return os.path.join(self.save_dir, self.name)\n\n    @property\n    def log_dir(self) -> str:\n        \"\"\"\n        The directory for this run's tensorboard checkpoint. By default, it is named\n        ``'version_${self.version}'`` but it can be overridden by passing a string value\n        for the constructor's version parameter instead of ``None`` or an int.\n        \"\"\"\n        # create a pseudo standard path ala test-tube\n        version = self.version if isinstance(self.version, str) else f\"version_{self.version}\"\n        log_dir = os.path.join(self.root_dir, version)\n        return log_dir\n\n    @property\n    def save_dir(self) -> Optional[str]:\n        return self._save_dir\n\n    @property\n    @rank_zero_experiment\n    def experiment(self) -> SummaryWriter:\n        r\"\"\"\n        Actual tensorboard object. To use TensorBoard features in your\n        :class:`~pytorch_lightning.core.lightning.LightningModule` do the following.\n\n        Example::\n\n            self.logger.experiment.some_tensorboard_function()\n\n        \"\"\"\n        if self._experiment is not None:\n            return self._experiment\n\n        assert rank_zero_only.rank == 0, 'tried to init log dirs in non global_rank=0'\n        if self.root_dir and not gfile.exists(str(self.root_dir)):\n            makedirs(self.root_dir)\n        self._experiment = SummaryWriter(log_dir=self.log_dir, **self._kwargs)\n        return self._experiment\n\n    @rank_zero_only\n    def log_hyperparams(self, params: Union[Dict[str, Any], Namespace],\n                        metrics: Optional[Dict[str, Any]] = None) -> None:\n        params = self._convert_params(params)\n\n        # store params to output\n        if OMEGACONF_AVAILABLE and isinstance(params, Container):\n            self.hparams = OmegaConf.merge(self.hparams, params)\n        else:\n            self.hparams.update(params)\n\n        # format params into the suitable for tensorboard\n        params = self._flatten_dict(params)\n        params = self._sanitize_params(params)\n\n        if parse_version(torch.__version__) < parse_version(\"1.3.0\"):\n            warn(\n                f\"Hyperparameter logging is not available for Torch version {torch.__version__}.\"\n                \" Skipping log_hyperparams. Upgrade to Torch 1.3.0 or above to enable\"\n                \" hyperparameter logging.\"\n            )\n        else:\n            from torch.utils.tensorboard.summary import hparams\n\n            if metrics is None:\n                if self._default_hp_metric:\n                    metrics = {\"hp_metric\": -1}\n            elif not isinstance(metrics, dict):\n                metrics = {\"hp_metric\": metrics}\n\n            if metrics:\n                self.log_metrics(metrics, 0)\n                exp, ssi, sei = hparams(params, metrics)\n                writer = self.experiment._get_file_writer()\n                writer.add_summary(exp)\n                writer.add_summary(ssi)\n                writer.add_summary(sei)\n\n    @rank_zero_only\n    def log_metrics(self, metrics: Dict[str, float], step: Optional[int] = None) -> None:\n        assert rank_zero_only.rank == 0, 'experiment tried to log from global_rank != 0'\n\n        for k, v in metrics.items():\n            if isinstance(v, torch.Tensor):\n                v = v.item()\n            self.experiment.add_scalar(k, v, step)\n\n    @rank_zero_only\n    def log_graph(self, model: LightningModule, input_array=None):\n        if self._log_graph:\n            if input_array is None:\n                input_array = model.example_input_array\n\n            if input_array is not None:\n                input_array = model.transfer_batch_to_device(input_array, model.device)\n                self.experiment.add_graph(model, input_array)\n            else:\n                rank_zero_warn('Could not log computational graph since the'\n                               ' `model.example_input_array` attribute is not set'\n                               ' or `input_array` was not given',\n                               UserWarning)\n\n    @rank_zero_only\n    def save(self) -> None:\n        super().save()\n        dir_path = self.log_dir\n        if not gfile.isdir(dir_path):\n            dir_path = self.save_dir\n\n        # prepare the file path\n        hparams_file = os.path.join(dir_path, self.NAME_HPARAMS_FILE)\n\n        # save the metatags file\n        save_hparams_to_yaml(hparams_file, self.hparams)\n\n    @rank_zero_only\n    def finalize(self, status: str) -> None:\n        self.save()\n\n    @property\n    def name(self) -> str:\n        return self._name\n\n    @property\n    def version(self) -> int:\n        if self._version is None:\n            self._version = self._get_next_version()\n        return self._version\n\n    def _get_next_version(self):\n        root_dir = os.path.join(self.save_dir, self.name)\n\n        if not gfile.isdir(root_dir):\n            log.warning('Missing logger folder: %s', root_dir)\n            return 0\n\n        existing_versions = []\n        for d in gfile.listdir(root_dir):\n            if gfile.isdir(os.path.join(root_dir, d)) and d.startswith(\"version_\"):\n                existing_versions.append(int(d.split(\"_\")[1]))\n\n        if len(existing_versions) == 0:\n            return 0\n\n        return max(existing_versions) + 1\n\n    def __getstate__(self):\n        state = self.__dict__.copy()\n        state[\"_experiment\"] = None\n        return state\n", "path": "pytorch_lightning/loggers/tensorboard.py"}]}