{"record":{"id":"bc553da8cebc6c48","repo":"WZMIAOMIAO/deep-learning-for-image-processing","slug":"sampler-should-be-an-instance-of-torch-utils-data-bc553d","errorCode":null,"errorMessage":"sampler should be an instance of torch.utils.data.Sampler, but got sampler={}","messagePattern":"sampler should be an instance of torch\\.utils\\.data\\.Sampler, but got sampler=(.+?)","errorType":"validation","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"pytorch_object_detection/train_coco_dataset/train_utils/group_by_aspect_ratio.py","lineNumber":39,"sourceCode":"\n\nclass GroupedBatchSampler(BatchSampler):\n    \"\"\"\n    Wraps another sampler to yield a mini-batch of indices.\n    It enforces that the batch only contain elements from the same group.\n    It also tries to provide mini-batches which follows an ordering which is\n    as close as possible to the ordering from the original sampler.\n    Arguments:\n        sampler (Sampler): Base sampler.\n        group_ids (list[int]): If the sampler produces indices in range [0, N),\n            `group_ids` must be a list of `N` ints which contains the group id of each sample.\n            The group ids must be a continuous set of integers starting from\n            0, i.e. they must be in the range [0, num_groups).\n        batch_size (int): Size of mini-batch.\n    \"\"\"\n    def __init__(self, sampler, group_ids, batch_size):\n        if not isinstance(sampler, Sampler):\n            raise ValueError(\n                \"sampler should be an instance of \"\n                \"torch.utils.data.Sampler, but got sampler={}\".format(sampler)\n            )\n        self.sampler = sampler\n        self.group_ids = group_ids\n        self.batch_size = batch_size\n\n    def __iter__(self):\n        buffer_per_group = defaultdict(list)\n        samples_per_group = defaultdict(list)\n\n        num_batches = 0\n        for idx in self.sampler:\n            group_id = self.group_ids[idx]\n            buffer_per_group[group_id].append(idx)\n            samples_per_group[group_id].append(idx)\n            if len(buffer_per_group[group_id]) == self.batch_size:\n                yield buffer_per_group[group_id]","sourceCodeStart":21,"sourceCodeEnd":57,"githubUrl":"https://github.com/WZMIAOMIAO/deep-learning-for-image-processing/blob/1ec3fe6f374fc9969973a61f819de25658595afa/pytorch_object_detection/train_coco_dataset/train_utils/group_by_aspect_ratio.py#L21-L57","documentation":"GroupedBatchSampler's __init__ validates that the sampler argument is an instance of torch.utils.data.Sampler. If any other object (list, iterable, None, custom class not inheriting Sampler) is passed, it raises ValueError naming the offending object. This guarantees the sampler exposes __iter__/__len__ semantics the batch sampler relies on.","triggerScenarios":"Calling GroupedBatchSampler(sampler, group_ids, batch_size) with a plain list, generator, Dataset, or a custom sampler class that does not subclass torch.utils.data.Sampler.","commonSituations":"Refactoring code that previously iterated indices directly; passing indices=list(range(len(dataset))) instead of wrapping in a Sampler; using a third-party sampler from an older torch version with a different base class.","solutions":["Wrap the indices in torch.utils.data.Sampler (e.g. create a subclass with __iter__/__len__) before passing it","If you already have a sampler-like object, make it inherit from torch.utils.data.Sampler","Check what you are passing: print(type(sampler)) and confirm it is not a list or ndarray"],"exampleFix":"// before\nsampler = list(range(len(dataset)))\nbatch_sampler = GroupedBatchSampler(sampler, group_ids, batch_size)\n// after\nfrom torch.utils.data import Sampler\nclass MySampler(Sampler):\n    def __init__(self, data_source):\n        self.data_source = data_source\n    def __iter__(self):\n        return iter(range(len(self.data_source)))\n    def __len__(self):\n        return len(self.data_source)\nbatch_sampler = GroupedBatchSampler(MySampler(dataset), group_ids, batch_size)","handlingStrategy":"type-guard","validationCode":"from torch.utils.data import Sampler\nif not isinstance(sampler, Sampler):\n    raise TypeError(f'expected torch.utils.data.Sampler, got {type(sampler)}')","typeGuard":"def is_torch_sampler(obj) -> bool:\n    import torch.utils.data as td\n    return isinstance(obj, td.Sampler)","tryCatchPattern":"try:\n    bs = GroupedBatchSampler(sampler, group_ids, batch_size)\nexcept ValueError as e:\n    if 'sampler should be an instance' in str(e):\n        sampler = ListSampler(list(sampler))\n        bs = GroupedBatchSampler(sampler, group_ids, batch_size)\n    else:\n        raise","preventionTips":["Always subclass torch.utils.data.Sampler for custom samplers","Assert isinstance(sampler, Sampler) at the call site before constructing batch samplers","Wrap raw index lists in a Sampler subclass instead of passing lists directly"],"tags":["python","pytorch","type-error","sampler"],"backgroundTag":"invalid-argument-type","analyzedSha":"1ec3fe6f374fc9969973a61f819de25658595afa","analyzedAt":"2026-08-30T09:19:11.901Z","schemaVersion":2},"datasetVersion":"2026-08-30T13:17:10.514Z"}