internlm/SWE-Fixer-Train-110K huggingface dataset:
Repository: Project-MONAI/MONAI

Issue:
`pixel` variable can be undefined 
**Describe the bug**

https://github.com/Project-MONAI/MONAI/blob/d0d720d0e9cea7d279cbf3cbb2066292f7efd333/monai/apps/pathology/transforms/post/array.py#L461

If none of the if/elif conditions are satisfied, `pixel` is undefined here.


Discussion:
I created a [PR ](https://github.com/Project-MONAI/MONAI/pull/5732) to add `FillHoles` before `generate_instance_contour`, which may prevent the issue when instances contain holes.
Thanks @KumoLiu! That helps in this pipeline so it is not a blocker anymore but we should consider the edge cases to work with this transform. Can you see if you can skip that particular contour or that image instead of raising error (and maybe just give a warning to the user)? Thanks

Resolving patch:
diff --git a/monai/apps/pathology/transforms/post/array.py b/monai/apps/pathology/transforms/post/array.py
--- a/monai/apps/pathology/transforms/post/array.py
+++ b/monai/apps/pathology/transforms/post/array.py
@@ -9,6 +9,7 @@
 # See the License for the specific language governing permissions and
 # limitations under the License.
 
+import warnings
 from typing import Callable, Dict, List, Optional, Sequence, Tuple, Union
 
 import numpy as np
@@ -458,6 +459,9 @@ def __call__(self, contours: List[np.ndarray]) -> np.ndarray:
                     elif coord[1] == self.width - 1:
                         corner = 2
                         pixel = (int(coord[0] - 0.5), int(coord[1]))
+                    else:
+                        warnings.warn(f"Invalid contour coord {coord} is generated, skip this instance.")
+                        return None  # type: ignore
                     sequence.append(pixel)
                     last_added = pixel
                 elif i == len(group) - 1:
@@ -555,7 +559,8 @@ def __call__(self, inst_mask: NdarrayOrTensor, offset: Optional[Sequence[int]] =
         inst_contour_cv = find_contours(inst_mask, level=self.contour_level)
         generate_contour = GenerateSuccinctContour(inst_mask.shape[0], inst_mask.shape[1])
         inst_contour = generate_contour(inst_contour_cv)
-
+        if inst_contour is None:
+            return None
         # less than `self.min_num_points` points don't make a contour, so skip.
         # They are likely to be artifacts as the contours obtained via approximation.
         if inst_contour.shape[0] < self.min_num_points:


Test patch:
Repository: Project-MONAI/MONAI

Issue:
`_get_latest_bundle_version` issue on Windows
https://github.com/Project-MONAI/MONAI/blob/69463a69637d4383056455b1b12bdff58294363e/monai/bundle/scripts.py#L185

On Windows, `os.path.join` will produce backslash rather than slash. Therefore, the created url will be wrong (`os.path.join(repo_owner, repo_name)`)
May need to handle this to avoid issues for Windows users.


Discussion:

Resolving patch:
diff --git a/monai/bundle/scripts.py b/monai/bundle/scripts.py
--- a/monai/bundle/scripts.py
+++ b/monai/bundle/scripts.py
@@ -182,7 +182,7 @@ def _get_latest_bundle_version(source: str, name: str, repo: str):
         return None
     elif source == "github":
         repo_owner, repo_name, tag_name = repo.split("/")
-        return get_bundle_versions(name, repo=os.path.join(repo_owner, repo_name), tag=tag_name)["latest_version"]
+        return get_bundle_versions(name, repo=f"{repo_owner}/{repo_name}", tag=tag_name)["latest_version"]
     else:
         raise ValueError(f"To get the latest bundle version, source should be 'github' or 'ngc', got {source}.")
 


Test patch:
diff --git a/tests/test_bundle_download.py b/tests/test_bundle_download.py
--- a/tests/test_bundle_download.py
+++ b/tests/test_bundle_download.py
@@ -26,7 +26,6 @@
     command_line_tests,
     skip_if_downloading_fails,
     skip_if_quick,
-    skip_if_windows,
 )
 
 TEST_CASE_1 = ["test_bundle", None]
@@ -58,7 +57,6 @@
 ]
 
 
-@skip_if_windows
 class TestDownload(unittest.TestCase):
     @parameterized.expand([TEST_CASE_1, TEST_CASE_2])
     @skip_if_quick
