{"record":{"id":"7fb45c80d7aca05b","repo":"WZMIAOMIAO/deep-learning-for-image-processing","slug":"sampler-should-be-an-instance-of-torch-utils-data","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_keypoint/HRNet/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_keypoint/HRNet/train_utils/group_by_aspect_ratio.py#L21-L57","documentation":"BatchSampler-style __init__ validates that the sampler argument is an instance of torch.utils.data.Sampler and raises ValueError otherwise, echoing the received object. This GroupedBatchSampler groups indices by aspect ratio, so it depends on the Sampler protocol (iter/len) to produce batches.","triggerScenarios":"Passing a plain list, range, generator, or a non-Sampler iterable as the first argument to the grouped batch sampler constructor, e.g. GroupedBatchSampler(dataset_indices, group_ids, batch_size) instead of a Sampler wrapping them.","commonSituations":"Upgrading PyTorch: newer torchvision versions made aspect-ratio grouping samplers subclass differently and older call sites pass indices directly; refactoring code that previously iterated raw index lists; confusing batch_sampler with sampler arguments in DataLoader.","solutions":["Wrap plain indices in torch.utils.data.sampler.SubsetRandomSampler or RandomSampler before passing.","If you have aspect-ratio grouped data, build the sampler with create_aspect_ratio_groups() from the same module, which returns a proper Sampler.","Ensure you pass the sampler positionally in the right order (sampler, group_ids, batch_size).","If using torchvision's aspect ratio grouping, prefer torchvision.utils.dataset grouping utilities matching your torch version."],"exampleFix":"# before\nsampler = list(range(len(dataset)))\nbatch_sampler = GroupedBatchSampler(sampler, group_ids, batch_size)  # ValueError\n# after\nfrom torch.utils.data.sampler import SubsetRandomSampler\nsampler = SubsetRandomSampler(list(range(len(dataset))))\nbatch_sampler = GroupedBatchSampler(sampler, group_ids, batch_size)","handlingStrategy":"type-guard","validationCode":"from torch.utils.data import Sampler\nassert isinstance(sampler, Sampler), f\"got {type(sampler).__name__}; wrap indices in a Sampler\"","typeGuard":"from torch.utils.data import Sampler\ndef is_valid_sampler(obj) -> bool:\n    return isinstance(obj, Sampler)","tryCatchPattern":"try:\n    batch_sampler = GroupedBatchSampler(sampler, group_ids, batch_size)\nexcept ValueError as e:\n    logging.error(\"Bad sampler: %s — wrapping in SubsetRandomSampler\", e)\n    batch_sampler = GroupedBatchSampler(SubsetRandomSampler(sampler), group_ids, batch_size)","preventionTips":["Never pass raw lists/ranges where a Sampler is documented.","Use create_aspect_ratio_groups() from the same module to build the sampler.","Check torch/torchvision version notes when upgrading sampler code."],"tags":["pytorch","sampler","type-error","dataloader","validation"],"backgroundTag":"invalid-sampler-type","analyzedSha":"1ec3fe6f374fc9969973a61f819de25658595afa","analyzedAt":"2026-08-30T09:19:11.901Z","schemaVersion":2},"datasetVersion":"2026-08-30T13:17:10.514Z"}