We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Seemingly unnecessary dictionary comprehension in contrib's BaseOutputHandler
Hi,
`output_dict` is made sure to be a dictionary just above the line below. 

https://github.com/pytorch/ignite/blob/21a2ccc25dd7ff0aec5f1538387597cb093fe36e/ignite/contrib/handlers/base_logger.py#L108

So this line could be replaced with:

```python
metrics_state_attrs.update(output_dict) 
```
Seemingly unnecessary dictionary comprehension in contrib's BaseOutputHandler
Hi,
`output_dict` is made sure to be a dictionary just above the line below. 

https://github.com/pytorch/ignite/blob/21a2ccc25dd7ff0aec5f1538387597cb093fe36e/ignite/contrib/handlers/base_logger.py#L108

So this line could be replaced with:

```python
metrics_state_attrs.update(output_dict) 
```

--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `ignite/contrib/handlers/base_logger.py`
Content:
```
1 """Base logger and its helper handlers."""
2 import numbers
3 import warnings
4 from abc import ABCMeta, abstractmethod
5 from collections import OrderedDict
6 from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union
7 
8 import torch
9 import torch.nn as nn
10 from torch.optim import Optimizer
11 
12 from ignite.engine import Engine, Events, EventsList, State
13 from ignite.engine.events import CallableEventWithFilter, RemovableEventHandle
14 
15 
16 class BaseHandler(metaclass=ABCMeta):
17     """Base handler for defining various useful handlers."""
18 
19     @abstractmethod
20     def __call__(self, engine: Engine, logger: Any, event_name: Union[str, Events]) -> None:
21         pass
22 
23 
24 class BaseOptimizerParamsHandler(BaseHandler):
25     """
26     Base handler for logging optimizer parameters
27     """
28 
29     def __init__(self, optimizer: Optimizer, param_name: str = "lr", tag: Optional[str] = None):
30         if not (
31             isinstance(optimizer, Optimizer)
32             or (hasattr(optimizer, "param_groups") and isinstance(optimizer.param_groups, Sequence))
33         ):
34             raise TypeError(
35                 "Argument optimizer should be torch.optim.Optimizer or has attribute 'param_groups' as list/tuple, "
36                 f"but given {type(optimizer)}"
37             )
38 
39         self.optimizer = optimizer
40         self.param_name = param_name
41         self.tag = tag
42 
43 
44 class BaseOutputHandler(BaseHandler):
45     """
46     Helper handler to log engine's output and/or metrics
47     """
48 
49     def __init__(
50         self,
51         tag: str,
52         metric_names: Optional[Union[str, List[str]]] = None,
53         output_transform: Optional[Callable] = None,
54         global_step_transform: Optional[Callable] = None,
55         state_attributes: Optional[List[str]] = None,
56     ):
57 
58         if metric_names is not None:
59             if not (isinstance(metric_names, list) or (isinstance(metric_names, str) and metric_names == "all")):
60                 raise TypeError(
61                     f"metric_names should be either a list or equal 'all', got {type(metric_names)} instead."
62                 )
63 
64         if output_transform is not None and not callable(output_transform):
65             raise TypeError(f"output_transform should be a function, got {type(output_transform)} instead.")
66 
67         if output_transform is None and metric_names is None and state_attributes is None:
68             raise ValueError("Either metric_names, output_transform or state_attributes should be defined")
69 
70         if global_step_transform is not None and not callable(global_step_transform):
71             raise TypeError(f"global_step_transform should be a function, got {type(global_step_transform)} instead.")
72 
73         if global_step_transform is None:
74 
75             def global_step_transform(engine: Engine, event_name: Union[str, Events]) -> int:
76                 return engine.state.get_event_attrib_value(event_name)
77 
78         self.tag = tag
79         self.metric_names = metric_names
80         self.output_transform = output_transform
81         self.global_step_transform = global_step_transform
82         self.state_attributes = state_attributes
83 
84     def _setup_output_metrics_state_attrs(
85         self, engine: Engine, log_text: Optional[bool] = False, key_tuple: Optional[bool] = True
86     ) -> Dict[Any, Any]:
87         """Helper method to setup metrics and state attributes to log"""
88         metrics_state_attrs = OrderedDict()
89         if self.metric_names is not None:
90             if isinstance(self.metric_names, str) and self.metric_names == "all":
91                 metrics_state_attrs = OrderedDict(engine.state.metrics)
92             else:
93                 for name in self.metric_names:
94                     if name not in engine.state.metrics:
95                         warnings.warn(
96                             f"Provided metric name '{name}' is missing "
97                             f"in engine's state metrics: {list(engine.state.metrics.keys())}"
98                         )
99                         continue
100                     metrics_state_attrs[name] = engine.state.metrics[name]
101 
102         if self.output_transform is not None:
103             output_dict = self.output_transform(engine.state.output)
104 
105             if not isinstance(output_dict, dict):
106                 output_dict = {"output": output_dict}
107 
108             metrics_state_attrs.update({name: value for name, value in output_dict.items()})
109 
110         if self.state_attributes is not None:
111             metrics_state_attrs.update({name: getattr(engine.state, name, None) for name in self.state_attributes})
112 
113         metrics_state_attrs_dict = OrderedDict()  # type: Dict[Any, Union[str, float, numbers.Number]]
114 
115         def key_tuple_tf(tag: str, name: str, *args: str) -> Tuple[str, ...]:
116             return (tag, name) + args
117 
118         def key_str_tf(tag: str, name: str, *args: str) -> str:
119             return "/".join((tag, name) + args)
120 
121         key_tf = key_tuple_tf if key_tuple else key_str_tf
122 
123         for name, value in metrics_state_attrs.items():
124             if isinstance(value, numbers.Number):
125                 metrics_state_attrs_dict[key_tf(self.tag, name)] = value
126             elif isinstance(value, torch.Tensor) and value.ndimension() == 0:
127                 metrics_state_attrs_dict[key_tf(self.tag, name)] = value.item()
128             elif isinstance(value, torch.Tensor) and value.ndimension() == 1:
129                 for i, v in enumerate(value):
130                     metrics_state_attrs_dict[key_tf(self.tag, name, str(i))] = v.item()
131             else:
132                 if isinstance(value, str) and log_text:
133                     metrics_state_attrs_dict[key_tf(self.tag, name)] = value
134                 else:
135                     warnings.warn(f"Logger output_handler can not log metrics value type {type(value)}")
136         return metrics_state_attrs_dict
137 
138 
139 class BaseWeightsScalarHandler(BaseHandler):
140     """
141     Helper handler to log model's weights as scalars.
142     """
143 
144     def __init__(self, model: nn.Module, reduction: Callable = torch.norm, tag: Optional[str] = None):
145         if not isinstance(model, torch.nn.Module):
146             raise TypeError(f"Argument model should be of type torch.nn.Module, but given {type(model)}")
147 
148         if not callable(reduction):
149             raise TypeError(f"Argument reduction should be callable, but given {type(reduction)}")
150 
151         def _is_0D_tensor(t: torch.Tensor) -> bool:
152             return isinstance(t, torch.Tensor) and t.ndimension() == 0
153 
154         # Test reduction function on a tensor
155         o = reduction(torch.ones(4, 2))
156         if not (isinstance(o, numbers.Number) or _is_0D_tensor(o)):
157             raise TypeError(f"Output of the reduction function should be a scalar, but got {type(o)}")
158 
159         self.model = model
160         self.reduction = reduction
161         self.tag = tag
162 
163 
164 class BaseWeightsHistHandler(BaseHandler):
165     """
166     Helper handler to log model's weights as histograms.
167     """
168 
169     def __init__(self, model: nn.Module, tag: Optional[str] = None):
170         if not isinstance(model, torch.nn.Module):
171             raise TypeError(f"Argument model should be of type torch.nn.Module, but given {type(model)}")
172 
173         self.model = model
174         self.tag = tag
175 
176 
177 class BaseLogger(metaclass=ABCMeta):
178     """
179     Base logger handler. See implementations: TensorboardLogger, VisdomLogger, PolyaxonLogger, MLflowLogger, ...
180 
181     """
182 
183     def attach(
184         self,
185         engine: Engine,
186         log_handler: Callable,
187         event_name: Union[str, Events, CallableEventWithFilter, EventsList],
188         *args: Any,
189         **kwargs: Any,
190     ) -> RemovableEventHandle:
191         """Attach the logger to the engine and execute `log_handler` function at `event_name` events.
192 
193         Args:
194             engine: engine object.
195             log_handler: a logging handler to execute
196             event_name: event to attach the logging handler to. Valid events are from
197                 :class:`~ignite.engine.events.Events` or :class:`~ignite.engine.events.EventsList` or any `event_name`
198                 added by :meth:`~ignite.engine.engine.Engine.register_events`.
199             args: args forwarded to the `log_handler` method
200             kwargs: kwargs forwarded to the  `log_handler` method
201 
202         Returns:
203             :class:`~ignite.engine.events.RemovableEventHandle`, which can be used to remove the handler.
204         """
205         if isinstance(event_name, EventsList):
206             for name in event_name:
207                 if name not in State.event_to_attr:
208                     raise RuntimeError(f"Unknown event name '{name}'")
209                 engine.add_event_handler(name, log_handler, self, name)
210 
211             return RemovableEventHandle(event_name, log_handler, engine)
212 
213         else:
214 
215             if event_name not in State.event_to_attr:
216                 raise RuntimeError(f"Unknown event name '{event_name}'")
217 
218             return engine.add_event_handler(event_name, log_handler, self, event_name, *args, **kwargs)
219 
220     def attach_output_handler(self, engine: Engine, event_name: Any, *args: Any, **kwargs: Any) -> RemovableEventHandle:
221         """Shortcut method to attach `OutputHandler` to the logger.
222 
223         Args:
224             engine: engine object.
225             event_name: event to attach the logging handler to. Valid events are from
226                 :class:`~ignite.engine.events.Events` or any `event_name` added by
227                 :meth:`~ignite.engine.engine.Engine.register_events`.
228             args: args to initialize `OutputHandler`
229             kwargs: kwargs to initialize `OutputHandler`
230 
231         Returns:
232             :class:`~ignite.engine.events.RemovableEventHandle`, which can be used to remove the handler.
233         """
234         return self.attach(engine, self._create_output_handler(*args, **kwargs), event_name=event_name)
235 
236     def attach_opt_params_handler(
237         self, engine: Engine, event_name: Any, *args: Any, **kwargs: Any
238     ) -> RemovableEventHandle:
239         """Shortcut method to attach `OptimizerParamsHandler` to the logger.
240 
241         Args:
242             engine: engine object.
243             event_name: event to attach the logging handler to. Valid events are from
244                 :class:`~ignite.engine.events.Events` or any `event_name` added by
245                 :meth:`~ignite.engine.engine.Engine.register_events`.
246             args: args to initialize `OptimizerParamsHandler`
247             kwargs: kwargs to initialize `OptimizerParamsHandler`
248 
249         Returns:
250             :class:`~ignite.engine.events.RemovableEventHandle`, which can be used to remove the handler.
251 
252         .. versionchanged:: 0.4.3
253             Added missing return statement.
254         """
255         return self.attach(engine, self._create_opt_params_handler(*args, **kwargs), event_name=event_name)
256 
257     @abstractmethod
258     def _create_output_handler(self, engine: Engine, *args: Any, **kwargs: Any) -> Callable:
259         pass
260 
261     @abstractmethod
262     def _create_opt_params_handler(self, *args: Any, **kwargs: Any) -> Callable:
263         pass
264 
265     def __enter__(self) -> "BaseLogger":
266         return self
267 
268     def __exit__(self, type: Any, value: Any, traceback: Any) -> None:
269         self.close()
270 
271     def close(self) -> None:
272         pass
273
```
--- 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/ignite/contrib/handlers/base_logger.py b/ignite/contrib/handlers/base_logger.py
--- a/ignite/contrib/handlers/base_logger.py
+++ b/ignite/contrib/handlers/base_logger.py
@@ -105,7 +105,7 @@
             if not isinstance(output_dict, dict):
                 output_dict = {"output": output_dict}
 
