{"record":{"id":"3267a8753ab945bf","repo":"WZMIAOMIAO/deep-learning-for-image-processing","slug":"if-in-training-matched-idxs-should-not-be-none","errorCode":null,"errorMessage":"if in training, matched_idxs should not be None","messagePattern":"if in training, matched_idxs should not be None","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"pytorch_object_detection/mask_rcnn/network_files/roi_head.py","lineNumber":526,"sourceCode":"            }\n        else:\n            boxes, scores, labels = self.postprocess_detections(class_logits, box_regression, proposals, image_shapes)\n            num_images = len(boxes)\n            for i in range(num_images):\n                result.append(\n                    {\n                        \"boxes\": boxes[i],\n                        \"labels\": labels[i],\n                        \"scores\": scores[i],\n                    }\n                )\n\n        if self.has_mask():\n            mask_proposals = [p[\"boxes\"] for p in result]  # 将最终预测的Boxes信息取出\n            if self.training:\n                # matched_idxs为每个proposal在正负样本匹配过程中得到的gt索引(背景的gt索引也默认设置成了0)\n                if matched_idxs is None:\n                    raise ValueError(\"if in training, matched_idxs should not be None\")\n\n                # during training, only focus on positive boxes\n                num_images = len(proposals)\n                mask_proposals = []\n                pos_matched_idxs = []\n                for img_id in range(num_images):\n                    pos = torch.where(labels[img_id] > 0)[0]  # 寻找对应gt类别大于0，即正样本\n                    mask_proposals.append(proposals[img_id][pos])\n                    pos_matched_idxs.append(matched_idxs[img_id][pos])\n            else:\n                pos_matched_idxs = None\n\n            mask_features = self.mask_roi_pool(features, mask_proposals, image_shapes)\n            mask_features = self.mask_head(mask_features)\n            mask_logits = self.mask_predictor(mask_features)\n\n            loss_mask = {}\n            if self.training:","sourceCodeStart":508,"sourceCodeEnd":544,"githubUrl":"https://github.com/WZMIAOMIAO/deep-learning-for-image-processing/blob/1ec3fe6f374fc9969973a61f819de25658595afa/pytorch_object_detection/mask_rcnn/network_files/roi_head.py#L508-L544","documentation":"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.","triggerScenarios":"Calling RoIHeads.forward(images, detections, image_shapes, targets) directly with self.training=True and matched_idxs omitted (default None).","commonSituations":"Subclassing or directly invoking RoIHeads in a custom training loop; bypassing the top-level MaskRCNN.forward that normally wires matched_idxs through.","solutions":["Call the model's full forward (MaskRCNN(images, targets)) instead of invoking roi_heads.forward directly in training","If calling roi_heads.forward manually, pass the matched_idxs returned by select_training_samples","Set model.eval() if you only intend to run inference so the training branch is skipped"],"exampleFix":"// before\nresult, losses = model.roi_heads(images, detections, image_shapes, targets)\n// after\nproposals, losses = model.roi_heads.select_training_samples(proposals, targets)\nresult, loss_dict = model.roi_heads(images, detections, image_shapes, targets, matched_idxs)  # pass matched_idxs from select_training_samples","handlingStrategy":"validation","validationCode":"assert matched_idxs is not None or not roi_heads.training, \"matched_idxs required in training\"\nresult, losses = roi_heads(images, detections, shapes, targets, matched_idxs)","typeGuard":"def can_forward_roi_heads(roi_heads, matched_idxs):\n    return not roi_heads.training or matched_idxs is not None","tryCatchPattern":"try:\n    out = roi_heads(images, detections, shapes, targets, matched_idxs)\nexcept ValueError as e:\n    if 'matched_idxs' in str(e): raise RuntimeError('call select_training_samples first') from e\n    raise","preventionTips":["Prefer the top-level model.forward over calling roi_heads directly","Always consume the full return of select_training_samples","Keep custom training loops mirroring torchvision's TwoMGPTrainer flow"],"tags":["python","mask-rcnn","training"],"backgroundTag":"missing-required-argument","analyzedSha":"1ec3fe6f374fc9969973a61f819de25658595afa","analyzedAt":"2026-08-30T09:19:11.901Z","schemaVersion":2},"datasetVersion":"2026-08-30T13:17:10.514Z"}