{"record":{"id":"0137fcfc2282eef4","repo":"WZMIAOMIAO/deep-learning-for-image-processing","slug":"in-training-mode-targets-should-be-passed-0137fc","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/ssd/src/ssd_model.py","lineNumber":123,"sourceCode":"    def forward(self, image, targets=None):\n        x = self.feature_extractor(image)\n\n        # Feature Map 38x38x1024, 19x19x512, 10x10x512, 5x5x256, 3x3x256, 1x1x256\n        detection_features = torch.jit.annotate(List[Tensor], [])  # [x]\n        detection_features.append(x)\n        for layer in self.additional_blocks:\n            x = layer(x)\n            detection_features.append(x)\n\n        # Feature Map 38x38x4, 19x19x6, 10x10x6, 5x5x6, 3x3x4, 1x1x4\n        locs, confs = self.bbox_view(detection_features, self.loc, self.conf)\n\n        # For SSD 300, shall return nbatch x 8732 x {nlabels, nlocs} results\n        # 38x38x4 + 19x19x6 + 10x10x6 + 5x5x6 + 3x3x4 + 1x1x4 = 8732\n\n        if self.training:\n            if targets is None:\n                raise ValueError(\"In training mode, targets should be passed\")\n            # bboxes_out (Tensor 8732 x 4), labels_out (Tensor 8732)\n            bboxes_out = targets['boxes']\n            bboxes_out = bboxes_out.transpose(1, 2).contiguous()\n            # print(bboxes_out.is_contiguous())\n            labels_out = targets['labels']\n            # print(labels_out.is_contiguous())\n\n            # ploc, plabel, gloc, glabel\n            loss = self.compute_loss(locs, confs, bboxes_out, labels_out)\n            return {\"total_losses\": loss}\n\n        # 将预测回归参数叠加到default box上得到最终预测box，并执行非极大值抑制虑除重叠框\n        # results = self.encoder.decode_batch(locs, confs)\n        results = self.postprocess(locs, confs)\n        return results\n\n\nclass Loss(nn.Module):","sourceCodeStart":105,"sourceCodeEnd":141,"githubUrl":"https://github.com/WZMIAOMIAO/deep-learning-for-image-processing/blob/1ec3fe6f374fc9969973a61f819de25658595afa/pytorch_object_detection/ssd/src/ssd_model.py#L105-L141","documentation":"SSD300.forward in training mode requires a targets dict with 'boxes' and 'labels' to compute the multibox loss; if targets is None it raises ValueError. In eval mode targets are optional, so this error specifically means train() mode with inference-style call.","triggerScenarios":"Calling model(images) during training without passing targets argument; forgetting to build the targets dict {boxes, labels} in the training loop; leaving the model in train() mode while doing validation.","commonSituations":"Copying an eval-time forward call into the training loop; dataloader collate_fn dropping targets; running model.train() during sanity-check inference.","solutions":["Call model(images, targets=targets) in the training loop with targets = {'boxes': ..., 'labels': ...}\nUse model.eval() when running inference without targets\nEnsure custom collate_fn returns both images and targets and neither is None"],"exampleFix":"// before\npredictions = model(images)  # in train mode\n// after\ntargets = [{'boxes': b, 'labels': l} for b, l in batch]\nloss = model(images, targets=targets)","handlingStrategy":"validation","validationCode":"if model.training:\n    assert targets is not None and 'boxes' in targets and 'labels' in targets, 'train forward needs targets'","typeGuard":"def has_targets(targets) -> bool:\n    return isinstance(targets, dict) and 'boxes' in targets and 'labels' in targets","tryCatchPattern":"try:\n    losses = model(images, targets=targets)\nexcept ValueError as e:\n    print(f'Forward misused: {e}; pass targets in train mode')","preventionTips":["Switch to model.eval() for any inference without targets","Keep training loop signature model(images, targets) consistent","Validate dataloader collate_fn returns non-None targets"],"tags":["pytorch","ssd","training-mode","forward","api-misuse"],"backgroundTag":"missing-training-targets","analyzedSha":"1ec3fe6f374fc9969973a61f819de25658595afa","analyzedAt":"2026-08-30T09:19:11.901Z","schemaVersion":2},"datasetVersion":"2026-08-30T13:17:10.514Z"}