-            metrics_state_attrs.update({name: value for name, value in output_dict.items()})
+            metrics_state_attrs.update(output_dict)
 
         if self.state_attributes is not None:
             metrics_state_attrs.update({name: getattr(engine.state, name, None) for name in self.state_attributes})

{"golden_diff": "diff --git a/ignite/contrib/handlers/base_logger.py b/ignite/contrib/handlers/base_logger.py\n--- a/ignite/contrib/handlers/base_logger.py\n+++ b/ignite/contrib/handlers/base_logger.py\n@@ -105,7 +105,7 @@\n             if not isinstance(output_dict, dict):\n                 output_dict = {\"output\": output_dict}\n \n-            metrics_state_attrs.update({name: value for name, value in output_dict.items()})\n+            metrics_state_attrs.update(output_dict)\n \n         if self.state_attributes is not None:\n             metrics_state_attrs.update({name: getattr(engine.state, name, None) for name in self.state_attributes})\n", "issue": "Seemingly unnecessary dictionary comprehension in contrib's BaseOutputHandler\nHi,\r\n`output_dict` is made sure to be a dictionary just above the line below. \r\n\r\nhttps://github.com/pytorch/ignite/blob/21a2ccc25dd7ff0aec5f1538387597cb093fe36e/ignite/contrib/handlers/base_logger.py#L108\r\n\r\nSo this line could be replaced with:\r\n\r\n```python\r\nmetrics_state_attrs.update(output_dict) \r\n```\nSeemingly unnecessary dictionary comprehension in contrib's BaseOutputHandler\nHi,\r\n`output_dict` is made sure to be a dictionary just above the line below. \r\n\r\nhttps://github.com/pytorch/ignite/blob/21a2ccc25dd7ff0aec5f1538387597cb093fe36e/ignite/contrib/handlers/base_logger.py#L108\r\n\r\nSo this line could be replaced with:\r\n\r\n```python\r\nmetrics_state_attrs.update(output_dict) \r\n```\n", "before_files": [{"content": "\"\"\"Base logger and its helper handlers.\"\"\"\nimport numbers\nimport warnings\nfrom abc import ABCMeta, abstractmethod\nfrom collections import OrderedDict\nfrom typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union\n\nimport torch\nimport torch.nn as nn\nfrom torch.optim import Optimizer\n\nfrom ignite.engine import Engine, Events, EventsList, State\nfrom ignite.engine.events import CallableEventWithFilter, RemovableEventHandle\n\n\nclass BaseHandler(metaclass=ABCMeta):\n    \"\"\"Base handler for defining various useful handlers.\"\"\"\n\n    @abstractmethod\n    def __call__(self, engine: Engine, logger: Any, event_name: Union[str, Events]) -> None:\n        pass\n\n\nclass BaseOptimizerParamsHandler(BaseHandler):\n    \"\"\"\n    Base handler for logging optimizer parameters\n    \"\"\"\n\n    def __init__(self, optimizer: Optimizer, param_name: str = \"lr\", tag: Optional[str] = None):\n        if not (\n            isinstance(optimizer, Optimizer)\n            or (hasattr(optimizer, \"param_groups\") and isinstance(optimizer.param_groups, Sequence))\n        ):\n            raise TypeError(\n                \"Argument optimizer should be torch.optim.Optimizer or has attribute 'param_groups' as list/tuple, \"\n                f\"but given {type(optimizer)}\"\n            )\n\n        self.optimizer = optimizer\n        self.param_name = param_name\n        self.tag = tag\n\n\nclass BaseOutputHandler(BaseHandler):\n    \"\"\"\n    Helper handler to log engine's output and/or metrics\n    \"\"\"\n\n    def __init__(\n        self,\n        tag: str,\n        metric_names: Optional[Union[str, List[str]]] = None,\n        output_transform: Optional[Callable] = None,\n        global_step_transform: Optional[Callable] = None,\n        state_attributes: Optional[List[str]] = None,\n    ):\n\n        if metric_names is not None:\n            if not (isinstance(metric_names, list) or (isinstance(metric_names, str) and metric_names == \"all\")):\n                raise TypeError(\n                    f\"metric_names should be either a list or equal 'all', got {type(metric_names)} instead.\"\n                )\n\n        if output_transform is not None and not callable(output_transform):\n            raise TypeError(f\"output_transform should be a function, got {type(output_transform)} instead.\")\n\n        if output_transform is None and metric_names is None and state_attributes is None:\n            raise ValueError(\"Either metric_names, output_transform or state_attributes should be defined\")\n\n        if global_step_transform is not None and not callable(global_step_transform):\n            raise TypeError(f\"global_step_transform should be a function, got {type(global_step_transform)} instead.\")\n\n        if global_step_transform is None:\n\n            def global_step_transform(engine: Engine, event_name: Union[str, Events]) -> int:\n                return engine.state.get_event_attrib_value(event_name)\n\n        self.tag = tag\n        self.metric_names = metric_names\n        self.output_transform = output_transform\n        self.global_step_transform = global_step_transform\n        self.state_attributes = state_attributes\n\n    def _setup_output_metrics_state_attrs(\n        self, engine: Engine, log_text: Optional[bool] = False, key_tuple: Optional[bool] = True\n    ) -> Dict[Any, Any]:\n        \"\"\"Helper method to setup metrics and state attributes to log\"\"\"\n        metrics_state_attrs = OrderedDict()\n        if self.metric_names is not None:\n            if isinstance(self.metric_names, str) and self.metric_names == \"all\":\n                metrics_state_attrs = OrderedDict(engine.state.metrics)\n            else:\n                for name in self.metric_names:\n                    if name not in engine.state.metrics:\n                        warnings.warn(\n                            f\"Provided metric name '{name}' is missing \"\n                            f\"in engine's state metrics: {list(engine.state.metrics.keys())}\"\n                        )\n                        continue\n                    metrics_state_attrs[name] = engine.state.metrics[name]\n\n        if self.output_transform is not None:\n            output_dict = self.output_transform(engine.state.output)\n\n            if not isinstance(output_dict, dict):\n                output_dict = {\"output\": output_dict}\n\n            metrics_state_attrs.update({name: value for name, value in output_dict.items()})\n\n        if self.state_attributes is not None:\n            metrics_state_attrs.update({name: getattr(engine.state, name, None) for name in self.state_attributes})\n\n        metrics_state_attrs_dict = OrderedDict()  # type: Dict[Any, Union[str, float, numbers.Number]]\n\n        def key_tuple_tf(tag: str, name: str, *args: str) -> Tuple[str, ...]:\n            return (tag, name) + args\n\n        def key_str_tf(tag: str, name: str, *args: str) -> str:\n            return \"/\".join((tag, name) + args)\n\n        key_tf = key_tuple_tf if key_tuple else key_str_tf\n\n        for name, value in metrics_state_attrs.items():\n            if isinstance(value, numbers.Number):\n                metrics_state_attrs_dict[key_tf(self.tag, name)] = value\n            elif isinstance(value, torch.Tensor) and value.ndimension() == 0:\n                metrics_state_attrs_dict[key_tf(self.tag, name)] = value.item()\n            elif isinstance(value, torch.Tensor) and value.ndimension() == 1:\n                for i, v in enumerate(value):\n                    metrics_state_attrs_dict[key_tf(self.tag, name, str(i))] = v.item()\n            else:\n                if isinstance(value, str) and log_text:\n                    metrics_state_attrs_dict[key_tf(self.tag, name)] = value\n                else:\n                    warnings.warn(f\"Logger output_handler can not log metrics value type {type(value)}\")\n        return metrics_state_attrs_dict\n\n\nclass BaseWeightsScalarHandler(BaseHandler):\n    \"\"\"\n    Helper handler to log model's weights as scalars.\n    \"\"\"\n\n    def __init__(self, model: nn.Module, reduction: Callable = torch.norm, tag: Optional[str] = None):\n        if not isinstance(model, torch.nn.Module):\n            raise TypeError(f\"Argument model should be of type torch.nn.Module, but given {type(model)}\")\n\n        if not callable(reduction):\n            raise TypeError(f\"Argument reduction should be callable, but given {type(reduction)}\")\n\n        def _is_0D_tensor(t: torch.Tensor) -> bool:\n            return isinstance(t, torch.Tensor) and t.ndimension() == 0\n\n        # Test reduction function on a tensor\n        o = reduction(torch.ones(4, 2))\n        if not (isinstance(o, numbers.Number) or _is_0D_tensor(o)):\n            raise TypeError(f\"Output of the reduction function should be a scalar, but got {type(o)}\")\n\n        self.model = model\n        self.reduction = reduction\n        self.tag = tag\n\n\nclass BaseWeightsHistHandler(BaseHandler):\n    \"\"\"\n    Helper handler to log model's weights as histograms.\n    \"\"\"\n\n    def __init__(self, model: nn.Module, tag: Optional[str] = None):\n        if not isinstance(model, torch.nn.Module):\n            raise TypeError(f\"Argument model should be of type torch.nn.Module, but given {type(model)}\")\n\n        self.model = model\n        self.tag = tag\n\n\nclass BaseLogger(metaclass=ABCMeta):\n    \"\"\"\n    Base logger handler. See implementations: TensorboardLogger, VisdomLogger, PolyaxonLogger, MLflowLogger, ...\n\n    \"\"\"\n\n    def attach(\n        self,\n        engine: Engine,\n        log_handler: Callable,\n        event_name: Union[str, Events, CallableEventWithFilter, EventsList],\n        *args: Any,\n        **kwargs: Any,\n    ) -> RemovableEventHandle:\n        \"\"\"Attach the logger to the engine and execute `log_handler` function at `event_name` events.\n\n        Args:\n            engine: engine object.\n            log_handler: a logging handler to execute\n            event_name: event to attach the logging handler to. Valid events are from\n                :class:`~ignite.engine.events.Events` or :class:`~ignite.engine.events.EventsList` or any `event_name`\n                added by :meth:`~ignite.engine.engine.Engine.register_events`.\n            args: args forwarded to the `log_handler` method\n            kwargs: kwargs forwarded to the  `log_handler` method\n\n        Returns:\n            :class:`~ignite.engine.events.RemovableEventHandle`, which can be used to remove the handler.\n        \"\"\"\n        if isinstance(event_name, EventsList):\n            for name in event_name:\n                if name not in State.event_to_attr:\n                    raise RuntimeError(f\"Unknown event name '{name}'\")\n                engine.add_event_handler(name, log_handler, self, name)\n\n            return RemovableEventHandle(event_name, log_handler, engine)\n\n        else:\n\n            if event_name not in State.event_to_attr:\n                raise RuntimeError(f\"Unknown event name '{event_name}'\")\n\n            return engine.add_event_handler(event_name, log_handler, self, event_name, *args, **kwargs)\n\n    def attach_output_handler(self, engine: Engine, event_name: Any, *args: Any, **kwargs: Any) -> RemovableEventHandle:\n        \"\"\"Shortcut method to attach `OutputHandler` to the logger.\n\n        Args:\n            engine: engine object.\n            event_name: event to attach the logging handler to. Valid events are from\n                :class:`~ignite.engine.events.Events` or any `event_name` added by\n                :meth:`~ignite.engine.engine.Engine.register_events`.\n            args: args to initialize `OutputHandler`\n            kwargs: kwargs to initialize `OutputHandler`\n\n        Returns:\n            :class:`~ignite.engine.events.RemovableEventHandle`, which can be used to remove the handler.\n        \"\"\"\n        return self.attach(engine, self._create_output_handler(*args, **kwargs), event_name=event_name)\n\n    def attach_opt_params_handler(\n        self, engine: Engine, event_name: Any, *args: Any, **kwargs: Any\n    ) -> RemovableEventHandle:\n        \"\"\"Shortcut method to attach `OptimizerParamsHandler` to the logger.\n\n        Args:\n            engine: engine object.\n            event_name: event to attach the logging handler to. Valid events are from\n                :class:`~ignite.engine.events.Events` or any `event_name` added by\n                :meth:`~ignite.engine.engine.Engine.register_events`.\n            args: args to initialize `OptimizerParamsHandler`\n            kwargs: kwargs to initialize `OptimizerParamsHandler`\n\n        Returns:\n            :class:`~ignite.engine.events.RemovableEventHandle`, which can be used to remove the handler.\n\n        .. versionchanged:: 0.4.3\n            Added missing return statement.\n        \"\"\"\n        return self.attach(engine, self._create_opt_params_handler(*args, **kwargs), event_name=event_name)\n\n    @abstractmethod\n    def _create_output_handler(self, engine: Engine, *args: Any, **kwargs: Any) -> Callable:\n        pass\n\n    @abstractmethod\n    def _create_opt_params_handler(self, *args: Any, **kwargs: Any) -> Callable:\n        pass\n\n    def __enter__(self) -> \"BaseLogger\":\n        return self\n\n    def __exit__(self, type: Any, value: Any, traceback: Any) -> None:\n        self.close()\n\n    def close(self) -> None:\n        pass\n", "path": "ignite/contrib/handlers/base_logger.py"}], "after_files": [{"content": "\"\"\"Base logger and its helper handlers.\"\"\"\nimport numbers\nimport warnings\nfrom abc import ABCMeta, abstractmethod\nfrom collections import OrderedDict\nfrom typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union\n\nimport torch\nimport torch.nn as nn\nfrom torch.optim import Optimizer\n\nfrom ignite.engine import Engine, Events, EventsList, State\nfrom ignite.engine.events import CallableEventWithFilter, RemovableEventHandle\n\n\nclass BaseHandler(metaclass=ABCMeta):\n    \"\"\"Base handler for defining various useful handlers.\"\"\"\n\n    @abstractmethod\n    def __call__(self, engine: Engine, logger: Any, event_name: Union[str, Events]) -> None:\n        pass\n\n\nclass BaseOptimizerParamsHandler(BaseHandler):\n    \"\"\"\n    Base handler for logging optimizer parameters\n    \"\"\"\n\n    def __init__(self, optimizer: Optimizer, param_name: str = \"lr\", tag: Optional[str] = None):\n        if not (\n            isinstance(optimizer, Optimizer)\n            or (hasattr(optimizer, \"param_groups\") and isinstance(optimizer.param_groups, Sequence))\n        ):\n            raise TypeError(\n                \"Argument optimizer should be torch.optim.Optimizer or has attribute 'param_groups' as list/tuple, \"\n                f\"but given {type(optimizer)}\"\n            )\n\n        self.optimizer = optimizer\n        self.param_name = param_name\n        self.tag = tag\n\n\nclass BaseOutputHandler(BaseHandler):\n    \"\"\"\n    Helper handler to log engine's output and/or metrics\n    \"\"\"\n\n    def __init__(\n        self,\n        tag: str,\n        metric_names: Optional[Union[str, List[str]]] = None,\n        output_transform: Optional[Callable] = None,\n        global_step_transform: Optional[Callable] = None,\n        state_attributes: Optional[List[str]] = None,\n    ):\n\n        if metric_names is not None:\n            if not (isinstance(metric_names, list) or (isinstance(metric_names, str) and metric_names == \"all\")):\n                raise TypeError(\n                    f\"metric_names should be either a list or equal 'all', got {type(metric_names)} instead.\"\n                )\n\n        if output_transform is not None and not callable(output_transform):\n            raise TypeError(f\"output_transform should be a function, got {type(output_transform)} instead.\")\n\n        if output_transform is None and metric_names is None and state_attributes is None:\n            raise ValueError(\"Either metric_names, output_transform or state_attributes should be defined\")\n\n        if global_step_transform is not None and not callable(global_step_transform):\n            raise TypeError(f\"global_step_transform should be a function, got {type(global_step_transform)} instead.\")\n\n        if global_step_transform is None:\n\n            def global_step_transform(engine: Engine, event_name: Union[str, Events]) -> int:\n                return engine.state.get_event_attrib_value(event_name)\n\n        self.tag = tag\n        self.metric_names = metric_names\n        self.output_transform = output_transform\n        self.global_step_transform = global_step_transform\n        self.state_attributes = state_attributes\n\n    def _setup_output_metrics_state_attrs(\n        self, engine: Engine, log_text: Optional[bool] = False, key_tuple: Optional[bool] = True\n    ) -> Dict[Any, Any]:\n        \"\"\"Helper method to setup metrics and state attributes to log\"\"\"\n        metrics_state_attrs = OrderedDict()\n        if self.metric_names is not None:\n            if isinstance(self.metric_names, str) and self.metric_names == \"all\":\n                metrics_state_attrs = OrderedDict(engine.state.metrics)\n            else:\n                for name in self.metric_names:\n                    if name not in engine.state.metrics:\n                        warnings.warn(\n                            f\"Provided metric name '{name}' is missing \"\n                            f\"in engine's state metrics: {list(engine.state.metrics.keys())}\"\n                        )\n                        continue\n                    metrics_state_attrs[name] = engine.state.metrics[name]\n\n        if self.output_transform is not None:\n            output_dict = self.output_transform(engine.state.output)\n\n            if not isinstance(output_dict, dict):\n                output_dict = {\"output\": output_dict}\n\n            metrics_state_attrs.update(output_dict)\n\n        if self.state_attributes is not None:\n            metrics_state_attrs.update({name: getattr(engine.state, name, None) for name in self.state_attributes})\n\n        metrics_state_attrs_dict = OrderedDict()  # type: Dict[Any, Union[str, float, numbers.Number]]\n\n        def key_tuple_tf(tag: str, name: str, *args: str) -> Tuple[str, ...]:\n            return (tag, name) + args\n\n        def key_str_tf(tag: str, name: str, *args: str) -> str:\n            return \"/\".join((tag, name) + args)\n\n        key_tf = key_tuple_tf if key_tuple else key_str_tf\n\n        for name, value in metrics_state_attrs.items():\n            if isinstance(value, numbers.Number):\n                metrics_state_attrs_dict[key_tf(self.tag, name)] = value\n            elif isinstance(value, torch.Tensor) and value.ndimension() == 0:\n                metrics_state_attrs_dict[key_tf(self.tag, name)] = value.item()\n            elif isinstance(value, torch.Tensor) and value.ndimension() == 1:\n                for i, v in enumerate(value):\n                    metrics_state_attrs_dict[key_tf(self.tag, name, str(i))] = v.item()\n            else:\n                if isinstance(value, str) and log_text:\n                    metrics_state_attrs_dict[key_tf(self.tag, name)] = value\n                else:\n                    warnings.warn(f\"Logger output_handler can not log metrics value type {type(value)}\")\n        return metrics_state_attrs_dict\n\n\nclass BaseWeightsScalarHandler(BaseHandler):\n    \"\"\"\n    Helper handler to log model's weights as scalars.\n    \"\"\"\n\n    def __init__(self, model: nn.Module, reduction: Callable = torch.norm, tag: Optional[str] = None):\n        if not isinstance(model, torch.nn.Module):\n            raise TypeError(f\"Argument model should be of type torch.nn.Module, but given {type(model)}\")\n\n        if not callable(reduction):\n            raise TypeError(f\"Argument reduction should be callable, but given {type(reduction)}\")\n\n        def _is_0D_tensor(t: torch.Tensor) -> bool:\n            return isinstance(t, torch.Tensor) and t.ndimension() == 0\n\n        # Test reduction function on a tensor\n        o = reduction(torch.ones(4, 2))\n        if not (isinstance(o, numbers.Number) or _is_0D_tensor(o)):\n            raise TypeError(f\"Output of the reduction function should be a scalar, but got {type(o)}\")\n\n        self.model = model\n        self.reduction = reduction\n        self.tag = tag\n\n\nclass BaseWeightsHistHandler(BaseHandler):\n    \"\"\"\n    Helper handler to log model's weights as histograms.\n    \"\"\"\n\n    def __init__(self, model: nn.Module, tag: Optional[str] = None):\n        if not isinstance(model, torch.nn.Module):\n            raise TypeError(f\"Argument model should be of type torch.nn.Module, but given {type(model)}\")\n\n        self.model = model\n        self.tag = tag\n\n\nclass BaseLogger(metaclass=ABCMeta):\n    \"\"\"\n    Base logger handler. See implementations: TensorboardLogger, VisdomLogger, PolyaxonLogger, MLflowLogger, ...\n\n    \"\"\"\n\n    def attach(\n        self,\n        engine: Engine,\n        log_handler: Callable,\n        event_name: Union[str, Events, CallableEventWithFilter, EventsList],\n        *args: Any,\n        **kwargs: Any,\n    ) -> RemovableEventHandle:\n        \"\"\"Attach the logger to the engine and execute `log_handler` function at `event_name` events.\n\n        Args:\n            engine: engine object.\n            log_handler: a logging handler to execute\n            event_name: event to attach the logging handler to. Valid events are from\n                :class:`~ignite.engine.events.Events` or :class:`~ignite.engine.events.EventsList` or any `event_name`\n                added by :meth:`~ignite.engine.engine.Engine.register_events`.\n            args: args forwarded to the `log_handler` method\n            kwargs: kwargs forwarded to the  `log_handler` method\n\n        Returns:\n            :class:`~ignite.engine.events.RemovableEventHandle`, which can be used to remove the handler.\n        \"\"\"\n        if isinstance(event_name, EventsList):\n            for name in event_name:\n                if name not in State.event_to_attr:\n                    raise RuntimeError(f\"Unknown event name '{name}'\")\n                engine.add_event_handler(name, log_handler, self, name)\n\n            return RemovableEventHandle(event_name, log_handler, engine)\n\n        else:\n\n            if event_name not in State.event_to_attr:\n                raise RuntimeError(f\"Unknown event name '{event_name}'\")\n\n            return engine.add_event_handler(event_name, log_handler, self, event_name, *args, **kwargs)\n\n    def attach_output_handler(self, engine: Engine, event_name: Any, *args: Any, **kwargs: Any) -> RemovableEventHandle:\n        \"\"\"Shortcut method to attach `OutputHandler` to the logger.\n\n        Args:\n            engine: engine object.\n            event_name: event to attach the logging handler to. Valid events are from\n                :class:`~ignite.engine.events.Events` or any `event_name` added by\n                :meth:`~ignite.engine.engine.Engine.register_events`.\n            args: args to initialize `OutputHandler`\n            kwargs: kwargs to initialize `OutputHandler`\n\n        Returns:\n            :class:`~ignite.engine.events.RemovableEventHandle`, which can be used to remove the handler.\n        \"\"\"\n        return self.attach(engine, self._create_output_handler(*args, **kwargs), event_name=event_name)\n\n    def attach_opt_params_handler(\n        self, engine: Engine, event_name: Any, *args: Any, **kwargs: Any\n    ) -> RemovableEventHandle:\n        \"\"\"Shortcut method to attach `OptimizerParamsHandler` to the logger.\n\n        Args:\n            engine: engine object.\n            event_name: event to attach the logging handler to. Valid events are from\n                :class:`~ignite.engine.events.Events` or any `event_name` added by\n                :meth:`~ignite.engine.engine.Engine.register_events`.\n            args: args to initialize `OptimizerParamsHandler`\n            kwargs: kwargs to initialize `OptimizerParamsHandler`\n\n        Returns:\n            :class:`~ignite.engine.events.RemovableEventHandle`, which can be used to remove the handler.\n\n        .. versionchanged:: 0.4.3\n            Added missing return statement.\n        \"\"\"\n        return self.attach(engine, self._create_opt_params_handler(*args, **kwargs), event_name=event_name)\n\n    @abstractmethod\n    def _create_output_handler(self, engine: Engine, *args: Any, **kwargs: Any) -> Callable:\n        pass\n\n    @abstractmethod\n    def _create_opt_params_handler(self, *args: Any, **kwargs: Any) -> Callable:\n        pass\n\n    def __enter__(self) -> \"BaseLogger\":\n        return self\n\n    def __exit__(self, type: Any, value: Any, traceback: Any) -> None:\n        self.close()\n\n    def close(self) -> None:\n        pass\n", "path": "ignite/contrib/handlers/base_logger.py"}]}