WZMIAOMIAO/deep-learning-for-image-processing · error · ValueError

if in training, matched_idxs should not be None

Error message

if in training, matched_idxs should not be None

What it means

In training mode, RoIHeads.forward needs matched_idxs — the ground-truth indices produced by proposal matching in select_training_samples — to isolate positive proposals for the mask branch. If self.training is True but matched_idxs was not passed, the head cannot recover which proposals are positives and raises ValueError.

Source

Thrown at pytorch_object_detection/mask_rcnn/network_files/roi_head.py:526

            }
        else:
            boxes, scores, labels = self.postprocess_detections(class_logits, box_regression, proposals, image_shapes)
            num_images = len(boxes)
            for i in range(num_images):
                result.append(
                    {
                        "boxes": boxes[i],
                        "labels": labels[i],
                        "scores": scores[i],
                    }
                )

        if self.has_mask():
            mask_proposals = [p["boxes"] for p in result]  # 将最终预测的Boxes信息取出
            if self.training:
                # matched_idxs为每个proposal在正负样本匹配过程中得到的gt索引(背景的gt索引也默认设置成了0)
                if matched_idxs is None:
                    raise ValueError("if in training, matched_idxs should not be None")

                # during training, only focus on positive boxes
                num_images = len(proposals)
                mask_proposals = []
                pos_matched_idxs = []
                for img_id in range(num_images):
                    pos = torch.where(labels[img_id] > 0)[0]  # 寻找对应gt类别大于0,即正样本
                    mask_proposals.append(proposals[img_id][pos])
                    pos_matched_idxs.append(matched_idxs[img_id][pos])
            else:
                pos_matched_idxs = None

            mask_features = self.mask_roi_pool(features, mask_proposals, image_shapes)
            mask_features = self.mask_head(mask_features)
            mask_logits = self.mask_predictor(mask_features)

            loss_mask = {}
            if self.training:

View on GitHub (pinned to 1ec3fe6f37)

Solutions

  1. Call the model's full forward (MaskRCNN(images, targets)) instead of invoking roi_heads.forward directly in training
  2. If calling roi_heads.forward manually, pass the matched_idxs returned by select_training_samples
  3. Set model.eval() if you only intend to run inference so the training branch is skipped

Example fix

// before
result, losses = model.roi_heads(images, detections, image_shapes, targets)
// after
proposals, losses = model.roi_heads.select_training_samples(proposals, targets)
result, loss_dict = model.roi_heads(images, detections, image_shapes, targets, matched_idxs)  # pass matched_idxs from select_training_samples
Defensive patterns

Strategy: validation

Validate before calling

assert matched_idxs is not None or not roi_heads.training, "matched_idxs required in training"
result, losses = roi_heads(images, detections, shapes, targets, matched_idxs)

Type guard

def can_forward_roi_heads(roi_heads, matched_idxs):
    return not roi_heads.training or matched_idxs is not None

Try / catch

try:
    out = roi_heads(images, detections, shapes, targets, matched_idxs)
except ValueError as e:
    if 'matched_idxs' in str(e): raise RuntimeError('call select_training_samples first') from e
    raise

Prevention

When it happens

Trigger: Calling RoIHeads.forward(images, detections, image_shapes, targets) directly with self.training=True and matched_idxs omitted (default None).

Common situations: Subclassing or directly invoking RoIHeads in a custom training loop; bypassing the top-level MaskRCNN.forward that normally wires matched_idxs through.

Understand the failure class

Background: "missing required argument" and "the following required arguments were not provided": what required-argument errors mean and how to fix them — this error's family across 20 libraries.

Related errors


AI-assisted analysis of WZMIAOMIAO/deep-learning-for-image-processing@1ec3fe6f37 (2026-08-30). Data as JSON: /api/errors/3267a8753ab945bf. Report an issue: GitHub.