{"record":{"id":"a92a01b69af59b2b","repo":"WZMIAOMIAO/deep-learning-for-image-processing","slug":"sampler-should-be-an-instance-of-torch-utils-data-a92a01","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/retinaNet/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/retinaNet/train_utils/group_by_aspect_ratio.py#L21-L57","documentation":"BatchSampler subclass GroupedBatchSampler validates that the sampler argument is an instance of torch.utils.data.Sampler. Passing any other iterable raises ValueError. It needs a Sampler because it iterates via sampler.__len__ and index yields, not arbitrary containers.","triggerScenarios":"Constructing GroupedBatchSampler with a plain list, generator, or a non-torch sampler object; passing a dataset instead of a sampler; custom sampler that only quacks like one but doesn't inherit torch.utils.data.Sampler.","commonSituations":"Refactoring aspect-ratio grouped training code and passing indices list directly; wrapping a sampler in another class without inheriting Sampler; using torchvision API copied without its RandomSampler wrapper.","solutions":["Wrap your indices in torch.utils.data.sampler.SubsetRandomSampler or pass RandomSampler(dataset)","Make the custom sampler inherit from torch.utils.data.Sampler","Pass the sampler that was already constructed in the training setup (e.g. RandomSampler) rather than the dataset"],"exampleFix":"// before\nGroupedBatchSampler(dataset, group_ids, batch_size)\n// after\nsampler = RandomSampler(dataset)\nGroupedBatchSampler(sampler, group_ids, batch_size)","handlingStrategy":"type-guard","validationCode":"from torch.utils.data import Sampler\nassert isinstance(sampler, Sampler), 'pass a torch Sampler (e.g. RandomSampler)'\nassert isinstance(group_ids, (list, tuple)) and len(group_ids) == len(sampler)","typeGuard":"def is_torch_sampler(obj) -> bool:\n    from torch.utils.data import Sampler\n    return isinstance(obj, Sampler)","tryCatchPattern":"try:\n    grouped = GroupedBatchSampler(sampler, group_ids, batch_size)\nexcept ValueError as e:\n    print(f'Sampler invalid: {e}; wrap indices in SubsetRandomSampler')","preventionTips":["Always build samplers via torch.utils.data factories","If passing indices manually, wrap in SubsetRandomSampler","Keep the sampler construction close to the grouped sampler call"],"tags":["pytorch","sampler","typeerror","dataloader"],"backgroundTag":"invalid-sampler-type","analyzedSha":"1ec3fe6f374fc9969973a61f819de25658595afa","analyzedAt":"2026-08-30T09:19:11.901Z","schemaVersion":2},"datasetVersion":"2026-08-30T13:17:10.514Z"}