{"record":{"id":"7f63d866aaaec0f7","repo":"open-mmlab/mmdetection","slug":"sampler-should-be-an-instance-of-sampler-but","errorCode":null,"errorMessage":"sampler should be an instance of ``Sampler``, but got {sampler}","messagePattern":"sampler should be an instance of ``Sampler``, but got (.+?)","errorType":"validation","errorClass":"TypeError","httpStatus":null,"severity":"error","filePath":"mmdet/datasets/samplers/batch_sampler.py","lineNumber":29,"sourceCode":"@DATA_SAMPLERS.register_module()\nclass AspectRatioBatchSampler(BatchSampler):\n    \"\"\"A sampler wrapper for grouping images with similar aspect ratio (< 1 or.\n\n    >= 1) into a same batch.\n\n    Args:\n        sampler (Sampler): Base sampler.\n        batch_size (int): Size of mini-batch.\n        drop_last (bool): If ``True``, the sampler will drop the last batch if\n            its size would be less than ``batch_size``.\n    \"\"\"\n\n    def __init__(self,\n                 sampler: Sampler,\n                 batch_size: int,\n                 drop_last: bool = False) -> None:\n        if not isinstance(sampler, Sampler):\n            raise TypeError('sampler should be an instance of ``Sampler``, '\n                            f'but got {sampler}')\n        if not isinstance(batch_size, int) or batch_size <= 0:\n            raise ValueError('batch_size should be a positive integer value, '\n                             f'but got batch_size={batch_size}')\n        self.sampler = sampler\n        self.batch_size = batch_size\n        self.drop_last = drop_last\n        # two groups for w < h and w >= h\n        self._aspect_ratio_buckets = [[] for _ in range(2)]\n\n    def __iter__(self) -> Sequence[int]:\n        for idx in self.sampler:\n            data_info = self.sampler.dataset.get_data_info(idx)\n            width, height = data_info['width'], data_info['height']\n            bucket_id = 0 if width < height else 1\n            bucket = self._aspect_ratio_buckets[bucket_id]\n            bucket.append(idx)\n            # yield a batch of indices in the same aspect ratio group","sourceCodeStart":11,"sourceCodeEnd":47,"githubUrl":"https://github.com/open-mmlab/mmdetection/blob/cfd5d3a985b0249de009b67d04f37263e11cdf3d/mmdet/datasets/samplers/batch_sampler.py#L11-L47","documentation":"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.","triggerScenarios":"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.","commonSituations":"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__).","solutions":["Pass an instance of a torch Sampler (or subclass like DefaultSampler/RandomSampler/ClassAwareSampler) as the sampler argument","If using a custom sampler, make it inherit from torch.utils.data.Sampler and instantiate it before passing","In configs, ensure sampler=dict(type='DefaultSampler', shuffle=True) and the dataloader wrapper builds it rather than passing raw lists"],"exampleFix":"# before\nbatch_sampler = AspectRatioBatchSampler(sampler=[0, 1, 2, 3], batch_size=2)\n# after\nfrom torch.utils.data import RandomSampler\nbatch_sampler = AspectRatioBatchSampler(sampler=RandomSampler(dataset), batch_size=2)","handlingStrategy":"type-guard","validationCode":"from torch.utils.data import Sampler\nassert isinstance(sampler, Sampler), 'sampler must be a torch Sampler instance'","typeGuard":"from torch.utils.data import Sampler\n\ndef is_torch_sampler(obj) -> bool:\n    return isinstance(obj, Sampler)","tryCatchPattern":null,"preventionTips":["Always construct samplers from torch.utils.data subclasses rather than passing index lists","In config files use sampler=dict(type='DefaultSampler', ...) so mmengine builds a proper instance"],"tags":["mmdet","sampler","batch-sampler","typeerror","pytorch"],"backgroundTag":"invalid-argument-type","analyzedSha":"cfd5d3a985b0249de009b67d04f37263e11cdf3d","analyzedAt":"2026-08-27T20:54:20.183Z","schemaVersion":2},"datasetVersion":"2026-08-28T00:17:15.603Z"}