WZMIAOMIAO/deep-learning-for-image-processing · critical · ValueError
target should not be None.
Error message
target should not be None.
What it means
During training, ROIHeads.select_training_samples needs ground-truth targets to match proposals against and compute classification/box losses. The code checks targets via check_targets first, then raises ValueError if the targets argument itself is None, since training cannot proceed without annotations.
Source
Thrown at pytorch_object_detection/mask_rcnn/network_files/roi_head.py:322
proposals, # type: List[Tensor]
targets # type: Optional[List[Dict[str, Tensor]]]
):
# type: (...) -> Tuple[List[Tensor], List[Tensor], List[Tensor], List[Tensor]]
"""
划分正负样本,统计对应gt的标签以及边界框回归信息
list元素个数为batch_size
Args:
proposals: rpn预测的boxes
targets:
Returns:
"""
# 检查target数据是否为空
self.check_targets(targets)
if targets is None:
raise ValueError("target should not be None.")
dtype = proposals[0].dtype
device = proposals[0].device
# 获取标注好的boxes以及labels信息
gt_boxes = [t["boxes"].to(dtype) for t in targets]
gt_labels = [t["labels"] for t in targets]
# append ground-truth bboxes to proposal
# 将gt_boxes拼接到proposal后面
proposals = self.add_gt_proposals(proposals, gt_boxes)
# get matching gt indices for each proposal
# 为每个proposal匹配对应的gt_box,并划分到正负样本中
matched_idxs, labels = self.assign_targets_to_proposals(proposals, gt_boxes, gt_labels)
# sample a fixed proportion of positive-negative proposals
# 按给定数量和比例采样正负样本
sampled_inds = self.subsample(labels)View on GitHub (pinned to 1ec3fe6f37)
Solutions
- Pass a non-None list of target dicts (with 'boxes' and 'labels') in training mode
- Verify the dataloader actually yields targets and filters out empty samples
- Only omit targets during inference under torch.no_grad() with model.eval()
Example fix
// before
loss_dict = model(images)
// after
loss_dict = model(images, targets) # targets = [{'boxes': ..., 'labels': ..., 'masks': ...}] Defensive patterns
Strategy: validation
Validate before calling
if model.training:
assert targets is not None and all('boxes' in t and 'labels' in t for t in targets), "targets required in train mode"
losses = model(images, targets) Type guard
def has_valid_targets(targets):
return targets is not None and isinstance(targets, list) and all(isinstance(t, dict) and 'boxes' in t for t in targets) Try / catch
try:
losses = model(images, targets)
except ValueError as e:
if 'target' in str(e): targets = load_targets(batch)
raise Prevention
- Never call a detection model in train() mode without targets
- Filter out unlabeled samples in the dataset __getitem__
- Use model.eval() for inference-only paths
When it happens
Trigger: Calling model(images) in train() mode (model.train()) without passing targets, e.g. model(images) instead of model(images, targets).
Common situations: Forgetting to pass targets in the training loop; a dataloader returning None targets for unlabeled samples; reusing inference code for training.
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
- if in training, matched_idxs should not be None
- targets, pos_matched_idxs, mask_logits cannot be None when t
- num_classes should be None when mask_predictor is specified
- expected stages_repeats as list of 3 positive ints
- expected stages_out_channels as list of 5 positive ints
AI-assisted analysis of WZMIAOMIAO/deep-learning-for-image-processing@1ec3fe6f37 (2026-08-30).
Data as JSON: /api/errors/43dcc24666f4c4b5.
Report an issue: GitHub.