Repository: Project-MONAI/MONAI

Issue:
`build-docs` workflow failed
The workflow failed in recent PRs such as: https://github.com/Project-MONAI/MONAI/actions/runs/3805194186/jobs/6472957035#step:7:243


Discussion:

Resolving patch:
diff --git a/docs/source/conf.py b/docs/source/conf.py
--- a/docs/source/conf.py
+++ b/docs/source/conf.py
@@ -118,6 +118,7 @@ def generate_apidocs(*args):
     "show_toc_level": 1,
     "footer_items": ["copyright"],
     "navbar_align": "content",
+    "logo": {"image_light": "../images/MONAI-logo-color.png", "image_dark": "../images/MONAI-logo-color.png"},
 }
 html_context = {
     "github_user": "Project-MONAI",


Test patch:
Repository: Project-MONAI/MONAI

Issue:
Nondeterministic in `HoVerNet`
In the current `HoVerNet` implementation of MONAI, it uses `UpSample` with `NONTRAINABLE` mode which used [torch.nn.functional.interpolate()](https://pytorch.org/docs/stable/generated/torch.nn.functional.interpolate.html#torch.nn.functional.interpolate) may cause nondeterministic.
https://github.com/Project-MONAI/MONAI/blob/d0db5fd9d4da3bc7027d22c52bb9c405c3b9e879/monai/networks/nets/hovernet.py#L535-L537

https://pytorch.org/docs/stable/generated/torch.use_deterministic_algorithms.html#torch.use_deterministic_algorithms

**Describe the solution you'd like**
It may need to be explained in the docstring.


Discussion:
cc @JHancox @drbeh, could you please double confirm it?
@KumoLiu Is this non-determinism specific to Upsample? Also, doesn't it use torch.nn.Upsample rather than torch.nn.functional.interpolate?
Yes, it uses [torch.nn.functional.interpolate()](https://pytorch.org/docs/stable/generated/torch.nn.functional.interpolate.html#torch.nn.functional.interpolate) in torch.nn.UpSample.
https://github.com/pytorch/pytorch/blob/b136f3f310aa01a8b3c1e63dc0bfda8fd2234b06/torch/nn/modules/upsampling.py#L156
thanks, I'm labelling this a feature request to update the docstring for both hovernet and UpSample

Resolving patch:
diff --git a/monai/networks/blocks/upsample.py b/monai/networks/blocks/upsample.py
--- a/monai/networks/blocks/upsample.py
+++ b/monai/networks/blocks/upsample.py
@@ -31,6 +31,9 @@ class UpSample(nn.Sequential):
         - "nontrainable": uses :py:class:`torch.nn.Upsample`.
         - "pixelshuffle": uses :py:class:`monai.networks.blocks.SubpixelUpsample`.
 
+    This operation will cause non-deterministic when ``mode`` is ``UpsampleMode.NONTRAINABLE``.
+    Please check the link below for more details:
+    https://pytorch.org/docs/stable/generated/torch.use_deterministic_algorithms.html#torch.use_deterministic_algorithms
     This module can optionally take a pre-convolution
     (often used to map the number of features from `in_channels` to `out_channels`).
     """
diff --git a/monai/networks/nets/hovernet.py b/monai/networks/nets/hovernet.py
--- a/monai/networks/nets/hovernet.py
+++ b/monai/networks/nets/hovernet.py
@@ -416,6 +416,10 @@ class HoVerNet(nn.Module):
       https://github.com/vqdang/hover_net
       https://pytorch.org/vision/main/models/generated/torchvision.models.resnet50.html
 
+    This network is non-deterministic since it uses `torch.nn.Upsample` with ``UpsampleMode.NONTRAINABLE`` mode which
+    is implemented with torch.nn.functional.interpolate(). Please check the link below for more details:
+    https://pytorch.org/docs/stable/generated/torch.use_deterministic_algorithms.html#torch.use_deterministic_algorithms
+
     Args:
         mode: use original implementation (`HoVerNetMODE.ORIGINAL` or "original") or
           a faster implementation (`HoVerNetMODE.FAST` or "fast"). Defaults to `HoVerNetMODE.FAST`.


Test patch:
Repository: Project-MONAI/MONAI

Issue:
pytytpe premerge check
**Describe the bug**
https://github.com/Project-MONAI/MONAI/actions/runs/3887475308/jobs/6633774758
```pytype
2023.01.10
usage: __main__.py [options] input [input ...]
__main__.py: error: Need an input.
failed!
```
pytytpe premerge check
**Describe the bug**
https://github.com/Project-MONAI/MONAI/actions/runs/3887475308/jobs/6633774758
```pytype
2023.01.10
usage: __main__.py [options] input [input ...]
__main__.py: error: Need an input.
failed!
```


Discussion:

Resolving patch:
diff --git a/monai/transforms/utils.py b/monai/transforms/utils.py
--- a/monai/transforms/utils.py
+++ b/monai/transforms/utils.py
@@ -1544,6 +1544,8 @@ def get_transform_backends():
             not in [
                 "BatchInverseTransform",
                 "Compose",
+                "CuCIM",
+                "CuCIMD",
                 "Decollated",
                 "InvertD",
                 "InvertibleTransform",
@@ -1551,6 +1553,8 @@ def get_transform_backends():
                 "LambdaD",
                 "MapTransform",
                 "OneOf",
+                "RandCuCIM",
+                "RandCuCIMD",
                 "RandomOrder",
                 "PadListDataCollate",
                 "RandLambda",


Test patch:
Repository: Project-MONAI/MONAI

Issue:
Auto3DSeg templates need updating
**Describe the bug**

The main branch in [research-contributions](https://github.com/Project-MONAI/research-contributions) updated some features compared to MONAI 1.1.0. The MONAI dev should pick them in the upcoming weekly builds.



Discussion:

Resolving patch:
diff --git a/monai/apps/auto3dseg/bundle_gen.py b/monai/apps/auto3dseg/bundle_gen.py
--- a/monai/apps/auto3dseg/bundle_gen.py
+++ b/monai/apps/auto3dseg/bundle_gen.py
@@ -35,7 +35,7 @@
 from monai.utils import ensure_tuple
 
 logger = get_logger(module_name=__name__)
-ALGO_HASH = os.environ.get("MONAI_ALGO_HASH", "1dde7a1")
+ALGO_HASH = os.environ.get("MONAI_ALGO_HASH", "d0fa876d")
 
 __all__ = ["BundleAlgo", "BundleGen"]
 


Test patch:
Repository: Project-MONAI/MONAI

Issue:
Deprecate `create_multi_gpu_supervised_trainer` APIs
**Is your feature request related to a problem? Please describe.**
As we already set up MONAI workflow based on our own SupervisedTrainer, seems no need to keep the ignite trainer APIs which were developed at the beginning of the project.
Would be nice to deprecate them:
https://github.com/Project-MONAI/MONAI/blob/dev/monai/engines/multi_gpu_supervised_trainer.py


Discussion:

Resolving patch:
diff --git a/monai/engines/multi_gpu_supervised_trainer.py b/monai/engines/multi_gpu_supervised_trainer.py
--- a/monai/engines/multi_gpu_supervised_trainer.py
+++ b/monai/engines/multi_gpu_supervised_trainer.py
@@ -20,7 +20,7 @@
 
 from monai.config import IgniteInfo
 from monai.engines.utils import get_devices_spec
-from monai.utils import min_version, optional_import
+from monai.utils import deprecated, min_version, optional_import
 
 create_supervised_trainer, _ = optional_import(
     "ignite.engine", IgniteInfo.OPT_IMPORT_VERSION, min_version, "create_supervised_trainer"
@@ -53,6 +53,11 @@ def _default_eval_transform(
     return y_pred, y
 
 
+@deprecated(
+    since="1.1",
+    removed="1.3",
+    msg_suffix=("Native ignite engine lacks support of many MONAI features, please use `SupervisedTrainer` instead."),
+)
 def create_multigpu_supervised_trainer(
     net: torch.nn.Module,
     optimizer: Optimizer,
@@ -100,10 +105,23 @@ def create_multigpu_supervised_trainer(
         net = DataParallel(net)
 
     return create_supervised_trainer(  # type: ignore[no-any-return]
-        net, optimizer, loss_fn, devices_[0], non_blocking, prepare_batch, output_transform
+        model=net,
+        optimizer=optimizer,
+        loss_fn=loss_fn,
+        device=devices_[0],
+        non_blocking=non_blocking,
+        prepare_batch=prepare_batch,
+        output_transform=output_transform,
     )
 
 
+@deprecated(
+    since="1.1",
+    removed="1.3",
+    msg_suffix=(
+        "Native ignite evaluator lacks support of many MONAI features, please use `SupervisedEvaluator` instead."
+    ),
+)
 def create_multigpu_supervised_evaluator(
     net: torch.nn.Module,
     metrics: dict[str, Metric] | None = None,
@@ -153,5 +171,10 @@ def create_multigpu_supervised_evaluator(
         net = DataParallel(net)
 
     return create_supervised_evaluator(  # type: ignore[no-any-return]
-        net, metrics, devices_[0], non_blocking, prepare_batch, output_transform
+        model=net,
+        metrics=metrics,
+        device=devices_[0],
+        non_blocking=non_blocking,
+        prepare_batch=prepare_batch,
+        output_transform=output_transform,
     )


Test patch:
Repository: Project-MONAI/MONAI

Issue:
NrrdReader: Add the ability to not convert the affine matrix to "RAS"
**Is your feature request related to a problem? Please describe.**
Add the ability to not convert the affine matrix to "RAS" when loading images using `NrrdReader`.

**Describe the solution you'd like**
Add a `affine_lps_to_ras` argument  to `NrrdReader` controlling whether to convert the affine matrix from "LPS" to "RAS" or not.
This is how the option is implemented for ITKReader and PydicomReader.

**Describe alternatives you've considered**
A workaround is to create a new class that inherits  NrrdReader and implements this functionality.

**Additional context**
Not needed.



Discussion:
agreed, we can have a `affine_lps_to_ras` True or False to switch it on/off. also define a `affine_lps_to_ras=None` as the default, automatically deciding this from the metadata.
would you like to create a pull request? thanks!

Resolving patch:
diff --git a/monai/data/image_reader.py b/monai/data/image_reader.py
--- a/monai/data/image_reader.py
+++ b/monai/data/image_reader.py
@@ -1522,6 +1522,9 @@ class NrrdReader(ImageReader):
         dtype: dtype of the data array when loading image.
         index_order: Specify whether the returned data array should be in C-order (‘C’) or Fortran-order (‘F’).
             Numpy is usually in C-order, but default on the NRRD header is F
+        affine_lps_to_ras: whether to convert the affine matrix from "LPS" to "RAS". Defaults to ``True``.
+            Set to ``True`` to be consistent with ``NibabelReader``, otherwise the affine matrix is unmodified.
+
         kwargs: additional args for `nrrd.read` API. more details about available args:
             https://github.com/mhe/pynrrd/blob/master/nrrd/reader.py
 
@@ -1532,11 +1535,13 @@ def __init__(
         channel_dim: int | None = None,
         dtype: np.dtype | type | str | None = np.float32,
         index_order: str = "F",
+        affine_lps_to_ras: bool = True,
         **kwargs,
     ):
         self.channel_dim = channel_dim
         self.dtype = dtype
         self.index_order = index_order
+        self.affine_lps_to_ras = affine_lps_to_ras
         self.kwargs = kwargs
 
     def verify_suffix(self, filename: Sequence[PathLike] | PathLike) -> bool:
@@ -1590,7 +1595,10 @@ def get_data(self, img: NrrdImage | list[NrrdImage]) -> tuple[np.ndarray, dict]:
             if self.index_order == "C":
                 header = self._convert_f_to_c_order(header)
             header[MetaKeys.ORIGINAL_AFFINE] = self._get_affine(i)
-            header = self._switch_lps_ras(header)
+
+            if self.affine_lps_to_ras:
+                header = self._switch_lps_ras(header)
+
             header[MetaKeys.AFFINE] = header[MetaKeys.ORIGINAL_AFFINE].copy()
             header[MetaKeys.SPATIAL_SHAPE] = header["sizes"]
             [header.pop(k) for k in ("sizes", "space origin", "space directions")]  # rm duplicated data in header


Test patch:
Repository: Project-MONAI/MONAI

Issue:
WSIReader, cucim , tifffile, performance regressions
with pathology MIL classification tutorial, as an example
https://github.com/Project-MONAI/tutorials/blob/main/pathology/multiple_instance_learning/panda_mil_train_evaluate_pytorch_gpu.py

WSIReader is now imported from  `from monai.data.wsi_reader import WSIReader`. If changing the import to the old way (now deprecated)  `from monai.data.image_reader import WSIReader`, and setting backend=tifffile, then training is ~10% faster.  seems like a performance regression.

Training time on 8gpu, 1 epoch
- from monai.data.wsi_reader import WSIReader, (backend=cucim)   313 seconds
- from monai.data.wsi_reader import WSIReader, (backend=tiffile)   303 seconds
- from monai.data.image_reader import WSIReader, (backend=tiffile)   283 seconds
 


Discussion:
Hi @myron, thank you very much for reporting this. I have investigated this issue and realized that the root cause is an "unnecessary" array copy in the `wsi_reader.WSIReader`. After fixing this, `wsi_reader.WSIReader` seems to be faster than `image_reader.WSIReader` (see blow). I will submit the PR momentarily. It would be great if you can check the run time of MIL tutorial after the PR is merged. Thanks

```python
from monai.data.wsi_reader import WSIReader
from monai.data.image_reader import WSIReader as WSIReader2

filename = "temp_CMU-1.tiff"
reader1 = WSIReader(backend="TiffFile")
reader2 = WSIReader2(backend="TiffFile")
obj1 = reader1.read(filename)
obj2 = reader2.read(filename)
```
```python
%%timeit
reader1.get_data(obj1, level=1)
```
current performance: 2.32 s ± 97.7
after fixing the issue: 1.45 s ± 12.9 ms

```python
%%timeit
reader2.get_data(obj2, level=1)
```
current performance:  1.97 s ± 50.2 ms
after fixing the issue:. 1.93 s ± 141 ms

Resolving patch:
diff --git a/monai/data/wsi_reader.py b/monai/data/wsi_reader.py
--- a/monai/data/wsi_reader.py
+++ b/monai/data/wsi_reader.py
@@ -825,7 +825,7 @@ def _get_patch(
         # Extract patch
         downsampling_ratio = self.get_downsample_ratio(wsi=wsi, level=level)
         location_ = [round(location[i] / downsampling_ratio) for i in range(len(location))]
-        patch = wsi_image[location_[0] : location_[0] + size[0], location_[1] : location_[1] + size[1], :].copy()
+        patch = wsi_image[location_[0] : location_[0] + size[0], location_[1] : location_[1] + size[1], :]
 
         # Make the channel to desired dimensions
         patch = np.moveaxis(patch, -1, self.channel_dim)


Test patch:
Repository: Project-MONAI/MONAI

Issue:
`resample=False` by default for `SaveImage`
**Is your feature request related to a problem? Please describe.**
`resample=True` in `SaveImage` was useful for saving the model predictions for voxel-wise evaluations in early versions of monai.

Now invertible transform and MetaTensor provide better ways and `resample=True` is not needed any more. this is a feature request to change the default to `resample=False`.


`resample=False` by default for `SaveImage`
**Is your feature request related to a problem? Please describe.**
`resample=True` in `SaveImage` was useful for saving the model predictions for voxel-wise evaluations in early versions of monai.

Now invertible transform and MetaTensor provide better ways and `resample=True` is not needed any more. this is a feature request to change the default to `resample=False`.




Discussion:

Resolving patch:
diff --git a/monai/transforms/io/array.py b/monai/transforms/io/array.py
--- a/monai/transforms/io/array.py
+++ b/monai/transforms/io/array.py
@@ -367,6 +367,7 @@ class SaveImage(Transform):
             see also: :py:func:`monai.data.folder_layout.default_name_formatter`.
     """
 
+    @deprecated_arg_default("resample", True, False, since="1.1", replaced="1.3")
     def __init__(
         self,
         output_dir: PathLike = "./",
diff --git a/monai/transforms/io/dictionary.py b/monai/transforms/io/dictionary.py
--- a/monai/transforms/io/dictionary.py
+++ b/monai/transforms/io/dictionary.py
@@ -248,6 +248,7 @@ class SaveImaged(MapTransform):
 
     """
 
+    @deprecated_arg_default("resample", True, False, since="1.1", replaced="1.3")
     def __init__(
         self,
         keys: KeysCollection,


Test patch:
Repository: Project-MONAI/MONAI

Issue:
#6094 - add `warn` flag to RandCropByLabelClasses
Fixes #6094.

### Description

Adds the `warn` flag to `RandCropByLabelClasses`. If `True` the behavior of the class remains unchanged. If `False` the function will not print a warning if a class is not present in the label. 

### Types of changes
<!--- Put an `x` in all the boxes that apply, and remove the not applicable items -->
- [x] Non-breaking change (fix or new feature that would not break existing functionality).
- [ ] Breaking change (fix or new feature that would cause existing functionality to change).
- [ ] New tests added to cover the changes.
- [ ] Integration tests passed locally by running `./runtests.sh -f -u --net --coverage`.
- [ ] Quick tests passed locally by running `./runtests.sh --quick --unittests  --disttests`.
- [x] In-line docstrings updated.
- [ ] Documentation updated, tested `make html` command in the `docs/` folder.



Discussion:
please also change the dictionary version https://github.com/Project-MONAI/MONAI/blob/b85e2c6751d525488dddc2e3b0b05576d81208be/monai/transforms/croppad/dictionary.py#L895
/build

Resolving patch:
diff --git a/monai/transforms/utils.py b/monai/transforms/utils.py
--- a/monai/transforms/utils.py
+++ b/monai/transforms/utils.py
@@ -569,9 +569,10 @@ def generate_label_classes_crop_centers(
         raise ValueError(f"ratios should not contain negative number, got {ratios_}.")
 
     for i, array in enumerate(indices):
-        if len(array) == 0 and warn:
-            warnings.warn(f"no available indices of class {i} to crop, set the crop ratio of this class to zero.")
+        if len(array) == 0:
             ratios_[i] = 0
+            if warn:
+                warnings.warn(f"no available indices of class {i} to crop, set the crop ratio of this class to zero.")
 
     centers = []
     classes = rand_state.choice(len(ratios_), size=num_samples, p=np.asarray(ratios_) / np.sum(ratios_))


Test patch:
Repository: Project-MONAI/MONAI

Issue:
deprecating tests for python3.7, torch1.8.*
**Is your feature request related to a problem? Please describe.**
with new tests in https://github.com/Project-MONAI/MONAI/issues/6152, now removing tests for
- python3.7 end of life 27 Jun 2023
- torch 1.8.* and cuda10.2


Discussion:

Resolving patch:
diff --git a/monai/__init__.py b/monai/__init__.py
--- a/monai/__init__.py
+++ b/monai/__init__.py
@@ -17,7 +17,7 @@
 from ._version import get_versions
 
 PY_REQUIRED_MAJOR = 3
-PY_REQUIRED_MINOR = 7
+PY_REQUIRED_MINOR = 8
 
 version_dict = get_versions()
 __version__: str = version_dict.get("version", "0+unknown")


Test patch:
diff --git a/tests/testing_data/integration_answers.py b/tests/testing_data/integration_answers.py
--- a/tests/testing_data/integration_answers.py
+++ b/tests/testing_data/integration_answers.py
@@ -221,7 +221,7 @@
             ],
         },
     },
-    {  # test answers for PyTorch 1.8
+    {  # test answers for cuda 10.x
         "integration_classification_2d": {
             "losses": [0.777176220515731, 0.16019743723664315, 0.07480076164197011, 0.045643698364780966],
             "best_metric": 0.9999418774120775,
Repository: Project-MONAI/MONAI

Issue:
Error when user created files in algorithm config folder
User reported auto runner running error when jupyter notebook created .ipynb_checkpoint file in algorithm config folder



Discussion:

Resolving patch:
diff --git a/monai/apps/auto3dseg/bundle_gen.py b/monai/apps/auto3dseg/bundle_gen.py
--- a/monai/apps/auto3dseg/bundle_gen.py
+++ b/monai/apps/auto3dseg/bundle_gen.py
@@ -155,6 +155,8 @@ def _create_cmd(self, train_params=None):
         if os.path.isdir(config_dir):
             base_cmd = ""
             for file in os.listdir(config_dir):
+                if not (file.endswith("yaml") or file.endswith("json")):
+                    continue
                 if len(base_cmd) == 0:
                     base_cmd += f"{train_py} run --config_file="
                 else:


Test patch: