We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Use setup_logger in handlers
## 🚀 Feature

Idea is to replace in handlers (`EarlyStopping`, `TerminateOnNan`, etc.)
```
self.logger = logging.getLogger(__name__ + "." + self.__class__.__name__)
```
by `setup_logger` from `ignite.utils`
```
self.logger = setup_logger(__name__ + "." + self.__class__.__name__)
```

--- 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/handlers/early_stopping.py`
Content:
```
1 import logging
2 from collections import OrderedDict
3 from typing import Callable, Mapping, Optional, cast
4 
5 from ignite.base import Serializable
6 from ignite.engine import Engine
7 
8 __all__ = ["EarlyStopping"]
9 
10 
11 class EarlyStopping(Serializable):
12     """EarlyStopping handler can be used to stop the training if no improvement after a given number of events.
13 
14     Args:
15         patience (int):
16             Number of events to wait if no improvement and then stop the training.
17         score_function (callable):
18             It should be a function taking a single argument, an :class:`~ignite.engine.engine.Engine` object,
19             and return a score `float`. An improvement is considered if the score is higher.
20         trainer (Engine):
21             trainer engine to stop the run if no improvement.
22         min_delta (float, optional):
23             A minimum increase in the score to qualify as an improvement,
24             i.e. an increase of less than or equal to `min_delta`, will count as no improvement.
25         cumulative_delta (bool, optional):
26             It True, `min_delta` defines an increase since the last `patience` reset, otherwise,
27             it defines an increase after the last event. Default value is False.
28 
29     Examples:
30 
31     .. code-block:: python
32 
33         from ignite.engine import Engine, Events
34         from ignite.handlers import EarlyStopping
35 
36         def score_function(engine):
37             val_loss = engine.state.metrics['nll']
38             return -val_loss
39 
40         handler = EarlyStopping(patience=10, score_function=score_function, trainer=trainer)
41         # Note: the handler is attached to an *Evaluator* (runs one epoch on validation dataset).
42         evaluator.add_event_handler(Events.COMPLETED, handler)
43 
44     """
45 
46     _state_dict_all_req_keys = (
47         "counter",
48         "best_score",
49     )
50 
51     def __init__(
52         self,
53         patience: int,
54         score_function: Callable,
55         trainer: Engine,
56         min_delta: float = 0.0,
57         cumulative_delta: bool = False,
58     ):
59 
60         if not callable(score_function):
61             raise TypeError("Argument score_function should be a function.")
62 
63         if patience < 1:
64             raise ValueError("Argument patience should be positive integer.")
65 
66         if min_delta < 0.0:
67             raise ValueError("Argument min_delta should not be a negative number.")
68 
69         if not isinstance(trainer, Engine):
70             raise TypeError("Argument trainer should be an instance of Engine.")
71 
72         self.score_function = score_function
73         self.patience = patience
74         self.min_delta = min_delta
75         self.cumulative_delta = cumulative_delta
76         self.trainer = trainer
77         self.counter = 0
78         self.best_score = None  # type: Optional[float]
79         self.logger = logging.getLogger(__name__ + "." + self.__class__.__name__)
80 
81     def __call__(self, engine: Engine) -> None:
82         score = self.score_function(engine)
83 
84         if self.best_score is None:
85             self.best_score = score
86         elif score <= self.best_score + self.min_delta:
87             if not self.cumulative_delta and score > self.best_score:
88                 self.best_score = score
89             self.counter += 1
90             self.logger.debug("EarlyStopping: %i / %i" % (self.counter, self.patience))
91             if self.counter >= self.patience:
92                 self.logger.info("EarlyStopping: Stop training")
93                 self.trainer.terminate()
94         else:
95             self.best_score = score
96             self.counter = 0
97 
98     def state_dict(self) -> "OrderedDict[str, float]":
99         return OrderedDict([("counter", self.counter), ("best_score", cast(float, self.best_score))])
100 
101     def load_state_dict(self, state_dict: Mapping) -> None:
102         super().load_state_dict(state_dict)
103         self.counter = state_dict["counter"]
104         self.best_score = state_dict["best_score"]
105
```

Path: `ignite/handlers/terminate_on_nan.py`
Content:
```
1 import logging
2 import numbers
3 from typing import Callable, Union
4 
5 import torch
6 
7 from ignite.engine import Engine
8 from ignite.utils import apply_to_type
9 
10 __all__ = ["TerminateOnNan"]
11 
12 
13 class TerminateOnNan:
14     """TerminateOnNan handler can be used to stop the training if the `process_function`'s output
15     contains a NaN or infinite number or `torch.tensor`.
16     The output can be of type: number, tensor or collection of them. The training is stopped if
17     there is at least a single number/tensor have NaN or Infinite value. For example, if the output is
18     `[1.23, torch.tensor(...), torch.tensor(float('nan'))]` the handler will stop the training.
19 
20     Args:
21         output_transform (callable, optional): a callable that is used to transform the
22             :class:`~ignite.engine.engine.Engine`'s ``process_function``'s output into a number or `torch.tensor`
23             or collection of them. This can be useful if, for example, you have a multi-output model and
24             you want to check one or multiple values of the output.
25 
26 
27     Examples:
28 
29     .. code-block:: python
30 
31         trainer.add_event_handler(Events.ITERATION_COMPLETED, TerminateOnNan())
32 
33     """
34 
35     def __init__(self, output_transform: Callable = lambda x: x):
36         self.logger = logging.getLogger(__name__ + "." + self.__class__.__name__)
37         self.logger.addHandler(logging.StreamHandler())
38         self._output_transform = output_transform
39 
40     def __call__(self, engine: Engine) -> None:
41         output = self._output_transform(engine.state.output)
42 
43         def raise_error(x: Union[float, torch.Tensor]) -> None:
44 
45             if isinstance(x, numbers.Number):
46                 x = torch.tensor(x)
47 
48             if isinstance(x, torch.Tensor) and not bool(torch.isfinite(x).all()):
49                 raise RuntimeError("Infinite or NaN tensor found.")
50 
51         try:
52             apply_to_type(output, (numbers.Number, torch.Tensor), raise_error)
53         except RuntimeError:
54             self.logger.warning(f"{self.__class__.__name__}: Output '{output}' contains NaN or Inf. Stop training")
55             engine.terminate()
56
```

Path: `ignite/handlers/time_limit.py`
Content:
```
1 import logging
2 import time
3 from typing import Optional
4 
5 from ignite.engine import Engine
6 
7 __all__ = ["TimeLimit"]
8 
9 
10 class TimeLimit:
11     """TimeLimit handler can be used to control training time for computing environments where session time is limited.
12     Timer starts when handler is created and not training started.
13     This handler gracefully terminates the training if time passed in the training exceeds a limit.
14 
15     Args:
16         limit_sec (int, optional): Maximum time before training terminates (in seconds). Defaults to 28800.
17 
18     Examples:
19 
20         .. code-block:: python
21 
22             from ignite.engine import Events
23             from ignite.handlers import TimeLimit
24 
25             handler = TimeLimit() # 8 hours of training
26             trainer.add_event_handler(Events.ITERATION_COMPLETED, handler)
27 
28     .. versionadded:: 0.4.3
29     """
30 
31     def __init__(self, limit_sec: Optional[int] = 28800):
32 
33         if not isinstance(limit_sec, int):
34             raise TypeError("Argument limit_sec should be an integer.")
35         if limit_sec <= 0:
36             raise ValueError("Argument limit_sec should be a positive integer.")
37 
38         self.limit_sec = limit_sec
39         self.start_time = time.time()
40         self.logger = logging.getLogger(__name__ + "." + self.__class__.__name__)
41 
42     def __call__(self, engine: Engine) -> None:
43         elapsed_time = time.time() - self.start_time
44         if elapsed_time > self.limit_sec:
45             self.logger.info("Reached the time limit: {} sec. Stop training".format(self.limit_sec))
46             engine.terminate()
47
```
--- 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/handlers/early_stopping.py b/ignite/handlers/early_stopping.py
--- a/ignite/handlers/early_stopping.py
+++ b/ignite/handlers/early_stopping.py
@@ -1,9 +1,9 @@
-import logging
 from collections import OrderedDict
 from typing import Callable, Mapping, Optional, cast
 
 from ignite.base import Serializable
 from ignite.engine import Engine
+from ignite.utils import setup_logger
 
 __all__ = ["EarlyStopping"]
 
@@ -76,7 +76,7 @@
         self.trainer = trainer
         self.counter = 0
         self.best_score = None  # type: Optional[float]
-        self.logger = logging.getLogger(__name__ + "." + self.__class__.__name__)
+        self.logger = setup_logger(__name__ + "." + self.__class__.__name__)
 
     def __call__(self, engine: Engine) -> None:
         score = self.score_function(engine)
diff --git a/ignite/handlers/terminate_on_nan.py b/ignite/handlers/terminate_on_nan.py
--- a/ignite/handlers/terminate_on_nan.py
+++ b/ignite/handlers/terminate_on_nan.py
@@ -5,7 +5,7 @@
 import torch
 
 from ignite.engine import Engine
-from ignite.utils import apply_to_type
+from ignite.utils import apply_to_type, setup_logger
 
 __all__ = ["TerminateOnNan"]
 
@@ -33,7 +33,7 @@
     """
 
     def __init__(self, output_transform: Callable = lambda x: x):
-        self.logger = logging.getLogger(__name__ + "." + self.__class__.__name__)
+        self.logger = setup_logger(__name__ + "." + self.__class__.__name__)
         self.logger.addHandler(logging.StreamHandler())
         self._output_transform = output_transform
 
diff --git a/ignite/handlers/time_limit.py b/ignite/handlers/time_limit.py
--- a/ignite/handlers/time_limit.py
+++ b/ignite/handlers/time_limit.py
@@ -1,4 +1,3 @@
-import logging
 import time
 from typing import Optional
 
@@ -6,6 +5,8 @@
 
 __all__ = ["TimeLimit"]
 
+from ignite.utils import setup_logger
+
 
 class TimeLimit:
     """TimeLimit handler can be used to control training time for computing environments where session time is limited.
@@ -37,7 +38,7 @@
 
         self.limit_sec = limit_sec
         self.start_time = time.time()
-        self.logger = logging.getLogger(__name__ + "." + self.__class__.__name__)
+        self.logger = setup_logger(__name__ + "." + self.__class__.__name__)
 
     def __call__(self, engine: Engine) -> None:
         elapsed_time = time.time() - self.start_time

{"golden_diff": "diff --git a/ignite/handlers/early_stopping.py b/ignite/handlers/early_stopping.py\n--- a/ignite/handlers/early_stopping.py\n+++ b/ignite/handlers/early_stopping.py\n@@ -1,9 +1,9 @@\n-import logging\n from collections import OrderedDict\n from typing import Callable, Mapping, Optional, cast\n \n from ignite.base import Serializable\n from ignite.engine import Engine\n+from ignite.utils import setup_logger\n \n __all__ = [\"EarlyStopping\"]\n \n@@ -76,7 +76,7 @@\n         self.trainer = trainer\n         self.counter = 0\n         self.best_score = None  # type: Optional[float]\n-        self.logger = logging.getLogger(__name__ + \".\" + self.__class__.__name__)\n+        self.logger = setup_logger(__name__ + \".\" + self.__class__.__name__)\n \n     def __call__(self, engine: Engine) -> None:\n         score = self.score_function(engine)\ndiff --git a/ignite/handlers/terminate_on_nan.py b/ignite/handlers/terminate_on_nan.py\n--- a/ignite/handlers/terminate_on_nan.py\n+++ b/ignite/handlers/terminate_on_nan.py\n@@ -5,7 +5,7 @@\n import torch\n \n from ignite.engine import Engine\n-from ignite.utils import apply_to_type\n+from ignite.utils import apply_to_type, setup_logger\n \n __all__ = [\"TerminateOnNan\"]\n \n@@ -33,7 +33,7 @@\n     \"\"\"\n \n     def __init__(self, output_transform: Callable = lambda x: x):\n-        self.logger = logging.getLogger(__name__ + \".\" + self.__class__.__name__)\n+        self.logger = setup_logger(__name__ + \".\" + self.__class__.__name__)\n         self.logger.addHandler(logging.StreamHandler())\n         self._output_transform = output_transform\n \ndiff --git a/ignite/handlers/time_limit.py b/ignite/handlers/time_limit.py\n--- a/ignite/handlers/time_limit.py\n+++ b/ignite/handlers/time_limit.py\n@@ -1,4 +1,3 @@\n-import logging\n import time\n from typing import Optional\n \n@@ -6,6 +5,8 @@\n \n __all__ = [\"TimeLimit\"]\n \n+from ignite.utils import setup_logger\n+\n \n class TimeLimit:\n     \"\"\"TimeLimit handler can be used to control training time for computing environments where session time is limited.\n@@ -37,7 +38,7 @@\n \n         self.limit_sec = limit_sec\n         self.start_time = time.time()\n-        self.logger = logging.getLogger(__name__ + \".\" + self.__class__.__name__)\n+        self.logger = setup_logger(__name__ + \".\" + self.__class__.__name__)\n \n     def __call__(self, engine: Engine) -> None:\n         elapsed_time = time.time() - self.start_time\n", "issue": "Use setup_logger in handlers\n## \ud83d\ude80 Feature\r\n\r\nIdea is to replace in handlers (`EarlyStopping`, `TerminateOnNan`, etc.)\r\n```\r\nself.logger = logging.getLogger(__name__ + \".\" + self.__class__.__name__)\r\n```\r\nby `setup_logger` from `ignite.utils`\r\n```\r\nself.logger = setup_logger(__name__ + \".\" + self.__class__.__name__)\r\n```\n", "before_files": [{"content": "import logging\nfrom collections import OrderedDict\nfrom typing import Callable, Mapping, Optional, cast\n\nfrom ignite.base import Serializable\nfrom ignite.engine import Engine\n\n__all__ = [\"EarlyStopping\"]\n\n\nclass EarlyStopping(Serializable):\n    \"\"\"EarlyStopping handler can be used to stop the training if no improvement after a given number of events.\n\n    Args:\n        patience (int):\n            Number of events to wait if no improvement and then stop the training.\n        score_function (callable):\n            It should be a function taking a single argument, an :class:`~ignite.engine.engine.Engine` object,\n            and return a score `float`. An improvement is considered if the score is higher.\n        trainer (Engine):\n            trainer engine to stop the run if no improvement.\n        min_delta (float, optional):\n            A minimum increase in the score to qualify as an improvement,\n            i.e. an increase of less than or equal to `min_delta`, will count as no improvement.\n        cumulative_delta (bool, optional):\n            It True, `min_delta` defines an increase since the last `patience` reset, otherwise,\n            it defines an increase after the last event. Default value is False.\n\n    Examples:\n\n    .. code-block:: python\n\n        from ignite.engine import Engine, Events\n        from ignite.handlers import EarlyStopping\n\n        def score_function(engine):\n            val_loss = engine.state.metrics['nll']\n            return -val_loss\n\n        handler = EarlyStopping(patience=10, score_function=score_function, trainer=trainer)\n        # Note: the handler is attached to an *Evaluator* (runs one epoch on validation dataset).\n        evaluator.add_event_handler(Events.COMPLETED, handler)\n\n    \"\"\"\n\n    _state_dict_all_req_keys = (\n        \"counter\",\n        \"best_score\",\n    )\n\n    def __init__(\n        self,\n        patience: int,\n        score_function: Callable,\n        trainer: Engine,\n        min_delta: float = 0.0,\n        cumulative_delta: bool = False,\n    ):\n\n        if not callable(score_function):\n            raise TypeError(\"Argument score_function should be a function.\")\n\n        if patience < 1:\n            raise ValueError(\"Argument patience should be positive integer.\")\n\n        if min_delta < 0.0:\n            raise ValueError(\"Argument min_delta should not be a negative number.\")\n\n        if not isinstance(trainer, Engine):\n            raise TypeError(\"Argument trainer should be an instance of Engine.\")\n\n        self.score_function = score_function\n        self.patience = patience\n        self.min_delta = min_delta\n        self.cumulative_delta = cumulative_delta\n        self.trainer = trainer\n        self.counter = 0\n        self.best_score = None  # type: Optional[float]\n        self.logger = logging.getLogger(__name__ + \".\" + self.__class__.__name__)\n\n    def __call__(self, engine: Engine) -> None:\n        score = self.score_function(engine)\n\n        if self.best_score is None:\n            self.best_score = score\n        elif score <= self.best_score + self.min_delta:\n            if not self.cumulative_delta and score > self.best_score:\n                self.best_score = score\n            self.counter += 1\n            self.logger.debug(\"EarlyStopping: %i / %i\" % (self.counter, self.patience))\n            if self.counter >= self.patience:\n                self.logger.info(\"EarlyStopping: Stop training\")\n                self.trainer.terminate()\n        else:\n            self.best_score = score\n            self.counter = 0\n\n    def state_dict(self) -> \"OrderedDict[str, float]\":\n        return OrderedDict([(\"counter\", self.counter), (\"best_score\", cast(float, self.best_score))])\n\n    def load_state_dict(self, state_dict: Mapping) -> None:\n        super().load_state_dict(state_dict)\n        self.counter = state_dict[\"counter\"]\n        self.best_score = state_dict[\"best_score\"]\n", "path": "ignite/handlers/early_stopping.py"}, {"content": "import logging\nimport numbers\nfrom typing import Callable, Union\n\nimport torch\n\nfrom ignite.engine import Engine\nfrom ignite.utils import apply_to_type\n\n__all__ = [\"TerminateOnNan\"]\n\n\nclass TerminateOnNan:\n    \"\"\"TerminateOnNan handler can be used to stop the training if the `process_function`'s output\n    contains a NaN or infinite number or `torch.tensor`.\n    The output can be of type: number, tensor or collection of them. The training is stopped if\n    there is at least a single number/tensor have NaN or Infinite value. For example, if the output is\n    `[1.23, torch.tensor(...), torch.tensor(float('nan'))]` the handler will stop the training.\n\n    Args:\n        output_transform (callable, optional): a callable that is used to transform the\n            :class:`~ignite.engine.engine.Engine`'s ``process_function``'s output into a number or `torch.tensor`\n            or collection of them. This can be useful if, for example, you have a multi-output model and\n            you want to check one or multiple values of the output.\n\n\n    Examples:\n\n    .. code-block:: python\n\n        trainer.add_event_handler(Events.ITERATION_COMPLETED, TerminateOnNan())\n\n    \"\"\"\n\n    def __init__(self, output_transform: Callable = lambda x: x):\n        self.logger = logging.getLogger(__name__ + \".\" + self.__class__.__name__)\n        self.logger.addHandler(logging.StreamHandler())\n        self._output_transform = output_transform\n\n    def __call__(self, engine: Engine) -> None:\n        output = self._output_transform(engine.state.output)\n\n        def raise_error(x: Union[float, torch.Tensor]) -> None:\n\n            if isinstance(x, numbers.Number):\n                x = torch.tensor(x)\n\n            if isinstance(x, torch.Tensor) and not bool(torch.isfinite(x).all()):\n                raise RuntimeError(\"Infinite or NaN tensor found.\")\n\n        try:\n            apply_to_type(output, (numbers.Number, torch.Tensor), raise_error)\n        except RuntimeError:\n            self.logger.warning(f\"{self.__class__.__name__}: Output '{output}' contains NaN or Inf. Stop training\")\n            engine.terminate()\n", "path": "ignite/handlers/terminate_on_nan.py"}, {"content": "import logging\nimport time\nfrom typing import Optional\n\nfrom ignite.engine import Engine\n\n__all__ = [\"TimeLimit\"]\n\n\nclass TimeLimit:\n    \"\"\"TimeLimit handler can be used to control training time for computing environments where session time is limited.\n    Timer starts when handler is created and not training started.\n    This handler gracefully terminates the training if time passed in the training exceeds a limit.\n\n    Args:\n        limit_sec (int, optional): Maximum time before training terminates (in seconds). Defaults to 28800.\n\n    Examples:\n\n        .. code-block:: python\n\n            from ignite.engine import Events\n            from ignite.handlers import TimeLimit\n\n            handler = TimeLimit() # 8 hours of training\n            trainer.add_event_handler(Events.ITERATION_COMPLETED, handler)\n\n    .. versionadded:: 0.4.3\n    \"\"\"\n\n    def __init__(self, limit_sec: Optional[int] = 28800):\n\n        if not isinstance(limit_sec, int):\n            raise TypeError(\"Argument limit_sec should be an integer.\")\n        if limit_sec <= 0:\n            raise ValueError(\"Argument limit_sec should be a positive integer.\")\n\n        self.limit_sec = limit_sec\n        self.start_time = time.time()\n        self.logger = logging.getLogger(__name__ + \".\" + self.__class__.__name__)\n\n    def __call__(self, engine: Engine) -> None:\n        elapsed_time = time.time() - self.start_time\n        if elapsed_time > self.limit_sec:\n            self.logger.info(\"Reached the time limit: {} sec. Stop training\".format(self.limit_sec))\n            engine.terminate()\n", "path": "ignite/handlers/time_limit.py"}], "after_files": [{"content": "from collections import OrderedDict\nfrom typing import Callable, Mapping, Optional, cast\n\nfrom ignite.base import Serializable\nfrom ignite.engine import Engine\nfrom ignite.utils import setup_logger\n\n__all__ = [\"EarlyStopping\"]\n\n\nclass EarlyStopping(Serializable):\n    \"\"\"EarlyStopping handler can be used to stop the training if no improvement after a given number of events.\n\n    Args:\n        patience (int):\n            Number of events to wait if no improvement and then stop the training.\n        score_function (callable):\n            It should be a function taking a single argument, an :class:`~ignite.engine.engine.Engine` object,\n            and return a score `float`. An improvement is considered if the score is higher.\n        trainer (Engine):\n            trainer engine to stop the run if no improvement.\n        min_delta (float, optional):\n            A minimum increase in the score to qualify as an improvement,\n            i.e. an increase of less than or equal to `min_delta`, will count as no improvement.\n        cumulative_delta (bool, optional):\n            It True, `min_delta` defines an increase since the last `patience` reset, otherwise,\n            it defines an increase after the last event. Default value is False.\n\n    Examples:\n\n    .. code-block:: python\n\n        from ignite.engine import Engine, Events\n        from ignite.handlers import EarlyStopping\n\n        def score_function(engine):\n            val_loss = engine.state.metrics['nll']\n            return -val_loss\n\n        handler = EarlyStopping(patience=10, score_function=score_function, trainer=trainer)\n        # Note: the handler is attached to an *Evaluator* (runs one epoch on validation dataset).\n        evaluator.add_event_handler(Events.COMPLETED, handler)\n\n    \"\"\"\n\n    _state_dict_all_req_keys = (\n        \"counter\",\n        \"best_score\",\n    )\n\n    def __init__(\n        self,\n        patience: int,\n        score_function: Callable,\n        trainer: Engine,\n        min_delta: float = 0.0,\n        cumulative_delta: bool = False,\n    ):\n\n        if not callable(score_function):\n            raise TypeError(\"Argument score_function should be a function.\")\n\n        if patience < 1:\n            raise ValueError(\"Argument patience should be positive integer.\")\n\n        if min_delta < 0.0:\n            raise ValueError(\"Argument min_delta should not be a negative number.\")\n\n        if not isinstance(trainer, Engine):\n            raise TypeError(\"Argument trainer should be an instance of Engine.\")\n\n        self.score_function = score_function\n        self.patience = patience\n        self.min_delta = min_delta\n        self.cumulative_delta = cumulative_delta\n        self.trainer = trainer\n        self.counter = 0\n        self.best_score = None  # type: Optional[float]\n        self.logger = setup_logger(__name__ + \".\" + self.__class__.__name__)\n\n    def __call__(self, engine: Engine) -> None:\n        score = self.score_function(engine)\n\n        if self.best_score is None:\n            self.best_score = score\n        elif score <= self.best_score + self.min_delta:\n            if not self.cumulative_delta and score > self.best_score:\n                self.best_score = score\n            self.counter += 1\n            self.logger.debug(\"EarlyStopping: %i / %i\" % (self.counter, self.patience))\n            if self.counter >= self.patience:\n                self.logger.info(\"EarlyStopping: Stop training\")\n                self.trainer.terminate()\n        else:\n            self.best_score = score\n            self.counter = 0\n\n    def state_dict(self) -> \"OrderedDict[str, float]\":\n        return OrderedDict([(\"counter\", self.counter), (\"best_score\", cast(float, self.best_score))])\n\n    def load_state_dict(self, state_dict: Mapping) -> None:\n        super().load_state_dict(state_dict)\n        self.counter = state_dict[\"counter\"]\n        self.best_score = state_dict[\"best_score\"]\n", "path": "ignite/handlers/early_stopping.py"}, {"content": "import logging\nimport numbers\nfrom typing import Callable, Union\n\nimport torch\n\nfrom ignite.engine import Engine\nfrom ignite.utils import apply_to_type, setup_logger\n\n__all__ = [\"TerminateOnNan\"]\n\n\nclass TerminateOnNan:\n    \"\"\"TerminateOnNan handler can be used to stop the training if the `process_function`'s output\n    contains a NaN or infinite number or `torch.tensor`.\n    The output can be of type: number, tensor or collection of them. The training is stopped if\n    there is at least a single number/tensor have NaN or Infinite value. For example, if the output is\n    `[1.23, torch.tensor(...), torch.tensor(float('nan'))]` the handler will stop the training.\n\n    Args:\n        output_transform (callable, optional): a callable that is used to transform the\n            :class:`~ignite.engine.engine.Engine`'s ``process_function``'s output into a number or `torch.tensor`\n            or collection of them. This can be useful if, for example, you have a multi-output model and\n            you want to check one or multiple values of the output.\n\n\n    Examples:\n\n    .. code-block:: python\n\n        trainer.add_event_handler(Events.ITERATION_COMPLETED, TerminateOnNan())\n\n    \"\"\"\n\n    def __init__(self, output_transform: Callable = lambda x: x):\n        self.logger = setup_logger(__name__ + \".\" + self.__class__.__name__)\n        self.logger.addHandler(logging.StreamHandler())\n        self._output_transform = output_transform\n\n    def __call__(self, engine: Engine) -> None:\n        output = self._output_transform(engine.state.output)\n\n        def raise_error(x: Union[float, torch.Tensor]) -> None:\n\n            if isinstance(x, numbers.Number):\n                x = torch.tensor(x)\n\n            if isinstance(x, torch.Tensor) and not bool(torch.isfinite(x).all()):\n                raise RuntimeError(\"Infinite or NaN tensor found.\")\n\n        try:\n            apply_to_type(output, (numbers.Number, torch.Tensor), raise_error)\n        except RuntimeError:\n            self.logger.warning(f\"{self.__class__.__name__}: Output '{output}' contains NaN or Inf. Stop training\")\n            engine.terminate()\n", "path": "ignite/handlers/terminate_on_nan.py"}, {"content": "import time\nfrom typing import Optional\n\nfrom ignite.engine import Engine\n\n__all__ = [\"TimeLimit\"]\n\nfrom ignite.utils import setup_logger\n\n\nclass TimeLimit:\n    \"\"\"TimeLimit handler can be used to control training time for computing environments where session time is limited.\n    Timer starts when handler is created and not training started.\n    This handler gracefully terminates the training if time passed in the training exceeds a limit.\n\n    Args:\n        limit_sec (int, optional): Maximum time before training terminates (in seconds). Defaults to 28800.\n\n    Examples:\n\n        .. code-block:: python\n\n            from ignite.engine import Events\n            from ignite.handlers import TimeLimit\n\n            handler = TimeLimit() # 8 hours of training\n            trainer.add_event_handler(Events.ITERATION_COMPLETED, handler)\n\n    .. versionadded:: 0.4.3\n    \"\"\"\n\n    def __init__(self, limit_sec: Optional[int] = 28800):\n\n        if not isinstance(limit_sec, int):\n            raise TypeError(\"Argument limit_sec should be an integer.\")\n        if limit_sec <= 0:\n            raise ValueError(\"Argument limit_sec should be a positive integer.\")\n\n        self.limit_sec = limit_sec\n        self.start_time = time.time()\n        self.logger = setup_logger(__name__ + \".\" + self.__class__.__name__)\n\n    def __call__(self, engine: Engine) -> None:\n        elapsed_time = time.time() - self.start_time\n        if elapsed_time > self.limit_sec:\n            self.logger.info(\"Reached the time limit: {} sec. Stop training\".format(self.limit_sec))\n            engine.terminate()\n", "path": "ignite/handlers/time_limit.py"}]}