internlm/SWE-Fixer-Train-110K huggingface dataset:
Repository: open-mmlab/mmdetection

Issue:
typo
I think `mmdet` should be `mmcv`
https://github.com/open-mmlab/mmdetection/blob/885b86bae849529735129c0945d729b91ff3b79a/mmdet/core/evaluation/mean_ap.py#L298


Discussion:
you are right, thank you!

Resolving patch:
diff --git a/mmdet/core/evaluation/mean_ap.py b/mmdet/core/evaluation/mean_ap.py
--- a/mmdet/core/evaluation/mean_ap.py
+++ b/mmdet/core/evaluation/mean_ap.py
@@ -295,7 +295,7 @@ def eval_map(det_results,
             there are minor differences in metrics for different datsets, e.g.
             "voc07", "imagenet_det", etc. Default: None.
         logger (logging.Logger | str | None): The way to print the mAP
-            summary. See `mmdet.utils.print_log()` for details. Default: None.
+            summary. See `mmcv.utils.print_log()` for details. Default: None.
         tpfp_fn (callable | None): The function used to determine true/
             false positives. If None, :func:`tpfp_default` is used as default
             unless dataset is 'det' or 'vid' (:func:`tpfp_imagenet` in this
@@ -417,7 +417,7 @@ def print_map_summary(mean_ap,
         dataset (list[str] | str | None): Dataset name or dataset classes.
         scale_ranges (list[tuple] | None): Range of scales to be evaluated.
         logger (logging.Logger | str | None): The way to print the mAP
-            summary. See `mmdet.utils.print_log()` for details. Default: None.
+            summary. See `mmcv.utils.print_log()` for details. Default: None.
     """
 
     if logger == 'silent':
diff --git a/mmdet/core/evaluation/recall.py b/mmdet/core/evaluation/recall.py
--- a/mmdet/core/evaluation/recall.py
+++ b/mmdet/core/evaluation/recall.py
@@ -74,7 +74,7 @@ def eval_recalls(gts,
         proposal_nums (int | Sequence[int]): Top N proposals to be evaluated.
         iou_thrs (float | Sequence[float]): IoU thresholds. Default: 0.5.
         logger (logging.Logger | str | None): The way to print the recall
-            summary. See `mmdet.utils.print_log()` for details. Default: None.
+            summary. See `mmcv.utils.print_log()` for details. Default: None.
 
     Returns:
         ndarray: recalls of different ious and proposal nums
@@ -121,7 +121,7 @@ def print_recall_summary(recalls,
         row_idxs (ndarray): which rows(proposal nums) to print
         col_idxs (ndarray): which cols(iou thresholds) to print
         logger (logging.Logger | str | None): The way to print the recall
-            summary. See `mmdet.utils.print_log()` for details. Default: None.
+            summary. See `mmcv.utils.print_log()` for details. Default: None.
     """
     proposal_nums = np.array(proposal_nums, dtype=np.int32)
     iou_thrs = np.array(iou_thrs)


Test patch:
Repository: open-mmlab/mmdetection

Issue:
Invalid link in readme of cityscape
Hi, Thank you very much for the amazing project! 

I would like to report that the [model](http://download.openmmlab.com/mmdetection/v2.0/cityscapes/mask_rcnn_r50_fpn_1x_cityscapes_20200502-6ea77f0e.pth) in the [readme](https://github.com/open-mmlab/mmdetection/blob/master/configs/cityscapes/README.md) in the cityscape is invalid. 

Meanwhile, may I ask whether there are more pre-trained models on Cityscape? I would like to evaluate the models elaborately. 

Thank you!


Discussion:
Hi @luzai, thanks for your comments, and we will train the model and provide the checkpoints soon.

Resolving patch:
diff --git a/configs/paa/paa_r101_fpn_mstrain_3x_coco.py b/configs/paa/paa_r101_fpn_mstrain_3x_coco.py
new file mode 100644
--- /dev/null
+++ b/configs/paa/paa_r101_fpn_mstrain_3x_coco.py
@@ -0,0 +1,2 @@
+_base_ = './paa_r50_fpn_mstrain_3x_coco.py'
+model = dict(pretrained='torchvision://resnet101', backbone=dict(depth=101))
diff --git a/configs/paa/paa_r50_fpn_mstrain_3x_coco.py b/configs/paa/paa_r50_fpn_mstrain_3x_coco.py
new file mode 100644
--- /dev/null
+++ b/configs/paa/paa_r50_fpn_mstrain_3x_coco.py
@@ -0,0 +1,20 @@
+_base_ = './paa_r50_fpn_1x_coco.py'
+img_norm_cfg = dict(
+    mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True)
+train_pipeline = [
+    dict(type='LoadImageFromFile'),
+    dict(type='LoadAnnotations', with_bbox=True),
+    dict(
+        type='Resize',
+        img_scale=[(1333, 640), (1333, 800)],
+        multiscale_mode='range',
+        keep_ratio=True),
+    dict(type='RandomFlip', flip_ratio=0.5),
+    dict(type='Normalize', **img_norm_cfg),
+    dict(type='Pad', size_divisor=32),
+    dict(type='DefaultFormatBundle'),
+    dict(type='Collect', keys=['img', 'gt_bboxes', 'gt_labels']),
+]
+data = dict(train=dict(pipeline=train_pipeline))
+lr_config = dict(step=[28, 34])
+total_epochs = 36


Test patch:
Repository: open-mmlab/mmdetection

Issue:
crpn_faster_rcnn gets "No gt bboxes" error
Hello, 

I have been trying to run crpn_faster_rcnn but the training always fails with "No gt bboxes" error. 

I am using custom models but the model does have a region proposals as I am loading the weights from pre-trained weights for crpn I created from the same dataset. 

I've played around with the learning rate but no chance.

Do you have any hint or advice on what is going on? Thanks.


Discussion:
This is the error message
![Screenshot 2021-01-22 at 13 03 07](https://user-images.githubusercontent.com/5387810/105494072-2d5dfb00-5cb2-11eb-9b98-8c2dd0c8bcc2.png)

I have met the same problem.Have you solve it?

> This is the error message
> ![Screenshot 2021-01-22 at 13 03 07](https://user-images.githubusercontent.com/5387810/105494072-2d5dfb00-5cb2-11eb-9b98-8c2dd0c8bcc2.png)


It seems that cascade RPN does not support empty GT images from the [code here](https://github.com/open-mmlab/mmdetection/blob/master/mmdet/core/bbox/assigners/region_assigner.py#L107). I am not sure whether this has specific motivation for that, so may involve @thangvubk's help to have a look on that. Maybe we can enable similar logic for empty GT in other [assigner](https://github.com/open-mmlab/mmdetection/blob/master/mmdet/core/bbox/assigners/max_iou_assigner.py#L145).
Hi. I think just enable logic for empty GT in other assigners to resolve the problem. I will update the code. 

Resolving patch:
diff --git a/mmdet/core/bbox/assigners/region_assigner.py b/mmdet/core/bbox/assigners/region_assigner.py
--- a/mmdet/core/bbox/assigners/region_assigner.py
+++ b/mmdet/core/bbox/assigners/region_assigner.py
@@ -101,12 +101,29 @@ def assign(self,
         Returns:
             :obj:`AssignResult`: The assign result.
         """
-        # TODO support gt_bboxes_ignore
         if gt_bboxes_ignore is not None:
             raise NotImplementedError
-        if gt_bboxes.shape[0] == 0:
-            raise ValueError('No gt bboxes')
+
         num_gts = gt_bboxes.shape[0]
+        num_bboxes = sum(x.shape[0] for x in mlvl_anchors)
+
+        if num_gts == 0 or num_bboxes == 0:
+            # No ground truth or boxes, return empty assignment
+            max_overlaps = gt_bboxes.new_zeros((num_bboxes, ))
+            assigned_gt_inds = gt_bboxes.new_zeros((num_bboxes, ),
+                                                   dtype=torch.long)
+            if gt_labels is None:
+                assigned_labels = None
+            else:
+                assigned_labels = gt_bboxes.new_full((num_bboxes, ),
+                                                     -1,
+                                                     dtype=torch.long)
+            return AssignResult(
+                num_gts,
+                assigned_gt_inds,
+                max_overlaps,
+                labels=assigned_labels)
+
         num_lvls = len(mlvl_anchors)
         r1 = (1 - self.center_ratio) / 2
         r2 = (1 - self.ignore_ratio) / 2


Test patch:
Repository: open-mmlab/mmdetection

Issue:
Missing '**kwargs' parameters passing to imshow_bboxes() in show_result() of rpn.py
https://github.com/open-mmlab/mmdetection/blob/bde7b4b7eea9dd6ee91a486c6996b2d68662366d/mmdet/models/detectors/rpn.py#L155

'**kwargs' parameters haven't passed to mmcv.imshow_bboxes() in show_result() of mmdetection/mmdet/models/detectors/rpn.py



Discussion:
Thanks for your reporting. Would you mind creating a PR to fix it?

Resolving patch:
diff --git a/mmdet/models/detectors/rpn.py b/mmdet/models/detectors/rpn.py
--- a/mmdet/models/detectors/rpn.py
+++ b/mmdet/models/detectors/rpn.py
@@ -152,4 +152,4 @@ def show_result(self, data, result, top_k=20, **kwargs):
         Returns:
             np.ndarray: The image with bboxes drawn on it.
         """
-        mmcv.imshow_bboxes(data, result, top_k=top_k)
+        mmcv.imshow_bboxes(data, result, top_k=top_k, **kwargs)


Test patch:
Repository: open-mmlab/mmdetection

Issue:
Shape of ONNX export dynamic batch
Thanks for your error report and we appreciate it a lot.

https://github.com/open-mmlab/mmdetection/blob/master/tools/deployment/pytorch2onnx.py#L71

This line should be 
```
    if dynamic_export:
        dynamic_axes = {
            input_name: {
                0: 'batch',
                2: 'height',
                3: 'width'
            },
            'dets': {
                0: 'batch',
                1: 'num_dets',
            },
            'labels': {
                0: 'batch',
                1: 'num_dets',
            },
        }
```

Based on the way the line below is implemented the dynamic axis should be `bs x c x h x w`. 
https://github.com/open-mmlab/mmdetection/blob/master/tools/deployment/pytorch2onnx.py#L139


I can create a quick PR for this if needed. 




Discussion:
@aravind-anantha Thanks for creating a PR to fix it.

Resolving patch:
diff --git a/tools/deployment/pytorch2onnx.py b/tools/deployment/pytorch2onnx.py
--- a/tools/deployment/pytorch2onnx.py
+++ b/tools/deployment/pytorch2onnx.py
@@ -71,8 +71,8 @@ def pytorch2onnx(model,
         dynamic_axes = {
             input_name: {
                 0: 'batch',
-                2: 'width',
-                3: 'height'
+                2: 'height',
+                3: 'width'
             },
             'dets': {
                 0: 'batch',


Test patch:
Repository: open-mmlab/mmdetection

Issue:
[BUG]bug in ConvFCBBoxHead's init cfg.
https://github.com/open-mmlab/mmdetection/blob/c88509cb9a73d6bd1edcba64eb924d3cf3cfe85d/mmdet/models/roi_heads/bbox_heads/convfc_bbox_head.py#L103

This line will override initializers for fc_cls and fc_reg because they are also nn.Linear. 
Or is it what's intended? But I see the old way to initialize fc_cls and fc_reg is using Normal.


Discussion:
Can anyone tell me if it is an error or it is supposed to be like this? I really want to know, as tests on small dataset (voc07) shows a big difference. 
> Can anyone tell me if it is an error or it is supposed to be like this? I really want to know, as tests on small dataset (voc07) shows a big difference.

I will check it
> https://github.com/open-mmlab/mmdetection/blob/c88509cb9a73d6bd1edcba64eb924d3cf3cfe85d/mmdet/models/roi_heads/bbox_heads/convfc_bbox_head.py#L103
> 
> This line will override initializers for fc_cls and fc_reg because they are also nn.Linear. Or is it what's intended? But I see the old way to initialize fc_cls and fc_reg is using Normal.

Sorry for the late respondence, 
you are right, we will fix asap 

Resolving patch:
diff --git a/mmdet/models/roi_heads/bbox_heads/convfc_bbox_head.py b/mmdet/models/roi_heads/bbox_heads/convfc_bbox_head.py
--- a/mmdet/models/roi_heads/bbox_heads/convfc_bbox_head.py
+++ b/mmdet/models/roi_heads/bbox_heads/convfc_bbox_head.py
@@ -97,10 +97,16 @@ def __init__(self,
                 out_features=out_dim_reg)
 
         if init_cfg is None:
+            # when init_cfg is None,
+            # It has been set to
+            # [[dict(type='Normal', std=0.01, override=dict(name='fc_cls'))],
+            #  [dict(type='Normal', std=0.001, override=dict(name='fc_reg'))]
+            # after `super(ConvFCBBoxHead, self).__init__()`
+            # we only need to append additional configuration
+            # for `shared_fcs`, `cls_fcs` and `reg_fcs`
             self.init_cfg += [
                 dict(
                     type='Xavier',
-                    layer='Linear',
                     override=[
                         dict(name='shared_fcs'),
                         dict(name='cls_fcs'),


Test patch:
Repository: open-mmlab/mmdetection

Issue:
[Bug]: Can not using custom loss when determine sampling by loss type.
This hardcode has caused some bugs when using custom loss.

https://github.com/open-mmlab/mmdetection/blob/2295154d0413a5d9df26579c56ef067be30e48b9/mmdet/models/dense_heads/anchor_head.py#L65-L68


Discussion:

Resolving patch:
diff --git a/mmdet/models/dense_heads/anchor_head.py b/mmdet/models/dense_heads/anchor_head.py
--- a/mmdet/models/dense_heads/anchor_head.py
+++ b/mmdet/models/dense_heads/anchor_head.py
@@ -1,4 +1,6 @@
 # Copyright (c) OpenMMLab. All rights reserved.
+import warnings
+
 import torch
 import torch.nn as nn
 from mmcv.runner import force_fp32
@@ -63,10 +65,6 @@ def __init__(self,
         self.num_classes = num_classes
         self.feat_channels = feat_channels
         self.use_sigmoid_cls = loss_cls.get('use_sigmoid', False)
-        # TODO better way to determine whether sample or not
-        self.sampling = loss_cls['type'] not in [
-            'FocalLoss', 'GHMC', 'QualityFocalLoss'
-        ]
         if self.use_sigmoid_cls:
             self.cls_out_channels = num_classes
         else:
@@ -83,10 +81,24 @@ def __init__(self,
         self.test_cfg = test_cfg
         if self.train_cfg:
             self.assigner = build_assigner(self.train_cfg.assigner)
-            # use PseudoSampler when sampling is False
-            if self.sampling and hasattr(self.train_cfg, 'sampler'):
+            if hasattr(self.train_cfg,
+                       'sampler') and self.train_cfg.sampler.type.split(
+                           '.')[-1] != 'PseudoSampler':
+                self.sampling = True
                 sampler_cfg = self.train_cfg.sampler
+                # avoid BC-breaking
+                if loss_cls['type'] in [
+                        'FocalLoss', 'GHMC', 'QualityFocalLoss'
+                ]:
+                    warnings.warn(
+                        'DeprecationWarning: Determining whether to sampling'
+                        'by loss type is deprecated, please delete sampler in'
+                        'your config when using `FocalLoss`, `GHMC`, '
+                        '`QualityFocalLoss` or other FocalLoss variant.')
+                    self.sampling = False
+                    sampler_cfg = dict(type='PseudoSampler')
             else:
+                self.sampling = False
                 sampler_cfg = dict(type='PseudoSampler')
             self.sampler = build_sampler(sampler_cfg, context=self)
         self.fp16_enabled = False


Test patch:
Repository: open-mmlab/mmdetection

Issue:
An editing error in the Tutorial Documentation
Thank you for ur contribution, I am a newbie to this project, maybe I found an editing error in the latest [Tutorial Documentation](https://mmdetection.readthedocs.io/en/latest/2_new_data_model.html). The detailed description is shown in the figure.

![图片](https://user-images.githubusercontent.com/23495527/140485815-7beba29e-b8f8-4309-96b8-300b74ee6d41.png)

it should be `python tools/test.py configs/balloon/mask_rcnn_r50_caffe_fpn_mstrain-poly_1x_balloon.py work_dirs/mask_rcnn_r50_caffe_fpn_mstrain-poly_1x_balloon/latest.pth --eval bbox segm`


Discussion:
Seems you are right, you can create a Pull Request to fix this error


Resolving patch:
diff --git a/tools/train.py b/tools/train.py
--- a/tools/train.py
+++ b/tools/train.py
@@ -112,6 +112,12 @@ def main():
     # init distributed env first, since logger depends on the dist info.
     if args.launcher == 'none':
         distributed = False
+        if len(cfg.gpu_ids) > 1:
+            warnings.warn(
+                f'We treat {cfg.gpu_ids} as gpu-ids, and reset to '
+                f'{cfg.gpu_ids[0:1]} as gpu-ids to avoid potential error in '
+                'non-distribute training time.')
+            cfg.gpu_ids = cfg.gpu_ids[0:1]
     else:
         distributed = True
         init_dist(args.launcher, **cfg.dist_params)


Test patch:
diff --git a/tools/test.py b/tools/test.py
--- a/tools/test.py
+++ b/tools/test.py
@@ -33,6 +33,12 @@ def parse_args():
         action='store_true',
         help='Whether to fuse conv and bn, this will slightly increase'
         'the inference speed')
+    parser.add_argument(
+        '--gpu-ids',
+        type=int,
+        nargs='+',
+        help='ids of gpus to use '
+        '(only applicable to non-distributed testing)')
     parser.add_argument(
         '--format-only',
         action='store_true',
@@ -155,9 +161,20 @@ def main():
             for ds_cfg in cfg.data.test:
                 ds_cfg.pipeline = replace_ImageToTensor(ds_cfg.pipeline)
 
+    if args.gpu_ids is not None:
+        cfg.gpu_ids = args.gpu_ids
+    else:
+        cfg.gpu_ids = range(1)
+
     # init distributed env first, since logger depends on the dist info.
     if args.launcher == 'none':
         distributed = False
+        if len(cfg.gpu_ids) > 1:
+            warnings.warn(
+                f'We treat {cfg.gpu_ids} as gpu-ids, and reset to '
+                f'{cfg.gpu_ids[0:1]} as gpu-ids to avoid potential error in '
+                'non-distribute testing time.')
+            cfg.gpu_ids = cfg.gpu_ids[0:1]
     else:
         distributed = True
         init_dist(args.launcher, **cfg.dist_params)
@@ -195,7 +212,7 @@ def main():
         model.CLASSES = dataset.CLASSES
 
     if not distributed:
-        model = MMDataParallel(model, device_ids=[0])
+        model = MMDataParallel(model, device_ids=cfg.gpu_ids)
         outputs = single_gpu_test(model, data_loader, args.show, args.show_dir,
                                   args.show_score_thr)
     else:
Repository: open-mmlab/mmdetection

Issue:
Wrong docs in BaseDetector forward_train()
In https://github.com/open-mmlab/mmdetection/blob/f3817df55709e4b13098ebaa9cf72a77b68ce994/mmdet/models/detectors/base.py?_pjax=%23js-repo-pjax-container%2C%20div%5Bitemtype%3D%22http%3A%2F%2Fschema.org%2FSoftwareSourceCode%22%5D%20main%2C%20%5Bdata-pjax-container%5D#L66

```python
   def forward_train(self, imgs, img_metas, **kwargs):
        """
        Args:
            img (list[Tensor]): List of tensors of shape (1, C, H, W).
                Typically these should be mean centered and std scaled.
```
The Arg imgs is described as list of tensors, however, when printing type(imgs), it returns ```<class 'torch.Tensor'>```
It seems that the docs in BaseDetector is not latest. 

I check the docs in TwoStageDetector, its description is correct
```python
    def forward_train(self,
                      img,
                      img_metas,
                      gt_bboxes,
                      gt_labels,
                      gt_bboxes_ignore=None,
                      gt_masks=None,
                      proposals=None,
                      **kwargs):
        """
        Args:
            img (Tensor): of shape (N, C, H, W) encoding input images.
                Typically these should be mean centered and std scaled.
```
https://github.com/open-mmlab/mmdetection/blob/5e246d5e3bc3310b5c625fb57bc03d2338ca39bc/mmdet/models/detectors/two_stage.py?_pjax=%23js-repo-pjax-container%2C%20div%5Bitemtype%3D%22http%3A%2F%2Fschema.org%2FSoftwareSourceCode%22%5D%20main%2C%20%5Bdata-pjax-container%5D#L101



Discussion:

Resolving patch:
diff --git a/mmdet/models/detectors/base.py b/mmdet/models/detectors/base.py
--- a/mmdet/models/detectors/base.py
+++ b/mmdet/models/detectors/base.py
@@ -63,7 +63,7 @@ def extract_feats(self, imgs):
     def forward_train(self, imgs, img_metas, **kwargs):
         """
         Args:
-            img (list[Tensor]): List of tensors of shape (1, C, H, W).
+            img (Tensor): of shape (N, C, H, W) encoding input images.
                 Typically these should be mean centered and std scaled.
             img_metas (list[dict]): List of image info dict where each dict
                 has: 'img_shape', 'scale_factor', 'flip', and may also contain


Test patch:
Repository: open-mmlab/mmdetection

Issue:
Confusion matrix error
While trying to generate the confusion matrix with this command:
```
python tools/analysis_tools/confusion_matrix.py ./work_dirs/perception-types--D06-01-2022--T09-23-45/perception-types.py results.pkl ./temp  --show
```
I ran into this error:
```
Traceback (most recent call last):
  File "tools/analysis_tools/confusion_matrix.py", line 261, in <module>
    main()
  File "tools/analysis_tools/confusion_matrix.py", line 257, in main
    show=args.show)
  File "tools/analysis_tools/confusion_matrix.py", line 210, in plot_confusion_matrix
    '{}%'.format(int(confusion_matrix[i, j])),
ValueError: cannot convert float NaN to integer
```
Would appreciate any help or suggestions! Thanks



Discussion:
I ran into the same problem so I would appreciate if someone could help us with this.
Thanks for reporting the bug. We will fix it asap.

Resolving patch:
diff --git a/tools/analysis_tools/confusion_matrix.py b/tools/analysis_tools/confusion_matrix.py
--- a/tools/analysis_tools/confusion_matrix.py
+++ b/tools/analysis_tools/confusion_matrix.py
@@ -207,7 +207,10 @@ def plot_confusion_matrix(confusion_matrix,
             ax.text(
                 j,
                 i,
-                '{}%'.format(int(confusion_matrix[i, j])),
+                '{}%'.format(
+                    int(confusion_matrix[
+                        i,
+                        j]) if not np.isnan(confusion_matrix[i, j]) else -1),
                 ha='center',
                 va='center',
                 color='w',


Test patch:
Repository: open-mmlab/mmdetection

Issue:
FileNotFoundError: img file does not exist: tools/deployment/../demo/demo.jpg
```
Traceback (most recent call last):
  File "tools/deployment/onnx2tensorrt.py", line 255, in <module>
    verbose=args.verbose)
  File "tools/deployment/onnx2tensorrt.py", line 54, in onnx2tensorrt
    one_img, one_meta = preprocess_example_input(input_config)
  File "/workspace/mmdetection-2.18.1/mmdet/core/export/pytorch2onnx.py", line 139, in preprocess_example_input
    one_img = mmcv.imread(input_path)
  File "/workspace/mmcv-1.3.17-trt/mmcv/image/io.py", line 177, in imread
    f'img file does not exist: {img_or_path}')
  File "/workspace/mmcv-1.3.17-trt/mmcv/utils/path.py", line 23, in check_file_exist
    raise FileNotFoundError(msg_tmpl.format(filename))
FileNotFoundError: img file does not exist: tools/deployment/../demo/demo.jpg
```


Discussion:

Resolving patch:
diff --git a/tools/deployment/onnx2tensorrt.py b/tools/deployment/onnx2tensorrt.py
--- a/tools/deployment/onnx2tensorrt.py
+++ b/tools/deployment/onnx2tensorrt.py
@@ -201,7 +201,7 @@ def parse_args():
         parsed directly from config file and are deprecated and will be \
         removed in future releases.')
     if not args.input_img:
-        args.input_img = osp.join(osp.dirname(__file__), '../demo/demo.jpg')
+        args.input_img = osp.join(osp.dirname(__file__), '../../demo/demo.jpg')
 
     cfg = Config.fromfile(args.config)
 


Test patch: