{"record":{"id":"46c2a49185657c4b","repo":"WZMIAOMIAO/deep-learning-for-image-processing","slug":"sampler-should-be-an-instance-of-torch-utils-data-46c2a4","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/yolov3_spp/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/yolov3_spp/train_utils/group_by_aspect_ratio.py#L21-L57","documentation":"GroupedBatchSampler validates in __init__ that the sampler argument is an instance of torch.utils.data.Sampler, because it iterates the sampler to build grouped batches. Passing any other object (e.g. a list, an iterator, or a function) raises ValueError with the repr of the object.","triggerScenarios":"Constructing GroupedBatchSampler(sampler, group_ids, batch_size) where sampler is a plain list/iterator instead of a torch.utils.data.Sampler instance (e.g. RandomSampler, SequentialSampler, or a custom Sampler subclass).","commonSituations":"Passing range(len(dataset)) or a shuffled list directly; using a custom sampler that subclasses object/Iterator but not torch.utils.data.Sampler; adapting code from torchvision's references where a real sampler is created first.","solutions":["Wrap the indices in torch.utils.data.SubsetRandomSampler or RandomSampler before passing it in.","If you have a custom sampler, make it inherit from torch.utils.data.Sampler.","If you only have an index list, convert it: sampler = torch.utils.data.sampler.SubsetRandomSampler(indices)."],"exampleFix":"// before\nsampler = torch.randperm(len(dataset)).tolist()\nbatch_sampler = GroupedBatchSampler(sampler, group_ids, batch_size)\n// after\nfrom torch.utils.data import SubsetRandomSampler\nsampler = SubsetRandomSampler(torch.randperm(len(dataset)).tolist())\nbatch_sampler = GroupedBatchSampler(sampler, group_ids, batch_size)","handlingStrategy":"type-guard","validationCode":"from torch.utils.data import Sampler\nassert isinstance(sampler, Sampler), type(sampler)","typeGuard":"from torch.utils.data import Sampler\ndef is_torch_sampler(s) -> bool:\n    return isinstance(s, Sampler)","tryCatchPattern":"try:\n    gbs = GroupedBatchSampler(sampler, group_ids, batch_size)\nexcept ValueError as e:\n    logging.error(f\"bad sampler: {e}\"); raise","preventionTips":["Always construct samplers via torch.utils.data (RandomSampler/SubsetRandomSampler)","Make custom samplers subclass torch.utils.data.Sampler","Never pass raw lists/ranges where a Sampler is expected"],"tags":["value-error","sampler","type-check","dataloader"],"backgroundTag":"invalid-sampler-type","analyzedSha":"1ec3fe6f374fc9969973a61f819de25658595afa","analyzedAt":"2026-08-30T09:19:11.901Z","schemaVersion":2},"datasetVersion":"2026-08-30T13:17:10.514Z"}