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

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.

Source

Thrown at pytorch_object_detection/mask_rcnn/network_files/faster_rcnn_framework.py:60

        return detections

    def forward(self, images, targets=None):
        # type: (List[Tensor], Optional[List[Dict[str, Tensor]]]) -> Tuple[Dict[str, Tensor], List[Dict[str, Tensor]]]
        """
        Arguments:
            images (list[Tensor]): images to be processed
            targets (list[Dict[Tensor]]): ground-truth boxes present in the image (optional)

        Returns:
            result (list[BoxList] or dict[Tensor]): the output from the model.
                During training, it returns a dict[Tensor] which contains the losses.
                During testing, it returns list[BoxList] contains additional fields
                like `scores`, `labels` and `mask` (for Mask R-CNN models).

        """
        if self.training and targets is None:
            raise ValueError("In training mode, targets should be passed")

        if self.training:
            assert targets is not None
            for target in targets:         # 进一步判断传入的target的boxes参数是否符合规定
                boxes = target["boxes"]
                if isinstance(boxes, torch.Tensor):
                    if len(boxes.shape) != 2 or boxes.shape[-1] != 4:
                        raise ValueError("Expected target boxes to be a tensor"
                                         "of shape [N, 4], got {:}.".format(
                                          boxes.shape))
                else:
                    raise ValueError("Expected target boxes to be of type "
                                     "Tensor, got {:}.".format(type(boxes)))

        original_image_sizes = torch.jit.annotate(List[Tuple[int, int]], [])
        for img in images:
            val = img.shape[-2:]
            assert len(val) == 2  # 防止输入的是个一维向量

View on GitHub (pinned to 1ec3fe6f37)

Solutions

  1. Pass a list of target dicts with 'boxes' and 'labels' tensors when training: model(images, targets)
  2. Call model.eval() before inference so targets are not required
  3. In custom loops, branch on model.training to decide whether to supply targets

Example fix

// before
model.train()
losses = model(images)  # targets missing
// after
model.train()
losses = model(images, targets)  # each target: {'boxes': Tensor[N,4], 'labels': Tensor[N]}
// or for inference
model.eval()
outputs = model(images)
Defensive patterns

Strategy: try-catch

Validate before calling

if model.training:
    assert targets is not None and len(targets) == len(images), 'training forward needs one target per image'

Try / catch

try:
    out = model(images, targets if model.training else None)
except ValueError as e:
    if 'targets should be passed' in str(e):
        raise RuntimeError('call model.eval() for inference or supply targets for training') from e
    raise

Prevention

When it happens

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

Common situations: Reusing inference code paths in training; copying eval scripts but leaving model.train() active; building a custom training loop that omits targets.

Understand the failure class

Background: "missing required argument" and "the following required arguments were not provided": what required-argument errors mean and how to fix them — this error's family across 20 libraries.

Related errors


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