internlm/SWE-Fixer-Train-110K huggingface dataset:
Repository: pytorch/ignite

Issue:
utils.convert_tensor considers `device = 0` to be no device
## 🐛 Bug description
In utils.convert_tensor, this line appears:
`return tensor.to(device=device, non_blocking=non_blocking) if device else tensor`

This means that for `device = 0` (as returned from `torch.cuda.current_device`) no conversion is applied, which can be very confusing. I might add a PR for that tomorrow, unless people tell me there's a reason to leave that line as it is.

For reproduction:
```python
import torch
from ignite.utils import convert_tensor

mytens = torch.zeros(2)
device = torch.cuda.current_device()
converted_tens = convert_tensor(mytens, device)
assert converted_tens.device == device
```

## Environment

 - PyTorch Version (e.g., 1.4): 1.4
 - Ignite Version (e.g., 0.3.0): 0.3
 - OS (e.g., Linux): Windows 10
 - How you installed Ignite (`conda`, `pip`, source): conda
 - Python version: 3.7.6




Discussion:
Thanks for the report @bendboaz ! Yes, please send a PR to fix that with `if device is not None`

Resolving patch:
diff --git a/ignite/utils.py b/ignite/utils.py
--- a/ignite/utils.py
+++ b/ignite/utils.py
@@ -15,7 +15,7 @@ def convert_tensor(
     """Move tensors to relevant device."""
 
     def _func(tensor: torch.Tensor) -> torch.Tensor:
-        return tensor.to(device=device, non_blocking=non_blocking) if device else tensor
+        return tensor.to(device=device, non_blocking=non_blocking) if device is not None else tensor
 
     return apply_to_tensor(input_, _func)
 


Test patch:
Repository: pytorch/ignite

Issue:
Mistake in MLflow logger documentation
MLflow log_params(params: dict) method accept dict, not arguments.

https://github.com/pytorch/ignite/blob/4b311cc82fe45b3082661125cd7ee54007283fb0/ignite/contrib/handlers/mlflow_logger.py#L202


Discussion:
@Muhamob thanks for the report !
Yes, you are right. I fixed this in the examples but forgot about the docs. If you would like to contribute, please feel free to send a PR with removing `**`. Otherwise, I can do this. 
Yes, I can send PR

Resolving patch:
diff --git a/ignite/contrib/handlers/mlflow_logger.py b/ignite/contrib/handlers/mlflow_logger.py
--- a/ignite/contrib/handlers/mlflow_logger.py
+++ b/ignite/contrib/handlers/mlflow_logger.py
@@ -199,7 +199,7 @@ class MLflowLogger(BaseLogger):
             mlflow_logger = MLflowLogger()
 
             # Log experiment parameters:
-            mlflow_logger.log_params(**{
+            mlflow_logger.log_params({
                 "seed": seed,
                 "batch_size": batch_size,
                 "model": model.__class__.__name__,


Test patch:
Repository: pytorch/ignite

Issue:
[Typing] Bad type of Events in Timer
## 🐛 Bug description

Timer class has wrong type (str) for events:
 https://github.com/pytorch/ignite/blob/efc45a79ee0a5bf8105c3caff194758439db2426/ignite/handlers/timing.py#L87-L94



## Environment

 - PyTorch Version (e.g., 1.4): 1.4
 - Ignite Version (e.g., 0.3.0): master




Discussion:
In addition to that, fix all `Any` type hints that were put to avoid circular deps by type hints as strings (https://docs.python.org/3/library/typing.html#typing.ForwardRef):
https://github.com/pytorch/ignite/blob/c8e0089d90b13362727a6d108e44a100a07714e4/ignite/engine/events.py#L48-L51



Resolving patch:
diff --git a/ignite/engine/events.py b/ignite/engine/events.py
--- a/ignite/engine/events.py
+++ b/ignite/engine/events.py
@@ -45,10 +45,9 @@ def value(self):
         """The value of the Enum member."""
         return self._value_
 
-    # Will return CallableEventWithFilter but can't annotate that way due to python <= 3.7
     def __call__(
         self, event_filter: Optional[Callable] = None, every: Optional[int] = None, once: Optional[int] = None
-    ) -> Any:
+    ) -> "CallableEventWithFilter":
         """
         Makes the event class callable and accepts either an arbitrary callable as filter
         (which must take in the engine and current event value and return a boolean) or an every or once value
diff --git a/ignite/handlers/timing.py b/ignite/handlers/timing.py
--- a/ignite/handlers/timing.py
+++ b/ignite/handlers/timing.py
@@ -87,10 +87,10 @@ def __init__(self, average: bool = False):
     def attach(
         self,
         engine: Engine,
-        start: str = Events.STARTED,
-        pause: str = Events.COMPLETED,
-        resume: Optional[str] = None,
-        step: Optional[str] = None,
+        start: Events = Events.STARTED,
+        pause: Events = Events.COMPLETED,
+        resume: Optional[Events] = None,
+        step: Optional[Events] = None,
     ):
         """ Register callbacks to control the timer.
 


Test patch:
Repository: pytorch/ignite

Issue:
NeptuneSaver saves more checkpoints than specified by the n_saved parameter
## 🐛 Bug description

The recent change to Checkpointing in PR #937 seemed to have affected the NeptuneSaver in that it saves more than the specified `n_saved` checkpoints.  It is probably because it doesn't have the the `BaseSaveHandler` interface. Maybe because of this change [checkpoint.py]( https://github.com/vfdev-5/ignite/blob/f5d00c9887888fa31059ca4cc7a5e744889ce49f/ignite/handlers/checkpoint.py#L249)

## Environment

 - PyTorch Version (e.g., 1.4): 1.4
 - Ignite Version (e.g., 0.3.0): nightly
 - OS (e.g., Linux): Linux
 - How you installed Ignite (`conda`, `pip`, source): pip
 - Python version: 3.7




Discussion:

Resolving patch:
diff --git a/ignite/contrib/handlers/neptune_logger.py b/ignite/contrib/handlers/neptune_logger.py
--- a/ignite/contrib/handlers/neptune_logger.py
+++ b/ignite/contrib/handlers/neptune_logger.py
@@ -6,6 +6,7 @@
 import torch
 
 import ignite
+from ignite.handlers.checkpoint import BaseSaveHandler
 from ignite.contrib.handlers.base_logger import (
     BaseLogger,
     BaseOptimizerParamsHandler,
@@ -466,7 +467,7 @@ def close(self):
         self.stop()
 
 
-class NeptuneSaver:
+class NeptuneSaver(BaseSaveHandler):
     """Handler that saves input checkpoint to the Neptune server.
 
     Args:


Test patch:
diff --git a/tests/ignite/contrib/handlers/test_neptune_logger.py b/tests/ignite/contrib/handlers/test_neptune_logger.py
--- a/tests/ignite/contrib/handlers/test_neptune_logger.py
+++ b/tests/ignite/contrib/handlers/test_neptune_logger.py
@@ -6,6 +6,7 @@
 import torch
 
 from ignite.engine import Engine, Events, State
+from ignite.handlers.checkpoint import Checkpoint
 from ignite.contrib.handlers.neptune_logger import *
 
 
@@ -414,7 +415,7 @@ def dummy_handler(engine, logger, event_name):
         trainer.run(data, max_epochs=n_epochs)
 
 
-def test_neptune_saver_serializable(dummy_model_factory, dirname):
+def test_neptune_saver_serializable():
 
     mock_logger = MagicMock(spec=NeptuneLogger)
     mock_logger.log_artifact = MagicMock()
@@ -428,7 +429,28 @@ def test_neptune_saver_serializable(dummy_model_factory, dirname):
     assert mock_logger.log_artifact.call_count == 1
 
 
-def test_neptune_saver_non_serializable(dirname):
+def test_neptune_saver_integration():
+
+    model = torch.nn.Module()
+    to_save_serializable = {"model": model}
+
+    mock_logger = MagicMock(spec=NeptuneLogger)
+    mock_logger.log_artifact = MagicMock()
+    mock_logger.delete_artifacts = MagicMock()
+    saver = NeptuneSaver(mock_logger)
+
+    checkpoint = Checkpoint(to_save=to_save_serializable, save_handler=saver, n_saved=1)
+
+    trainer = Engine(lambda e, b: None)
+    trainer.state = State(epoch=0, iteration=0)
+    checkpoint(trainer)
+    trainer.state.iteration = 1
+    checkpoint(trainer)
+    assert mock_logger.log_artifact.call_count == 2
+    assert mock_logger.delete_artifacts.call_count == 1
+
+
+def test_neptune_saver_non_serializable():
 
     mock_logger = MagicMock(spec=NeptuneLogger)
     mock_logger.log_artifact = MagicMock()
Repository: pytorch/ignite

Issue:
Deprecate ignite.contrib.handlers.custom_events.CustomPeriodicEvent
## 🚀 Feature

Custom events `CustomPeriodicEvent` from contrib seem heavy and unusable. 

Idea is to 

- [ ] raise a warning about deprecation since v0.4.0 and removing since v0.5.0 and suggest to use filtered events.
- [ ] remove all docs about them 



Discussion:

Resolving patch:
diff --git a/ignite/contrib/handlers/custom_events.py b/ignite/contrib/handlers/custom_events.py
--- a/ignite/contrib/handlers/custom_events.py
+++ b/ignite/contrib/handlers/custom_events.py
@@ -1,8 +1,11 @@
 from ignite.engine import Events, State, EventEnum
+import warnings
 
 
 class CustomPeriodicEvent:
-    """Handler to define a custom periodic events as a number of elapsed iterations/epochs for an engine.
+    """DEPRECATED. Use filtered events instead.
+    Handler to define a custom periodic events as a number of elapsed iterations/epochs
+    for an engine.
 
     When custom periodic event is created and attached to an engine, the following events are fired:
     1) K iterations is specified:
@@ -51,6 +54,11 @@ def on_every_10_epochs(engine):
 
     def __init__(self, n_iterations=None, n_epochs=None):
 
+        warnings.warn(
+            "CustomPeriodicEvent is deprecated since 0.4.0 and will be removed in 0.5.0. Use filtered events instead.",
+            DeprecationWarning,
+        )
+
         if n_iterations is not None and (not isinstance(n_iterations, int) or n_iterations < 1):
             raise ValueError("Argument n_iterations should be positive integer number")
 


Test patch:
Repository: pytorch/ignite

Issue:
Interoperability of logging with ignite logger
## 🐛 Bug description

This bug is related to logger from module logging. Actually, (logging) handlers are attached to loggers created by user. https://github.com/pytorch/ignite/blob/bef668c152dc86334a8ab09e9ce9368c48e48102/ignite/utils.py#L64-L137

From `logging` documentation (https://docs.python.org/3/howto/logging.html#loggers)

> Child loggers propagate messages up to the handlers associated with their ancestor loggers. Because of this, it is unnecessary to define and configure handlers for all the loggers an application uses. It is sufficient to configure handlers for a top-level logger and create child loggers as needed. (You can, however, turn off propagation by setting the propagate attribute of a logger to False.)

This code shows the problem of propagation to ancestor 

```python
# no ancestor so print is ok
logger = setup_logger("logger")
logger.info("message 1 from test logger") 

# logging creates root ancestor of all loggers including one above 
logging.info("message from default logging, a root logger is defined !")

# root + logger dump...
logger.info("message 2 from test logger")
```

Result is
```
> 2020-05-05 09:24:27,583 logger INFO: message 1 from test logger
> 2020-05-05 09:24:27,583 logger INFO: message 2 from test logger
> INFO:logger:message 2 from test logger
```

## Environment

 - PyTorch Version (e.g., 1.4): 1.5
 - Ignite Version (e.g., 0.3.0): 0.4
 - OS (e.g., Linux): Linux
 - How you installed Ignite (`conda`, `pip`, source): conda
 - Python version: 3.7
 - Any other relevant information:




Discussion:

Resolving patch:
diff --git a/ignite/utils.py b/ignite/utils.py
--- a/ignite/utils.py
+++ b/ignite/utils.py
@@ -105,6 +105,12 @@ def setup_logger(
     """
     logger = logging.getLogger(name)
 
+    # don't propagate to ancestors
+    # the problem here is to attach handlers to loggers
+    # should we provide a default configuration less open ?
+    if name is not None:
+        logger.propagate = False
+
     # Remove previous handlers
     if logger.hasHandlers():
         for h in list(logger.handlers):


Test patch:
Repository: pytorch/ignite

Issue:
PyTorch dependency is lacking version constraint
## 🐛 Bug description

<!-- A clear and concise description of what the bug is. -->
PyTorch is a dependency of Ignite and, thus, is specified in `setup.py`

https://github.com/pytorch/ignite/blob/4b311cc82fe45b3082661125cd7ee54007283fb0/setup.py#L24-L26

and `conda.recipe/meta.yaml`:

https://github.com/pytorch/ignite/blob/4b311cc82fe45b3082661125cd7ee54007283fb0/conda.recipe/meta.yaml#L15-L23

The PyTorch dependency is lacking a version constraint which may work fine right now, but there is no guarantee that Ignite will be compatible with any future major PyTorch release (e.g. PyTorch v2.x).

I suggest to constrain the PyTorch version that Ignite is compatible with, e.g. `>=1.0,<2` or `<2` if any `0.x` and `1.x` version works. If PyTorch has a new major release, even previous Ignite versions can become compatible with the new major PyTorch release (especially if no changes to the code are necessary) by making new bug fix releases with relaxed version constraints to include the new PyTorch version.

In my opinion, it is highly preferable to be conservative about dependency version constraints through a [compatible release constraint](https://www.python.org/dev/peps/pep-0440/#compatible-release) in case the dependency conforms with semantic versioning. It is impossible to guarantee compatibility with a future major release of a dependency as its API can change arbitrarily.


Discussion:
@sisp this makes sense, thanks for the suggestion ! 
Currently, we maintain and test the compatibility with the latest stable and nightly version of PyTorch.
Yes, I think we can add `>=1.0,<2` as compatible release constrain.

cc @ykumards @sdesrozis 

We should provide tools to configure virtual envs with good like this `conda.yaml`
```
name: ignite_env
channels:
  - pytorch
dependencies:
  - pip
  - pytorch>=1.4
  - torchvision>=0.5
  - tensorboard>=2.1
  - pandas>=1.0
  - pyyaml>=5.3
  - pip:
    - git+https://github.com/pytorch/ignite
```
usable like `conda env create -f conda.yml`

and `Dockerfile` maybe

Resolving patch:
diff --git a/setup.py b/setup.py
--- a/setup.py
+++ b/setup.py
@@ -22,7 +22,7 @@ def find_version(*file_paths):
 VERSION = find_version("ignite", "__init__.py")
 
 requirements = [
-    "torch",
+    "torch>=1.0,<2",
 ]
 
 setup(


Test patch:
Repository: pytorch/ignite

Issue:
Backport and deprecate `CallableEvents`
## 🐛 Bug description

According to https://github.com/pytorch/ignite/issues/1070#issuecomment-634046751 user could use `CallableEvents` since v0.3.0. To improve backward compatibility, we need to reintroduce `CallableEvents` as `CallableEventWithFilter` and put a deprecation note (removed since v0.5.0 and use `Events`).

## Environment

 - PyTorch Version (e.g., 1.4):
 - Ignite Version (e.g., 0.3.0):
 - OS (e.g., Linux):
 - How you installed Ignite (`conda`, `pip`, source):
 - Python version:
 - Any other relevant information:



Discussion:

Resolving patch:
diff --git a/ignite/engine/events.py b/ignite/engine/events.py
--- a/ignite/engine/events.py
+++ b/ignite/engine/events.py
@@ -1,12 +1,13 @@
 import numbers
+import warnings
 import weakref
 from enum import Enum
 from types import DynamicClassAttribute
-from typing import Any, Callable, Optional, Union
+from typing import Callable, Optional, Union
 
 from ignite.engine.utils import _check_signature
 
-__all__ = ["Events", "State"]
+__all__ = ["CallableEventWithFilter", "EventEnum", "Events", "State"]
 
 
 class CallableEventWithFilter:
@@ -129,6 +130,17 @@ def __or__(self, other):
         return EventsList() | self | other
 
 
+class CallableEvents(CallableEventWithFilter):
+    # For backward compatibility
+    def __init__(self, *args, **kwargs):
+        super(CallableEvents, self).__init__(*args, **kwargs)
+        warnings.warn(
+            "Class ignite.engine.events.CallableEvents is deprecated. It will be removed in 0.5.0. "
+            "Please, use ignite.engine.EventEnum instead",
+            DeprecationWarning,
+        )
+
+
 class EventEnum(CallableEventWithFilter, Enum):
     pass
 


Test patch:
diff --git a/tests/ignite/engine/test_custom_events.py b/tests/ignite/engine/test_custom_events.py
--- a/tests/ignite/engine/test_custom_events.py
+++ b/tests/ignite/engine/test_custom_events.py
@@ -5,7 +5,18 @@
 import torch
 
 from ignite.engine import Engine, Events
-from ignite.engine.events import CallableEventWithFilter, EventEnum, EventsList
+from ignite.engine.events import CallableEvents, CallableEventWithFilter, EventEnum, EventsList
+
+
+def test_deprecated_callable_events_class():
+    engine = Engine(lambda engine, batch: 0)
+
+    with pytest.warns(DeprecationWarning, match=r"Class ignite\.engine\.events\.CallableEvents is deprecated"):
+
+        class CustomEvents(CallableEvents, Enum):
+            TEST_EVENT = "test_event"
+
+        engine.register_events(*CustomEvents)
 
 
 def test_custom_events():
Repository: pytorch/ignite

Issue:
ProgressBar does not close the bar on Colab if every is used
## 🐛 Bug description

Progress bar is set with `common.setup_common_training_handlers(... log_every_iters=15, ...)` and it does not close itself as being not terminated ...

<img width="451" alt="Screen Shot 2020-06-09 at 16 34 53" src="https://user-images.githubusercontent.com/2459423/84161178-48effa80-aa6f-11ea-9fd1-5b6c673c940f.png">

## Environment

 - PyTorch Version (e.g., 1.4): 
 - Ignite Version (e.g., 0.3.0):
 - OS (e.g., Linux):
 - How you installed Ignite (`conda`, `pip`, source):
 - Python version:
 - Any other relevant information:



Discussion:
~~Do you have the notebook ?~~

EDIT : ok, I reproduce it
EDIT2 : failed on jupyterlab
It seems that if `pbar` doesn't reach `pbar_total` on notebook, the bar persists... Actually I don't know why. 
Found why here
https://github.com/tqdm/tqdm/blob/0cd9448b2bc08125e74538a2aea6af42ee1a7b6f/tqdm/notebook.py#L240-L250

```python
    def close(self, *args, **kwargs):
        super(tqdm_notebook, self).close(*args, **kwargs)
        # Try to detect if there was an error or KeyboardInterrupt
        # in manual mode: if n < total, things probably got wrong
        if self.total and self.n < self.total:
            self.sp(bar_style='danger')
        else:
            if self.leave:
                self.sp(bar_style='success')
            else:
                self.sp(close=True)
```

Resolving patch:
diff --git a/ignite/contrib/handlers/tqdm_logger.py b/ignite/contrib/handlers/tqdm_logger.py
--- a/ignite/contrib/handlers/tqdm_logger.py
+++ b/ignite/contrib/handlers/tqdm_logger.py
@@ -199,6 +199,11 @@ def _reset(self, pbar_total):
 
     def _close(self, engine):
         if self.pbar is not None:
+            # https://github.com/tqdm/notebook.py#L240-L250
+            # issue #1115 : notebook backend of tqdm checks if n < total (error or KeyboardInterrupt)
+            # and the bar persists in 'danger' mode
+            if self.pbar.total is not None:
+                self.pbar.n = self.pbar.total
             self.pbar.close()
         self.pbar = None
 


Test patch:
Repository: pytorch/ignite

Issue:
idist initialize with nccl backend without GPU
## 🐛 Bug description

Call `idist.initialize("nccl", ...)` without GPU (but pytorch providing `nccl`) raises an error 
```commandline
Floating point exception
```
Exception is thrown in barrier following `dist.initialize`.

Case `nccl` + no GPU should raise an explicit exception.

## Environment

 - PyTorch Version (e.g., 1.4): 1.5
 - Ignite Version (e.g., 0.3.0): 0.4
 - OS (e.g., Linux): Linux
 - How you installed Ignite (`conda`, `pip`, source): conda
 - Python version: 3.7
 - Any other relevant information:



Discussion:

Resolving patch:
diff --git a/ignite/distributed/comp_models/native.py b/ignite/distributed/comp_models/native.py
--- a/ignite/distributed/comp_models/native.py
+++ b/ignite/distributed/comp_models/native.py
@@ -74,6 +74,9 @@ def _create_from_backend(self, backend, timeout=None, **kwargs):
             if timeout is not None:
                 init_pg_kwargs["timeout"] = timeout
 
+            if backend == dist.Backend.NCCL and not torch.cuda.is_available():
+                raise RuntimeError("Nccl backend is required but no cuda capable devices")
+
             dist.init_process_group(backend, init_method="env://", **init_pg_kwargs)
             # https://github.com/facebookresearch/maskrcnn-benchmark/issues/172
             dist.barrier()


Test patch:
diff --git a/tests/ignite/conftest.py b/tests/ignite/conftest.py
--- a/tests/ignite/conftest.py
+++ b/tests/ignite/conftest.py
@@ -216,3 +216,12 @@ def _xla_execute(fn, args, nprocs):
 @pytest.fixture()
 def xmp_executor():
     yield _xla_execute
+
+
+@pytest.fixture()
+def mock_gpu_is_not_available():
+    from unittest.mock import patch
+
+    with patch("torch.cuda") as mock_cuda:
+        mock_cuda.is_available.return_value = False
+        yield mock_cuda
diff --git a/tests/ignite/distributed/comp_models/test_native.py b/tests/ignite/distributed/comp_models/test_native.py
--- a/tests/ignite/distributed/comp_models/test_native.py
+++ b/tests/ignite/distributed/comp_models/test_native.py
@@ -32,6 +32,20 @@ def test__native_dist_model():
         assert "mpi" not in available_backends
 
 
+@pytest.mark.distributed
+@pytest.mark.skipif(not dist.is_nccl_available(), reason="Skip if nccl not available")
+def test__native_nccl_but_no_gpu(mock_gpu_is_not_available):
+
+    env_backup = os.environ
+
+    with pytest.raises(RuntimeError, match=r"Nccl backend is required but no cuda capable devices"):
+        _NativeDistModel(backend="nccl")
+
+    # environ could be corrupted by _NativeDistModel
+    os.environ.clear()
+    os.environ.update(env_backup)
+
+
 @pytest.mark.distributed
 @pytest.mark.skipif("WORLD_SIZE" in os.environ, reason="Skip if launched as multiproc")
 def test__native_dist_model_create_from_backend_bad_config():