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

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.

Source

Thrown at pytorch_object_detection/retinaNet/network_files/retinanet.py:455

        return detections

    def forward(self, images, targets=None):
        # type: (List[Tensor], Optional[List[Dict[str, Tensor]]]) -> Tuple[Dict[str, Tensor], List[Dict[str, Tensor]]]
        """
        Args:
            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
            # check targets info
            for target in targets:
                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)))

        # get the original images sizes
        original_img_sizes: List[Tuple[int, int]] = []
        for img in images:
            val = img.shape[-2:]

View on GitHub (pinned to 1ec3fe6f37)

Solutions

  1. Pass targets: model(images, targets) with a list of dicts containing 'boxes' and 'labels'.
  2. Call model.eval() before any inference/validation forward pass (also fixes BatchNorm/Dropout behavior).
  3. In custom loops, branch: losses = model(images, targets) if training else model(images).
  4. Ensure your DataLoader collate actually returns targets (check batch dict keys).

Example fix

// before
model.train()
outputs = model(images)  # ValueError
// after
model.train()
outputs = model(images, targets)  # targets = [{'boxes': ..., 'labels': ...}, ...]
Defensive patterns

Strategy: try-catch

Validate before calling

if model.training and targets is None:
    raise RuntimeError("targets required in training mode; call model.eval() for inference")

Type guard

def ready_for_forward(model, images, targets) -> bool:
    import torch
    if model.training:
        return targets is not None and len(targets) == len(images)
    return True

Try / catch

try:
    outputs = model(images, targets if model.training else None)
except ValueError as e:
    if "targets should be passed" in str(e):
        model.eval()
        with torch.no_grad():
            outputs = model(images)
    else:
        raise

Prevention

When it happens

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

Common situations: 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.

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/9aee804d695f593c. Report an issue: GitHub.