We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Metatags are saved over and over in TensorBoardLogger when logging metrics
Is it okay that the metatags are saved every time metrics are logged in `TensorBoardLogger`? I find that it slows down training a bit.

[I found a related discussion.](https://github.com/PyTorchLightning/pytorch-lightning/pull/687/files#r367010524)

This is the part I'm talking about:

https://github.com/PyTorchLightning/pytorch-lightning/blob/83ab3eadb6bd32a761fd2e710a7a28778efa0360/pytorch_lightning/loggers/tensorboard.py#L201-L211

which is called by:

https://github.com/PyTorchLightning/pytorch-lightning/blob/83ab3eadb6bd32a761fd2e710a7a28778efa0360/pytorch_lightning/trainer/logging.py#L88-L91

which is in turn called by:

https://github.com/PyTorchLightning/pytorch-lightning/blob/83ab3eadb6bd32a761fd2e710a7a28778efa0360/pytorch_lightning/trainer/training_loop.py#L749-L757

--- 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 Any, Dict, Optional, Union
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.lightning import LightningModule
31 from pytorch_lightning.core.saving import save_hparams_to_yaml
32 from pytorch_lightning.loggers.base import LightningLoggerBase, rank_zero_experiment
33 from pytorch_lightning.utilities import rank_zero_only, rank_zero_warn
34 from pytorch_lightning.utilities.cloud_io import get_filesystem
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         default_hp_metric: Enables a placeholder metric with key `hp_metric` when `log_hyperparams` is
69             called without a metric (otherwise calls to log_hyperparams without a metric are ignored).
70         \**kwargs: Additional arguments like `comment`, `filename_suffix`, etc. used by
71             :class:`SummaryWriter` can be passed as keyword arguments in this logger.
72 
73     """
74     NAME_HPARAMS_FILE = 'hparams.yaml'
75 
76     def __init__(
77         self,
78         save_dir: str,
79         name: Optional[str] = "default",
80         version: Optional[Union[int, str]] = None,
81         log_graph: bool = False,
82         default_hp_metric: bool = True,
83         **kwargs
84     ):
85         super().__init__()
86         self._save_dir = save_dir
87         self._name = name or ''
88         self._version = version
89         self._log_graph = log_graph
90         self._default_hp_metric = default_hp_metric
91         self._fs = get_filesystem(save_dir)
92 
93         self._experiment = None
94         self.hparams = {}
95         self._kwargs = kwargs
96 
97     @property
98     def root_dir(self) -> str:
99         """
100         Parent directory for all tensorboard checkpoint subdirectories.
101         If the experiment name parameter is ``None`` or the empty string, no experiment subdirectory is used
102         and the checkpoint will be saved in "save_dir/version_dir"
103         """
104         if self.name is None or len(self.name) == 0:
105             return self.save_dir
106         else:
107             return os.path.join(self.save_dir, self.name)
108 
109     @property
110     def log_dir(self) -> str:
111         """
112         The directory for this run's tensorboard checkpoint. By default, it is named
113         ``'version_${self.version}'`` but it can be overridden by passing a string value
114         for the constructor's version parameter instead of ``None`` or an int.
115         """
116         # create a pseudo standard path ala test-tube
117         version = self.version if isinstance(self.version, str) else f"version_{self.version}"
118         log_dir = os.path.join(self.root_dir, version)
119         return log_dir
120 
121     @property
122     def save_dir(self) -> Optional[str]:
123         return self._save_dir
124 
125     @property
126     @rank_zero_experiment
127     def experiment(self) -> SummaryWriter:
128         r"""
129         Actual tensorboard object. To use TensorBoard features in your
130         :class:`~pytorch_lightning.core.lightning.LightningModule` do the following.
131 
132         Example::
133 
134             self.logger.experiment.some_tensorboard_function()
135 
136         """
137         if self._experiment is not None:
138             return self._experiment
139 
140         assert rank_zero_only.rank == 0, 'tried to init log dirs in non global_rank=0'
141         if self.root_dir:
142             self._fs.makedirs(self.root_dir, exist_ok=True)
143         self._experiment = SummaryWriter(log_dir=self.log_dir, **self._kwargs)
144         return self._experiment
145 
146     @rank_zero_only
147     def log_hyperparams(self, params: Union[Dict[str, Any], Namespace],
148                         metrics: Optional[Dict[str, Any]] = None) -> None:
149         params = self._convert_params(params)
150 
151         # store params to output
152         if OMEGACONF_AVAILABLE and isinstance(params, Container):
153             self.hparams = OmegaConf.merge(self.hparams, params)
154         else:
155             self.hparams.update(params)
156 
157         # format params into the suitable for tensorboard
158         params = self._flatten_dict(params)
159         params = self._sanitize_params(params)
160 
161         if parse_version(torch.__version__) < parse_version("1.3.0"):
162             warn(
163                 f"Hyperparameter logging is not available for Torch version {torch.__version__}."
164                 " Skipping log_hyperparams. Upgrade to Torch 1.3.0 or above to enable"
165                 " hyperparameter logging."
166             )
167         else:
168             from torch.utils.tensorboard.summary import hparams
169 
170             if metrics is None:
171                 if self._default_hp_metric:
172                     metrics = {"hp_metric": -1}
173             elif not isinstance(metrics, dict):
174                 metrics = {"hp_metric": metrics}
175 
176             if metrics:
177                 self.log_metrics(metrics, 0)
178                 exp, ssi, sei = hparams(params, metrics)
179                 writer = self.experiment._get_file_writer()
180                 writer.add_summary(exp)
181                 writer.add_summary(ssi)
182                 writer.add_summary(sei)
183 
184     @rank_zero_only
185     def log_metrics(self, metrics: Dict[str, float], step: Optional[int] = None) -> None:
186         assert rank_zero_only.rank == 0, 'experiment tried to log from global_rank != 0'
187 
188         for k, v in metrics.items():
189             if isinstance(v, torch.Tensor):
190                 v = v.item()
191             self.experiment.add_scalar(k, v, step)
192 
193     @rank_zero_only
194     def log_graph(self, model: LightningModule, input_array=None):
195         if self._log_graph:
196             if input_array is None:
197                 input_array = model.example_input_array
198 
199             if input_array is not None:
200                 input_array = model.transfer_batch_to_device(input_array, model.device)
201                 self.experiment.add_graph(model, input_array)
202             else:
203                 rank_zero_warn('Could not log computational graph since the'
204                                ' `model.example_input_array` attribute is not set'
205                                ' or `input_array` was not given',
206                                UserWarning)
207 
208     @rank_zero_only
209     def save(self) -> None:
210         super().save()
211         dir_path = self.log_dir
212         if not self._fs.isdir(dir_path):
213             dir_path = self.save_dir
214 
215         # prepare the file path
216         hparams_file = os.path.join(dir_path, self.NAME_HPARAMS_FILE)
217 
218         # save the metatags file
219         save_hparams_to_yaml(hparams_file, self.hparams)
220 
221     @rank_zero_only
222     def finalize(self, status: str) -> None:
223         self.save()
224 
225     @property
226     def name(self) -> str:
227         return self._name
228 
229     @property
230     def version(self) -> int:
231         if self._version is None:
232             self._version = self._get_next_version()
233         return self._version
234 
235     def _get_next_version(self):
236         root_dir = os.path.join(self.save_dir, self.name)
237 
238         if not self._fs.isdir(root_dir):
239             log.warning('Missing logger folder: %s', root_dir)
240             return 0
241 
242         existing_versions = []
243         for d in self._fs.ls(root_dir):
244             bn = os.path.basename(d)
245             if self._fs.isdir(d) and bn.startswith("version_"):
246                 dir_ver = bn.split("_")[1].replace('/', '')
247                 existing_versions.append(int(dir_ver))
248         if len(existing_versions) == 0:
249             return 0
250 
251         return max(existing_versions) + 1
252 
253     def __getstate__(self):
254         state = self.__dict__.copy()
255         state["_experiment"] = None
256         return state
257
```
--- 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
@@ -215,8 +215,9 @@
         # prepare the file path
         hparams_file = os.path.join(dir_path, self.NAME_HPARAMS_FILE)
 
-        # save the metatags file
-        save_hparams_to_yaml(hparams_file, self.hparams)
+        # save the metatags file if it doesn't exist
+        if not os.path.isfile(hparams_file):
+            save_hparams_to_yaml(hparams_file, self.hparams)
 
     @rank_zero_only
     def finalize(self, status: str) -> 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@@ -215,8 +215,9 @@\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+        # save the metatags file if it doesn't exist\n+        if not os.path.isfile(hparams_file):\n+            save_hparams_to_yaml(hparams_file, self.hparams)\n \n     @rank_zero_only\n     def finalize(self, status: str) -> None:\n", "issue": "Metatags are saved over and over in TensorBoardLogger when logging metrics\nIs it okay that the metatags are saved every time metrics are logged in `TensorBoardLogger`? I find that it slows down training a bit.\r\n\r\n[I found a related discussion.](https://github.com/PyTorchLightning/pytorch-lightning/pull/687/files#r367010524)\r\n\r\nThis is the part I'm talking about:\r\n\r\nhttps://github.com/PyTorchLightning/pytorch-lightning/blob/83ab3eadb6bd32a761fd2e710a7a28778efa0360/pytorch_lightning/loggers/tensorboard.py#L201-L211\r\n\r\nwhich is called by:\r\n\r\nhttps://github.com/PyTorchLightning/pytorch-lightning/blob/83ab3eadb6bd32a761fd2e710a7a28778efa0360/pytorch_lightning/trainer/logging.py#L88-L91\r\n\r\nwhich is in turn called by:\r\n\r\nhttps://github.com/PyTorchLightning/pytorch-lightning/blob/83ab3eadb6bd32a761fd2e710a7a28778efa0360/pytorch_lightning/trainer/training_loop.py#L749-L757\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 Any, Dict, Optional, Union\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.lightning import LightningModule\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 get_filesystem\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: Additional arguments like `comment`, `filename_suffix`, etc. used by\n            :class:`SummaryWriter` can be passed as keyword arguments in this logger.\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        self._fs = get_filesystem(save_dir)\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:\n            self._fs.makedirs(self.root_dir, exist_ok=True)\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 self._fs.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 self._fs.isdir(root_dir):\n            log.warning('Missing logger folder: %s', root_dir)\n            return 0\n\n        existing_versions = []\n        for d in self._fs.ls(root_dir):\n            bn = os.path.basename(d)\n            if self._fs.isdir(d) and bn.startswith(\"version_\"):\n                dir_ver = bn.split(\"_\")[1].replace('/', '')\n                existing_versions.append(int(dir_ver))\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 Any, Dict, Optional, Union\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.lightning import LightningModule\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 get_filesystem\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: Additional arguments like `comment`, `filename_suffix`, etc. used by\n            :class:`SummaryWriter` can be passed as keyword arguments in this logger.\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        self._fs = get_filesystem(save_dir)\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:\n            self._fs.makedirs(self.root_dir, exist_ok=True)\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 self._fs.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 if it doesn't exist\n        if not os.path.isfile(hparams_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 self._fs.isdir(root_dir):\n            log.warning('Missing logger folder: %s', root_dir)\n            return 0\n\n        existing_versions = []\n        for d in self._fs.ls(root_dir):\n            bn = os.path.basename(d)\n            if self._fs.isdir(d) and bn.startswith(\"version_\"):\n                dir_ver = bn.split(\"_\")[1].replace('/', '')\n                existing_versions.append(int(dir_ver))\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"}]}