{"record":{"id":"6d341dc6f4e1e7c0","repo":"WZMIAOMIAO/deep-learning-for-image-processing","slug":"sampler-should-be-an-instance-of-torch-utils-data-6d341d","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":"exception","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"pytorch_object_detection/mask_rcnn/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/mask_rcnn/train_utils/group_by_aspect_ratio.py#L21-L57","documentation":"GroupedBatchSampler's __init__ requires sampler to be an instance of torch.utils.data.Sampler because it iterates the sampler to build batches per group. Passing a list, range, or DataLoader instead of a Sampler raises ValueError with the repr of the object.","triggerScenarios":"Instantiating GroupedBatchSampler(batch_size=..., group_ids=...) with a plain list, range object, or dataset as sampler — commonly when using batch_sampler=GroupedBatchSampler(dataset, ...) instead of a sampler instance.","commonSituations":"Passing a DataLoader where a sampler is expected; confusing torch's BatchSampler composition order; using a non-torch sampler implementation.","solutions":["Pass a torch.utils.data.Sampler subclass instance, e.g. torch.utils.data.RandomSampler(dataset) or a custom aspect-ratio sampler","Wrap any iterable in Sampler: class ListSampler(Sampler): def __init__(self, lst): self.lst = lst; def __iter__(self): return iter(self.lst); def __len__(self): return len(self.lst)","Ensure the DataLoader wiring is sampler=GroupedBatchSampler(sampler, group_ids, batch_size), not batch_sampler with wrong args"],"exampleFix":"// before\nsampler = GroupedBatchSampler(dataset, group_ids, batch_size=4)  # dataset is not a Sampler\n// after\nbase = torch.utils.data.RandomSampler(dataset)\nsampler = GroupedBatchSampler(base, group_ids, batch_size=4)","handlingStrategy":"type-guard","validationCode":"from torch.utils.data import Sampler\nassert isinstance(sampler, Sampler), 'GroupedBatchSampler requires a torch Sampler instance'\ngbs = GroupedBatchSampler(sampler, group_ids, batch_size)","typeGuard":"def is_torch_sampler(s):\n    from torch.utils.data import Sampler\n    return isinstance(s, Sampler)","tryCatchPattern":"try:\n    gbs = GroupedBatchSampler(sampler, group_ids, batch_size)\nexcept ValueError as e:\n    if 'instance of' in str(e):\n        sampler = torch.utils.data.RandomSampler(dataset)\n        gbs = GroupedBatchSampler(sampler, group_ids, batch_size)\n    else:\n        raise","preventionTips":["Always pass a Sampler subclass, never a raw iterable","Remember len(group_ids) must equal len(sampler)/dataset","Verify the DataLoader uses sampler= not batch_sampler= when composing yourself"],"tags":["python","sampler","dataloader"],"backgroundTag":"invalid-argument-type","analyzedSha":"1ec3fe6f374fc9969973a61f819de25658595afa","analyzedAt":"2026-08-30T09:19:11.901Z","schemaVersion":2},"datasetVersion":"2026-08-30T13:17:10.514Z"}