facebookresearch/detectron2 · error · NotImplementedError

Empty Instances does not support __len__!

Error message

Empty Instances does not support __len__!

What it means

Instances.__len__ returns the length of the first field; with zero fields there is nothing to measure, so calling len() on an empty Instances raises NotImplementedError rather than guessing 0.

Source

Thrown at detectron2/structures/instances.py:148

            If `item` is a string, return the data in the corresponding field.
            Otherwise, returns an `Instances` where all fields are indexed by `item`.
        """
        if type(item) is int:
            if item >= len(self) or item < -len(self):
                raise IndexError("Instances index out of range!")
            else:
                item = slice(item, None, len(self))

        ret = Instances(self._image_size)
        for k, v in self._fields.items():
            ret.set(k, v[item])
        return ret

    def __len__(self) -> int:
        for v in self._fields.values():
            # use __len__ because len() has to be int and is not friendly to tracing
            return v.__len__()
        raise NotImplementedError("Empty Instances does not support __len__!")

    def __iter__(self):
        raise NotImplementedError("`Instances` object is not iterable!")

    @staticmethod
    def cat(instance_lists: List["Instances"]) -> "Instances":
        """
        Args:
            instance_lists (list[Instances])

        Returns:
            Instances
        """
        assert all(isinstance(i, Instances) for i in instance_lists)
        assert len(instance_lists) > 0
        if len(instance_lists) == 1:
            return instance_lists[0]

View on GitHub (pinned to a2f4a8771a)

Solutions

  1. Set at least one field before calling len(), e.g. instances.set('pred_boxes', Boxes(torch.zeros(0,4)))
  2. Guard with len(instances.get_fields()) > 0 before calling len()
  3. Use detectron2's empty_input context / handle the no-detection branch separately

Example fix

# before
n = len(instances)
# after
fields = instances.get_fields()
n = len(next(iter(fields.values()))) if fields else 0
Defensive patterns

Strategy: validation

Validate before calling

def instances_len(instances) -> int:
    fields = instances.get_fields()
    return len(next(iter(fields.values()))) if fields else 0

Prevention

When it happens

Trigger: len(Instances(image_size)) right after construction, or on an Instances whose fields were never set (e.g. empty detections built manually).

Common situations: Postprocessing code doing len(predictions['instances']) before any head populated fields; iterating results of a model with all heads disabled.

Related errors


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