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

Issue:
Unused 'affine' argument in Spacing transform
**Describe the bug**
The `Spacing` transform accepts an `affine` argument, but  the argument is unused by the `__call__` function and has no effect on the output. 

**To Reproduce**

```python
from monai import transforms as trans
from monai.data.meta_tensor import MetaTensor

def test_monai_utils():

    # fake data
    x = np.ones((1, 64, 64, 64))

    # fake affines
    affine_1 = np.eye(4)
    affine_2 = np.eye(4) * 2

    resamp = trans.Spacing(pixdim=[1, 1, 1], diagonal=False, mode='bilinear')

    # using MetaTensor works as expected
    y_1 = resamp(MetaTensor(x, affine=affine_1))
    y_2 = resamp(MetaTensor(x, affine=affine_2))
    assert not all(i == j for i, j in zip(y_1.shape, y_2.shape))

    # using affine has no effect
    y_1 = resamp(x, affine=affine_1)
    y_2 = resamp(x, affine=affine_2)

    # these shapes should be different!
    assert not all(i == j for i, j in zip(y_1.shape, y_2.shape))
```

**Expected behavior**
Either have the `affine` argument override the input `data_array.affine`, or remove the `affine` argument altogether in favor of `data_array.affine`.





Discussion:

Resolving patch:
diff --git a/monai/transforms/spatial/array.py b/monai/transforms/spatial/array.py
--- a/monai/transforms/spatial/array.py
+++ b/monai/transforms/spatial/array.py
@@ -515,15 +515,16 @@ def __call__(
         sr = len(original_spatial_shape)
         if sr <= 0:
             raise ValueError("data_array must have at least one spatial dimension.")
+        input_affine: Optional[NdarrayOrTensor] = None
         affine_: np.ndarray
-        affine_np: np.ndarray
-        if isinstance(data_array, MetaTensor):
-            affine_np, *_ = convert_data_type(data_array.affine, np.ndarray)
-            affine_ = to_affine_nd(sr, affine_np)
-        else:
+        if affine is not None:
+            warnings.warn("arg `affine` is deprecated, the affine of MetaTensor in data_array has higher priority.")
+        input_affine = data_array.affine if isinstance(data_array, MetaTensor) else affine
+        if input_affine is None:
             warnings.warn("`data_array` is not of type MetaTensor, assuming affine to be identity.")
             # default to identity
-            affine_ = np.eye(sr + 1, dtype=np.float64)
+            input_affine = np.eye(sr + 1, dtype=np.float64)
+        affine_ = to_affine_nd(sr, convert_data_type(input_affine, np.ndarray)[0])
 
         out_d = self.pixdim[:sr]
         if out_d.size < sr:


Test patch:
Repository: Project-MONAI/MONAI

Issue:
ProbMap indexing has an error
**Describe the bug**
The location values of probability mask is not being used correctly in the numpy output. The locations are a numpy array (instead of a tuple) so when used in indexing an ndarray, they are not being interpreted as the location in two/three dimension. Instead they are treated as the index of the first dimension. Explicit conversion to tuple can solve this issue.

https://github.com/Project-MONAI/MONAI/blob/c1eaf427ed2310483856e33e57e7b83d59c85b13/monai/handlers/probability_maps.py#L98


Discussion:

Resolving patch:
diff --git a/monai/handlers/probability_maps.py b/monai/handlers/probability_maps.py
--- a/monai/handlers/probability_maps.py
+++ b/monai/handlers/probability_maps.py
@@ -95,7 +95,7 @@ def __call__(self, engine: Engine) -> None:
         locs = engine.state.batch["metadata"][ProbMapKeys.LOCATION]
         probs = engine.state.output[self.prob_key]
         for name, loc, prob in zip(names, locs, probs):
-            self.prob_map[name][loc] = prob
+            self.prob_map[name][tuple(loc)] = prob
             with self.lock:
                 self.counter[name] -= 1
                 if self.counter[name] == 0:


Test patch:
diff --git a/tests/test_handler_prob_map_producer.py b/tests/test_handler_prob_map_producer.py
--- a/tests/test_handler_prob_map_producer.py
+++ b/tests/test_handler_prob_map_producer.py
@@ -36,9 +36,9 @@ def __init__(self, name, size):
                     "image": name,
                     ProbMapKeys.COUNT.value: size,
                     ProbMapKeys.SIZE.value: np.array([size, size]),
-                    ProbMapKeys.LOCATION.value: np.array([i, i]),
+                    ProbMapKeys.LOCATION.value: np.array([i, i + 1]),
                 }
