facebookresearch/detectron2 · error · IndexError
Instances index out of range!
Error message
Instances index out of range!
What it means
Instances.__getitem__ with an int index validates it against the instance count (length of the first field). Out-of-range indices raise IndexError before any field is sliced.
Source
Thrown at detectron2/structures/instances.py:135
ret = Instances(self._image_size)
for k, v in self._fields.items():
if hasattr(v, "to"):
v = v.to(*args, **kwargs)
ret.set(k, v)
return ret
def __getitem__(self, item: Union[int, slice, torch.BoolTensor]) -> "Instances":
"""
Args:
item: an index-like object and will be used to index all the fields.
Returns:
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!")
@staticmethodView on GitHub (pinned to a2f4a8771a)
Solutions
- Check len(instances) > 0 before indexing
- Iterate via zip over fields or use instances[:k] slicing which never raises
- Filter confidently first and handle the empty case explicitly
Example fix
# before
for i in range(batch_size):
inst = instances[i]
# after
for i in range(min(batch_size, len(instances))):
inst = instances[i] Defensive patterns
Strategy: validation
Validate before calling
if len(instances.get_fields()) == 0:
return # nothing detected
assert -len(instances) <= i < len(instances), 'Instances index out of range' Try / catch
try:
inst = instances[i]
except IndexError:
inst = None Prevention
- Check len(instances) and handle 0 detections
- Prefer slicing instances[:k] which is always safe
When it happens
Trigger: instances[10] on an Instances with 3 rows; common in visualization or per-instance loops that assume detections exist.
Common situations: Looping range(N) over a fixed batch size while an image has 0 detections (len 0 makes every index invalid); off-by-one after filtering.
Related errors
- Cannot find field '{}' in the given Instances!
- Empty Instances does not support __len__!
- `Instances` object is not iterable!
- Unsupported type {} for concatenation
- Cannot match one checkpoint key to multiple keys in the mode
AI-assisted analysis of facebookresearch/detectron2@a2f4a8771a (2026-08-27).
Data as JSON: /api/errors/89bbf0c008b00102.
Report an issue: GitHub.