{"record":{"id":"389042055d5ddb09","repo":"WZMIAOMIAO/deep-learning-for-image-processing","slug":"in-training-mode-targets-should-be-passed","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/faster_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/faster_rcnn/network_files/faster_rcnn_framework.py#L42-L78","documentation":"FasterRCNN.forward requires a `targets` list when the module is in training mode (self.training == True); calling it with targets=None raises this ValueError. During training the model must compute losses against ground-truth boxes/labels, which is impossible without targets.","triggerScenarios":"Calling model(images) without the second argument (or passing None) after model.train(), e.g. forgetting to unpack both outputs of the dataloader: for images in loader instead of for images, targets in loader.","commonSituations":"Copy-pasting inference code into a training loop, forgetting model.eval() before inference-only calls, or a dataloader yielding only images because the dataset doesn't return targets.","solutions":["Ensure the model is in eval mode (model.eval()) if you only want predictions.","In the training loop, unpack and pass targets: loss_dict = model(images, targets).","Verify the dataset/collate_fn returns (image, target) pairs and targets is a list of dicts with 'boxes' and 'labels'.","Wrap targets=None cases: skip training steps where targets are missing."],"exampleFix":"# before\nfor images in train_loader:\n    loss_dict = model(images)\n# after\nfor images, targets in train_loader:\n    loss_dict = model(images, targets)","handlingStrategy":"validation","validationCode":"if model.training:\n    assert targets is not None and isinstance(targets, list) and len(targets) == len(images), \"targets required in training mode\"","typeGuard":"def has_targets(batch) -> bool:\n    images, targets = batch\n    return targets is not None and len(targets) == len(images) and all('boxes' in t and 'labels' in t for t in targets)","tryCatchPattern":"try:\n    loss_dict = model(images, targets)\nexcept ValueError as e:\n    if 'targets should be passed' in str(e):\n        raise RuntimeError('Training loop must supply targets; use model.eval() for inference') from e\n    raise","preventionTips":["Unpack both images and targets from the dataloader in training loops","Switch to model.eval() before any inference call","Ensure the dataset returns (image, target) pairs","Never call a model in train() mode without targets"],"tags":["training","targets","api-misuse","faster-rcnn"],"backgroundTag":"missing-targets-in-training","analyzedSha":"1ec3fe6f374fc9969973a61f819de25658595afa","analyzedAt":"2026-08-30T09:19:11.901Z","schemaVersion":2},"datasetVersion":"2026-08-30T13:17:10.514Z"}