{"record":{"id":"da2ac1b89cdd704d","repo":"WZMIAOMIAO/deep-learning-for-image-processing","slug":"in-training-mode-targets-should-be-passed-da2ac1","errorCode":null,"errorMessage":"In training mode, targets should be passed","messagePattern":"In training mode, targets should be passed","errorType":"validation","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"pytorch_object_detection/mask_rcnn/network_files/faster_rcnn_framework.py","lineNumber":60,"sourceCode":"\n        return detections\n\n    def forward(self, images, targets=None):\n        # type: (List[Tensor], Optional[List[Dict[str, Tensor]]]) -> Tuple[Dict[str, Tensor], List[Dict[str, Tensor]]]\n        \"\"\"\n        Arguments:\n            images (list[Tensor]): images to be processed\n            targets (list[Dict[Tensor]]): ground-truth boxes present in the image (optional)\n\n        Returns:\n            result (list[BoxList] or dict[Tensor]): the output from the model.\n                During training, it returns a dict[Tensor] which contains the losses.\n                During testing, it returns list[BoxList] contains additional fields\n                like `scores`, `labels` and `mask` (for Mask R-CNN models).\n\n        \"\"\"\n        if self.training and targets is None:\n            raise ValueError(\"In training mode, targets should be passed\")\n\n        if self.training:\n            assert targets is not None\n            for target in targets:         # 进一步判断传入的target的boxes参数是否符合规定\n                boxes = target[\"boxes\"]\n                if isinstance(boxes, torch.Tensor):\n                    if len(boxes.shape) != 2 or boxes.shape[-1] != 4:\n                        raise ValueError(\"Expected target boxes to be a tensor\"\n                                         \"of shape [N, 4], got {:}.\".format(\n                                          boxes.shape))\n                else:\n                    raise ValueError(\"Expected target boxes to be of type \"\n                                     \"Tensor, got {:}.\".format(type(boxes)))\n\n        original_image_sizes = torch.jit.annotate(List[Tuple[int, int]], [])\n        for img in images:\n            val = img.shape[-2:]\n            assert len(val) == 2  # 防止输入的是个一维向量","sourceCodeStart":42,"sourceCodeEnd":78,"githubUrl":"https://github.com/WZMIAOMIAO/deep-learning-for-image-processing/blob/1ec3fe6f374fc9969973a61f819de25658595afa/pytorch_object_detection/mask_rcnn/network_files/faster_rcnn_framework.py#L42-L78","documentation":"FasterRCNN.forward requires a targets list when the model is in training mode, because training computes losses that need ground-truth boxes/labels. Calling forward with targets=None while self.training is True raises this ValueError before any processing.","triggerScenarios":"Calling model(images) without the second argument after model.train(); forgetting to switch to model.eval() for inference; passing targets=None explicitly during a training loop.","commonSituations":"Reusing inference code paths in training; copying eval scripts but leaving model.train() active; building a custom training loop that omits targets.","solutions":["Pass a list of target dicts with 'boxes' and 'labels' tensors when training: model(images, targets)","Call model.eval() before inference so targets are not required","In custom loops, branch on model.training to decide whether to supply targets"],"exampleFix":"// before\nmodel.train()\nlosses = model(images)  # targets missing\n// after\nmodel.train()\nlosses = model(images, targets)  # each target: {'boxes': Tensor[N,4], 'labels': Tensor[N]}\n// or for inference\nmodel.eval()\noutputs = model(images)","handlingStrategy":"try-catch","validationCode":"if model.training:\n    assert targets is not None and len(targets) == len(images), 'training forward needs one target per image'","typeGuard":null,"tryCatchPattern":"try:\n    out = model(images, targets if model.training else None)\nexcept ValueError as e:\n    if 'targets should be passed' in str(e):\n        raise RuntimeError('call model.eval() for inference or supply targets for training') from e\n    raise","preventionTips":["Always pair model.train() with target-bearing forward calls and model.eval() with inference","In training loops, zip(images, targets) so counts stay aligned","Add a loop-level assertion that targets is a non-empty list when training"],"tags":["pytorch","training","api-misuse"],"backgroundTag":"missing-required-argument","analyzedSha":"1ec3fe6f374fc9969973a61f819de25658595afa","analyzedAt":"2026-08-30T09:19:11.901Z","schemaVersion":2},"datasetVersion":"2026-08-30T13:17:10.514Z"}