We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Add args/kwargs to `BaseLogger.attach` method
## 🚀 Feature

Following this question: https://github.com/pytorch/ignite/discussions/2031 we can easily propagate args/kwargs for custom handlers:
```diff
def attach(
-     self, engine: Engine, log_handler: Callable, event_name: Union[str, Events, CallableEventWithFilter, EventsList]
+    self, engine: Engine, log_handler: Callable, event_name: Union[str, Events, CallableEventWithFilter, EventsList], *args, **kwargs
):
...

- engine.add_event_handler(event_name, log_handler, self, event_name)
+ engine.add_event_handler(event_name, log_handler, self, event_name, *args, **kwargs)
```

--- 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, 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     ):
56 
57         if metric_names is not None:
58             if not (isinstance(metric_names, list) or (isinstance(metric_names, str) and metric_names == "all")):
59                 raise TypeError(
60                     f"metric_names should be either a list or equal 'all', got {type(metric_names)} instead."
61                 )
62 
63         if output_transform is not None and not callable(output_transform):
64             raise TypeError(f"output_transform should be a function, got {type(output_transform)} instead.")
65 
66         if output_transform is None and metric_names is None:
67             raise ValueError("Either metric_names or output_transform should be defined")
68 
69         if global_step_transform is not None and not callable(global_step_transform):
70             raise TypeError(f"global_step_transform should be a function, got {type(global_step_transform)} instead.")
71 
72         if global_step_transform is None:
73 
74             def global_step_transform(engine: Engine, event_name: Union[str, Events]) -> int:
75                 return engine.state.get_event_attrib_value(event_name)
76 
77         self.tag = tag
78         self.metric_names = metric_names
79         self.output_transform = output_transform
80         self.global_step_transform = global_step_transform
81 
82     def _setup_output_metrics(self, engine: Engine) -> Dict[str, Any]:
83         """Helper method to setup metrics to log
84         """
85         metrics = OrderedDict()
86         if self.metric_names is not None:
87             if isinstance(self.metric_names, str) and self.metric_names == "all":
88                 metrics = OrderedDict(engine.state.metrics)
89             else:
90                 for name in self.metric_names:
91                     if name not in engine.state.metrics:
92                         warnings.warn(
93                             f"Provided metric name '{name}' is missing "
94                             f"in engine's state metrics: {list(engine.state.metrics.keys())}"
95                         )
96                         continue
97                     metrics[name] = engine.state.metrics[name]
98 
99         if self.output_transform is not None:
100             output_dict = self.output_transform(engine.state.output)
101 
102             if not isinstance(output_dict, dict):
103                 output_dict = {"output": output_dict}
104 
105             metrics.update({name: value for name, value in output_dict.items()})
106         return metrics
107 
108 
109 class BaseWeightsScalarHandler(BaseHandler):
110     """
111     Helper handler to log model's weights as scalars.
112     """
113 
114     def __init__(self, model: nn.Module, reduction: Callable = torch.norm, tag: Optional[str] = None):
115         if not isinstance(model, torch.nn.Module):
116             raise TypeError(f"Argument model should be of type torch.nn.Module, but given {type(model)}")
117 
118         if not callable(reduction):
119             raise TypeError(f"Argument reduction should be callable, but given {type(reduction)}")
120 
121         def _is_0D_tensor(t: torch.Tensor) -> bool:
122             return isinstance(t, torch.Tensor) and t.ndimension() == 0
123 
124         # Test reduction function on a tensor
125         o = reduction(torch.ones(4, 2))
126         if not (isinstance(o, numbers.Number) or _is_0D_tensor(o)):
127             raise TypeError(f"Output of the reduction function should be a scalar, but got {type(o)}")
128 
129         self.model = model
130         self.reduction = reduction
131         self.tag = tag
132 
133 
134 class BaseWeightsHistHandler(BaseHandler):
135     """
136     Helper handler to log model's weights as histograms.
137     """
138 
139     def __init__(self, model: nn.Module, tag: Optional[str] = None):
140         if not isinstance(model, torch.nn.Module):
141             raise TypeError(f"Argument model should be of type torch.nn.Module, but given {type(model)}")
142 
143         self.model = model
144         self.tag = tag
145 
146 
147 class BaseLogger(metaclass=ABCMeta):
148     """
149     Base logger handler. See implementations: TensorboardLogger, VisdomLogger, PolyaxonLogger, MLflowLogger, ...
150 
151     """
152 
153     def attach(
154         self, engine: Engine, log_handler: Callable, event_name: Union[str, Events, CallableEventWithFilter, EventsList]
155     ) -> RemovableEventHandle:
156         """Attach the logger to the engine and execute `log_handler` function at `event_name` events.
157 
158         Args:
159             engine: engine object.
160             log_handler: a logging handler to execute
161             event_name: event to attach the logging handler to. Valid events are from
162                 :class:`~ignite.engine.events.Events` or :class:`~ignite.engine.events.EventsList` or any `event_name`
163                 added by :meth:`~ignite.engine.engine.Engine.register_events`.
164 
165         Returns:
166             :class:`~ignite.engine.events.RemovableEventHandle`, which can be used to remove the handler.
167         """
168         if isinstance(event_name, EventsList):
169             for name in event_name:
170                 if name not in State.event_to_attr:
171                     raise RuntimeError(f"Unknown event name '{name}'")
172                 engine.add_event_handler(name, log_handler, self, name)
173 
174             return RemovableEventHandle(event_name, log_handler, engine)
175 
176         else:
177 
178             if event_name not in State.event_to_attr:
179                 raise RuntimeError(f"Unknown event name '{event_name}'")
180 
181             return engine.add_event_handler(event_name, log_handler, self, event_name)
182 
183     def attach_output_handler(self, engine: Engine, event_name: Any, *args: Any, **kwargs: Any) -> RemovableEventHandle:
184         """Shortcut method to attach `OutputHandler` to the logger.
185 
186         Args:
187             engine: engine object.
188             event_name: event to attach the logging handler to. Valid events are from
189                 :class:`~ignite.engine.events.Events` or any `event_name` added by
190                 :meth:`~ignite.engine.engine.Engine.register_events`.
191             args: args to initialize `OutputHandler`
192             kwargs: kwargs to initialize `OutputHandler`
193 
194         Returns:
195             :class:`~ignite.engine.events.RemovableEventHandle`, which can be used to remove the handler.
196         """
197         return self.attach(engine, self._create_output_handler(*args, **kwargs), event_name=event_name)
198 
199     def attach_opt_params_handler(
200         self, engine: Engine, event_name: Any, *args: Any, **kwargs: Any
201     ) -> RemovableEventHandle:
202         """Shortcut method to attach `OptimizerParamsHandler` to the logger.
203 
204         Args:
205             engine: engine object.
206             event_name: event to attach the logging handler to. Valid events are from
207                 :class:`~ignite.engine.events.Events` or any `event_name` added by
208                 :meth:`~ignite.engine.engine.Engine.register_events`.
209             args: args to initialize `OptimizerParamsHandler`
210             kwargs: kwargs to initialize `OptimizerParamsHandler`
211 
212         Returns:
213             :class:`~ignite.engine.events.RemovableEventHandle`, which can be used to remove the handler.
214 
215         .. versionchanged:: 0.4.3
216             Added missing return statement.
217         """
218         return self.attach(engine, self._create_opt_params_handler(*args, **kwargs), event_name=event_name)
219 
220     @abstractmethod
221     def _create_output_handler(self, engine: Engine, *args: Any, **kwargs: Any) -> Callable:
222         pass
223 
224     @abstractmethod
225     def _create_opt_params_handler(self, *args: Any, **kwargs: Any) -> Callable:
226         pass
227 
228     def __enter__(self) -> "BaseLogger":
229         return self
230 
231     def __exit__(self, type: Any, value: Any, traceback: Any) -> None:
232         self.close()
233 
234     def close(self) -> None:
235         pass
236
```
--- 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
@@ -151,7 +151,12 @@
     """
 
     def attach(
-        self, engine: Engine, log_handler: Callable, event_name: Union[str, Events, CallableEventWithFilter, EventsList]
+        self,
+        engine: Engine,
+        log_handler: Callable,
+        event_name: Union[str, Events, CallableEventWithFilter, EventsList],
+        *args: Any,
+        **kwargs: Any,
     ) -> RemovableEventHandle:
         """Attach the logger to the engine and execute `log_handler` function at `event_name` events.
 
@@ -161,6 +166,8 @@
             event_name: event to attach the logging handler to. Valid events are from
                 :class:`~ignite.engine.events.Events` or :class:`~ignite.engine.events.EventsList` or any `event_name`
                 added by :meth:`~ignite.engine.engine.Engine.register_events`.
+            args: args forwarded to the `log_handler` method
+            kwargs: kwargs forwarded to the  `log_handler` method
 
         Returns:
             :class:`~ignite.engine.events.RemovableEventHandle`, which can be used to remove the handler.
@@ -178,7 +185,7 @@
             if event_name not in State.event_to_attr:
                 raise RuntimeError(f"Unknown event name '{event_name}'")
 
-            return engine.add_event_handler(event_name, log_handler, self, event_name)
+            return engine.add_event_handler(event_name, log_handler, self, event_name, *args, **kwargs)
 
     def attach_output_handler(self, engine: Engine, event_name: Any, *args: Any, **kwargs: Any) -> RemovableEventHandle:
         """Shortcut method to attach `OutputHandler` to the logger.

{"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@@ -151,7 +151,12 @@\n     \"\"\"\n \n     def attach(\n-        self, engine: Engine, log_handler: Callable, event_name: Union[str, Events, CallableEventWithFilter, EventsList]\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@@ -161,6 +166,8 @@\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@@ -178,7 +185,7 @@\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)\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", "issue": "Add args/kwargs to `BaseLogger.attach` method\n## \ud83d\ude80 Feature\r\n\r\nFollowing this question: https://github.com/pytorch/ignite/discussions/2031 we can easily propagate args/kwargs for custom handlers:\r\n```diff\r\ndef attach(\r\n-     self, engine: Engine, log_handler: Callable, event_name: Union[str, Events, CallableEventWithFilter, EventsList]\r\n+    self, engine: Engine, log_handler: Callable, event_name: Union[str, Events, CallableEventWithFilter, EventsList], *args, **kwargs\r\n):\r\n...\r\n\r\n- engine.add_event_handler(event_name, log_handler, self, event_name)\r\n+ engine.add_event_handler(event_name, log_handler, self, event_name, *args, **kwargs)\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, 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    ):\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:\n            raise ValueError(\"Either metric_names or output_transform 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\n    def _setup_output_metrics(self, engine: Engine) -> Dict[str, Any]:\n        \"\"\"Helper method to setup metrics to log\n        \"\"\"\n        metrics = OrderedDict()\n        if self.metric_names is not None:\n            if isinstance(self.metric_names, str) and self.metric_names == \"all\":\n                metrics = 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[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.update({name: value for name, value in output_dict.items()})\n        return metrics\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, engine: Engine, log_handler: Callable, event_name: Union[str, Events, CallableEventWithFilter, EventsList]\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\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)\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, 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    ):\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:\n            raise ValueError(\"Either metric_names or output_transform 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\n    def _setup_output_metrics(self, engine: Engine) -> Dict[str, Any]:\n        \"\"\"Helper method to setup metrics to log\n        \"\"\"\n        metrics = OrderedDict()\n        if self.metric_names is not None:\n            if isinstance(self.metric_names, str) and self.metric_names == \"all\":\n                metrics = 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[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.update({name: value for name, value in output_dict.items()})\n        return metrics\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"}]}