-                for i in range(size)
+                for i in range(size - 1)
             ]
         )
         self.image_data = [
@@ -94,7 +94,8 @@ def inference(enging, batch):
         engine.run(data_loader)
 
         prob_map = np.load(os.path.join(output_dir, name + ".npy"))
-        self.assertListEqual(np.diag(prob_map).astype(int).tolist(), list(range(1, size + 1)))
+        self.assertListEqual(np.vstack(prob_map.nonzero()).T.tolist(), [[i, i + 1] for i in range(size - 1)])
+        self.assertListEqual(prob_map[prob_map.nonzero()].tolist(), [i + 1 for i in range(size - 1)])
 
 
 if __name__ == "__main__":
Repository: Project-MONAI/MONAI

Issue:
Update PyTorch base container to 22.07
**Is your feature request related to a problem? Please describe.**
22.07 is released now:
CUDA 11.7 Update 1 Preview
CuBLAS 11.10.3.66
NCCL 2.12.12
CuDNN 8.4.1.67
TensorRT 8.4.1
DALI 1.15
Nsight Systems 2022.1.3.3

TensorRT 8.4 will be quite useful to support accelerated inference on the new A100 or 3090Ti GPUs.

Thanks.




Discussion:

Resolving patch:
diff --git a/monai/data/box_utils.py b/monai/data/box_utils.py
--- a/monai/data/box_utils.py
+++ b/monai/data/box_utils.py
@@ -1063,7 +1063,7 @@ def non_max_suppression(
 
     # initialize the list of picked indexes
     pick = []
-    idxs = torch.Tensor(list(range(0, boxes_sort.shape[0]))).to(torch.long)
+    idxs = torch.Tensor(list(range(0, boxes_sort.shape[0]))).to(device=boxes_t.device, dtype=torch.long)
 
     # keep looping while some indexes still remain in the indexes list
     while len(idxs) > 0:


Test patch:
Repository: Project-MONAI/MONAI

Issue:
Enhance Documentation of LoadImage to Clarify Image Transposition
**Is your feature request related to a problem? Please describe.**
Image data loaded from non-medical 2D formats like jpeg are transposed by the `ImageReader` class loading them, this is because these images are WH order and typical Pytorch ordering is HW. It's not clear to users that this is happening and can be really confused when using the loaders with natural images or photographs, or even MedNIST data as compared to loading with PIL directly.

**Describe the solution you'd like**
Documentation for `LoadImage` should be updated to state that this occurs for a number of non-medical specific file formats. 

**Describe alternatives you've considered**
Tilting my head to the side any time I visualise an image.

**Additional context**
I had forgotten this was intended behaviour and wasn't helped by documentation. 



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
@@ -99,6 +99,10 @@ class LoadImage(Transform):
         - Current default readers: (nii, nii.gz -> NibabelReader), (png, jpg, bmp -> PILReader),
           (npz, npy -> NumpyReader), (nrrd -> NrrdReader), (DICOM file -> ITKReader).
 
+    Please note that for png, jpg, bmp, and other 2D formats, readers often swap axis 0 and 1 after
+    loading the array because the `HW` definition for non-medical specific file formats is different
+    from other common medical packages.
+
     See also:
 
         - tutorial: https://github.com/Project-MONAI/tutorials/blob/master/modules/load_medical_images.ipynb
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
@@ -51,6 +51,10 @@ class LoadImaged(MapTransform):
         - Current default readers: (nii, nii.gz -> NibabelReader), (png, jpg, bmp -> PILReader),
           (npz, npy -> NumpyReader), (dcm, DICOM series and others -> ITKReader).
 
+    Please note that for png, jpg, bmp, and other 2D formats, readers often swap axis 0 and 1 after
+    loading the array because the `HW` definition for non-medical specific file formats is different
+    from other common medical packages.
+
     Note:
 
         - If `reader` is specified, the loader will attempt to use the specified readers and the default supported


Test patch:
Repository: Project-MONAI/MONAI

Issue:
Vnet InputTransition ignores out_channel param
**Describe the bug**
The `InputTransition` class at `monai.networks.nets.vnet` takes in the parameter `out_channels` but ignores it in the implementation to the hard coded original value of 16. Check screenshots of the problem below.

**To Reproduce**
```python
from monai.networks.nets.vnet import InputTransition

in_tr = InputTransition(spatial_dims=3, in_channels=1, out_channel=32, act,= ("elu", {"inplace": True}),  bias=False)
inp = torch.zeros(1, 1,32, 32,32)
out = in_tr(inp)
print(out.shape[1])
```

**Expected behavior**
Expected behavior is to print `32` an not `16`.

**Screenshots**

![annotely_image](https://user-images.githubusercontent.com/23334003/184164330-eaf2a786-f8bf-41e6-b166-dac38342ea3e.jpeg)




Discussion:

Resolving patch:
diff --git a/monai/networks/nets/vnet.py b/monai/networks/nets/vnet.py
--- a/monai/networks/nets/vnet.py
+++ b/monai/networks/nets/vnet.py
@@ -67,16 +67,19 @@ def __init__(
     ):
         super().__init__()
 
-        if 16 % in_channels != 0:
-            raise ValueError(f"16 should be divisible by in_channels, got in_channels={in_channels}.")
+        if out_channels % in_channels != 0:
+            raise ValueError(
+                f"out channels should be divisible by in_channels. Got in_channels={in_channels}, out_channels={out_channels}."
+            )
 
         self.spatial_dims = spatial_dims
         self.in_channels = in_channels
-        self.act_function = get_acti_layer(act, 16)
+        self.out_channels = out_channels
+        self.act_function = get_acti_layer(act, out_channels)
         self.conv_block = Convolution(
             spatial_dims=spatial_dims,
             in_channels=in_channels,
-            out_channels=16,
+            out_channels=out_channels,
             kernel_size=5,
             act=None,
             norm=Norm.BATCH,
@@ -85,7 +88,7 @@ def __init__(
 
     def forward(self, x):
         out = self.conv_block(x)
-        repeat_num = 16 // self.in_channels
+        repeat_num = self.out_channels // self.in_channels
         x16 = x.repeat([1, repeat_num, 1, 1, 1][: self.spatial_dims + 2])
         out = self.act_function(torch.add(out, x16))
         return out


Test patch:
Repository: Project-MONAI/MONAI

Issue:
Doubt in BasicUNet documentation
Should cat_chns represent "number of channels from the encoder" instead of "number of channels from the decoder" since the encoder channels are concatenated with the upsampled decoder channels?

https://github.com/Project-MONAI/MONAI/blob/f49cc963179d1ca678f6ca2d05918157959bd9b3/monai/networks/nets/basic_unet.py#L127


Discussion:
Hi @Nic-Ma, 
Could you please help with it?
Thanks
Hi @yashika-git, thank you for pointing out this issue, I will update the docstring as soon as possible.

Resolving patch:
diff --git a/monai/networks/nets/basic_unet.py b/monai/networks/nets/basic_unet.py
--- a/monai/networks/nets/basic_unet.py
+++ b/monai/networks/nets/basic_unet.py
@@ -124,7 +124,7 @@ def __init__(
         Args:
             spatial_dims: number of spatial dimensions.
             in_chns: number of input channels to be upsampled.
-            cat_chns: number of channels from the decoder.
+            cat_chns: number of channels from the encoder.
             out_chns: number of output channels.
             act: activation type and arguments.
             norm: feature normalization type and arguments.


Test patch:
Repository: Project-MONAI/MONAI

Issue:
Add update time information in bundle api
As discussed with @zephyrie , each bundle's latest update time will be used in model zoo's website, thus it would be good to add it in `_get_all_bundles_info`


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
@@ -346,6 +346,8 @@ def _get_all_bundles_info(repo: str = "Project-MONAI/model-zoo", tag: str = "hos
                     "size": asset["size"],
                     "download_count": asset["download_count"],
                     "browser_download_url": asset["browser_download_url"],
+                    "created_at": asset["created_at"],
+                    "updated_at": asset["updated_at"],
                 }
             return bundles_info
     return bundles_info
@@ -405,7 +407,8 @@ def get_bundle_info(
     tag: str = "hosting_storage_v1",
 ):
     """
-    Get all information (include "id", "name", "size", "download_count", "browser_download_url") of a bundle
+    Get all information
+    (include "id", "name", "size", "download_count", "browser_download_url", "created_at", "updated_at") of a bundle
     with the specified bundle name and version.
 
     Args:


Test patch:
Repository: Project-MONAI/MONAI

Issue:
Is this typo? Or indeed it rotates images?
https://github.com/Project-MONAI/MONAI/blob/8087dc58ea6803099a0466abf62f420d7cdc9d2e/monai/transforms/intensity/dictionary.py#L585


Discussion:
Hi @Joeycho ,

Thanks for your reporint.
I think it's a typo, @KumoLiu Could you please help confirm it?

Thanks in advance.


Resolving patch:
diff --git a/monai/transforms/intensity/dictionary.py b/monai/transforms/intensity/dictionary.py
--- a/monai/transforms/intensity/dictionary.py
+++ b/monai/transforms/intensity/dictionary.py
@@ -382,8 +382,8 @@ def __init__(
             meta_key_postfix: if meta_keys is None, use `key_{postfix}` to fetch the metadata according
                 to the key data, default is `meta_dict`, the metadata is a dictionary object.
                 used to extract the factor value is `factor_key` is not None.
-            prob: probability of rotating.
-                (Default 0.1, with 10% probability it returns a rotated array.)
+            prob: probability of shift.
+                (Default 0.1, with 10% probability it returns an array shifted intensity.)
             allow_missing_keys: don't raise exception if key is missing.
         """
         MapTransform.__init__(self, keys, allow_missing_keys)
@@ -580,8 +580,8 @@ def __init__(
                 See also: :py:class:`monai.transforms.compose.MapTransform`
             factors: factor range to randomly scale by ``v = v * (1 + factor)``.
                 if single number, factor value is picked from (-factors, factors).
-            prob: probability of rotating.
-                (Default 0.1, with 10% probability it returns a rotated array.)
+            prob: probability of scale.
+                (Default 0.1, with 10% probability it returns a scaled array.)
             dtype: output data type, if None, same as input image. defaults to float32.
             allow_missing_keys: don't raise exception if key is missing.
 


Test patch:
Repository: Project-MONAI/MONAI

Issue:
Bundle: No check if logging config file exists.
https://github.com/Project-MONAI/MONAI/blob/71041fd89e11104a4ea79f11687a2469f331679c/monai/bundle/scripts.py#L496

Running from outside bundle directory gives a cryptic error. There should be a check and error message if the given file doesn't exits.

command: `torchrun --standalone --nnodes=1 --nproc_per_node=2 -m monai.bundle run training --meta_file configs/metadata.json --config_file "['configs/train.json','configs/multi_gpu_train.json']" --logging_file configs/logging.conf`

Error:
```
2022-09-30 00:20:10,616 - INFO - set logging properties based on config: configs/logging.conf.
Traceback (most recent call last):
  File "/opt/conda/lib/python3.8/runpy.py", line 194, in _run_module_as_main
    return _run_code(code, main_globals, None,
  File "/opt/conda/lib/python3.8/runpy.py", line 87, in _run_code
    exec(code, run_globals)
  File "/opt/monai/monai/bundle/__main__.py", line 19, in <module>
    fire.Fire()
  File "/opt/conda/lib/python3.8/site-packages/fire/core.py", line 141, in Fire
    component_trace = _Fire(component, args, parsed_flag_args, context, name)
  File "/opt/conda/lib/python3.8/site-packages/fire/core.py", line 466, in _Fire
    component, remaining_args = _CallAndUpdateTrace(
  File "/opt/conda/lib/python3.8/site-packages/fire/core.py", line 681, in _CallAndUpdateTrace
    component = fn(*varargs, **kwargs)
  File "/opt/monai/monai/bundle/scripts.py", line 498, in run
    fileConfig(logging_file_, disable_existing_loggers=False)
  File "/opt/conda/lib/python3.8/logging/config.py", line 71, in fileConfig
    formatters = _create_formatters(cp)
  File "/opt/conda/lib/python3.8/logging/config.py", line 104, in _create_formatters
    flist = cp["formatters"]["keys"]
  File "/opt/conda/lib/python3.8/configparser.py", line 960, in __getitem__
    raise KeyError(key)
KeyError: 'formatters'

```


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
@@ -494,6 +494,8 @@ def run(
         _args, "config_file", meta_file=None, runner_id="", logging_file=None
     )
     if logging_file_ is not None:
+        if not os.path.exists(logging_file_):
+            raise FileNotFoundError(f"can't find the logging config file: {logging_file_}.")
         logger.info(f"set logging properties based on config: {logging_file_}.")
         fileConfig(logging_file_, disable_existing_loggers=False)
 


Test patch:
Repository: Project-MONAI/MONAI

Issue:
allow_low_quality_matches is always set to True
**Describe the bug**
`allow_low_quality_matches` in `set_regular_matcher` is always set to `True` and it's not using value from the argument, in retinanet.
https://github.com/Project-MONAI/MONAI/blob/e9f48e3416a506c0775fbe2366528ff1a30906bc/monai/apps/detection/networks/retinanet_detector.py#L327



Discussion:
Hi @Can-Zhao ,

Could you please help confirm it and fix?

Thanks in advance.


Resolving patch:
diff --git a/monai/apps/detection/networks/retinanet_detector.py b/monai/apps/detection/networks/retinanet_detector.py
--- a/monai/apps/detection/networks/retinanet_detector.py
+++ b/monai/apps/detection/networks/retinanet_detector.py
@@ -318,13 +318,17 @@ def set_regular_matcher(self, fg_iou_thresh: float, bg_iou_thresh: float, allow_
         Args:
             fg_iou_thresh: foreground IoU threshold for Matcher, considered as matched if IoU > fg_iou_thresh
             bg_iou_thresh: background IoU threshold for Matcher, considered as not matched if IoU < bg_iou_thresh
+            allow_low_quality_matches: if True, produce additional matches
+                for predictions that have only low-quality match candidates.
         """
         if fg_iou_thresh < bg_iou_thresh:
             raise ValueError(
                 "Require fg_iou_thresh >= bg_iou_thresh. "
                 f"Got fg_iou_thresh={fg_iou_thresh}, bg_iou_thresh={bg_iou_thresh}."
             )
-        self.proposal_matcher = Matcher(fg_iou_thresh, bg_iou_thresh, allow_low_quality_matches=True)
+        self.proposal_matcher = Matcher(
+            fg_iou_thresh, bg_iou_thresh, allow_low_quality_matches=allow_low_quality_matches
+        )
 
     def set_atss_matcher(self, num_candidates: int = 4, center_in_gt: bool = False) -> None:
         """


Test patch:
Repository: Project-MONAI/MONAI

Issue:
FlexibleUNet is_pad
This argument isn't obvious to me, and I don't find the docstrings clear enough to understand what's going on. I think the English grammar isn't quite correct (happy to help there if necessary). I would appreciate further explanation here:

https://github.com/Project-MONAI/MONAI/blob/dev/monai/networks/nets/flexible_unet.py#L243-L244


Discussion:
please also remove this type of docstrings: https://github.com/Project-MONAI/MONAI/blob/b36ba6c84f8f56c08e80b16acace9d466b70078a/monai/networks/nets/flexible_unet.py#L220-L221, use a ticket instead.

Resolving patch:
diff --git a/monai/networks/nets/flexible_unet.py b/monai/networks/nets/flexible_unet.py
--- a/monai/networks/nets/flexible_unet.py
+++ b/monai/networks/nets/flexible_unet.py
@@ -217,9 +217,6 @@ def __init__(
         and the spatial size of each dimension must be a multiple of 32 if is pad parameter
         is False
 
-        TODO(binliu@nvidia.com): Add more backbones/encoders to this class and make a general
-        encoder-decoder structure. ETC:2022.09.01
-
         Args:
             in_channels: number of input channels.
             out_channels: number of output channels.
@@ -240,8 +237,9 @@ def __init__(
                 ``"nontrainable"``.
             interp_mode: {``"nearest"``, ``"linear"``, ``"bilinear"``, ``"bicubic"``, ``"trilinear"``}
                 Only used in the "nontrainable" mode.
-            is_pad: whether to use padding feature maps to enable the input spatial not necessary
-                to be a multiple of 32. Default to True.
+            is_pad: whether to pad upsampling features to fit features from encoder. Default to True.
+                If this parameter is set to "True", the spatial dim of network input can be arbitary
+                size, which is not supported by TensorRT. Otherwise, it must be a multiple of 32.
         """
         super().__init__()
 


Test patch:
Repository: Project-MONAI/MONAI

Issue:
Reduce redundant logging in multi-gpu training with MonaiAlgo
**Is your feature request related to a problem? Please describe.**
Currently, each rank is logging during multi-gpu training.

**Describe the solution you'd like**
Remove redundant logs.

**Describe alternatives you've considered**
n/a

**Additional context**
n/a



Discussion:

Resolving patch:
diff --git a/monai/fl/client/monai_algo.py b/monai/fl/client/monai_algo.py
--- a/monai/fl/client/monai_algo.py
+++ b/monai/fl/client/monai_algo.py
@@ -494,6 +494,11 @@ def initialize(self, extra=None):
             BundleKeys.DATASET_DIR, default=ConfigItem(None, BundleKeys.DATASET_DIR)
         )
 
+        if self.multi_gpu:
+            if self.rank > 0 and self.trainer:
+                self.trainer.logger.setLevel(logging.WARNING)
+            if self.rank > 0 and self.evaluator:
+                self.evaluator.logger.setLevel(logging.WARNING)
         self.logger.info(f"Initialized {self.client_name}.")
 
     def train(self, data: ExchangeObject, extra=None):


Test patch: