{"record":{"id":"9aee804d695f593c","repo":"WZMIAOMIAO/deep-learning-for-image-processing","slug":"in-training-mode-targets-should-be-passed-9aee80","errorCode":null,"errorMessage":"In training mode, targets should be passed","messagePattern":"In training mode, targets should be passed","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"pytorch_object_detection/retinaNet/network_files/retinanet.py","lineNumber":455,"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        Args:\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            # check targets info\n            for target in targets:\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(boxes.shape))\n                else:\n                    raise ValueError(\"Expected target boxes to be of type \"\n                                     \"Tensor, got {:}.\".format(type(boxes)))\n\n        # get the original images sizes\n        original_img_sizes: List[Tuple[int, int]] = []\n        for img in images:\n            val = img.shape[-2:]","sourceCodeStart":437,"sourceCodeEnd":473,"githubUrl":"https://github.com/WZMIAOMIAO/deep-learning-for-image-processing/blob/1ec3fe6f374fc9969973a61f819de25658595afa/pytorch_object_detection/retinaNet/network_files/retinanet.py#L437-L473","documentation":"RetinaNet.forward checks that when the model is in training mode (self.training True) the targets argument is not None, because losses cannot be computed without ground-truth boxes/labels. Calling the model in train mode without targets is treated as a programming error and raises ValueError immediately.","triggerScenarios":"model.train() followed by model(images) without targets; computing train-loss outside the trainer; calling forward on a model left in train mode during validation/inference (forgetting model.eval()).","commonSituations":"Validation loops that forget model.eval(); inference scripts reusing a training checkpoint module still in train mode; custom training loops calling the model with only images; frameworks like Lightning forwarding batches that lack the targets key.","solutions":["Pass targets: model(images, targets) with a list of dicts containing 'boxes' and 'labels'.","Call model.eval() before any inference/validation forward pass (also fixes BatchNorm/Dropout behavior).","In custom loops, branch: losses = model(images, targets) if training else model(images).","Ensure your DataLoader collate actually returns targets (check batch dict keys)."],"exampleFix":"// before\nmodel.train()\noutputs = model(images)  # ValueError\n// after\nmodel.train()\noutputs = model(images, targets)  # targets = [{'boxes': ..., 'labels': ...}, ...]","handlingStrategy":"try-catch","validationCode":"if model.training and targets is None:\n    raise RuntimeError(\"targets required in training mode; call model.eval() for inference\")","typeGuard":"def ready_for_forward(model, images, targets) -> bool:\n    import torch\n    if model.training:\n        return targets is not None and len(targets) == len(images)\n    return True","tryCatchPattern":"try:\n    outputs = model(images, targets if model.training else None)\nexcept ValueError as e:\n    if \"targets should be passed\" in str(e):\n        model.eval()\n        with torch.no_grad():\n            outputs = model(images)\n    else:\n        raise","preventionTips":["Call model.eval() before every validation/inference loop.","Assert batch targets are present in custom training loops.","Ensure DataLoader batches include the targets key.","Wrap training/eval forward paths in separate helper functions."],"tags":["pytorch","object-detection","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"}