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 module is in training mode (self.training == True); calling it with targets=None raises this ValueError. During training the model must compute losses against ground-truth boxes/labels, which is impossible without targets.
Source
Thrown at pytorch_object_detection/faster_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
- Ensure the model is in eval mode (model.eval()) if you only want predictions.
- In the training loop, unpack and pass targets: loss_dict = model(images, targets).
- Verify the dataset/collate_fn returns (image, target) pairs and targets is a list of dicts with 'boxes' and 'labels'.
- Wrap targets=None cases: skip training steps where targets are missing.
Example fix
# before
for images in train_loader:
loss_dict = model(images)
# after
for images, targets in train_loader:
loss_dict = model(images, targets) Defensive patterns
Strategy: validation
Validate before calling
if model.training:
assert targets is not None and isinstance(targets, list) and len(targets) == len(images), "targets required in training mode" Type guard
def has_targets(batch) -> bool:
images, targets = batch
return targets is not None and len(targets) == len(images) and all('boxes' in t and 'labels' in t for t in targets) Try / catch
try:
loss_dict = model(images, targets)
except ValueError as e:
if 'targets should be passed' in str(e):
raise RuntimeError('Training loop must supply targets; use model.eval() for inference') from e
raise Prevention
- Unpack both images and targets from the dataloader in training loops
- Switch to model.eval() before any inference call
- Ensure the dataset returns (image, target) pairs
- Never call a model in train() mode without targets
When it happens
Trigger: Calling model(images) without the second argument (or passing None) after model.train(), e.g. forgetting to unpack both outputs of the dataloader: for images in loader instead of for images, targets in loader.
Common situations: Copy-pasting inference code into a training loop, forgetting model.eval() before inference-only calls, or a dataloader yielding only images because the dataset doesn't return targets.
Related errors
- Expected target boxes to be a tensorof shape [N, 4], got {:}
- Expected target boxes to be of type Tensor, got {:}.
- num_classes should be None when box_predictor is specified
- In training mode, targets should be passed
- In training mode, targets should be passed
AI-assisted analysis of WZMIAOMIAO/deep-learning-for-image-processing@1ec3fe6f37 (2026-08-30).
Data as JSON: /api/errors/389042055d5ddb09.
Report an issue: GitHub.