open-mmlab/mmdetection · error · TypeError

sampler should be an instance of ``Sampler``, but got {sampl

Error message

sampler should be an instance of ``Sampler``, but got {sampler}

What it means

mmdet's aspect-ratio-aware AspectRatioBatchSampler requires its first constructor argument to be a torch.utils.data.Sampler instance. Passing anything else (a list of indices, a DataLoader, a dict config, or None) raises this TypeError before any attribute is set.

Source

Thrown at mmdet/datasets/samplers/batch_sampler.py:29

@DATA_SAMPLERS.register_module()
class AspectRatioBatchSampler(BatchSampler):
    """A sampler wrapper for grouping images with similar aspect ratio (< 1 or.

    >= 1) into a same batch.

    Args:
        sampler (Sampler): Base sampler.
        batch_size (int): Size of mini-batch.
        drop_last (bool): If ``True``, the sampler will drop the last batch if
            its size would be less than ``batch_size``.
    """

    def __init__(self,
                 sampler: Sampler,
                 batch_size: int,
                 drop_last: bool = False) -> None:
        if not isinstance(sampler, Sampler):
            raise TypeError('sampler should be an instance of ``Sampler``, '
                            f'but got {sampler}')
        if not isinstance(batch_size, int) or batch_size <= 0:
            raise ValueError('batch_size should be a positive integer value, '
                             f'but got batch_size={batch_size}')
        self.sampler = sampler
        self.batch_size = batch_size
        self.drop_last = drop_last
        # two groups for w < h and w >= h
        self._aspect_ratio_buckets = [[] for _ in range(2)]

    def __iter__(self) -> Sequence[int]:
        for idx in self.sampler:
            data_info = self.sampler.dataset.get_data_info(idx)
            width, height = data_info['width'], data_info['height']
            bucket_id = 0 if width < height else 1
            bucket = self._aspect_ratio_buckets[bucket_id]
            bucket.append(idx)
            # yield a batch of indices in the same aspect ratio group

View on GitHub (pinned to cfd5d3a985)

Solutions

  1. Pass an instance of a torch Sampler (or subclass like DefaultSampler/RandomSampler/ClassAwareSampler) as the sampler argument
  2. If using a custom sampler, make it inherit from torch.utils.data.Sampler and instantiate it before passing
  3. In configs, ensure sampler=dict(type='DefaultSampler', shuffle=True) and the dataloader wrapper builds it rather than passing raw lists

Example fix

# before
batch_sampler = AspectRatioBatchSampler(sampler=[0, 1, 2, 3], batch_size=2)
# after
from torch.utils.data import RandomSampler
batch_sampler = AspectRatioBatchSampler(sampler=RandomSampler(dataset), batch_size=2)
Defensive patterns

Strategy: type-guard

Validate before calling

from torch.utils.data import Sampler
assert isinstance(sampler, Sampler), 'sampler must be a torch Sampler instance'

Type guard

from torch.utils.data import Sampler

def is_torch_sampler(obj) -> bool:
    return isinstance(obj, Sampler)

Prevention

When it happens

Trigger: Wrapping an AspectRatioBatchSampler around a non-Sampler object, e.g. batch_sampler=dict(sampler=[0,1,2], ...) in a config, passing a Sequence/iterator of indices, or passing a ClassAwareSampler-like object that does not subclass torch's Sampler.

Common situations: Config mistakes where 'sampler' is given a plain list of indices or an uninstantiated class; version drift where a custom sampler stopped subclassing torch.utils.data.Sampler (e.g. only duck-types __iter__).

Understand the failure class

Background: Invalid argument type errors: "must be of type string", "expected X, got Y", and ERR_INVALID_ARG_TYPE explained — this error's family across 15 libraries.

Related errors


AI-assisted analysis of open-mmlab/mmdetection@cfd5d3a985 (2026-08-27). Data as JSON: /api/errors/7f63d866aaaec0f7. Report an issue: GitHub.