facebookresearch/detectron2 · error · AttributeError

Cannot find field '{}' in the given Instances!

Error message

Cannot find field '{}' in the given Instances!

What it means

Instances stores per-image fields in a dict; attribute access is forwarded to fields. Accessing an attribute that was never set (e.g. pred_masks before mask inference, gt_keypoints on a boxes-only dataset) raises AttributeError.

Source

Thrown at detectron2/structures/instances.py:66

            self.set(k, v)

    @property
    def image_size(self) -> Tuple[int, int]:
        """
        Returns:
            tuple: height, width
        """
        return self._image_size

    def __setattr__(self, name: str, val: Any) -> None:
        if name.startswith("_"):
            super().__setattr__(name, val)
        else:
            self.set(name, val)

    def __getattr__(self, name: str) -> Any:
        if name == "_fields" or name not in self._fields:
            raise AttributeError("Cannot find field '{}' in the given Instances!".format(name))
        return self._fields[name]

    def set(self, name: str, value: Any) -> None:
        """
        Set the field named `name` to `value`.
        The length of `value` must be the number of instances,
        and must agree with other existing fields in this object.
        """
        with warnings.catch_warnings(record=True):
            data_len = len(value)
        if len(self._fields):
            assert (
                len(self) == data_len
            ), "Adding a field of length {} to a Instances of length {}".format(data_len, len(self))
        self._fields[name] = value

    def has(self, name: str) -> bool:
        """

View on GitHub (pinned to a2f4a8771a)

Solutions

  1. Guard with hasattr(instance, 'pred_masks') or check available fields via instance.get_fields().keys()
  2. Enable the relevant head: cfg.MODEL.MASK_ON = True / MODEL.KEYPOINT_ON = True
  3. Check field name spelling against the head that produces it (pred_classes, scores, pred_masks, pred_keypoints)

Example fix

# before
masks = outputs['instances'].pred_masks
# after
inst = outputs['instances']
masks = inst.pred_masks if hasattr(inst, 'pred_masks') else None
Defensive patterns

Strategy: type-guard

Validate before calling

fields = instances.get_fields()
assert 'pred_masks' in fields, f'available: {list(fields)}'

Type guard

def has_field(instances, name: str) -> bool:
    return name in instances.get_fields()

Try / catch

try:
    val = instances.pred_masks
except AttributeError:
    val = None  # head disabled or field absent

Prevention

When it happens

Trigger: Reading instances.pred_masks when the mask head was disabled (MODEL.ROI_MASK_HEAD disabled or MODEL.MASK_ON=False); accessing any field name not present in instances._fields.

Common situations: Custom evaluation loops assuming all outputs exist; enabling/disabling heads in config but not updating downstream code; accessing 'scores' vs 'score' naming differences across versions.

Related errors


AI-assisted analysis of facebookresearch/detectron2@a2f4a8771a (2026-08-27). Data as JSON: /api/errors/54c2eeb309523231. Report an issue: GitHub.