WZMIAOMIAO/deep-learning-for-image-processing · error · ValueError

In training mode, targets should be passed

Error message

In training mode, targets should be passed

What it means

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.

Source

Thrown at pytorch_object_detection/ssd/src/ssd_model.py:123

    def forward(self, image, targets=None):
        x = self.feature_extractor(image)

        # Feature Map 38x38x1024, 19x19x512, 10x10x512, 5x5x256, 3x3x256, 1x1x256
        detection_features = torch.jit.annotate(List[Tensor], [])  # [x]
        detection_features.append(x)
        for layer in self.additional_blocks:
            x = layer(x)
            detection_features.append(x)

        # Feature Map 38x38x4, 19x19x6, 10x10x6, 5x5x6, 3x3x4, 1x1x4
        locs, confs = self.bbox_view(detection_features, self.loc, self.conf)

        # For SSD 300, shall return nbatch x 8732 x {nlabels, nlocs} results
        # 38x38x4 + 19x19x6 + 10x10x6 + 5x5x6 + 3x3x4 + 1x1x4 = 8732

        if self.training:
            if targets is None:
                raise ValueError("In training mode, targets should be passed")
            # bboxes_out (Tensor 8732 x 4), labels_out (Tensor 8732)
            bboxes_out = targets['boxes']
            bboxes_out = bboxes_out.transpose(1, 2).contiguous()
            # print(bboxes_out.is_contiguous())
            labels_out = targets['labels']
            # print(labels_out.is_contiguous())

            # ploc, plabel, gloc, glabel
            loss = self.compute_loss(locs, confs, bboxes_out, labels_out)
            return {"total_losses": loss}

        # 将预测回归参数叠加到default box上得到最终预测box,并执行非极大值抑制虑除重叠框
        # results = self.encoder.decode_batch(locs, confs)
        results = self.postprocess(locs, confs)
        return results


class Loss(nn.Module):

View on GitHub (pinned to 1ec3fe6f37)

Solutions

  1. Call model(images, targets=targets) in the training loop with targets = {'boxes': ..., 'labels': ...} Use model.eval() when running inference without targets Ensure custom collate_fn returns both images and targets and neither is None

Example fix

// before
predictions = model(images)  # in train mode
// after
targets = [{'boxes': b, 'labels': l} for b, l in batch]
loss = model(images, targets=targets)
Defensive patterns

Strategy: validation

Validate before calling

if model.training:
    assert targets is not None and 'boxes' in targets and 'labels' in targets, 'train forward needs targets'

Type guard

def has_targets(targets) -> bool:
    return isinstance(targets, dict) and 'boxes' in targets and 'labels' in targets

Try / catch

try:
    losses = model(images, targets=targets)
except ValueError as e:
    print(f'Forward misused: {e}; pass targets in train mode')

Prevention

When it happens

Trigger: 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.

Common situations: Copying an eval-time forward call into the training loop; dataloader collate_fn dropping targets; running model.train() during sanity-check inference.

Related errors


AI-assisted analysis of WZMIAOMIAO/deep-learning-for-image-processing@1ec3fe6f37 (2026-08-30). Data as JSON: /api/errors/0137fcfc2282eef4. Report an issue: GitHub.